-
Notifications
You must be signed in to change notification settings - Fork 3
/
debtor-controller.ts
394 lines (361 loc) · 14.8 KB
/
debtor-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
/**
* 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 debtor-controller.
*
* @module debtors
*/
import BaseController, { BaseControllerOptions } from './base-controller';
import { Response } from 'express';
import log4js, { Logger } from 'log4js';
import Policy from './policy';
import { RequestWithToken } from '../middleware/token-middleware';
import { parseRequestPagination } from '../helpers/pagination';
import DebtorService from '../service/debtor-service';
import User from '../entity/user/user';
import { asArrayOfDates, asArrayOfUserTypes, asDate, asFromAndTillDate, asReturnFileType } from '../helpers/validators';
import { In } from 'typeorm';
import { HandoutFinesRequest } from './request/debtor-request';
import Fine from '../entity/fine/fine';
import { ReturnFileType } from 'pdf-generator-client';
import { PdfError } from '../errors';
export default class DebtorController extends BaseController {
private logger: Logger = log4js.getLogger(' DebtorController');
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', 'Fine', ['*']),
handler: this.returnAllFineHandoutEvents.bind(this),
},
},
'/:id(\\d+)': {
GET: {
policy: async (req) => this.roleManager.can(req.token.roles, 'get', 'all', 'Fine', ['*']),
handler: this.returnSingleFineHandoutEvent.bind(this),
},
},
'/single/:id(\\d+)': {
DELETE: {
policy: async (req) => this.roleManager.can(req.token.roles, 'delete', 'all', 'Fine', ['*']),
handler: this.deleteFine.bind(this),
},
},
'/eligible': {
GET: {
policy: async (req) => this.roleManager.can(req.token.roles, 'get', 'all', 'Fine', ['*']),
handler: this.calculateFines.bind(this),
},
},
'/handout': {
POST: {
policy: async (req) => this.roleManager.can(req.token.roles, 'create', 'all', 'Fine', ['*']),
handler: this.handoutFines.bind(this),
body: { modelName: 'HandoutFinesRequest' },
},
},
'/notify': {
POST: {
policy: async (req) => this.roleManager.can(req.token.roles, 'notify', 'all', 'Fine', ['*']),
handler: this.notifyAboutFutureFines.bind(this),
body: { modelName: 'HandoutFinesRequest' },
},
},
'/report': {
GET: {
policy: async (req) => this.roleManager.can(req.token.roles, 'get', 'all', 'Fine', ['*']),
handler: this.getFineReport.bind(this),
},
},
'/report/pdf': {
GET: {
policy: async (req) => this.roleManager.can(req.token.roles, 'get', 'all', 'Fine', ['*']),
handler: this.getFineReportPdf.bind(this),
},
},
};
}
/**
* GET /fines
* @summary Get all fine handout events
* @tags debtors - Operations of the debtor controller
* @operationId returnAllFineHandoutEvents
* @security JWT
* @param {integer} take.query - How many entries the endpoint should return
* @param {integer} skip.query - How many entries should be skipped (for pagination)
* @return {PaginatedFineHandoutEventResponse} 200 - All existing fine handout events
* @return {string} 400 - Validation error
* @return {string} 500 - Internal server error
*/
public async returnAllFineHandoutEvents(req: RequestWithToken, res: Response): Promise<void> {
this.logger.trace('Get all fine handout events by ', 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;
}
try {
res.json(await new DebtorService().getFineHandoutEvents({ take, skip }));
} catch (error) {
this.logger.error('Could not return all fine handout event:', error);
res.status(500).json('Internal server error.');
}
}
/**
* GET /fines/{id}
* @summary Get all fine handout events
* @tags debtors - Operations of the debtor controller
* @operationId returnSingleFineHandoutEvent
* @security JWT
* @param {integer} id.path.required - The id of the fine handout event which should be returned
* @return {FineHandoutEventResponse} 200 - Requested fine handout event with corresponding fines
* @return {string} 400 - Validation error
* @return {string} 500 - Internal server error
*/
public async returnSingleFineHandoutEvent(req: RequestWithToken, res: Response): Promise<void> {
const { id } = req.params;
this.logger.trace('Get fine handout event', id, 'by', req.token.user);
try {
res.json(await new DebtorService().getSingleFineHandoutEvent(Number.parseInt(id, 10)));
} catch (error) {
this.logger.error('Could not return fine handout event:', error);
res.status(500).json('Internal server error.');
}
}
/**
* DELETE /fines/single/{id}
* @summary Delete a fine
* @tags debtors - Operations of the debtor controller
* @operationId deleteFine
* @security JWT
* @param {integer} id.path.required - The id of the fine which should be deleted
* @return 204 - Success
* @return {string} 400 - Validation error
* @return {string} 500 - Internal server error
*/
public async deleteFine(req: RequestWithToken, res: Response): Promise<void> {
const { id } = req.params;
this.logger.trace('Delete fine', id, 'by', req.token.user);
try {
const parsedId = Number.parseInt(id, 10);
const fine = await Fine.findOne({ where: { id: parsedId } });
if (fine == null) {
res.status(404).send();
return;
}
await new DebtorService().deleteFine(parsedId);
res.status(204).send();
} catch (error) {
this.logger.error('Could not return fine handout event:', error);
res.status(500).json('Internal server error.');
}
}
/**
* GET /fines/eligible
* @summary Return all users that had at most -5 euros balance both now and on the reference date.
* For all these users, also return their fine based on the reference date.
* @tags debtors - Operations of the debtor controller
* @operationId calculateFines
* @security JWT
* @param {Array<string>} userTypes.query - List of all user types fines should be calculated for (MEMBER, ORGAN, VOUCHER, LOCAL_USER, LOCAL_ADMIN, INVOICE, AUTOMATIC_INVOICE).
* @param {Array<string>} referenceDates.query.required - Dates to base the fines on. Every returned user has at
* least five euros debt on every reference date. The height of the fine is based on the first date in the array.
* @return {Array<UserToFineResponse>} 200 - List of eligible fines
* @return {string} 400 - Validation error
* @return {string} 500 - Internal server error
*/
public async calculateFines(req: RequestWithToken, res: Response): Promise<void> {
this.logger.trace('Get all possible fines by ', req.token.user);
let params;
try {
if (req.query.referenceDates === undefined) throw new Error('referenceDates is required');
const referenceDates = asArrayOfDates(req.query.referenceDates);
if (referenceDates === undefined) throw new Error('referenceDates is not a valid array');
params = {
userTypes: asArrayOfUserTypes(req.query.userTypes),
referenceDates,
};
if (params.userTypes === undefined && req.query.userTypes !== undefined) throw new Error('userTypes is not a valid array of UserTypes');
} catch (e) {
res.status(400).json(e.message);
return;
}
try {
res.json(await new DebtorService().calculateFinesOnDate(params));
} catch (error) {
this.logger.error('Could not calculate fines:', error);
res.status(500).json('Internal server error.');
}
}
/**
* POST /fines/handout
* @summary Handout fines to all given users. Fines will be handed out "now" to prevent rewriting history.
* @tags debtors - Operations of the debtor controller
* @operationId handoutFines
* @security JWT
* @param {HandoutFinesRequest} request.body.required
* @return {FineHandoutEventResponse} 200 - Created fine handout event with corresponding fines
* @return {string} 400 - Validation error
* @return {string} 500 - Internal server error
*/
public async handoutFines(req: RequestWithToken, res: Response): Promise<void> {
const body = req.body as HandoutFinesRequest;
this.logger.trace('Handout fines', body, 'by user', req.token.user);
let referenceDate: Date;
try {
// Todo: write code-consistent validator (either /src/controller/request/validators or custom validator.js function)
if (!Array.isArray(body.userIds)) throw new Error('userIds is not an array');
const users = await User.find({ where: { id: In(body.userIds) } });
if (users.length !== body.userIds.length) throw new Error('userIds is not a valid array of user IDs');
if (body.referenceDate !== undefined) {
referenceDate = asDate(body.referenceDate);
}
} catch (e) {
res.status(400).json(e.message);
return;
}
try {
const result = await new DebtorService().handOutFines({ referenceDate, userIds: body.userIds }, req.token.user);
res.json(result);
} catch (error) {
this.logger.error('Could not handout fines:', error);
res.status(500).json('Internal server error.');
}
}
/**
* POST /fines/notify
* @summary Send an email to all given users about their possible future fine.
* @tags debtors - Operations of the debtor controller
* @operationId notifyAboutFutureFines
* @security JWT
* @param {HandoutFinesRequest} request.body.required
* @return 204 - Success
* @return {string} 400 - Validation error
* @return {string} 500 - Internal server error
*/
public async notifyAboutFutureFines(req: RequestWithToken, res: Response): Promise<void> {
const body = req.body as HandoutFinesRequest;
this.logger.trace('Send future fine notification emails', body, 'by user', req.token.user);
let referenceDate: Date;
try {
// Todo: write code-consistent validator (either /src/controller/request/validators or custom validator.js function)
if (!Array.isArray(body.userIds)) throw new Error('userIds is not an array');
const users = await User.find({ where: { id: In(body.userIds) } });
if (users.length !== body.userIds.length) throw new Error('userIds is not a valid array of user IDs');
if (body.referenceDate !== undefined) {
referenceDate = asDate(body.referenceDate);
}
} catch (e) {
res.status(400).json(e.message);
return;
}
try {
await new DebtorService().sendFineWarnings({ referenceDate, userIds: body.userIds });
res.status(204).send();
} catch (error) {
this.logger.error('Could not send future fine notification emails:', error);
res.status(500).json('Internal server error.');
}
}
/**
* GET /fines/report
* @summary Get a report of all fines
* @tags debtors - Operations of the debtor controller
* @operationId getFineReport
* @security JWT
* @param {string} fromDate.query - The start date of the report, inclusive
* @param {string} toDate.query - The end date of the report, exclusive
* @return {FineReportResponse} 200 - The requested report
* @return {string} 400 - Validation error
* @return {string} 500 - Internal server error
*/
public async getFineReport(req: RequestWithToken, res: Response): Promise<void> {
this.logger.trace('Get fine report by ', req.token.user);
let fromDate, toDate;
try {
const filters = asFromAndTillDate(req.query.fromDate, req.query.toDate);
fromDate = filters.fromDate;
toDate = filters.tillDate;
} catch (e) {
res.status(400).json(e.message);
return;
}
try {
const report = await new DebtorService().getFineReport(fromDate, toDate);
res.json(report.toResponse());
} catch (error) {
this.logger.error('Could not get fine report:', error);
res.status(500).json('Internal server error.');
}
}
/**
* GET /fines/report/pdf
* @summary Get a report of all fines in pdf format
* @tags debtors - Operations of the debtor controller
* @operationId getFineReportPdf
* @security JWT
* @param {string} fromDate.query.required - The start date of the report, inclusive
* @param {string} toDate.query.required - The end date of the report, exclusive
* @param {string} fileType.query.required - enum:PDF,TEX - The file type of the report
* @returns {string} 200 - The requested report - application/pdf
* @return {string} 400 - Validation error
* @return {string} 500 - Internal server error
*/
public async getFineReportPdf(req: RequestWithToken, res: Response): Promise<void> {
this.logger.trace('Get fine report by ', req.token.user);
let fromDate, toDate;
let fileType: ReturnFileType;
try {
const filters = asFromAndTillDate(req.query.fromDate, req.query.toDate);
fromDate = filters.fromDate;
toDate = filters.tillDate;
fileType = asReturnFileType(req.query.fileType);
} catch (e) {
res.status(400).json(e.message);
return;
}
try {
const report = await new DebtorService().getFineReport(fromDate, toDate);
const buffer = fileType === 'PDF' ? await report.createPdf() : await report.createTex();
const from = `${fromDate.getFullYear()}${fromDate.getMonth() + 1}${fromDate.getDate()}`;
const to = `${toDate.getFullYear()}${toDate.getMonth() + 1}${toDate.getDate()}`;
const fileName = `fine-report-${from}-${to}.${fileType}`;
res.setHeader('Content-Type', 'application/pdf+tex');
res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);
res.send(buffer);
} catch (error) {
this.logger.error('Could not get fine report pdf:', error);
if (error instanceof PdfError) {
res.status(502).json('PDF Generator service failed.');
return;
}
res.status(500).json('Internal server error.');
}
}
}