-
Notifications
You must be signed in to change notification settings - Fork 3
/
event-controller.ts
461 lines (428 loc) · 16.7 KB
/
event-controller.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
/**
* SudoSOS back-end API service.
* Copyright (C) 2024 Study association GEWIS
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* @license
*/
/**
* This is the module page of event-controller.
*
* @module events
* @deprecated Events are out of scope for SudoSOS. Delete from 01/11/2026.
*/
import log4js, { Logger } from 'log4js';
import { Response } from 'express';
import BaseController, { BaseControllerOptions } from './base-controller';
import Policy from './policy';
import { RequestWithToken } from '../middleware/token-middleware';
import EventService, {
CreateEventParams,
EventFilterParameters,
parseEventFilterParameters, parseUpdateEventRequestParameters, UpdateEventAnswerParams, UpdateEventParams,
} from '../service/event-service';
import { parseRequestPagination } from '../helpers/pagination';
import { EventAnswerAssignmentRequest, EventAnswerAvailabilityRequest, EventRequest } from './request/event-request';
import Event from '../entity/event/event';
import EventShiftAnswer from '../entity/event/event-shift-answer';
import { asShiftAvailability } from '../helpers/validators';
/**
* @deprecated Events are out of scope for SudoSOS. Delete from 01/11/2026.
*/
export default class EventController extends BaseController {
private logger: Logger = log4js.getLogger('EventLogger');
/**
* Create a new user controller instance.
* @param options - The options passed to the base controller.
*/
public constructor(
options: BaseControllerOptions,
) {
super(options);
this.logger.level = process.env.LOG_LEVEL;
}
public getPolicy(): Policy {
return {
'/': {
GET: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'get', 'all', 'Event', ['*'],
),
handler: this.getAllEvents.bind(this),
},
POST: {
policy: async (req) => this.roleManager.can(
req.token.roles, 'create', 'all', 'Event', ['*'],
),
body: { modelName: 'CreateEventRequest' },
handler: this.createEvent.bind(this),
},
},
'/:id(\\d+)': {
GET: {
policy: async (req) => this.roleManager.can(req.token.roles, 'get', 'all', 'Event', ['*']),
handler: this.getSingleEvent.bind(this),
},
PATCH: {
policy: async (req) => this.roleManager.can(req.token.roles, 'update', 'all', 'Event', ['*']),
handler: this.updateEvent.bind(this),
body: { modelName: 'UpdateEventRequest' },
},
DELETE: {
policy: async (req) => this.roleManager.can(req.token.roles, 'delete', 'all', 'Event', ['*']),
handler: this.deleteEvent.bind(this),
},
},
'/:id(\\d+)/sync': {
POST: {
policy: async (req) => this.roleManager.can(req.token.roles, 'update', 'all', 'Event', ['*']),
handler: this.syncEventShiftAnswers.bind(this),
},
},
'/:eventId(\\d+)/shift/:shiftId(\\d+)/user/:userId(\\d+)/assign': {
PUT: {
policy: async (req) => this.roleManager.can(req.token.roles, 'assign', 'all', 'EventAnswer', ['*']),
handler: this.assignEventShift.bind(this),
body: { modelName: 'EventAnswerAssignmentRequest' },
},
},
'/:eventId(\\d+)/shift/:shiftId(\\d+)/user/:userId(\\d+)/availability': {
PUT: {
policy: async (req) => this.roleManager.can(req.token.roles, 'assign', EventController.getRelation(req), 'EventAnswer', ['*']),
handler: this.updateShiftAvailability.bind(this),
body: { modelName: 'EventAnswerAvailabilityRequest' },
},
},
};
}
private static getRelation(req: RequestWithToken): string {
return req.params.userId === req.token.user.id.toString() ? 'own' : 'all';
}
/**
* GET /events
* @summary Get all events
* @tags events - Operations of the event controller
* @operationId getAllEvents
* @security JWT
* @param {string} name.query - Name of the event
* @param {integer} createdById.query - ID of user that created the event
* @param {string} beforeDate.query - Get only events that start after this date
* @param {string} afterDate.query - Get only events that start before this date
* @param {string} type.query - Get only events that are this type
* @param {integer} take.query - How many entries the endpoint should return
* @param {integer} skip.query - How many entries should be skipped (for pagination)
* @return {PaginatedBaseEventResponse} 200 - All existing events
* @return {string} 400 - Validation error
* @return {string} 500 - Internal server error
* @deprecated Events are out of scope for SudoSOS. Delete from 01/11/2026.
*/
public async getAllEvents(req: RequestWithToken, res: Response): Promise<void> {
this.logger.trace('Get all events by user', req.token.user);
let take;
let skip;
try {
const pagination = parseRequestPagination(req);
take = pagination.take;
skip = pagination.skip;
} catch (e) {
res.status(400).json(e.message);
return;
}
let filters: EventFilterParameters;
try {
filters = parseEventFilterParameters(req);
} catch (e) {
res.status(400).json(e.message);
return;
}
// Handle request
try {
const events = await EventService.getEvents(filters, { take, skip });
res.json(events);
} catch (e) {
this.logger.error('Could not return all events:', e);
res.status(500).json('Internal server error.');
}
}
/**
* GET /events/{id}
* @summary Get a single event with its answers and shifts
* @tags events - Operations of the event controller
* @operationId getSingleEvent
* @security JWT
* @param {integer} id.path.required - The id of the event which should be returned
* @return {EventResponse} 200 - All existing events
* @return {string} 400 - Validation error
* @return {string} 500 - Internal server error
* @deprecated Events are out of scope for SudoSOS. Delete from 01/11/2026.
*/
public async getSingleEvent(req: RequestWithToken, res: Response) {
const { id } = req.params;
this.logger.trace('Get single event with ID', id, 'by', req.token.user);
try {
const parsedId = Number.parseInt(id, 10);
const event = await EventService.getSingleEvent(parsedId);
if (event == null) {
res.status(404).send();
return;
}
res.json(event);
} catch (error) {
this.logger.error('Could not return single event:', error);
res.status(500).json('Internal server error.');
}
}
/**
* POST /events
* @summary Create an event with its corresponding answers objects
* @tags events - Operations of the event controller
* @operationId createEvent
* @security JWT
* @param {CreateEventRequest} request.body.required
* @return {EventResponse} 200 - Created event
* @return {string} 400 - Validation error
* @return {string} 500 - Internal server error
* @deprecated Events are out of scope for SudoSOS. Delete from 01/11/2026.
*/
public async createEvent(req: RequestWithToken, res: Response) {
const body = req.body as EventRequest;
this.logger.trace('Create event', body, 'by user', req.token.user);
let params: CreateEventParams;
try {
params = {
...await parseUpdateEventRequestParameters(req),
createdById: req.token.user.id,
};
} catch (e) {
res.status(400).json(e.message);
return;
}
// handle request
try {
res.json(await EventService.createEvent(params));
} catch (error) {
this.logger.error('Could not create event:', error);
res.status(500).json('Internal server error.');
}
}
/**
* PATCH /events/{id}
* @summary Update an event with its corresponding answers objects
* @tags events - Operations of the event controller
* @operationId updateEvent
* @security JWT
* @param {integer} id.path.required - The id of the event which should be returned
* @param {UpdateEventRequest} request.body.required
* @return {EventResponse} 200 - Created event
* @return {string} 400 - Validation error
* @return {string} 500 - Internal server error
* @deprecated Events are out of scope for SudoSOS. Delete from 01/11/2026.
*/
public async updateEvent(req: RequestWithToken, res: Response) {
const { id } = req.params;
const body = req.body as EventRequest;
this.logger.trace('Update event', id, 'with body', body, 'by user', req.token.user);
let parsedId = Number.parseInt(id, 10);
try {
const event = await EventService.getSingleEvent(parsedId);
if (event == null) {
res.status(404).send();
return;
}
} catch (error) {
this.logger.error('Could not update event:', error);
res.status(500).json('Internal server error.');
}
let params: Partial<UpdateEventParams>;
try {
params = {
...await parseUpdateEventRequestParameters(req, true, parsedId),
};
} catch (e) {
res.status(400).json(e.message);
return;
}
// handle request
try {
res.json(await EventService.updateEvent(parsedId, params));
} catch (error) {
this.logger.error('Could not update event:', error);
res.status(500).json('Internal server error.');
}
}
/**
* DELETE /events/{id}
* @summary Delete an event with its answers
* @tags events - Operations of the event controller
* @operationId deleteEvent
* @security JWT
* @param {integer} id.path.required - The id of the event which should be deleted
* @return 204 - Success
* @return {string} 400 - Validation error
* @return {string} 500 - Internal server error
* @deprecated Events are out of scope for SudoSOS. Delete from 01/11/2026.
*/
public async deleteEvent(req: RequestWithToken, res: Response) {
const { id } = req.params;
this.logger.trace('Get single event with ID', id, 'by', req.token.user);
try {
const parsedId = Number.parseInt(id, 10);
const event = await EventService.getSingleEvent(parsedId);
if (event == null) {
res.status(404).send();
return;
}
await EventService.deleteEvent(parsedId);
res.status(204).send();
} catch (error) {
this.logger.error('Could not delete event:', error);
res.status(500).json('Internal server error.');
}
}
/**
* Synchronize an event, so that EventShiftAnswers are created/deleted
* for users that are (no longer) part of a shift
* @route GET /events/{id}/sync
* @tags events - Operations of the event controller
* @operationId syncEventShiftAnswers
* @security JWT
* @param {integer} id.path.required - The id of the event which should be returned
* @return {EventResponse} 200 - All existing events
* @return {string} 400 - Validation error
* @return {string} 500 - Internal server error
* @deprecated Events are out of scope for SudoSOS. Delete from 01/11/2026.
*/
public async syncEventShiftAnswers(req: RequestWithToken, res: Response) {
const { id } = req.params;
this.logger.trace('Synchronise single event with ID', id, 'by', req.token.user);
try {
const parsedId = Number.parseInt(id, 10);
const event = await Event.findOne({ where: { id: parsedId }, relations: ['answers', 'shifts'] });
if (event == null) {
res.status(404).send();
return;
}
await EventService.syncEventShiftAnswers(event);
res.status(200).json(await EventService.getSingleEvent(parsedId));
} catch (error) {
this.logger.error('Could not synchronize event answers:', error);
res.status(500).json('Internal server error.');
}
}
/**
* PUT /events/{eventId}/shift/{shiftId}/user/{userId}/assign
* @summary Change the assignment of users to shifts on an event
* @tags events - Operations of the event controller
* @operationId assignEventShift
* @security JWT
* @param {integer} eventId.path.required - The id of the event
* @param {integer} shiftId.path.required - The id of the shift
* @param {integer} userId.path.required - The id of the user
* @param {EventAnswerAssignmentRequest} request.body.required
* @return {BaseEventAnswerResponse} 200 - Created event
* @return {string} 400 - Validation error
* @return {string} 500 - Internal server error
* @deprecated Events are out of scope for SudoSOS. Delete from 01/11/2026.
*/
public async assignEventShift(req: RequestWithToken, res: Response) {
const { eventId: rawEventId, shiftId: rawShiftId, userId: rawUserId } = req.params;
const body = req.body as EventAnswerAssignmentRequest;
this.logger.trace('Update event shift selection for event', rawEventId, 'for shift', rawShiftId, 'for user', rawUserId, 'by', req.token.user);
let eventId = Number.parseInt(rawEventId, 10);
let shiftId = Number.parseInt(rawShiftId, 10);
let userId = Number.parseInt(rawUserId, 10);
try {
const answer = await EventShiftAnswer.findOne({ where: { eventId, shiftId, userId }, relations: ['event'] });
if (answer == null) {
res.status(404).send();
return;
}
if (answer.event.startDate.getTime() < new Date().getTime()) {
res.status(400).json('Event has already started or is already over.');
return;
}
} catch (error) {
this.logger.error('Could not update event:', error);
res.status(500).json('Internal server error.');
return;
}
let params: Partial<UpdateEventAnswerParams> = {
selected: body.selected,
};
// handle request
try {
const answer = await EventService.updateEventShiftAnswer(eventId, shiftId, userId, params);
res.json(answer);
} catch (error) {
this.logger.error('Could not update event:', error);
res.status(500).json('Internal server error.');
}
}
/**
* POST /events/{eventId}/shift/{shiftId}/user/{userId}/availability
* @summary Update the availability of a user for a shift in an event
* @tags events - Operations of the event controller
* @operationId updateEventShiftAvailability
* @security JWT
* @param {integer} eventId.path.required - The id of the event
* @param {integer} shiftId.path.required - The id of the shift
* @param {integer} userId.path.required - The id of the user
* @param {EventAnswerAvailabilityRequest} request.body.required
* @return {BaseEventAnswerResponse} 200 - Created event
* @return {string} 400 - Validation error
* @return {string} 500 - Internal server error
* @deprecated Events are out of scope for SudoSOS. Delete from 01/11/2026.
*/
public async updateShiftAvailability(req: RequestWithToken, res: Response) {
const { userId: rawUserId, shiftId: rawShiftId, eventId: rawEventId } = req.params;
const body = req.body as EventAnswerAvailabilityRequest;
this.logger.trace('Update event shift availability for user', rawUserId, 'for shift', rawShiftId, 'for event', rawEventId, 'by', req.token.user);
let userId = Number.parseInt(rawUserId, 10);
let shiftId = Number.parseInt(rawShiftId, 10);
let eventId = Number.parseInt(rawEventId, 10);
try {
const answer = await EventShiftAnswer.findOne({ where: { eventId, shiftId, userId }, relations: ['event'] });
if (answer == null) {
res.status(404).send();
return;
}
if (answer.event.startDate.getTime() < new Date().getTime()) {
res.status(400).json('Event has already started or is already over.');
return;
}
} catch (error) {
this.logger.error('Could not update event:', error);
res.status(500).json('Internal server error.');
return;
}
let params: Partial<UpdateEventAnswerParams>;
try {
params = {
availability: asShiftAvailability(body.availability),
};
} catch (e) {
res.status(400).json('Invalid event availability.');
return;
}
// handle request
try {
const answer = await EventService.updateEventShiftAnswer(eventId, shiftId, userId, params);
res.json(answer);
} catch (error) {
this.logger.error('Could not update event:', error);
res.status(500).json('Internal server error.');
}
}
}