From 9c42e85e964ce691d9e410db11bfcb77fdce7d44 Mon Sep 17 00:00:00 2001 From: jennymar Date: Thu, 10 Oct 2024 09:38:38 -0700 Subject: [PATCH] Attempt at fixing linting --- api/controllers/AdminController.ts | 48 +---- api/controllers/AttendanceController.ts | 59 ++---- api/controllers/EventController.ts | 58 ++---- api/controllers/FeedbackController.ts | 30 +-- api/controllers/LeaderboardController.ts | 18 +- api/controllers/MerchStoreController.ts | 228 ++++++++-------------- api/controllers/UserController.ts | 71 ++----- services/AttendanceService.ts | 153 ++++----------- services/EventService.ts | 21 +- services/FeedbackService.ts | 31 +-- services/MerchStoreService.ts | 236 ++++++----------------- services/UserAccountService.ts | 93 ++------- 12 files changed, 274 insertions(+), 772 deletions(-) diff --git a/api/controllers/AdminController.ts b/api/controllers/AdminController.ts index a92ff59c..3f26713c 100644 --- a/api/controllers/AdminController.ts +++ b/api/controllers/AdminController.ts @@ -1,13 +1,4 @@ -import { - JsonController, - Post, - Patch, - UploadedFile, - UseBefore, - ForbiddenError, - Body, - Get, -} from 'routing-controllers'; +import { JsonController, Post, Patch, UploadedFile, UseBefore, ForbiddenError, Body, Get } from 'routing-controllers'; import { UserAuthentication } from '../middleware/UserAuthentication'; import { CreateBonusRequest, @@ -53,9 +44,7 @@ export class AdminController { } @Get('/email') - async getAllNamesAndEmails( - @AuthenticatedUser() user: UserModel, - ): Promise { + async getAllNamesAndEmails(@AuthenticatedUser() user: UserModel): Promise { if (!PermissionsService.canSeeAllUserEmails(user)) throw new ForbiddenError(); const namesAndEmails = await this.userAccountService.getAllNamesAndEmails(); return { error: null, namesAndEmails }; @@ -67,9 +56,7 @@ export class AdminController { @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canCreateMilestones(user)) throw new ForbiddenError(); - await this.userAccountService.createMilestone( - createMilestoneRequest.milestone, - ); + await this.userAccountService.createMilestone(createMilestoneRequest.milestone); return { error: null }; } @@ -81,11 +68,7 @@ export class AdminController { if (!PermissionsService.canGrantPointBonuses(user)) throw new ForbiddenError(); const { bonus } = createBonusRequest; const emails = bonus.users.map((e) => e.toLowerCase()); - await this.userAccountService.grantBonusPoints( - emails, - bonus.description, - bonus.points, - ); + await this.userAccountService.grantBonusPoints(emails, bonus.description, bonus.points); return { error: null, emails }; } @@ -96,11 +79,7 @@ export class AdminController { }) file: File, ): Promise { - const banner = await this.storageService.upload( - file, - MediaType.BANNER, - 'banner', - ); + const banner = await this.storageService.upload(file, MediaType.BANNER, 'banner'); return { error: null, banner }; } @@ -112,12 +91,7 @@ export class AdminController { if (!PermissionsService.canSubmitAttendanceForUsers(currentUser)) throw new ForbiddenError(); const { users, event, asStaff } = submitAttendanceForUsersRequest; const emails = users.map((e) => e.toLowerCase()); - const attendances = await this.attendanceService.submitAttendanceForUsers( - emails, - event, - asStaff, - currentUser, - ); + const attendances = await this.attendanceService.submitAttendanceForUsers(emails, event, asStaff, currentUser); return { error: null, attendances }; } @@ -129,18 +103,12 @@ export class AdminController { if (!PermissionsService.canModifyUserAccessLevel(currentUser)) throw new ForbiddenError(); const { accessUpdates } = modifyUserAccessLevelRequest; const emails = accessUpdates.map((e) => e.user.toLowerCase()); - const updatedUsers = await this.userAccountService.updateUserAccessLevels( - accessUpdates, - emails, - currentUser, - ); + const updatedUsers = await this.userAccountService.updateUserAccessLevels(accessUpdates, emails, currentUser); return { error: null, updatedUsers }; } @Get('/access') - async getAllUsersWithAccessLevels( - @AuthenticatedUser() user: UserModel, - ): Promise { + async getAllUsersWithAccessLevels(@AuthenticatedUser() user: UserModel): Promise { if (!PermissionsService.canSeeAllUserAccessLevels(user)) throw new ForbiddenError(); const users = await this.userAccountService.getAllFullUserProfiles(); return { diff --git a/api/controllers/AttendanceController.ts b/api/controllers/AttendanceController.ts index 6441933b..307e9d01 100644 --- a/api/controllers/AttendanceController.ts +++ b/api/controllers/AttendanceController.ts @@ -1,27 +1,12 @@ -import { - JsonController, - Get, - Post, - UseBefore, - Params, - ForbiddenError, - Body, -} from 'routing-controllers'; +import { JsonController, Get, Post, UseBefore, Params, ForbiddenError, Body } from 'routing-controllers'; import EmailService from '../../services/EmailService'; import { UserAuthentication } from '../middleware/UserAuthentication'; import { AuthenticatedUser } from '../decorators/AuthenticatedUser'; -import { - AttendEventRequest, - AttendViaExpressCheckinRequest, -} from '../validators/AttendanceControllerRequests'; +import { AttendEventRequest, AttendViaExpressCheckinRequest } from '../validators/AttendanceControllerRequests'; import { UserModel } from '../../models/UserModel'; import AttendanceService from '../../services/AttendanceService'; import PermissionsService from '../../services/PermissionsService'; -import { - GetAttendancesForEventResponse, - GetAttendancesForUserResponse, - AttendEventResponse, -} from '../../types'; +import { GetAttendancesForEventResponse, GetAttendancesForUserResponse, AttendEventResponse } from '../../types'; import { UuidParam } from '../validators/GenericRequests'; @JsonController('/attendance') @@ -30,10 +15,7 @@ export class AttendanceController { private emailService: EmailService; - constructor( - attendanceService: AttendanceService, - emailService: EmailService, - ) { + constructor(attendanceService: AttendanceService, emailService: EmailService) { this.attendanceService = attendanceService; this.emailService = emailService; } @@ -45,9 +27,7 @@ export class AttendanceController { @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canSeeEventAttendances(user)) throw new ForbiddenError(); - const attendances = await this.attendanceService.getAttendancesForEvent( - params.uuid, - ); + const attendances = await this.attendanceService.getAttendancesForEvent(params.uuid); return { error: null, attendances: attendances.map((attendance) => attendance.getPublicAttendance()), @@ -56,9 +36,7 @@ export class AttendanceController { @UseBefore(UserAuthentication) @Get() - async getAttendancesForCurrentUser( - @AuthenticatedUser() user: UserModel, - ): Promise { + async getAttendancesForCurrentUser(@AuthenticatedUser() user: UserModel): Promise { const attendances = await this.attendanceService.getAttendancesForCurrentUser(user); return { error: null, @@ -75,9 +53,7 @@ export class AttendanceController { if (params.uuid === currentUser.uuid) { return this.getAttendancesForCurrentUser(currentUser); } - const attendances = await this.attendanceService.getAttendancesForUser( - params.uuid, - ); + const attendances = await this.attendanceService.getAttendancesForUser(params.uuid); return { error: null, attendances: attendances.map((attendance) => attendance.getPublicAttendance()), @@ -90,30 +66,17 @@ export class AttendanceController { @Body() body: AttendEventRequest, @AuthenticatedUser() user: UserModel, ): Promise { - const attendance = await this.attendanceService.attendEvent( - user, - body.attendanceCode, - body.asStaff, - ); + const attendance = await this.attendanceService.attendEvent(user, body.attendanceCode, body.asStaff); const { event } = attendance.getPublicAttendance(); return { error: null, event }; } @Post('/expressCheckin') - async attendViaExpressCheckin( - @Body() body: AttendViaExpressCheckinRequest, - ): Promise { + async attendViaExpressCheckin(@Body() body: AttendViaExpressCheckinRequest): Promise { body.email = body.email.toLowerCase(); const { email, attendanceCode } = body; - const { event } = await this.attendanceService.attendViaExpressCheckin( - attendanceCode, - email, - ); - await this.emailService.sendExpressCheckinConfirmation( - email, - event.title, - event.pointValue, - ); + const { event } = await this.attendanceService.attendViaExpressCheckin(attendanceCode, email); + await this.emailService.sendExpressCheckinConfirmation(email, event.title, event.pointValue); return { error: null, event }; } } diff --git a/api/controllers/EventController.ts b/api/controllers/EventController.ts index d631f085..fdb61ff9 100644 --- a/api/controllers/EventController.ts +++ b/api/controllers/EventController.ts @@ -12,10 +12,7 @@ import { Body, } from 'routing-controllers'; import EventService from '../../services/EventService'; -import { - UserAuthentication, - OptionalUserAuthentication, -} from '../middleware/UserAuthentication'; +import { UserAuthentication, OptionalUserAuthentication } from '../middleware/UserAuthentication'; import { AuthenticatedUser } from '../decorators/AuthenticatedUser'; import { UserModel } from '../../models/UserModel'; import PermissionsService from '../../services/PermissionsService'; @@ -49,11 +46,7 @@ export class EventController { private attendanceService: AttendanceService; - constructor( - eventService: EventService, - storageService: StorageService, - attendanceService: AttendanceService, - ) { + constructor(eventService: EventService, storageService: StorageService, attendanceService: AttendanceService) { this.eventService = eventService; this.storageService = storageService; this.attendanceService = attendanceService; @@ -63,7 +56,7 @@ export class EventController { @Get('/past') async getPastEvents( @QueryParams() options: EventSearchOptions, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { const canSeeAttendanceCode = !!user && PermissionsService.canEditEvents(user); const events = await this.eventService.getPastEvents(options); @@ -77,7 +70,7 @@ export class EventController { @Get('/future') async getFutureEvents( @QueryParams() options: EventSearchOptions, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { const canSeeAttendanceCode = !!user && PermissionsService.canEditEvents(user); const events = await this.eventService.getFutureEvents(options); @@ -93,16 +86,12 @@ export class EventController { @UploadedFile('image', { options: StorageService.getFileOptions(MediaType.EVENT_COVER), }) - file: File, - @Params() params: UuidParam, - @AuthenticatedUser() user: UserModel, + file: File, + @Params() params: UuidParam, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canEditEvents(user)) throw new ForbiddenError(); - const cover = await this.storageService.upload( - file, - MediaType.EVENT_COVER, - params.uuid, - ); + const cover = await this.storageService.upload(file, MediaType.EVENT_COVER, params.uuid); const event = await this.eventService.updateByUuid(params.uuid, { cover }); return { error: null, event: event.getPublicEvent(true) }; } @@ -110,25 +99,18 @@ export class EventController { @UseBefore(UserAuthentication) @Post('/:uuid/feedback') async submitEventFeedback( - @Params() params: UuidParam, + @Params() params: UuidParam, @Body() submitEventFeedbackRequest: SubmitEventFeedbackRequest, @AuthenticatedUser() user: UserModel, ) { if (!PermissionsService.canSubmitFeedback(user)) throw new ForbiddenError(); - await this.attendanceService.submitEventFeedback( - submitEventFeedbackRequest.feedback, - params.uuid, - user, - ); + await this.attendanceService.submitEventFeedback(submitEventFeedbackRequest.feedback, params.uuid, user); return { error: null }; } @UseBefore(OptionalUserAuthentication) @Get('/:uuid') - async getOneEvent( - @Params() params: UuidParam, - @AuthenticatedUser() user: UserModel, - ): Promise { + async getOneEvent(@Params() params: UuidParam, @AuthenticatedUser() user: UserModel): Promise { const canSeeAttendanceCode = !!user && PermissionsService.canEditEvents(user); const event = await this.eventService.findByUuid(params.uuid); return { error: null, event: event.getPublicEvent(canSeeAttendanceCode) }; @@ -138,23 +120,17 @@ export class EventController { @Patch('/:uuid') async updateEvent( @Params() params: UuidParam, - @Body() patchEventRequest: PatchEventRequest, - @AuthenticatedUser() user: UserModel, + @Body() patchEventRequest: PatchEventRequest, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canEditEvents(user)) throw new ForbiddenError(); - const event = await this.eventService.updateByUuid( - params.uuid, - patchEventRequest.event, - ); + const event = await this.eventService.updateByUuid(params.uuid, patchEventRequest.event); return { error: null, event: event.getPublicEvent(true) }; } @UseBefore(UserAuthentication) @Delete('/:uuid') - async deleteEvent( - @Params() params: UuidParam, - @AuthenticatedUser() user: UserModel, - ): Promise { + async deleteEvent(@Params() params: UuidParam, @AuthenticatedUser() user: UserModel): Promise { if (!PermissionsService.canEditEvents(user)) throw new ForbiddenError(); await this.eventService.deleteByUuid(params.uuid); return { error: null }; @@ -164,7 +140,7 @@ export class EventController { @Get() async getAllEvents( @QueryParams() options: EventSearchOptions, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { const canSeeAttendanceCode = !!user && PermissionsService.canEditEvents(user); const events = await this.eventService.getAllEvents(options); @@ -178,7 +154,7 @@ export class EventController { @Post() async createEvent( @Body() createEventRequest: CreateEventRequest, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canEditEvents(user)) throw new ForbiddenError(); const event = await this.eventService.create(createEventRequest.event); diff --git a/api/controllers/FeedbackController.ts b/api/controllers/FeedbackController.ts index ab7b162f..0edb9c0a 100644 --- a/api/controllers/FeedbackController.ts +++ b/api/controllers/FeedbackController.ts @@ -13,11 +13,7 @@ import { AuthenticatedUser } from '../decorators/AuthenticatedUser'; import { UserModel } from '../../models/UserModel'; import PermissionsService from '../../services/PermissionsService'; import FeedbackService from '../../services/FeedbackService'; -import { - GetFeedbackResponse, - SubmitFeedbackResponse, - UpdateFeedbackStatusResponse, -} from '../../types'; +import { GetFeedbackResponse, SubmitFeedbackResponse, UpdateFeedbackStatusResponse } from '../../types'; import { UuidParam } from '../validators/GenericRequests'; import { UserAuthentication } from '../middleware/UserAuthentication'; import { @@ -38,14 +34,10 @@ export class FeedbackController { @Get() async getFeedback( @QueryParams() options: FeedbackSearchOptions, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { const canSeeAllFeedback = PermissionsService.canSeeAllFeedback(user); - const feedback = await this.feedbackService.getFeedback( - canSeeAllFeedback, - user, - options, - ); + const feedback = await this.feedbackService.getFeedback(canSeeAllFeedback, user, options); return { error: null, feedback: feedback.map((fb) => fb.getPublicFeedback()), @@ -55,27 +47,21 @@ export class FeedbackController { @Post() async submitFeedback( @Body() submitFeedbackRequest: SubmitFeedbackRequest, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canSubmitFeedback(user)) throw new ForbiddenError(); - const feedback = await this.feedbackService.submitFeedback( - user, - submitFeedbackRequest.feedback, - ); + const feedback = await this.feedbackService.submitFeedback(user, submitFeedbackRequest.feedback); return { error: null, feedback: feedback.getPublicFeedback() }; } @Patch('/:uuid') async updateFeedbackStatus( @Params() params: UuidParam, - @Body() updateFeedbackStatusRequest: UpdateFeedbackStatusRequest, - @AuthenticatedUser() user: UserModel, + @Body() updateFeedbackStatusRequest: UpdateFeedbackStatusRequest, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canSeeAllFeedback(user)) throw new ForbiddenError(); - const feedback = await this.feedbackService.updateFeedbackStatus( - params.uuid, - updateFeedbackStatusRequest.status, - ); + const feedback = await this.feedbackService.updateFeedbackStatus(params.uuid, updateFeedbackStatusRequest.status); return { error: null, feedback: feedback.getPublicFeedback() }; } } diff --git a/api/controllers/LeaderboardController.ts b/api/controllers/LeaderboardController.ts index f1d47dfd..28ec47d5 100644 --- a/api/controllers/LeaderboardController.ts +++ b/api/controllers/LeaderboardController.ts @@ -1,9 +1,4 @@ -import { - UseBefore, - JsonController, - Get, - QueryParams, -} from 'routing-controllers'; +import { UseBefore, JsonController, Get, QueryParams } from 'routing-controllers'; import { GetLeaderboardResponse } from '../../types'; import { UserAuthentication } from '../middleware/UserAuthentication'; import UserAccountService from '../../services/UserAccountService'; @@ -19,16 +14,9 @@ export class LeaderboardController { } @Get() - async getLeaderboard( - @QueryParams() filters: SlidingLeaderboardQueryParams, - ): Promise { + async getLeaderboard(@QueryParams() filters: SlidingLeaderboardQueryParams): Promise { const { from, to, offset, limit } = filters; - const leaderboard = await this.userAccountService.getLeaderboard( - from, - to, - offset, - limit, - ); + const leaderboard = await this.userAccountService.getLeaderboard(from, to, offset, limit); return { error: null, leaderboard: leaderboard.map((u) => u.getPublicProfile()), diff --git a/api/controllers/MerchStoreController.ts b/api/controllers/MerchStoreController.ts index 54965427..4124d1c6 100644 --- a/api/controllers/MerchStoreController.ts +++ b/api/controllers/MerchStoreController.ts @@ -97,31 +97,22 @@ export class MerchStoreController { @Get('/collection/:uuid') async getOneMerchCollection( @Params() params: UuidParam, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canAccessMerchStore(user)) throw new ForbiddenError(); const canSeeHiddenItems = PermissionsService.canEditMerchStore(user); - const collection = await this.merchStoreService.findCollectionByUuid( - params.uuid, - canSeeHiddenItems, - ); + const collection = await this.merchStoreService.findCollectionByUuid(params.uuid, canSeeHiddenItems); return { error: null, - collection: canSeeHiddenItems - ? collection - : collection.getPublicMerchCollection(), + collection: canSeeHiddenItems ? collection : collection.getPublicMerchCollection(), }; } @Get('/collection') - async getAllMerchCollections( - @AuthenticatedUser() user: UserModel, - ): Promise { + async getAllMerchCollections(@AuthenticatedUser() user: UserModel): Promise { if (!PermissionsService.canAccessMerchStore(user)) throw new ForbiddenError(); const canSeeInactiveCollections = PermissionsService.canEditMerchStore(user); - const collections = await this.merchStoreService.getAllCollections( - canSeeInactiveCollections, - ); + const collections = await this.merchStoreService.getAllCollections(canSeeInactiveCollections); return { error: null, collections: collections.map((c) => c.getPublicMerchCollection(canSeeInactiveCollections)), @@ -131,33 +122,28 @@ export class MerchStoreController { @Post('/collection') async createMerchCollection( @Body() createCollectionRequest: CreateMerchCollectionRequest, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canEditMerchStore(user)) throw new ForbiddenError(); - const collection = await this.merchStoreService.createCollection( - createCollectionRequest.collection, - ); + const collection = await this.merchStoreService.createCollection(createCollectionRequest.collection); return { error: null, collection }; } @Patch('/collection/:uuid') async editMerchCollection( @Params() params: UuidParam, - @Body() editCollectionRequest: EditMerchCollectionRequest, - @AuthenticatedUser() user: UserModel, + @Body() editCollectionRequest: EditMerchCollectionRequest, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canEditMerchStore(user)) throw new ForbiddenError(); - const collection = await this.merchStoreService.editCollection( - params.uuid, - editCollectionRequest.collection, - ); + const collection = await this.merchStoreService.editCollection(params.uuid, editCollectionRequest.collection); return { error: null, collection }; } @Delete('/collection/:uuid') async deleteMerchCollection( @Params() params: UuidParam, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canEditMerchStore(user)) throw new ForbiddenError(); await this.merchStoreService.deleteCollection(params.uuid); @@ -170,10 +156,10 @@ export class MerchStoreController { @UploadedFile('image', { options: StorageService.getFileOptions(MediaType.MERCH_PHOTO), }) - file: File, - @Params() params: UuidParam, - @Body() createCollectionRequest: CreateCollectionPhotoRequest, - @AuthenticatedUser() user: UserModel, + file: File, + @Params() params: UuidParam, + @Body() createCollectionRequest: CreateCollectionPhotoRequest, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canEditMerchStore(user)) throw new ForbiddenError(); @@ -187,10 +173,10 @@ export class MerchStoreController { uniqueFileName, params.uuid, ); - const collectionPhoto = await this.merchStoreService.createCollectionPhoto( - params.uuid, - { uploadedPhoto, position }, - ); + const collectionPhoto = await this.merchStoreService.createCollectionPhoto(params.uuid, { + uploadedPhoto, + position, + }); return { error: null, @@ -202,7 +188,7 @@ export class MerchStoreController { @Delete('/collection/picture/:uuid') async deleteMerchCollectionPhoto( @Params() params: UuidParam, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canEditMerchStore(user)) throw new ForbiddenError(); const photoToDelete = await this.merchStoreService.getCollectionPhotoForDeletion(params.uuid); @@ -214,7 +200,7 @@ export class MerchStoreController { @Get('/item/:uuid') async getOneMerchItem( @Params() params: UuidParam, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canAccessMerchStore(user)) throw new ForbiddenError(); const item = await this.merchStoreService.findItemByUuid(params.uuid, user); @@ -224,35 +210,30 @@ export class MerchStoreController { @Post('/item') async createMerchItem( @Body() createItemRequest: CreateMerchItemRequest, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canEditMerchStore(user)) throw new ForbiddenError(); // Default behavior is to have variants disabled if not specified createItemRequest.merchandise.hasVariantsEnabled ??= false; - const item = await this.merchStoreService.createItem( - createItemRequest.merchandise, - ); + const item = await this.merchStoreService.createItem(createItemRequest.merchandise); return { error: null, item }; } @Patch('/item/:uuid') async editMerchItem( @Params() params: UuidParam, - @Body() editItemRequest: EditMerchItemRequest, - @AuthenticatedUser() user: UserModel, + @Body() editItemRequest: EditMerchItemRequest, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canEditMerchStore(user)) throw new ForbiddenError(); - const item = await this.merchStoreService.editItem( - params.uuid, - editItemRequest.merchandise, - ); + const item = await this.merchStoreService.editItem(params.uuid, editItemRequest.merchandise); return { error: null, item }; } @Delete('/item/:uuid') async deleteMerchItem( @Params() params: UuidParam, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canEditMerchStore(user)) throw new ForbiddenError(); await this.merchStoreService.deleteItem(params.uuid); @@ -265,10 +246,10 @@ export class MerchStoreController { @UploadedFile('image', { options: StorageService.getFileOptions(MediaType.MERCH_PHOTO), }) - file: File, - @Params() params: UuidParam, - @Body() createItemPhotoRequest: CreateMerchItemPhotoRequest, - @AuthenticatedUser() user: UserModel, + file: File, + @Params() params: UuidParam, + @Body() createItemPhotoRequest: CreateMerchItemPhotoRequest, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canEditMerchStore(user)) throw new ForbiddenError(); @@ -282,10 +263,7 @@ export class MerchStoreController { uniqueFileName, params.uuid, ); - const merchPhoto = await this.merchStoreService.createItemPhoto( - params.uuid, - { uploadedPhoto, position }, - ); + const merchPhoto = await this.merchStoreService.createItemPhoto(params.uuid, { uploadedPhoto, position }); return { error: null, merchPhoto: merchPhoto.getPublicMerchItemPhoto() }; } @@ -294,12 +272,10 @@ export class MerchStoreController { @Delete('/item/picture/:uuid') async deleteMerchItemPhoto( @Params() params: UuidParam, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canEditMerchStore(user)) throw new ForbiddenError(); - const photoToDelete = await this.merchStoreService.getItemPhotoForDeletion( - params.uuid, - ); + const photoToDelete = await this.merchStoreService.getItemPhotoForDeletion(params.uuid); await this.storageService.deleteAtUrl(photoToDelete.uploadedPhoto); await this.merchStoreService.deleteItemPhoto(photoToDelete); return { error: null }; @@ -308,21 +284,18 @@ export class MerchStoreController { @Post('/option/:uuid') async createMerchItemOption( @Params() params: UuidParam, - @Body() createItemOptionRequest: CreateMerchItemOptionRequest, - @AuthenticatedUser() user: UserModel, + @Body() createItemOptionRequest: CreateMerchItemOptionRequest, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canEditMerchStore(user)) throw new ForbiddenError(); - const option = await this.merchStoreService.createItemOption( - params.uuid, - createItemOptionRequest.option, - ); + const option = await this.merchStoreService.createItemOption(params.uuid, createItemOptionRequest.option); return { error: null, option: option.getPublicMerchItemOption() }; } @Delete('/option/:uuid') async deleteMerchItemOption( @Params() params: UuidParam, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canEditMerchStore(user)) throw new ForbiddenError(); await this.merchStoreService.deleteItemOption(params.uuid); @@ -332,36 +305,26 @@ export class MerchStoreController { @Get('/order/:uuid') async getOneMerchOrder( @Params() params: UuidParam, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canAccessMerchStore(user)) throw new ForbiddenError(); // get "public" order bc canSeeMerchOrder need singular merchPhoto field // default order has merchPhotos field, which cause incorrect casting - const publicOrder = ( - await this.merchOrderService.findOrderByUuid(params.uuid) - ).getPublicOrderWithItems(); + const publicOrder = (await this.merchOrderService.findOrderByUuid(params.uuid)).getPublicOrderWithItems(); if (!PermissionsService.canSeeMerchOrder(user, publicOrder)) throw new NotFoundError(); return { error: null, order: publicOrder }; } @Get('/orders/all') - async getMerchOrdersForAllUsers( - @AuthenticatedUser() user: UserModel, - ): Promise { - if ( - !( - PermissionsService.canAccessMerchStore(user) - && PermissionsService.canSeeAllMerchOrders(user) - ) - ) throw new ForbiddenError(); + async getMerchOrdersForAllUsers(@AuthenticatedUser() user: UserModel): Promise { + if (!(PermissionsService.canAccessMerchStore(user) && PermissionsService.canSeeAllMerchOrders(user))) + throw new ForbiddenError(); const orders = await this.merchOrderService.getAllOrdersForAllUsers(); return { error: null, orders: orders.map((o) => o.getPublicOrder()) }; } @Get('/orders') - async getMerchOrdersForCurrentUser( - @AuthenticatedUser() user: UserModel, - ): Promise { + async getMerchOrdersForCurrentUser(@AuthenticatedUser() user: UserModel): Promise { if (!PermissionsService.canAccessMerchStore(user)) throw new ForbiddenError(); const orders = await this.merchOrderService.getAllOrdersForUser(user); return { error: null, orders: orders.map((o) => o.getPublicOrder()) }; @@ -370,35 +333,25 @@ export class MerchStoreController { @Post('/order') async placeMerchOrder( @Body() placeOrderRequest: PlaceMerchOrderRequest, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canAccessMerchStore(user)) throw new ForbiddenError(); - const originalOrder = this.validateMerchOrderRequest( - placeOrderRequest.order, - ); - const order = await this.merchOrderService.placeOrder( - originalOrder, - user, - placeOrderRequest.pickupEvent, - ); + const originalOrder = this.validateMerchOrderRequest(placeOrderRequest.order); + const order = await this.merchOrderService.placeOrder(originalOrder, user, placeOrderRequest.pickupEvent); return { error: null, order: order.getPublicOrderWithItems() }; } @Post('/order/verification') async verifyMerchOrder( @Body() verifyOrderRequest: VerifyMerchOrderRequest, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { - const originalOrder = this.validateMerchOrderRequest( - verifyOrderRequest.order, - ); + const originalOrder = this.validateMerchOrderRequest(verifyOrderRequest.order); await this.merchOrderService.validateOrder(originalOrder, user); return { error: null }; } - private validateMerchOrderRequest( - orderRequest: MerchItemOptionAndQuantity[], - ): MerchItemOptionAndQuantity[] { + private validateMerchOrderRequest(orderRequest: MerchItemOptionAndQuantity[]): MerchItemOptionAndQuantity[] { const originalOrder = orderRequest.filter((oi) => oi.quantity > 0); const orderIsEmpty = originalOrder.reduce((x, n) => x + n.quantity, 0) === 0; if (orderIsEmpty) throw new UserError('There are no items in this order'); @@ -410,92 +363,73 @@ export class MerchStoreController { @Post('/order/:uuid/reschedule') async rescheduleOrderPickup( @Params() params: UuidParam, - @Body() rescheduleOrderPickupRequest: RescheduleOrderPickupRequest, - @AuthenticatedUser() user: UserModel, + @Body() rescheduleOrderPickupRequest: RescheduleOrderPickupRequest, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canAccessMerchStore(user)) throw new ForbiddenError(); - await this.merchOrderService.rescheduleOrderPickup( - params.uuid, - rescheduleOrderPickupRequest.pickupEvent, - user, - ); + await this.merchOrderService.rescheduleOrderPickup(params.uuid, rescheduleOrderPickupRequest.pickupEvent, user); return { error: null }; } @Post('/order/:uuid/cancel') async cancelMerchOrder( @Params() params: UuidParam, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canAccessMerchStore(user)) throw new ForbiddenError(); - const order = await this.merchOrderService.cancelMerchOrder( - params.uuid, - user, - ); + const order = await this.merchOrderService.cancelMerchOrder(params.uuid, user); return { error: null, order: order.getPublicOrderWithItems() }; } @Post('/order/:uuid/fulfill') async fulfillMerchOrderItems( @Params() params: UuidParam, - @Body() fulfillOrderRequest: FulfillMerchOrderRequest, - @AuthenticatedUser() user: UserModel, + @Body() fulfillOrderRequest: FulfillMerchOrderRequest, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canManageMerchOrders(user)) throw new ForbiddenError(); - const numUniqueUuids = new Set( - fulfillOrderRequest.items.map((oi) => oi.uuid), - ).size; + const numUniqueUuids = new Set(fulfillOrderRequest.items.map((oi) => oi.uuid)).size; if (fulfillOrderRequest.items.length !== numUniqueUuids) { throw new BadRequestError('There are duplicate order items'); } - const updatedOrder = await this.merchOrderService.fulfillOrderItems( - fulfillOrderRequest.items, - params.uuid, - user, - ); + const updatedOrder = await this.merchOrderService.fulfillOrderItems(fulfillOrderRequest.items, params.uuid, user); return { error: null, order: updatedOrder.getPublicOrder() }; } @Post('/order/cleanup') - async cancelAllPendingMerchOrders( - @AuthenticatedUser() user: UserModel, - ): Promise { + async cancelAllPendingMerchOrders(@AuthenticatedUser() user: UserModel): Promise { if (!PermissionsService.canCancelAllPendingOrders(user)) throw new ForbiddenError(); await this.merchOrderService.cancelAllPendingOrders(user); return { error: null }; } @Get('/order/pickup/past') - async getPastPickupEvents( - @AuthenticatedUser() user: UserModel, - ): Promise { + async getPastPickupEvents(@AuthenticatedUser() user: UserModel): Promise { const pickupEvents = await this.merchOrderService.getPastPickupEvents(); const canSeePickupEventOrders = PermissionsService.canSeePickupEventOrders(user); - const publicPickupEvents = pickupEvents.map((pickupEvent) => pickupEvent - .getPublicOrderPickupEvent(canSeePickupEventOrders)); + const publicPickupEvents = pickupEvents.map((pickupEvent) => + pickupEvent.getPublicOrderPickupEvent(canSeePickupEventOrders), + ); return { error: null, pickupEvents: publicPickupEvents }; } @Get('/order/pickup/future') - async getFuturePickupEvents( - @AuthenticatedUser() user: UserModel, - ): Promise { + async getFuturePickupEvents(@AuthenticatedUser() user: UserModel): Promise { const pickupEvents = await this.merchOrderService.getFuturePickupEvents(); const canSeePickupEventOrders = PermissionsService.canSeePickupEventOrders(user); - const publicPickupEvents = pickupEvents.map((pickupEvent) => pickupEvent - .getPublicOrderPickupEvent(canSeePickupEventOrders)); + const publicPickupEvents = pickupEvents.map((pickupEvent) => + pickupEvent.getPublicOrderPickupEvent(canSeePickupEventOrders), + ); return { error: null, pickupEvents: publicPickupEvents }; } @Get('/order/pickup/:uuid') async getOnePickupEvent( @Params() params: UuidParam, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canManagePickupEvents(user)) throw new ForbiddenError(); - const pickupEvent = await this.merchOrderService.getPickupEvent( - params.uuid, - ); + const pickupEvent = await this.merchOrderService.getPickupEvent(params.uuid); return { error: null, pickupEvent: pickupEvent.getPublicOrderPickupEvent(true), @@ -505,12 +439,10 @@ export class MerchStoreController { @Post('/order/pickup') async createPickupEvent( @Body() createOrderPickupEventRequest: CreateOrderPickupEventRequest, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canManagePickupEvents(user)) throw new ForbiddenError(); - const pickupEvent = await this.merchOrderService.createPickupEvent( - createOrderPickupEventRequest.pickupEvent, - ); + const pickupEvent = await this.merchOrderService.createPickupEvent(createOrderPickupEventRequest.pickupEvent); return { error: null, pickupEvent: pickupEvent.getPublicOrderPickupEvent(), @@ -520,8 +452,8 @@ export class MerchStoreController { @Patch('/order/pickup/:uuid') async editPickupEvent( @Params() params: UuidParam, - @Body() editOrderPickupEventRequest: EditOrderPickupEventRequest, - @AuthenticatedUser() user: UserModel, + @Body() editOrderPickupEventRequest: EditOrderPickupEventRequest, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canManagePickupEvents(user)) throw new ForbiddenError(); const pickupEvent = await this.merchOrderService.editPickupEvent( @@ -537,7 +469,7 @@ export class MerchStoreController { @Delete('/order/pickup/:uuid') async deletePickupEvent( @Params() params: UuidParam, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canManagePickupEvents(user)) throw new ForbiddenError(); await this.merchOrderService.deletePickupEvent(params.uuid); @@ -547,7 +479,7 @@ export class MerchStoreController { @Post('/order/pickup/:uuid/cancel') async cancelPickupEvent( @Params() params: UuidParam, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canManagePickupEvents(user)) throw new ForbiddenError(); await this.merchOrderService.cancelPickupEvent(params.uuid); @@ -557,7 +489,7 @@ export class MerchStoreController { @Post('/order/pickup/:uuid/complete') async completePickupEvent( @Params() params: UuidParam, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canManagePickupEvents(user)) throw new ForbiddenError(); const ordersMarkedAsMissed = await this.merchOrderService.completePickupEvent(params.uuid); @@ -570,12 +502,10 @@ export class MerchStoreController { @Get('/cart') async getCartItems( @Body() getCartRequest: GetCartRequest, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { if (!PermissionsService.canAccessMerchStore(user)) throw new ForbiddenError(); - const cartItems = await this.merchStoreService.getCartItems( - getCartRequest.items, - ); + const cartItems = await this.merchStoreService.getCartItems(getCartRequest.items); return { error: null, cart: cartItems.map((option) => option.getPublicOrderMerchItemOption()), diff --git a/api/controllers/UserController.ts b/api/controllers/UserController.ts index 97eda42d..cf000019 100644 --- a/api/controllers/UserController.ts +++ b/api/controllers/UserController.ts @@ -1,14 +1,4 @@ -import { - JsonController, - Params, - Get, - Post, - Patch, - UseBefore, - UploadedFile, - Body, - Delete, -} from 'routing-controllers'; +import { JsonController, Params, Get, Post, Patch, UseBefore, UploadedFile, Body, Delete } from 'routing-controllers'; import { UserModel } from '../../models/UserModel'; import UserAccountService from '../../services/UserAccountService'; import UserSocialMediaService from '../../services/UserSocialMediaService'; @@ -29,10 +19,7 @@ import { } from '../../types'; import { UserHandleParam, UuidParam } from '../validators/GenericRequests'; import { PatchUserRequest } from '../validators/UserControllerRequests'; -import { - InsertSocialMediaRequest, - UpdateSocialMediaRequest, -} from '../validators/UserSocialMediaControllerRequests'; +import { InsertSocialMediaRequest, UpdateSocialMediaRequest } from '../validators/UserSocialMediaControllerRequests'; @UseBefore(UserAuthentication) @JsonController('/user') @@ -56,14 +43,12 @@ export class UserController { @Get('/:uuid/activity/') async getUserActivityStream( @Params() params: UuidParam, - @AuthenticatedUser() currentUser: UserModel, + @AuthenticatedUser() currentUser: UserModel, ): Promise { if (params.uuid === currentUser.uuid) { return this.getCurrentUserActivityStream(currentUser); } - const activityStream = await this.userAccountService.getUserActivityStream( - params.uuid, - ); + const activityStream = await this.userAccountService.getUserActivityStream(params.uuid); return { error: null, activity: activityStream.map((activity) => activity.getPublicActivity()), @@ -71,9 +56,7 @@ export class UserController { } @Get('/activity') - async getCurrentUserActivityStream( - @AuthenticatedUser() user: UserModel, - ): Promise { + async getCurrentUserActivityStream(@AuthenticatedUser() user: UserModel): Promise { const activityStream = await this.userAccountService.getCurrentUserActivityStream(user.uuid); return { error: null, @@ -86,26 +69,16 @@ export class UserController { @UploadedFile('image', { options: StorageService.getFileOptions(MediaType.PROFILE_PICTURE), }) - file: File, - @AuthenticatedUser() user: UserModel, + file: File, + @AuthenticatedUser() user: UserModel, ): Promise { - const profilePicture = await this.storageService.upload( - file, - MediaType.PROFILE_PICTURE, - user.uuid, - ); - const updatedUser = await this.userAccountService.updateProfilePicture( - user, - profilePicture, - ); + const profilePicture = await this.storageService.upload(file, MediaType.PROFILE_PICTURE, user.uuid); + const updatedUser = await this.userAccountService.updateProfilePicture(user, profilePicture); return { error: null, user: updatedUser.getFullUserProfile() }; } @Get('/:uuid') - async getUser( - @Params() params: UuidParam, - @AuthenticatedUser() currentUser: UserModel, - ): Promise { + async getUser(@Params() params: UuidParam, @AuthenticatedUser() currentUser: UserModel): Promise { if (params.uuid === currentUser.uuid) { return this.getCurrentUser(currentUser); } @@ -117,7 +90,7 @@ export class UserController { @Get('/handle/:handle') async getUserByHandle( @Params() params: UserHandleParam, - @AuthenticatedUser() currentUser: UserModel, + @AuthenticatedUser() currentUser: UserModel, ): Promise { if (params.handle === currentUser.handle) { return this.getCurrentUser(currentUser); @@ -128,9 +101,7 @@ export class UserController { } @Get() - async getCurrentUser( - @AuthenticatedUser() user: UserModel, - ): Promise { + async getCurrentUser(@AuthenticatedUser() user: UserModel): Promise { const userProfile = await this.userAccountService.getFullUserProfile(user); return { error: null, user: userProfile }; } @@ -138,19 +109,16 @@ export class UserController { @Patch() async patchCurrentUser( @Body() patchUserRequest: PatchUserRequest, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { - const patchedUser = await this.userAccountService.update( - user, - patchUserRequest.user, - ); + const patchedUser = await this.userAccountService.update(user, patchUserRequest.user); return { error: null, user: patchedUser.getFullUserProfile() }; } @Post('/socialMedia') async insertSocialMediaForUser( @Body() insertSocialMediaRequest: InsertSocialMediaRequest, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { const userSocialMedia = await this.userSocialMediaService.insertSocialMediaForUser( user, @@ -165,7 +133,7 @@ export class UserController { @Patch('/socialMedia') async updateSocialMediaForUser( @Body() updateSocialMediaRequest: UpdateSocialMediaRequest, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { const userSocialMedia = await this.userSocialMediaService.updateSocialMediaByUuid( user, @@ -180,12 +148,9 @@ export class UserController { @Delete('/socialMedia/:uuid') async deleteSocialMediaForUser( @Params() params: UuidParam, - @AuthenticatedUser() user: UserModel, + @AuthenticatedUser() user: UserModel, ): Promise { - await this.userSocialMediaService.deleteSocialMediaByUuid( - user, - params.uuid, - ); + await this.userSocialMediaService.deleteSocialMediaByUuid(user, params.uuid); return { error: null }; } } diff --git a/services/AttendanceService.ts b/services/AttendanceService.ts index 1bedc9e4..91464c03 100644 --- a/services/AttendanceService.ts +++ b/services/AttendanceService.ts @@ -1,10 +1,6 @@ import { Service } from 'typedi'; import { InjectManager } from 'typeorm-typedi-extensions'; -import { - BadRequestError, - ForbiddenError, - NotFoundError, -} from 'routing-controllers'; +import { BadRequestError, ForbiddenError, NotFoundError } from 'routing-controllers'; import { EntityManager } from 'typeorm'; import * as moment from 'moment'; import { ActivityType, PublicExpressCheckin, Uuid } from '../types'; @@ -25,18 +21,16 @@ export default class AttendanceService { } public async getAttendancesForEvent(event: Uuid): Promise { - const attendances = await this.transactions.readOnly(async (txn) => Repositories - .attendance(txn) - .getAttendancesForEvent(event)); + const attendances = await this.transactions.readOnly(async (txn) => + Repositories.attendance(txn).getAttendancesForEvent(event), + ); return attendances; } - public async getAttendancesForCurrentUser( - user: UserModel, - ): Promise { - const attendances = await this.transactions.readOnly(async (txn) => Repositories - .attendance(txn) - .getAttendancesForUser(user)); + public async getAttendancesForCurrentUser(user: UserModel): Promise { + const attendances = await this.transactions.readOnly(async (txn) => + Repositories.attendance(txn).getAttendancesForUser(user), + ); return attendances; } @@ -45,36 +39,21 @@ export default class AttendanceService { const user = await Repositories.user(txn).findByUuid(uuid); if (!user) throw new NotFoundError('User does not exist'); if (!user.isAttendancePublic) throw new ForbiddenError(); - const attendances = await Repositories.attendance( - txn, - ).getAttendancesForUser(user); + const attendances = await Repositories.attendance(txn).getAttendancesForUser(user); return attendances; }); } - public async attendEvent( - user: UserModel, - attendanceCode: string, - asStaff = false, - ): Promise { + public async attendEvent(user: UserModel, attendanceCode: string, asStaff = false): Promise { return this.transactions.readWrite(async (txn) => { - const event = await Repositories.event(txn).findByAttendanceCode( - attendanceCode, - ); + const event = await Repositories.event(txn).findByAttendanceCode(attendanceCode); this.validateEventToAttend(event); - const hasAlreadyAttended = await Repositories.attendance( - txn, - ).hasUserAttendedEvent(user, event); + const hasAlreadyAttended = await Repositories.attendance(txn).hasUserAttendedEvent(user, event); if (hasAlreadyAttended) throw new UserError('You have already attended this event'); - const attendance = await this.writeEventAttendance( - user, - event, - asStaff, - txn, - ); + const attendance = await this.writeEventAttendance(user, event, asStaff, txn); return attendance; }); } @@ -82,14 +61,10 @@ export default class AttendanceService { private validateEventToAttend(event: EventModel) { if (!event) throw new NotFoundError("Oh no! That code didn't work."); if (event.isTooEarlyToAttendEvent()) { - throw new UserError( - "This event hasn't started yet, please wait to check in.", - ); + throw new UserError("This event hasn't started yet, please wait to check in."); } if (event.isTooLateToAttendEvent()) { - throw new UserError( - 'This event has ended and is no longer accepting attendances', - ); + throw new UserError('This event has ended and is no longer accepting attendances'); } } @@ -100,16 +75,12 @@ export default class AttendanceService { txn: EntityManager, ): Promise { const attendedAsStaff = asStaff && user.isStaff() && event.requiresStaff; - const pointsEarned = attendedAsStaff - ? event.pointValue + event.staffPointBonus - : event.pointValue; + const pointsEarned = attendedAsStaff ? event.pointValue + event.staffPointBonus : event.pointValue; await Repositories.activity(txn).logActivity({ user, pointsEarned, - type: attendedAsStaff - ? ActivityType.ATTEND_EVENT_AS_STAFF - : ActivityType.ATTEND_EVENT, + type: attendedAsStaff ? ActivityType.ATTEND_EVENT_AS_STAFF : ActivityType.ATTEND_EVENT, }); await Repositories.user(txn).addPoints(user, pointsEarned); return Repositories.attendance(txn).writeAttendance({ @@ -119,14 +90,9 @@ export default class AttendanceService { }); } - public async attendViaExpressCheckin( - attendanceCode: string, - email: string, - ): Promise { + public async attendViaExpressCheckin(attendanceCode: string, email: string): Promise { return this.transactions.readWrite(async (txn) => { - const event = await Repositories.event(txn).findByAttendanceCode( - attendanceCode, - ); + const event = await Repositories.event(txn).findByAttendanceCode(attendanceCode); this.validateEventToAttend(event); @@ -135,21 +101,19 @@ export default class AttendanceService { const isEmailInUse = await Repositories.user(txn).isEmailInUse(email); if (isEmailInUse) { throw new UserError( - 'This email already has an account registered to it. ' - + 'Please login to your account to check-in to this event!', + 'This email already has an account registered to it. ' + + 'Please login to your account to check-in to this event!', ); } const pastExpressCheckin = await expressCheckinRepository.getPastExpressCheckin(email); if (pastExpressCheckin) { if (pastExpressCheckin.event.uuid === event.uuid) { - throw new UserError( - 'You have already successfully checked into this event!', - ); + throw new UserError('You have already successfully checked into this event!'); } else { throw new UserError( - 'You have already done an express check-in before for a previous event. ' - + 'Please complete your account registration to attend this event!', + 'You have already done an express check-in before for a previous event. ' + + 'Please complete your account registration to attend this event!', ); } } @@ -171,34 +135,18 @@ export default class AttendanceService { const users = await Repositories.user(txn).findByEmails(emails); const emailsFound = users.map((user) => user.email); - const emailsNotFound = emails.filter( - (email) => !emailsFound.includes(email), - ); + const emailsNotFound = emails.filter((email) => !emailsFound.includes(email)); if (emailsNotFound.length > 0) { - throw new BadRequestError( - `Couldn't find accounts matching these emails: ${emailsNotFound}`, - ); + throw new BadRequestError(`Couldn't find accounts matching these emails: ${emailsNotFound}`); } - const userAttendancesOfEvent = await this.haveUsersAttendedEvent( - users, - event, - txn, - ); - const usersThatHaventAttended = Array.from( - userAttendancesOfEvent.entries(), - ) + const userAttendancesOfEvent = await this.haveUsersAttendedEvent(users, event, txn); + const usersThatHaventAttended = Array.from(userAttendancesOfEvent.entries()) .filter(([_user, hasAttended]) => !hasAttended) .map(([user, _hasAttended]) => user); - return this.batchWriteEventAttendance( - usersThatHaventAttended, - event, - asStaff, - proxyUser, - txn, - ); + return this.batchWriteEventAttendance(usersThatHaventAttended, event, asStaff, proxyUser, txn); }); } @@ -207,15 +155,9 @@ export default class AttendanceService { event: EventModel, txn: EntityManager, ): Promise> { - const attendances = await Repositories.attendance( - txn, - ).getAttendancesForEvent(event.uuid); - const usersThatAttended = attendances.map( - (attendance) => attendance.user.uuid, - ); - return new Map( - users.map((user) => [user, usersThatAttended.includes(user.uuid)]), - ); + const attendances = await Repositories.attendance(txn).getAttendancesForEvent(event.uuid); + const usersThatAttended = attendances.map((attendance) => attendance.user.uuid); + return new Map(users.map((user) => [user, usersThatAttended.includes(user.uuid)])); } private async batchWriteEventAttendance( @@ -239,12 +181,8 @@ export default class AttendanceService { }; const activity = { user, - type: attendedAsStaff - ? ActivityType.ATTEND_EVENT_AS_STAFF - : ActivityType.ATTEND_EVENT, - pointsEarned: attendedAsStaff - ? event.pointValue + event.staffPointBonus - : event.pointValue, + type: attendedAsStaff ? ActivityType.ATTEND_EVENT_AS_STAFF : ActivityType.ATTEND_EVENT, + pointsEarned: attendedAsStaff ? event.pointValue + event.staffPointBonus : event.pointValue, description, }; @@ -257,37 +195,24 @@ export default class AttendanceService { return Repositories.attendance(txn).writeAttendanceBatch(attendances); } - public async submitEventFeedback( - feedback: string[], - eventUuid: Uuid, - user: UserModel, - ): Promise { + public async submitEventFeedback(feedback: string[], eventUuid: Uuid, user: UserModel): Promise { return this.transactions.readWrite(async (txn) => { const attendanceRepository = Repositories.attendance(txn); const event = await Repositories.event(txn).findByUuid(eventUuid); if (!event) throw new NotFoundError('Event not found'); - const attendance = await attendanceRepository.getUserAttendanceForEvent( - user, - event, - ); + const attendance = await attendanceRepository.getUserAttendanceForEvent(user, event); if (!attendance) { - throw new UserError( - 'You must attend this event before submiting feedback', - ); + throw new UserError('You must attend this event before submiting feedback'); } if (attendance.feedback) { - throw new UserError( - 'You cannot submit feedback for this event more than once', - ); + throw new UserError('You cannot submit feedback for this event more than once'); } const twoDaysPastEventEnd = moment(event.end).add(2, 'days').valueOf(); if (moment.now() > twoDaysPastEventEnd) { - throw new UserError( - 'You must submit feedback within 2 days of the event ending', - ); + throw new UserError('You must submit feedback within 2 days of the event ending'); } const attendanceWithFeedback = await attendanceRepository.submitEventFeedback(attendance, feedback); diff --git a/services/EventService.ts b/services/EventService.ts index 4091905c..7e6fe6f6 100644 --- a/services/EventService.ts +++ b/services/EventService.ts @@ -32,24 +32,18 @@ export default class EventService { return eventCreated; } - public async getAllEvents( - options: EventSearchOptions, - ): Promise { + public async getAllEvents(options: EventSearchOptions): Promise { const events = await this.transactions.readOnly(async (txn) => Repositories.event(txn).getAllEvents(options)); return events; } - public async getPastEvents( - options: EventSearchOptions, - ): Promise { + public async getPastEvents(options: EventSearchOptions): Promise { options.reverse ??= true; const events = await this.transactions.readOnly(async (txn) => Repositories.event(txn).getPastEvents(options)); return events; } - public async getFutureEvents( - options: EventSearchOptions, - ): Promise { + public async getFutureEvents(options: EventSearchOptions): Promise { const events = await this.transactions.readOnly(async (txn) => Repositories.event(txn).getFutureEvents(options)); return events; } @@ -60,10 +54,7 @@ export default class EventService { return event; } - public async updateByUuid( - uuid: Uuid, - changes: Partial, - ): Promise { + public async updateByUuid(uuid: Uuid, changes: Partial): Promise { const updatedEvent = await this.transactions.readWrite(async (txn) => { const eventRepository = Repositories.event(txn); const currentEvent = await eventRepository.findByUuid(uuid); @@ -82,9 +73,7 @@ export default class EventService { const eventRepository = Repositories.event(txn); const event = await eventRepository.findByUuid(uuid); if (!event) throw new NotFoundError('Event not found'); - const attendances = await Repositories.attendance( - txn, - ).getAttendancesForEvent(uuid); + const attendances = await Repositories.attendance(txn).getAttendancesForEvent(uuid); if (attendances.length > 0) throw new ForbiddenError('Cannot delete event that has attendances'); await eventRepository.deleteEvent(event); }); diff --git a/services/FeedbackService.ts b/services/FeedbackService.ts index 3d766b53..0092d787 100644 --- a/services/FeedbackService.ts +++ b/services/FeedbackService.ts @@ -5,13 +5,7 @@ import { NotFoundError } from 'routing-controllers'; import { FeedbackModel } from '../models/FeedbackModel'; import { UserModel } from '../models/UserModel'; import Repositories, { TransactionsManager } from '../repositories'; -import { - Feedback, - Uuid, - ActivityType, - FeedbackStatus, - FeedbackSearchOptions, -} from '../types'; +import { Feedback, Uuid, ActivityType, FeedbackStatus, FeedbackSearchOptions } from '../types'; import { UserError } from '../utils/Errors'; @Service() @@ -33,18 +27,12 @@ export default class FeedbackService { return feedbackRepository.getAllFeedback(options); } - const userFeedback = await feedbackRepository.getStandardUserFeedback( - user, - options, - ); + const userFeedback = await feedbackRepository.getStandardUserFeedback(user, options); return userFeedback; }); } - public async submitFeedback( - user: UserModel, - feedback: Feedback, - ): Promise { + public async submitFeedback(user: UserModel, feedback: Feedback): Promise { return this.transactions.readWrite(async (txn) => { const event = await Repositories.event(txn).findByUuid(feedback.event); if (!event) throw new NotFoundError('Event not found!'); @@ -53,18 +41,14 @@ export default class FeedbackService { const hasAlreadySubmittedFeedback = await feedbackRepository.hasUserSubmittedFeedback(user, event); if (hasAlreadySubmittedFeedback) { - throw new UserError( - 'You have already submitted feedback for this event!', - ); + throw new UserError('You have already submitted feedback for this event!'); } await Repositories.activity(txn).logActivity({ user, type: ActivityType.SUBMIT_FEEDBACK, }); - const addedFeedback = await feedbackRepository.upsertFeedback( - FeedbackModel.create({ ...feedback, user, event }), - ); + const addedFeedback = await feedbackRepository.upsertFeedback(FeedbackModel.create({ ...feedback, user, event })); return addedFeedback; }); } @@ -83,10 +67,7 @@ export default class FeedbackService { user, type: ActivityType.FEEDBACK_ACKNOWLEDGED, }); - const updatedFeedback = await feedbackRepository.upsertFeedback( - feedback, - { status }, - ); + const updatedFeedback = await feedbackRepository.upsertFeedback(feedback, { status }); return updatedFeedback; }); } diff --git a/services/MerchStoreService.ts b/services/MerchStoreService.ts index 49af57ca..73cd6810 100644 --- a/services/MerchStoreService.ts +++ b/services/MerchStoreService.ts @@ -37,10 +37,7 @@ export default class MerchStoreService { this.transactions = new TransactionsManager(entityManager); } - public async findItemByUuid( - uuid: Uuid, - user: UserModel, - ): Promise { + public async findItemByUuid(uuid: Uuid, user: UserModel): Promise { return this.transactions.readOnly(async (txn) => { const item = await Repositories.merchStoreItem(txn).findByUuid(uuid); @@ -50,12 +47,8 @@ export default class MerchStoreService { const merchOrderItemRepository = Repositories.merchOrderItem(txn); const lifetimePurchaseHistory = await merchOrderItemRepository.getPastItemOrdersByUser(user, item); const oneMonthAgo = new Date(moment().subtract(1, 'month').unix()); - const pastMonthPurchaseHistory = lifetimePurchaseHistory.filter( - (oi) => oi.order.orderedAt > oneMonthAgo, - ); - const lifetimeCancelledItems = lifetimePurchaseHistory.filter( - (oi) => oi.order.status === OrderStatus.CANCELLED, - ); + const pastMonthPurchaseHistory = lifetimePurchaseHistory.filter((oi) => oi.order.orderedAt > oneMonthAgo); + const lifetimeCancelledItems = lifetimePurchaseHistory.filter((oi) => oi.order.status === OrderStatus.CANCELLED); const pastMonthCancelledItems = pastMonthPurchaseHistory.filter( (oi) => oi.order.status === OrderStatus.CANCELLED, ); @@ -77,20 +70,16 @@ export default class MerchStoreService { uuid: Uuid, canSeeInactiveCollections = false, ): Promise { - const collection = await this.transactions.readOnly(async (txn) => Repositories - .merchStoreCollection(txn) - .findByUuid(uuid)); + const collection = await this.transactions.readOnly(async (txn) => + Repositories.merchStoreCollection(txn).findByUuid(uuid), + ); if (!collection) throw new NotFoundError('Merch collection not found'); if (collection.archived && !canSeeInactiveCollections) throw new ForbiddenError(); - collection.collectionPhotos = collection.collectionPhotos.sort( - (a, b) => a.position - b.position, - ); + collection.collectionPhotos = collection.collectionPhotos.sort((a, b) => a.position - b.position); return collection; } - public async getAllCollections( - canSeeInactiveCollections = false, - ): Promise { + public async getAllCollections(canSeeInactiveCollections = false): Promise { return this.transactions.readOnly(async (txn) => { const merchCollectionRepository = Repositories.merchStoreCollection(txn); if (canSeeInactiveCollections) { @@ -101,37 +90,25 @@ export default class MerchStoreService { }); } - public async createCollection( - collection: MerchCollection, - ): Promise { - return this.transactions.readWrite(async (txn) => Repositories.merchStoreCollection(txn).upsertMerchCollection( - MerchandiseCollectionModel.create(collection), - )); + public async createCollection(collection: MerchCollection): Promise { + return this.transactions.readWrite(async (txn) => + Repositories.merchStoreCollection(txn).upsertMerchCollection(MerchandiseCollectionModel.create(collection)), + ); } - public async editCollection( - uuid: Uuid, - collectionEdit: MerchCollectionEdit, - ): Promise { + public async editCollection(uuid: Uuid, collectionEdit: MerchCollectionEdit): Promise { return this.transactions.readWrite(async (txn) => { const merchCollectionRepository = Repositories.merchStoreCollection(txn); - const currentCollection = await merchCollectionRepository.findByUuid( - uuid, - ); + const currentCollection = await merchCollectionRepository.findByUuid(uuid); if (!currentCollection) throw new NotFoundError('Merch collection not found'); const { discountPercentage, collectionPhotos, ...changes } = collectionEdit; if (discountPercentage !== undefined) { - await Repositories.merchStoreItemOption( - txn, - ).updateMerchItemOptionsInCollection(uuid, discountPercentage); + await Repositories.merchStoreItemOption(txn).updateMerchItemOptionsInCollection(uuid, discountPercentage); } if (changes.archived !== undefined) { - await Repositories.merchStoreItem(txn).updateMerchItemsInCollection( - uuid, - { hidden: changes.archived }, - ); + await Repositories.merchStoreItem(txn).updateMerchItemsInCollection(uuid, { hidden: changes.archived }); } // this part only handles updating the positions of the pictures @@ -140,16 +117,12 @@ export default class MerchStoreService { const dupSet = new Set(); collectionPhotos.forEach((merchPhoto) => { if (dupSet.has(merchPhoto.uuid)) { - throw new UserError( - `Multiple edits is made to photo: ${merchPhoto.uuid}`, - ); + throw new UserError(`Multiple edits is made to photo: ${merchPhoto.uuid}`); } dupSet.add(merchPhoto.uuid); }); - const photoUpdatesByUuid = new Map( - collectionPhotos.map((merchPhoto) => [merchPhoto.uuid, merchPhoto]), - ); + const photoUpdatesByUuid = new Map(collectionPhotos.map((merchPhoto) => [merchPhoto.uuid, merchPhoto])); currentCollection.collectionPhotos.map((currentPhoto) => { if (!photoUpdatesByUuid.has(currentPhoto.uuid)) return; @@ -158,10 +131,7 @@ export default class MerchStoreService { }); } - let updatedCollection = await merchCollectionRepository.upsertMerchCollection( - currentCollection, - changes, - ); + let updatedCollection = await merchCollectionRepository.upsertMerchCollection(currentCollection, changes); if (discountPercentage !== undefined || changes.archived !== undefined) { updatedCollection = await merchCollectionRepository.findByUuid(uuid); @@ -176,13 +146,9 @@ export default class MerchStoreService { const merchCollectionRepository = Repositories.merchStoreCollection(txn); const collection = await merchCollectionRepository.findByUuid(uuid); if (!collection) throw new NotFoundError('Merch collection not found'); - const hasBeenOrderedFrom = await Repositories.merchOrderItem( - txn, - ).hasCollectionBeenOrderedFrom(uuid); + const hasBeenOrderedFrom = await Repositories.merchOrderItem(txn).hasCollectionBeenOrderedFrom(uuid); if (hasBeenOrderedFrom) { - throw new UserError( - 'This collection has been ordered from and cannot be deleted', - ); + throw new UserError('This collection has been ordered from and cannot be deleted'); } return merchCollectionRepository.deleteMerchCollection(collection); }); @@ -191,9 +157,7 @@ export default class MerchStoreService { /** * Verify that collections have valid photots. */ - private static verifyCollectionHasValidPhotos( - collection: MerchCollection | MerchandiseCollectionModel, - ) { + private static verifyCollectionHasValidPhotos(collection: MerchCollection | MerchandiseCollectionModel) { if (collection.collectionPhotos.length > this.MAX_COLLECTION_PHOTO_COUNT) { throw new UserError('Collections cannot have more than 5 pictures'); } @@ -211,9 +175,7 @@ export default class MerchStoreService { properties: MerchCollectionPhoto, ): Promise { return this.transactions.readWrite(async (txn) => { - const merchCollection = await Repositories.merchStoreCollection( - txn, - ).findByUuid(collection); + const merchCollection = await Repositories.merchStoreCollection(txn).findByUuid(collection); if (!merchCollection) throw new NotFoundError('Collection not found'); const createdPhoto = MerchCollectionPhotoModel.create({ @@ -226,9 +188,7 @@ export default class MerchStoreService { merchCollection.collectionPhotos.push(createdPhoto); MerchStoreService.verifyCollectionHasValidPhotos(merchCollection); - const upsertedPhoto = await merchStoreCollectionPhotoRepository.upsertCollectionPhoto( - createdPhoto, - ); + const upsertedPhoto = await merchStoreCollectionPhotoRepository.upsertCollectionPhoto(createdPhoto); return upsertedPhoto; }); } @@ -240,19 +200,13 @@ export default class MerchStoreService { * @param uuid the uuid of photo to be deleted * @returns the photo object to be removed from database */ - public async getCollectionPhotoForDeletion( - uuid: Uuid, - ): Promise { + public async getCollectionPhotoForDeletion(uuid: Uuid): Promise { return this.transactions.readWrite(async (txn) => { const merchCollectionPhotoRepository = Repositories.merchStoreCollectionPhoto(txn); - const collectionPhoto = await merchCollectionPhotoRepository.findByUuid( - uuid, - ); + const collectionPhoto = await merchCollectionPhotoRepository.findByUuid(uuid); if (!collectionPhoto) throw new NotFoundError('Merch collection photo not found'); - const collection = await Repositories.merchStoreCollection( - txn, - ).findByUuid(collectionPhoto.merchCollection.uuid); + const collection = await Repositories.merchStoreCollection(txn).findByUuid(collectionPhoto.merchCollection.uuid); if (collection.collectionPhotos.length === 1) { throw new UserError('Cannot delete the only photo for a collection'); } @@ -267,14 +221,10 @@ export default class MerchStoreService { * @param merchPhoto the photo object to be removed * @returns the photo object removed from database */ - public async deleteCollectionPhoto( - collectionPhoto: MerchCollectionPhotoModel, - ): Promise { + public async deleteCollectionPhoto(collectionPhoto: MerchCollectionPhotoModel): Promise { return this.transactions.readWrite(async (txn) => { const merchStoreItemPhotoRepository = Repositories.merchStoreCollectionPhoto(txn); - await merchStoreItemPhotoRepository.deleteCollectionPhoto( - collectionPhoto, - ); + await merchStoreItemPhotoRepository.deleteCollectionPhoto(collectionPhoto); return collectionPhoto; }); } @@ -283,9 +233,7 @@ export default class MerchStoreService { return this.transactions.readWrite(async (txn) => { MerchStoreService.verifyItemHasValidOptions(item); - const collection = await Repositories.merchStoreCollection( - txn, - ).findByUuid(item.collection); + const collection = await Repositories.merchStoreCollection(txn).findByUuid(item.collection); if (!collection) throw new NotFoundError('Merch collection not found'); const merchItemRepository = Repositories.merchStoreItem(txn); @@ -299,33 +247,19 @@ export default class MerchStoreService { * Verify that items have valid options. An item with variants disabled cannot have multiple * options, and an item with variants enabled cannot have multiple option types. */ - private static verifyItemHasValidOptions( - item: MerchItem | MerchandiseItemModel, - ) { + private static verifyItemHasValidOptions(item: MerchItem | MerchandiseItemModel) { if (!item.hasVariantsEnabled && item.options.length > 1) { - throw new UserError( - 'Merch items with variants disabled cannot have multiple options', - ); + throw new UserError('Merch items with variants disabled cannot have multiple options'); } - if ( - item.hasVariantsEnabled - && !MerchStoreService.allOptionsHaveValidMetadata(item.options) - ) { - throw new UserError( - 'Merch options for items with variants enabled must have valid metadata', - ); + if (item.hasVariantsEnabled && !MerchStoreService.allOptionsHaveValidMetadata(item.options)) { + throw new UserError('Merch options for items with variants enabled must have valid metadata'); } - if ( - item.hasVariantsEnabled - && MerchStoreService.hasMultipleOptionTypes(item.options) - ) { + if (item.hasVariantsEnabled && MerchStoreService.hasMultipleOptionTypes(item.options)) { throw new UserError('Merch items cannot have multiple option types'); } } - private static allOptionsHaveValidMetadata( - options: MerchItemOption[], - ): boolean { + private static allOptionsHaveValidMetadata(options: MerchItemOption[]): boolean { return options.every((o) => !!o.metadata); } @@ -340,30 +274,18 @@ export default class MerchStoreService { * If the visibility of the item is set to visible, then the item cannot have 0 options. * @returns edited item */ - public async editItem( - uuid: Uuid, - itemEdit: MerchItemEdit, - ): Promise { + public async editItem(uuid: Uuid, itemEdit: MerchItemEdit): Promise { return this.transactions.readWrite(async (txn) => { const merchItemRepository = Repositories.merchStoreItem(txn); const item = await merchItemRepository.findByUuid(uuid); if (!item) throw new NotFoundError(); if (itemEdit.hidden === false && item.options.length === 0) { - throw new UserError( - 'Item cannot be set to visible if it has 0 options.', - ); + throw new UserError('Item cannot be set to visible if it has 0 options.'); } - const { - options, - merchPhotos, - collection: updatedCollection, - ...changes - } = itemEdit; + const { options, merchPhotos, collection: updatedCollection, ...changes } = itemEdit; if (options) { - const optionUpdatesByUuid = new Map( - options.map((option) => [option.uuid, option]), - ); + const optionUpdatesByUuid = new Map(options.map((option) => [option.uuid, option])); item.options.map((currentOption) => { if (!optionUpdatesByUuid.has(currentOption.uuid)) return; const optionUpdate = optionUpdatesByUuid.get(currentOption.uuid); @@ -373,9 +295,7 @@ export default class MerchStoreService { if (optionUpdate.quantityToAdd) { currentOption.quantity += optionUpdate.quantityToAdd; if (currentOption.quantity < 0) { - throw new UserError( - `Cannot decrement option quantity below 0 for option: ${currentOption.uuid}`, - ); + throw new UserError(`Cannot decrement option quantity below 0 for option: ${currentOption.uuid}`); } } return MerchandiseItemOptionModel.merge(currentOption, optionUpdate); @@ -388,16 +308,12 @@ export default class MerchStoreService { const dupSet = new Set(); merchPhotos.forEach((merchPhoto) => { if (dupSet.has(merchPhoto.uuid)) { - throw new UserError( - `Multiple edits is made to photo: ${merchPhoto.uuid}`, - ); + throw new UserError(`Multiple edits is made to photo: ${merchPhoto.uuid}`); } dupSet.add(merchPhoto.uuid); }); - const photoUpdatesByUuid = new Map( - merchPhotos.map((merchPhoto) => [merchPhoto.uuid, merchPhoto]), - ); + const photoUpdatesByUuid = new Map(merchPhotos.map((merchPhoto) => [merchPhoto.uuid, merchPhoto])); item.merchPhotos.map((currentPhoto) => { if (!photoUpdatesByUuid.has(currentPhoto.uuid)) return; @@ -410,9 +326,7 @@ export default class MerchStoreService { MerchStoreService.verifyItemHasValidOptions(updatedItem); if (updatedCollection) { - const collection = await Repositories.merchStoreCollection( - txn, - ).findByUuid(updatedCollection); + const collection = await Repositories.merchStoreCollection(txn).findByUuid(updatedCollection); if (!collection) throw new NotFoundError('Merch collection not found'); updatedItem.collection = collection; @@ -427,9 +341,7 @@ export default class MerchStoreService { const merchItemRepository = Repositories.merchStoreItem(txn); const item = await merchItemRepository.findByUuid(uuid); if (!item) throw new NotFoundError(); - const hasBeenOrdered = await Repositories.merchOrderItem( - txn, - ).hasItemBeenOrdered(uuid); + const hasBeenOrdered = await Repositories.merchOrderItem(txn).hasItemBeenOrdered(uuid); if (hasBeenOrdered) throw new UserError('This item has been ordered and cannot be deleted'); return merchItemRepository.deleteMerchItem(item); }); @@ -443,10 +355,7 @@ export default class MerchStoreService { * @param option merch item option * @returns created item option */ - public async createItemOption( - item: Uuid, - option: MerchItemOption, - ): Promise { + public async createItemOption(item: Uuid, option: MerchItemOption): Promise { return this.transactions.readWrite(async (txn) => { const merchItem = await Repositories.merchStoreItem(txn).findByUuid(item); if (!merchItem) throw new NotFoundError('Merch item not found'); @@ -476,22 +385,14 @@ export default class MerchStoreService { const merchItemOptionRepository = Repositories.merchStoreItemOption(txn); const option = await merchItemOptionRepository.findByUuid(uuid); if (!option) throw new NotFoundError(); - const hasBeenOrdered = await Repositories.merchOrderItem( - txn, - ).hasOptionBeenOrdered(uuid); + const hasBeenOrdered = await Repositories.merchOrderItem(txn).hasOptionBeenOrdered(uuid); if (hasBeenOrdered) { - throw new UserError( - 'This item option has been ordered and cannot be deleted', - ); + throw new UserError('This item option has been ordered and cannot be deleted'); } - const item = await Repositories.merchStoreItem(txn).findByUuid( - option.item.uuid, - ); + const item = await Repositories.merchStoreItem(txn).findByUuid(option.item.uuid); if (item.options.length === 1 && !option.item.hidden) { - throw new UserError( - 'Cannot delete the only option for a visible merch item', - ); + throw new UserError('Cannot delete the only option for a visible merch item'); } return merchItemOptionRepository.deleteMerchItemOption(option); @@ -502,9 +403,7 @@ export default class MerchStoreService { * Verify that items have valid options. An item with variants disabled cannot have multiple * options, and an item with variants enabled cannot have multiple option types. */ - private static verifyItemHasValidPhotos( - item: MerchItem | MerchandiseItemModel, - ) { + private static verifyItemHasValidPhotos(item: MerchItem | MerchandiseItemModel) { if (item.merchPhotos.length > MerchStoreService.MAX_MERCH_PHOTO_COUNT) { throw new UserError('Merch items cannot have more than 5 pictures'); } @@ -517,10 +416,7 @@ export default class MerchStoreService { * @param properties merch item photo picture url and position * @returns created item photo */ - public async createItemPhoto( - item: Uuid, - properties: MerchItemPhoto, - ): Promise { + public async createItemPhoto(item: Uuid, properties: MerchItemPhoto): Promise { return this.transactions.readWrite(async (txn) => { const merchItem = await Repositories.merchStoreItem(txn).findByUuid(item); if (!merchItem) throw new NotFoundError('Merch item not found'); @@ -547,21 +443,15 @@ export default class MerchStoreService { * @param uuid the uuid of photo to be deleted * @returns the photo object to be removed from database */ - public async getItemPhotoForDeletion( - uuid: Uuid, - ): Promise { + public async getItemPhotoForDeletion(uuid: Uuid): Promise { return this.transactions.readWrite(async (txn) => { const merchStoreItemPhotoRepository = Repositories.merchStoreItemPhoto(txn); const merchPhoto = await merchStoreItemPhotoRepository.findByUuid(uuid); if (!merchPhoto) throw new NotFoundError('Merch item photo not found'); - const merchItem = await Repositories.merchStoreItem(txn).findByUuid( - merchPhoto.merchItem.uuid, - ); + const merchItem = await Repositories.merchStoreItem(txn).findByUuid(merchPhoto.merchItem.uuid); if (merchItem.merchPhotos.length === 1 && !merchItem.hidden) { - throw new UserError( - 'Cannot delete the only photo for a visible merch item', - ); + throw new UserError('Cannot delete the only photo for a visible merch item'); } return merchPhoto; @@ -574,9 +464,7 @@ export default class MerchStoreService { * @param merchPhoto the photo object to be removed * @returns the photo object removed from database */ - public async deleteItemPhoto( - merchPhoto: MerchandiseItemPhotoModel, - ): Promise { + public async deleteItemPhoto(merchPhoto: MerchandiseItemPhotoModel): Promise { return this.transactions.readWrite(async (txn) => { const merchStoreItemPhotoRepository = Repositories.merchStoreItemPhoto(txn); await merchStoreItemPhotoRepository.deleteMerchItemPhoto(merchPhoto); @@ -584,20 +472,14 @@ export default class MerchStoreService { }); } - public async getCartItems( - options: string[], - ): Promise { + public async getCartItems(options: string[]): Promise { return this.transactions.readOnly(async (txn) => { const merchItemOptionRepository = Repositories.merchStoreItemOption(txn); - const itemOptionsByUuid = await merchItemOptionRepository.batchFindByUuid( - options, - ); + const itemOptionsByUuid = await merchItemOptionRepository.batchFindByUuid(options); const itemOptionUuidsFound = Array.from(itemOptionsByUuid.keys()); const missingItems = difference(options, itemOptionUuidsFound); if (missingItems.length > 0) { - throw new NotFoundError( - `The following items were not found: ${missingItems}`, - ); + throw new NotFoundError(`The following items were not found: ${missingItems}`); } return options.map((option) => itemOptionsByUuid.get(option)); }); diff --git a/services/UserAccountService.ts b/services/UserAccountService.ts index 25adfb7a..bd11569c 100644 --- a/services/UserAccountService.ts +++ b/services/UserAccountService.ts @@ -1,19 +1,11 @@ -import { - BadRequestError, - ForbiddenError, - NotFoundError, -} from 'routing-controllers'; +import { BadRequestError, ForbiddenError, NotFoundError } from 'routing-controllers'; import { Service } from 'typedi'; import { InjectManager } from 'typeorm-typedi-extensions'; import { EntityManager } from 'typeorm'; import * as moment from 'moment'; import * as faker from 'faker'; import { UserAccessUpdates } from 'api/validators/AdminControllerRequests'; -import { - RegExpMatcher, - englishDataset, - englishRecommendedTransformers, -} from 'obscenity'; +import { RegExpMatcher, englishDataset, englishRecommendedTransformers } from 'obscenity'; import { ActivityModel } from 'models/ActivityModel'; import Repositories, { TransactionsManager } from '../repositories'; import { @@ -58,10 +50,7 @@ export default class UserAccountService { /** * Generate a default user handle in the format of "[firstName]-[lastName]-[6 digit has]" truncated to 32 characters */ - public static generateDefaultHandle( - firstName: string, - lastName: string, - ): string { + public static generateDefaultHandle(firstName: string, lastName: string): string { const nameString = `${firstName}-${lastName}`.slice(0, 25); // Hexadecimals look like 0x1b9Dle so we have to truncate the fixed '0x'. const hashValue = faker.datatype.hexaDecimal(6).slice(2); @@ -78,12 +67,7 @@ export default class UserAccountService { }); } - public async getLeaderboard( - from?: number, - to?: number, - offset = 0, - limit = 100, - ): Promise { + public async getLeaderboard(from?: number, to?: number, offset = 0, limit = 100): Promise { // convert timestamps from seconds to milliseconds if (from) from *= 1000; if (to) to *= 1000; @@ -96,9 +80,7 @@ export default class UserAccountService { if (from) from = from > earliest ? moment(from).startOf('day').valueOf() : null; // if right bound is before the current day, round to the end of the day if (to) { - to = to <= moment().startOf('day').valueOf() - ? moment(to).endOf('day').valueOf() - : null; + to = to <= moment().startOf('day').valueOf() ? moment(to).endOf('day').valueOf() : null; } const leaderboardRepository = Repositories.leaderboard(txn); @@ -119,10 +101,7 @@ export default class UserAccountService { return users; } - public async update( - user: UserModel, - userPatches: UserPatches, - ): Promise { + public async update(user: UserModel, userPatches: UserPatches): Promise { const changes: Partial = userPatches; if (userPatches.passwordChange) { const { password: currentPassword, newPassword } = userPatches.passwordChange; @@ -137,9 +116,7 @@ export default class UserAccountService { return this.transactions.readWrite(async (txn) => { if (userPatches.handle) { const userRepository = Repositories.user(txn); - const isHandleTaken = await userRepository.isHandleTaken( - userPatches.handle, - ); + const isHandleTaken = await userRepository.isHandleTaken(userPatches.handle); if (isHandleTaken) throw new BadRequestError('This handle is already in use.'); } const updatedFields = Object.keys(userPatches).join(', '); @@ -153,19 +130,14 @@ export default class UserAccountService { }); } - public async updateProfilePicture( - user: UserModel, - profilePicture: string, - ): Promise { + public async updateProfilePicture(user: UserModel, profilePicture: string): Promise { return this.transactions.readWrite(async (txn) => Repositories.user(txn).upsertUser(user, { profilePicture })); } - public async getCurrentUserActivityStream( - uuid: Uuid, - ): Promise { - const stream = await this.transactions.readOnly(async (txn) => Repositories - .activity(txn) - .getCurrentUserActivityStream(uuid)); + public async getCurrentUserActivityStream(uuid: Uuid): Promise { + const stream = await this.transactions.readOnly(async (txn) => + Repositories.activity(txn).getCurrentUserActivityStream(uuid), + ); return stream; } @@ -180,32 +152,19 @@ export default class UserAccountService { public async createMilestone(milestone: Milestone): Promise { return this.transactions.readWrite(async (txn) => { await Repositories.user(txn).addPointsToAll(milestone.points); - await Repositories.activity(txn).logMilestone( - milestone.name, - milestone.points, - ); + await Repositories.activity(txn).logMilestone(milestone.name, milestone.points); }); } - public async grantBonusPoints( - emails: string[], - description: string, - points: number, - ) { + public async grantBonusPoints(emails: string[], description: string, points: number) { return this.transactions.readWrite(async (txn) => { const userRepository = Repositories.user(txn); const users = await userRepository.findByEmails(emails); const emailsFound = users.map((user) => user.email); - const emailsNotFound = emails.filter( - (email) => !emailsFound.includes(email), - ); + const emailsNotFound = emails.filter((email) => !emailsFound.includes(email)); if (emailsNotFound.length > 0) { - throw new BadRequestError( - `Couldn't find accounts matching these emails: ${JSON.stringify( - emailsNotFound, - )}`, - ); + throw new BadRequestError(`Couldn't find accounts matching these emails: ${JSON.stringify(emailsNotFound)}`); } await userRepository.addPointsToMany(users, points); @@ -225,9 +184,7 @@ export default class UserAccountService { return this.transactions.readOnly(async (txn) => { const userProfile = user.getFullUserProfile(); userProfile.resumes = await Repositories.resume(txn).findAllByUser(user); - userProfile.userSocialMedia = await Repositories.userSocialMedia( - txn, - ).getSocialMediaForUser(user); + userProfile.userSocialMedia = await Repositories.userSocialMedia(txn).getSocialMediaForUser(user); return userProfile; }); } @@ -235,9 +192,7 @@ export default class UserAccountService { public async getPublicProfile(user: UserModel): Promise { return this.transactions.readOnly(async (txn) => { const userProfile = user.getPublicProfile(); - userProfile.userSocialMedia = await Repositories.userSocialMedia( - txn, - ).getSocialMediaForUser(user); + userProfile.userSocialMedia = await Repositories.userSocialMedia(txn).getSocialMediaForUser(user); return userProfile; }); } @@ -265,14 +220,10 @@ export default class UserAccountService { const userRepository = Repositories.user(txn); const users = await userRepository.findByEmails(emails); const emailsFound = users.map((user) => user.email); - const emailsNotFound = emails.filter( - (email) => !emailsFound.includes(email), - ); + const emailsNotFound = emails.filter((email) => !emailsFound.includes(email)); if (emailsNotFound.length > 0) { - throw new BadRequestError( - `Couldn't find accounts matching these emails: ${emailsNotFound}`, - ); + throw new BadRequestError(`Couldn't find accounts matching these emails: ${emailsNotFound}`); } const emailToUserMap = users.reduce((map, user) => { @@ -294,9 +245,7 @@ export default class UserAccountService { // Prevent users from promoting to admin or demoting from admin if (oldAccess === 'ADMIN' || accessType === 'ADMIN') { - throw new ForbiddenError( - 'Cannot alter access level of admin users', - ); + throw new ForbiddenError('Cannot alter access level of admin users'); } const updatedUser = await userRepository.upsertUser(userToUpdate, {