-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathinvoice-service.ts
557 lines (493 loc) · 19.5 KB
/
invoice-service.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
549
550
551
552
553
554
555
556
557
/**
* SudoSOS back-end API service.
* Copyright (C) 2020 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/>.
*/
import { FindManyOptions, FindOptionsRelationByString, FindOptionsWhere, In } from 'typeorm';
import dinero from 'dinero.js';
import InvoiceStatus, { InvoiceState } from '../entity/invoices/invoice-status';
import {
BaseInvoiceResponse,
InvoiceEntryResponse,
InvoiceResponse,
InvoiceStatusResponse,
PaginatedInvoiceResponse,
} from '../controller/response/invoice-response';
import QueryFilter, { FilterMapping } from '../helpers/query-filter';
import Invoice from '../entity/invoices/invoice';
import InvoiceEntry from '../entity/invoices/invoice-entry';
import { CreateInvoiceParams, UpdateInvoiceParams } from '../controller/request/invoice-request';
import Transaction from '../entity/transactions/transaction';
import TransferService from './transfer-service';
import TransferRequest from '../controller/request/transfer-request';
import TransactionService, { TransactionFilterParameters } from './transaction-service';
import { DineroObjectRequest } from '../controller/request/dinero-request';
import { TransferResponse } from '../controller/response/transfer-response';
import { BaseTransactionResponse } from '../controller/response/transaction-response';
import { RequestWithToken } from '../middleware/token-middleware';
import { asBoolean, asDate, asInvoiceState, asNumber } from '../helpers/validators';
import { PaginationParameters } from '../helpers/pagination';
import InvoiceEntryRequest from '../controller/request/invoice-entry-request';
import User from '../entity/user/user';
import DineroTransformer from '../entity/transformer/dinero-transformer';
import SubTransactionRow from '../entity/transactions/sub-transaction-row';
import { parseUserToBaseResponse } from '../helpers/revision-to-response';
import {
collectByToId,
collectProductsByRevision,
reduceMapToInvoiceEntries,
} from '../helpers/transaction-mapper';
import SubTransaction from '../entity/transactions/sub-transaction';
export interface InvoiceFilterParameters {
/**
* Filter based on to user.
*/
toId?: number;
/**
* Filter based on InvoiceId
*/
invoiceId?: number;
/**
* Filter based on the current invoice state
*/
currentState?: InvoiceState
/**
* Boolean if the invoice entries should be added to the response.
*/
returnInvoiceEntries?: boolean
/**
* Filter based on from date,
*/
fromDate?: Date,
/**
* Filter based on till date,
*/
tillDate?: Date
}
export function parseInvoiceFilterParameters(req: RequestWithToken): InvoiceFilterParameters {
return {
toId: asNumber(req.query.toId),
invoiceId: asNumber(req.query.invoiceId),
currentState: asInvoiceState(req.query.currentState),
returnInvoiceEntries: asBoolean(req.query.returnInvoiceEntries),
fromDate: asDate(req.query.fromDate),
tillDate: asDate(req.query.tillDate),
};
}
export default class InvoiceService {
/**
* Parses an InvoiceEntry Object to a InvoiceEntryResponse
* @param invoiceEntries - The invoiceEntries to parse
*/
private static asInvoiceEntryResponse(invoiceEntries: InvoiceEntry): InvoiceEntryResponse {
return {
description: invoiceEntries.description,
amount: invoiceEntries.amount,
priceInclVat: invoiceEntries.priceInclVat.toObject(),
vatPercentage: invoiceEntries.vatPercentage,
} as InvoiceEntryResponse;
}
/**
* Parses an invoiceStatus Object to a InvoiceStatusResponse
* @param invoiceStatus - The invoiceStatus to parse
*/
private static asInvoiceStatusResponse(invoiceStatus: InvoiceStatus): InvoiceStatusResponse {
return {
state: InvoiceState[invoiceStatus.state],
changedBy: parseUserToBaseResponse(invoiceStatus.changedBy, false),
} as InvoiceStatusResponse;
}
/**
* Parses an Invoice Object to a BaseInvoiceResponse
* @param invoice - The Invoice to parse
*/
private static asBaseInvoiceResponse(invoice: Invoice): BaseInvoiceResponse {
return {
id: invoice.id,
createdAt: invoice.createdAt.toISOString(),
updatedAt: invoice.updatedAt.toISOString(),
to: parseUserToBaseResponse(invoice.to, false),
addressee: invoice.addressee,
transfer: invoice.transfer ? TransferService.asTransferResponse(invoice.transfer) : undefined,
description: invoice.description,
currentState: InvoiceService.asInvoiceStatusResponse(
invoice.invoiceStatus[invoice.invoiceStatus.length - 1],
),
} as BaseInvoiceResponse;
}
/**
* Parses an Invoice Object to a InvoiceResponse
* @param invoice - The Invoice to parse
*/
public static asInvoiceResponse(invoice: Invoice)
: InvoiceResponse {
return {
...this.asBaseInvoiceResponse(invoice),
invoiceEntries: invoice.invoiceEntries
? invoice.invoiceEntries.map(this.asInvoiceEntryResponse) : [],
} as InvoiceResponse;
}
/**
* Creates a Transfer for an Invoice from TransactionResponses
* @param forId - The user which receives the Invoice/Transfer
* @param transactions - The array of transactions which to create the Transfer for
* @param isCreditInvoice - If the invoice is a credit Invoice
*/
public static async createTransferFromTransactions(forId: number,
transactions: BaseTransactionResponse[], isCreditInvoice: boolean): Promise<TransferResponse> {
const dineroObjectRequest: DineroObjectRequest = {
amount: 0,
currency: dinero.defaultCurrency,
precision: dinero.defaultPrecision,
};
if (transactions.length !== 0) {
transactions.forEach((t) => { dineroObjectRequest.amount += t.value.amount; });
}
// Credit Invoices
let fromId = 0;
let toId = forId;
if (isCreditInvoice) {
toId = 0;
fromId = forId;
}
const transferRequest: TransferRequest = {
amount: dineroObjectRequest,
description: 'Invoice Transfer',
fromId,
toId,
};
return TransferService.postTransfer(transferRequest);
}
/**
* Creates InvoiceEntries from an array of Transactions
* @param invoice - The invoice of which the entries are.
* @param subTransactions - Array of sub transactions to parse.
*/
public static async createInvoiceEntriesTransactions(invoice: Invoice,
subTransactions: SubTransaction[]) {
const subTransactionRows = subTransactions.reduce<SubTransactionRow[]>((acc, cur) => acc.concat(cur.subTransactionRows), []);
// Cumulative entries.
const entryMap = new Map<string, SubTransactionRow[]>();
subTransactionRows.forEach((tSubRow) => collectProductsByRevision(entryMap, tSubRow));
const invoiceEntries: InvoiceEntry[] = await reduceMapToInvoiceEntries(entryMap, invoice);
return invoiceEntries;
}
/**
* Adds custom entries to the invoice.
* @param invoice - The Invoice to append to
* @param customEntries - THe custom entries to append
*/
private static async AddCustomEntries(invoice: Invoice,
customEntries: InvoiceEntryRequest[]): Promise<void> {
const promises: Promise<InvoiceEntry>[] = [];
customEntries.forEach((request) => {
const { description, amount, vatPercentage } = request;
const entry = Object.assign(new InvoiceEntry(), {
invoice,
description,
amount,
priceInclVat: DineroTransformer.Instance.from(request.priceInclVat.amount),
vatPercentage,
});
promises.push(entry.save());
});
await Promise.all(promises);
}
static isState(invoice: Invoice, state: InvoiceState): boolean {
return (invoice.invoiceStatus[invoice.invoiceStatus.length - 1]
.state === state);
}
/**
* Deletes the given invoice and makes an undo transfer
* @param invoiceId
* @param byId
*/
public static async deleteInvoice(invoiceId: number, byId: number)
: Promise<BaseInvoiceResponse | undefined> {
// Find base invoice.
const invoice = await Invoice.findOne({ where: { id: invoiceId }, relations: ['to', 'invoiceStatus', 'transfer', 'transfer.to', 'transfer.from'] });
if (!invoice) return undefined;
await this.createTransfersInvoiceSellers(invoice, true);
// Extract amount from transfer
const amount: DineroObjectRequest = {
amount: invoice.transfer.amount.getAmount(),
currency: invoice.transfer.amount.getCurrency(),
precision: invoice.transfer.amount.getPrecision(),
};
// We create an undo transfer that sends the money back to the void.
const undoTransfer: TransferRequest = {
amount,
description: `Deletion of Invoice #${invoice.id}`,
fromId: invoice.to.id,
toId: 0,
};
await TransferService.postTransfer(undoTransfer);
// Create a new InvoiceStatus
const invoiceStatus: InvoiceStatus = Object.assign(new InvoiceStatus(), {
invoice,
changedBy: byId,
state: InvoiceState.DELETED,
});
// Unreference invoices.
const { records } = await TransactionService.getTransactions({ invoiceId: invoice.id });
const tIds: number[] = records.map((t) => t.id);
const promises: Promise<any>[] = [];
const transactions = await Transaction.find({ where: { id: In(tIds) }, relations: ['subTransactions', 'subTransactions.subTransactionRows', 'subTransactions.subTransactionRows.invoice'] });
transactions.forEach((t) => {
t.subTransactions.forEach((tSub) => {
tSub.subTransactionRows.forEach((tSubRow) => {
const row = tSubRow;
if (row.invoice.id === invoice.id) {
row.invoice = null;
}
promises.push(row.save());
});
});
});
await Promise.all(promises);
// Add it to the invoice and save it.
await invoice.save().then(async () => {
invoice.invoiceStatus.push(invoiceStatus);
await invoiceStatus.save();
});
return ((await this.getInvoices({ invoiceId: invoice.id }))).records[0];
}
/**
* When an Invoice is created we subtract the relevant balance from the sellers
* @param invoice
* @param deletion - If the Invoice is being deleted we add the money to the account
*/
public static async createTransfersInvoiceSellers(invoice: Invoice, deletion = false): Promise<BaseInvoiceResponse | undefined> {
// By marking an invoice as paid we subtract the money from the seller accounts.
if (!invoice) return undefined;
const toIdMap = new Map<number, SubTransaction[]>();
const baseTransactions = (await TransactionService.getTransactions({ invoiceId: invoice.id })).records;
const transactions = await TransactionService.getTransactionsFromBaseTransactions(baseTransactions, false);
// Collect SubTransactions per Seller
transactions.forEach((t) => {
t.subTransactions.forEach((tSub) => {
collectByToId(toIdMap, tSub);
});
});
const transferRequests: TransferRequest[] = [];
// For every seller involved in the Invoice
toIdMap.forEach((value, key) => {
const fromId = key;
let totalInclVat = 0;
// Collect value of transfer
value.forEach((tSub) => {
tSub.subTransactionRows.forEach((tSubRow) => {
totalInclVat += tSubRow.amount * tSubRow.product.priceInclVat.getAmount();
});
});
const description = (deletion ? 'Deletion' : 'Payment') + ` of Invoice #${invoice.id}`;
// Create transfer
const transferRequest: TransferRequest = {
amount: {
amount: totalInclVat,
precision: dinero.defaultPrecision,
currency: dinero.defaultCurrency,
},
description,
// Swapping the to and from based on if it is a deletion.
fromId: deletion ? 0 : fromId,
toId: deletion ? fromId : 0,
};
transferRequests.push(transferRequest);
});
await Promise.all(transferRequests.map((t) => TransferService.postTransfer(t)));
}
/**
* Updates the Invoice
*
* It is not possible to change the amount or details of the transfer itself.
*
* @param update
*/
public static async updateInvoice(update: UpdateInvoiceParams) {
const base: Invoice = await Invoice.findOne({ where: { id: update.invoiceId }, relations: ['invoiceStatus'] });
// Return undefined if base does not exist.
if (!base || this.isState(base, InvoiceState.DELETED) || this.isState(base, InvoiceState.PAID)) {
return undefined;
}
if (update.state) {
// Deleting is a special case of an update.
if (update.state === InvoiceState.DELETED) return this.deleteInvoice(base.id, update.byId);
const invoiceStatus: InvoiceStatus = Object.assign(new InvoiceStatus(), {
invoice: base,
changedBy: update.byId,
state: update.state,
});
// Add it to the invoice and save it.
await base.save().then(async () => {
base.invoiceStatus.push(invoiceStatus);
await invoiceStatus.save();
});
}
base.description = update.description;
base.addressee = update.addressee;
await base.save();
// Return the newly updated Invoice.
return (await this.getInvoices(
{ invoiceId: base.id, returnInvoiceEntries: false },
)).records[0];
}
static async getSubTransactionsInvoice(invoice: Invoice, transactions: BaseTransactionResponse[], isCreditInvoice: boolean) {
const ids = transactions.map((t) => t.id);
let where: FindOptionsWhere<SubTransaction> = {
transaction: { id: In(ids) },
};
// If we have a credit invoice we filter out all unrelated subTransactions.
if (isCreditInvoice) where.to = { id: invoice.toId };
return SubTransaction.find({ where, relations: ['transaction', 'to', 'subTransactionRows', 'subTransactionRows.invoice', 'subTransactionRows.product', 'subTransactionRows.product.product', 'subTransactionRows.product.vat'] });
}
/**
* Set a reference to an Invoice for all given sub Transactions.
* @param invoice
* @param subTransactions
* @param isCreditInvoice
*/
static async setSubTransactionInvoice(invoice: Invoice,
subTransactions: SubTransaction[]) {
const promises: Promise<any>[] = [];
subTransactions.forEach((tSub) => {
tSub.subTransactionRows.forEach((tSubRow) => {
const row = tSubRow;
row.invoice = invoice;
promises.push(SubTransactionRow.save(row));
});
});
await Promise.all(promises);
}
/**
* Returns the latest invoice sent to a User that is not deleted.
* @param toId
*/
static async getLatestValidInvoice(toId: number): Promise<BaseInvoiceResponse> {
const invoices = (await this.getInvoices({ toId })).records;
// Filter the deleted invoices
const validInvoices = invoices.filter(
(invoice) => invoice.currentState.state !== InvoiceState[InvoiceState.DELETED],
);
return validInvoices[validInvoices.length - 1];
}
/**
* Creates an Invoice from an CreateInvoiceRequest
* @param invoiceRequest - The Invoice request to create
*/
public static async createInvoice(invoiceRequest: CreateInvoiceParams)
: Promise<InvoiceResponse> {
const { forId, byId, isCreditInvoice } = invoiceRequest;
let params: TransactionFilterParameters;
const user = await User.findOne({ where: { id: forId } });
// If transactions are specified.
if (invoiceRequest.transactionIDs) {
params = { transactionId: invoiceRequest.transactionIDs };
} else if (invoiceRequest.fromDate) {
params = { fromDate: asDate(invoiceRequest.fromDate) };
} else {
// By default we create an Invoice from all transactions since last invoice.
const latestInvoice = await this.getLatestValidInvoice(forId);
let date;
// If no invoice exists we use the time when the account was created.
if (latestInvoice) {
date = latestInvoice.createdAt;
} else {
date = user.createdAt;
}
params = { fromDate: new Date(date) };
}
if (isCreditInvoice) {
params.toId = user.id;
} else {
params.fromId = user.id;
}
const transactions = (await TransactionService.getTransactions(params, {})).records;
const transfer = await this.createTransferFromTransactions(forId, transactions, isCreditInvoice);
// Create a new Invoice
const newInvoice: Invoice = Object.assign(new Invoice(), {
toId: forId,
transfer: transfer.id,
addressee: invoiceRequest.addressee,
invoiceStatus: [],
invoiceEntries: [],
description: invoiceRequest.description,
});
// Create a new InvoiceStatus
const invoiceStatus: InvoiceStatus = Object.assign(new InvoiceStatus(), {
invoice: newInvoice,
changedBy: byId,
state: InvoiceState.CREATED,
});
// First save the Invoice, then the status.
await Invoice.save(newInvoice).then(async () => {
newInvoice.invoiceStatus.push(invoiceStatus);
await InvoiceStatus.save(invoiceStatus);
const subTransactions = await this.getSubTransactionsInvoice(newInvoice, transactions, isCreditInvoice);
await this.setSubTransactionInvoice(newInvoice, subTransactions);
await this.createInvoiceEntriesTransactions(newInvoice, subTransactions);
if (invoiceRequest.customEntries) {
await this.AddCustomEntries(newInvoice, invoiceRequest.customEntries);
}
if (!isCreditInvoice) {
await this.createTransfersInvoiceSellers(newInvoice);
}
});
// Return the newly created Invoice.
return (await this.getInvoices(
{ invoiceId: newInvoice.id, returnInvoiceEntries: true },
)).records[0] as InvoiceResponse;
}
/**
* Function that returns all the invoices based on the given params.
* Returns either BaseInvoiceResponse, that is without InvoiceEntries, or InvoiceResponse
* based on if returnInvoiceEntries is set to true.
* @param params - The filter params to apply
* @param pagination - The pagination params to apply
*/
public static async getInvoices(params: InvoiceFilterParameters = {},
pagination: PaginationParameters = {})
: Promise<PaginatedInvoiceResponse> {
const { take, skip } = pagination;
const filterMapping: FilterMapping = {
currentState: 'currentState',
toId: 'toId',
invoiceId: 'id',
};
const relations: FindOptionsRelationByString = ['to', 'invoiceStatus', 'transfer', 'transfer.to', 'transfer.from'];
const options: FindManyOptions<Invoice> = {
where: QueryFilter.createFilterWhereClause(filterMapping, params),
order: { createdAt: 'ASC' },
skip,
};
let records: (BaseInvoiceResponse | InvoiceResponse)[];
// Case distinction on if we want to return entries or not.
if (!params.returnInvoiceEntries) {
const invoices = await Invoice.find({ ...options, relations, take });
records = invoices.map(this.asBaseInvoiceResponse);
} else {
relations.push('invoiceEntries');
const invoices = await Invoice.find({ ...options, relations, take });
records = invoices.map(this.asInvoiceResponse.bind(this));
}
const count = await Invoice.count(options);
return {
_pagination: {
take, skip, count,
},
records,
};
}
}