-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathinvoice-controller.ts
548 lines (500 loc) · 19.9 KB
/
invoice-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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
/**
* 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 page of invoice controller.
*
* @module invoicing
*/
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 { PaginatedInvoiceResponse } from './response/invoice-response';
import InvoiceService, { InvoiceFilterParameters, parseInvoiceFilterParameters } from '../service/invoice-service';
import { parseRequestPagination } from '../helpers/pagination';
import {
CreateInvoiceParams,
CreateInvoiceRequest,
UpdateInvoiceParams,
UpdateInvoiceRequest,
} from './request/invoice-request';
import verifyCreateInvoiceRequest, { verifyUpdateInvoiceRequest } from './request/validators/invoice-request-spec';
import { isFail } from '../helpers/specification-validation';
import { asBoolean, asDate, asInvoiceState, asNumber } from '../helpers/validators';
import Invoice from '../entity/invoices/invoice';
import User, { UserType } from '../entity/user/user';
import { UpdateInvoiceUserRequest } from './request/user-request';
import InvoiceUser from '../entity/user/invoice-user';
import { parseInvoiceUserToResponse } from '../helpers/revision-to-response';
import { AppDataSource } from '../database/database';
import { NotImplementedError, PdfError } from '../errors';
/**
* The Invoice controller.
*/
export default class InvoiceController extends BaseController {
private logger: Logger = log4js.getLogger('InvoiceController');
/**
* Creates a new Invoice controller instance.
* @param options - The options passed to the base controller.
*/
public constructor(options: BaseControllerOptions) {
super(options);
this.logger.level = process.env.LOG_LEVEL;
}
/**
* @inhertidoc
*/
getPolicy(): Policy {
return {
'/': {
GET: {
policy: async (req) => this.roleManager.can(req.token.roles, 'get', 'all', 'Invoice', ['*']),
handler: this.getAllInvoices.bind(this),
},
POST: {
body: { modelName: 'CreateInvoiceRequest' },
policy: async (req) => this.roleManager.can(req.token.roles, 'create', 'all', 'Invoice', ['*']),
handler: this.createInvoice.bind(this),
},
},
'/users/:id(\\d+)': {
GET: {
policy: async (req) => this.roleManager.can(req.token.roles, 'get', 'all', 'Invoice', ['*']),
handler: this.getSingleInvoiceUser.bind(this),
},
PUT : {
body: { modelName: 'UpdateInvoiceUserRequest' },
policy: async (req) => this.roleManager.can(req.token.roles, 'update', 'all', 'Invoice', ['*']),
handler: this.updateInvoiceUser.bind(this),
},
DELETE: {
policy: async (req) => this.roleManager.can(req.token.roles, 'delete', 'all', 'Invoice', ['*']),
handler: this.deleteInvoiceUser.bind(this),
},
},
'/:id(\\d+)': {
GET: {
policy: async (req) => this.roleManager.can(req.token.roles, 'get', await InvoiceController.getRelation(req), 'Invoice', ['*']),
handler: this.getSingleInvoice.bind(this),
},
PATCH: {
body: { modelName: 'UpdateInvoiceRequest' },
policy: async (req) => this.roleManager.can(req.token.roles, 'update', 'all', 'Invoice', ['*']),
handler: this.updateInvoice.bind(this),
},
DELETE: {
policy: async (req) => this.roleManager.can(req.token.roles, 'delete', 'all', 'Invoice', ['*']),
handler: this.deleteInvoice.bind(this),
},
},
'/:id(\\d+)/pdf': {
GET: {
policy: async (req) => this.roleManager.can(req.token.roles, 'get', await InvoiceController.getRelation(req), 'Invoice', ['*']),
handler: this.getInvoicePDF.bind(this),
},
},
'/eligible-transactions': {
GET: {
policy: async (req) => this.roleManager.can(req.token.roles, 'get', 'all', 'Invoice', ['*']),
handler: this.getEligibleTransactions.bind(this),
},
},
};
}
/**
* GET /invoices
* @summary Returns all invoices in the system.
* @operationId getAllInvoices
* @tags invoices - Operations of the invoices controller
* @security JWT
* @param {integer} toId.query - Filter on Id of the debtor
* @param {number} invoiceId.query - Filter on invoice ID
* @param {Array<string|number>} currentState.query enum:CREATED,SENT,PAID,DELETED - Filter based on Invoice State.
* @param {boolean} returnEntries.query - Boolean if invoice entries should be returned
* @param {string} fromDate.query - Start date for selected invoices (inclusive)
* @param {string} tillDate.query - End date for selected invoices (exclusive)
* @param {integer} take.query - How many entries the endpoint should return
* @param {integer} skip.query - How many entries should be skipped (for pagination)
* @return {PaginatedInvoiceResponse} 200 - All existing invoices
* @return {string} 500 - Internal server error
*/
public async getAllInvoices(req: RequestWithToken, res: Response): Promise<void> {
const { body } = req;
this.logger.trace('Get all invoices', body, 'by user', req.token.user);
let take;
let skip;
let filters: InvoiceFilterParameters;
try {
const pagination = parseRequestPagination(req);
filters = parseInvoiceFilterParameters(req);
take = pagination.take;
skip = pagination.skip;
} catch (e) {
res.status(400).send(e.message);
return;
}
// Handle request
try {
const invoices: PaginatedInvoiceResponse = await new InvoiceService().getPaginatedInvoices(
filters, { take, skip },
);
res.json(invoices);
} catch (error) {
this.logger.error('Could not return all invoices:', error);
res.status(500).json('Internal server error.');
}
}
/**
* GET /invoices/{id}
* @summary Returns a single invoice in the system.
* @operationId getSingleInvoice
* @param {integer} id.path.required - The id of the requested invoice
* @tags invoices - Operations of the invoices controller
* @security JWT
* @param {boolean} returnEntries.query -
* Boolean if invoice entries should be returned, defaults to true.
* @return {InvoiceResponse} 200 - All existing invoices
* @return {string} 404 - Invoice not found
* @return {string} 500 - Internal server error
*/
public async getSingleInvoice(req: RequestWithToken, res: Response): Promise<void> {
const { id } = req.params;
const invoiceId = parseInt(id, 10);
this.logger.trace('Get invoice', invoiceId, 'by user', req.token.user);
// Handle request
try {
const returnInvoiceEntries = asBoolean(req.query.returnEntries) ?? true;
const invoices: Invoice[] = await new InvoiceService().getInvoices(
{ invoiceId, returnInvoiceEntries },
);
const invoice = invoices[0];
if (!invoice) {
res.status(404).json('Unknown invoice ID.');
return;
}
const response = returnInvoiceEntries
? InvoiceService.asInvoiceResponse(invoice)
: InvoiceService.asBaseInvoiceResponse(invoice);
res.json(response);
} catch (error) {
this.logger.error('Could not return invoice:', error);
res.status(500).json('Internal server error.');
}
}
/**
* POST /invoices
* @summary Adds an invoice to the system.
* @operationId createInvoice
* @tags invoices - Operations of the invoices controller
* @security JWT
* @param {CreateInvoiceRequest} request.body.required -
* The invoice which should be created
* @return {InvoiceResponse} 200 - The created invoice entity
* @return {string} 400 - Validation error
* @return {string} 500 - Internal server error
*/
public async createInvoice(req: RequestWithToken, res: Response): Promise<void> {
const body = req.body as CreateInvoiceRequest;
this.logger.trace('Create Invoice', body, 'by user', req.token.user);
// handle request
try {
const userDefinedDefaults = await new InvoiceService().getDefaultInvoiceParams(body.forId);
// If no byId is provided we use the token user id.
const params: CreateInvoiceParams = {
...userDefinedDefaults,
...body,
date: body.date ? new Date(body.date) : new Date(),
byId: body.byId ?? req.token.user.id,
description: body.description ?? '',
};
const validation = await verifyCreateInvoiceRequest(params);
if (isFail(validation)) {
res.status(400).json(validation.fail.value);
return;
}
const invoice: Invoice = await AppDataSource.manager.transaction(async (manager) =>
new InvoiceService(manager).createInvoice(params));
res.json(InvoiceService.asInvoiceResponse(invoice));
} catch (error) {
if (error instanceof NotImplementedError) {
res.status(501).json(error.message);
return;
}
this.logger.error('Could not create invoice:', error);
res.status(500).json('Internal server error.');
}
}
/**
* PATCH /invoices/{id}
* @summary Adds an invoice to the system.
* @operationId updateInvoice
* @tags invoices - Operations of the invoices controller
* @security JWT
* @param {integer} id.path.required - The id of the invoice which should be updated
* @param {UpdateInvoiceRequest} request.body.required -
* The invoice update to process
* @return {BaseInvoiceResponse} 200 - The updated invoice entity
* @return {string} 400 - Validation error
* @return {string} 500 - Internal server error
*/
public async updateInvoice(req: RequestWithToken, res: Response): Promise<void> {
const body = req.body as UpdateInvoiceRequest;
const { id } = req.params;
const invoiceId = parseInt(id, 10);
this.logger.trace('Update Invoice', body, 'by user', req.token.user);
try {
// Default byId to token user id.
const params: UpdateInvoiceParams = {
...body,
invoiceId,
state: asInvoiceState(body.state),
byId: body.byId ?? req.token.user.id,
};
const validation = await verifyUpdateInvoiceRequest(params);
if (isFail(validation)) {
res.status(400).json(validation.fail.value);
return;
}
const invoice: Invoice = await AppDataSource.manager.transaction(async (manager) =>
new InvoiceService(manager).updateInvoice(params));
res.json(InvoiceService.asBaseInvoiceResponse(invoice));
} catch (error) {
this.logger.error('Could not update invoice:', error);
res.status(500).json('Internal server error.');
}
}
/**
* DELETE /invoices/{id}
* @summary Deletes an invoice.
* @operationId deleteInvoice
* @tags invoices - Operations of the invoices controller
* @security JWT
* @param {integer} id.path.required - The id of the invoice which should be deleted
* @return {string} 404 - Invoice not found
* @return 204 - Deletion success
* @return {string} 500 - Internal server error
*/
// TODO Deleting of invoices that are not of state CREATED?
public async deleteInvoice(req: RequestWithToken, res: Response): Promise<void> {
const { id } = req.params;
const invoiceId = parseInt(id, 10);
this.logger.trace('Delete Invoice', id, 'by user', req.token.user);
try {
const invoice = await AppDataSource.manager.transaction(async (manager) =>
new InvoiceService(manager).deleteInvoice(invoiceId, req.token.user.id));
if (!invoice) {
res.status(404).json('Invoice not found.');
return;
}
res.status(204).send();
} catch (error) {
this.logger.error('Could not delete invoice:', error);
res.status(500).json('Internal server error.');
}
}
/**
* GET /invoices/{id}/pdf
* @summary Get an invoice pdf.
* @operationId getInvoicePdf
* @tags invoices - Operations of the invoices controller
* @security JWT
* @param {integer} id.path.required - The id of the invoice to return
* @param {boolean} force.query - Force creation of pdf
* @return {string} 404 - Invoice not found
* @return {string} 200 - The pdf location information.
* @return {string} 500 - Internal server error
*/
public async getInvoicePDF(req: RequestWithToken, res: Response): Promise<void> {
const { id } = req.params;
const invoiceId = parseInt(id, 10);
this.logger.trace('Get Invoice PDF', id, 'by user', req.token.user);
try {
const invoice = await Invoice.findOne(InvoiceService.getOptions({ invoiceId, returnInvoiceEntries: true }) );
if (!invoice) {
res.status(404).json('Invoice not found.');
return;
}
const pdf = await invoice.getOrCreatePdf(req.query.force === 'true');
res.status(200).json({ pdf: pdf.downloadName });
} catch (error) {
this.logger.error('Could get invoice PDF:', error);
if (error instanceof PdfError) {
res.status(502).json('PDF Generator service failed.');
return;
}
res.status(500).json('Internal server error.');
}
}
/**
* DELETE /invoices/users/{id}
* @summary Delete invoice user defaults.
* @operationId deleteInvoiceUser
* @tags invoices - Operations of the invoices controller
* @security JWT
* @param {integer} id.path.required - The id of the invoice user to delete.
* @return {string} 404 - Invoice User not found
* @return 204 - Success
* @return {string} 500 - Internal server error
*/
public async deleteInvoiceUser(req: RequestWithToken, res: Response): Promise<void> {
const { id } = req.params;
const userId = parseInt(id, 10);
this.logger.trace('Delete Invoice User', id, 'by user', req.token.user);
try {
const invoiceUser = await InvoiceUser.findOne({ where: { userId } });
if (!invoiceUser) {
res.status(404).json('Invoice User not found.');
return;
}
await InvoiceUser.delete(userId);
res.status(204).json();
} catch (error) {
this.logger.error('Could not get invoice user:', error);
res.status(500).json('Internal server error.');
}
}
/**
* GET /invoices/users/{id}
* @summary Get invoice user defaults.
* @operationId getSingleInvoiceUser
* @tags invoices - Operations of the invoices controller
* @security JWT
* @param {integer} id.path.required - The id of the invoice user to return.
* @return {string} 404 - Invoice User not found
* @return {string} 404 - User not found
* @return {string} 400 - User is not of type INVOICE
* @return {InvoiceUserResponse} 200 - The requested Invoice User
* @return {string} 500 - Internal server error
*/
public async getSingleInvoiceUser(req: RequestWithToken, res: Response): Promise<void> {
const { id } = req.params;
const userId = parseInt(id, 10);
this.logger.trace('Get Invoice User', id, 'by user', req.token.user);
try {
const user = await User.findOne({ where: { id: userId, deleted: false } });
if (!user) {
res.status(404).json('User not found.');
return;
}
if (user.type !== UserType.INVOICE) {
res.status(400).json(`User is of type ${UserType[user.type]} and not of type INVOICE.`);
return;
}
const invoiceUser = await InvoiceUser.findOne({ where: { userId }, relations: ['user'] });
if (!invoiceUser) {
res.status(404).json('Invoice User not found.');
return;
}
res.status(200).json(parseInvoiceUserToResponse(invoiceUser));
} catch (error) {
this.logger.error('Could not get invoice user:', error);
res.status(500).json('Internal server error.');
}
}
/**
* PUT /invoices/users/{id}
* @summary Update or create invoice user defaults.
* @operationId putInvoiceUser
* @tags invoices - Operations of the invoices controller
* @security JWT
* @param {integer} id.path.required - The id of the user to update
* @param {UpdateInvoiceUserRequest} request.body.required - The invoice user which should be updated
* @return {string} 404 - User not found
* @return {string} 400 - User is not of type INVOICE
* @return {InvoiceUserResponse} 200 - The updated / created Invoice User
* @return {string} 500 - Internal server error
*/
public async updateInvoiceUser(req: RequestWithToken, res: Response): Promise<void> {
const { id } = req.params;
const body = req.body as UpdateInvoiceUserRequest;
const userId = parseInt(id, 10);
this.logger.trace('Update Invoice User', id, 'by user', req.token.user);
try {
const user = await User.findOne({ where: { id: userId, deleted: false } });
if (!user) {
res.status(404).json('User not found.');
return;
}
if (!([UserType.INVOICE, UserType.ORGAN].includes(user.type))) {
res.status(400).json(`User is of type ${UserType[user.type]} and not of type INVOICE or ORGAN.`);
return;
}
let invoiceUser = Object.assign(new InvoiceUser(), {
...body,
user,
}) as InvoiceUser;
invoiceUser = await InvoiceUser.save(invoiceUser);
res.status(200).json(parseInvoiceUserToResponse(invoiceUser));
} catch (error) {
this.logger.error('Could not update invoice user:', error);
res.status(500).json('Internal server error.');
}
}
/**
* GET /invoices/eligible-transactions
* @summary Get eligible transactions for invoice creation.
* @operationId getEligibleTransactions
* @tags invoices - Operations of the invoices controller
* @security JWT
* @param {integer} forId.query.required - Filter on Id of the debtor
* @param {string} fromDate.query.required - Start date for selected transactions (inclusive)
* @param {string} tillDate.query - End date for selected transactions (exclusive)
* @return {TransactionResponse} 200 - The eligible transactions
* @return {string} 500 - Internal server error
*/
public async getEligibleTransactions(req: RequestWithToken, res: Response): Promise<void> {
this.logger.trace('Get eligible transactions for invoice creation', req.query, 'by user', req.token.user);
let fromDate, tillDate;
let forId;
try {
forId = asNumber(req.query.forId);
fromDate = asDate(req.query.fromDate);
tillDate = req.query.tillDate ? asDate(req.query.tillDate) : undefined;
} catch (e) {
res.status(400).send(e.message);
return;
}
try {
const transactions = await new InvoiceService().getTransactionsForInvoice({
forId,
fromDate,
tillDate,
});
res.json(transactions);
} catch (error) {
this.logger.error('Could not get eligible transactions:', error);
res.status(500).json('Internal server error.');
}
}
/**
* Function to determine which credentials are needed to get invoice
* all if user is not connected to invoice
* own if user is connected to invoice
* @param req
* @return whether invoice is connected to used token
*/
static async getRelation(req: RequestWithToken): Promise<string> {
const invoice: Invoice = await Invoice.findOne({ where: { id: parseInt(req.params.id, 10) }, relations: ['to'] });
if (!invoice) return 'all';
if (invoice.to.id === req.token.user.id) return 'own';
return 'all';
}
}