-
Notifications
You must be signed in to change notification settings - Fork 3
/
invoice-request-spec.ts
170 lines (154 loc) · 6.03 KB
/
invoice-request-spec.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
/**
* 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/>.
*/
import { In } from 'typeorm';
import {
BaseInvoice, CreateInvoiceParams, CreateInvoiceRequest, UpdateInvoiceParams,
} from '../invoice-request';
import {
createArrayRule,
Specification,
toFail,
toPass,
validateSpecification,
ValidationError,
} from '../../../helpers/specification-validation';
import Transaction from '../../../entity/transactions/transaction';
import InvoiceEntryRequest from '../invoice-entry-request';
import { validOrUndefinedDate } from './duration-spec';
import stringSpec from './string-spec';
import { positiveNumber, userMustExist } from './general-validators';
import {
INVALID_INVOICE_ID,
INVALID_TRANSACTION_IDS,
INVALID_TRANSACTION_OWNER,
INVOICE_IS_DELETED,
SAME_INVOICE_STATE, SUBTRANSACTION_ALREADY_INVOICED,
} from './validation-errors';
import { InvoiceState } from '../../../entity/invoices/invoice-status';
import Invoice from '../../../entity/invoices/invoice';
/**
* Checks whether all the transactions exists and are credited to the debtor or sold in case of credit Invoice.
*/
async function validTransactionIds<T extends BaseInvoice>(p: T) {
if (!p.transactionIDs) return toPass(p);
const transactions = await Transaction.find({
where: { id: In(p.transactionIDs) },
relations: { from: true, subTransactions: { to: true, subTransactionRows: { debitInvoice: true, creditInvoice: true } } },
});
let notOwnedByUser = [];
if (p.isCreditInvoice) {
transactions.forEach((t) => {
t.subTransactions.forEach((tSub) => {
if (tSub.to.id !== p.forId) notOwnedByUser.push(t);
});
});
} else {
notOwnedByUser.push(...transactions.filter((t) => t.from.id !== p.forId));
}
if (notOwnedByUser.length !== 0) return toFail(INVALID_TRANSACTION_OWNER());
if (transactions.length !== p.transactionIDs.length) return toFail(INVALID_TRANSACTION_IDS());
const alreadyInvoiced: number[] = [];
transactions.forEach((t) => {
t.subTransactions.forEach((tSub) => {
tSub.subTransactionRows.forEach((tSubRow) => {
if (!p.isCreditInvoice && tSubRow.debitInvoice !== null) alreadyInvoiced.push(tSubRow.id);
if (p.isCreditInvoice && tSubRow.creditInvoice !== null) alreadyInvoiced.push(tSubRow.id);
});
});
});
if (alreadyInvoiced.length !== 0) return toFail(SUBTRANSACTION_ALREADY_INVOICED(alreadyInvoiced));
return toPass(p);
}
/**
* Validates that Invoice exists and is not of state DELETED.
* @param p
*/
async function existsAndNotDeleted<T extends UpdateInvoiceParams>(p: T) {
const base: Invoice = await Invoice.findOne({ where: { id: p.invoiceId }, relations: ['latestStatus'] });
if (!base) return toFail(INVALID_INVOICE_ID());
if (base.latestStatus.state === InvoiceState.DELETED) {
return toFail(INVOICE_IS_DELETED());
}
return toPass(p);
}
/**
* Validates that the state of the update request is different than the current state.
* @param p
*/
async function differentState<T extends UpdateInvoiceParams>(p: T) {
if (!p.state) return toPass(p);
const base: Invoice = await Invoice.findOne({ where: { id: p.invoiceId }, relations: ['latestStatus'] });
if (base.latestStatus.state === p.state) {
return toFail(SAME_INVOICE_STATE());
}
return toPass(p);
}
/**
* Specification for an InvoiceEntryRequest.
*/
const invoiceEntryRequestSpec: () => Specification<InvoiceEntryRequest, ValidationError> = () => [
[[positiveNumber], 'amount', new ValidationError('amount:')],
[stringSpec(), 'description', new ValidationError('description:')],
];
/**
* Specification for an InvoiceRequest
*/
function baseInvoiceRequestSpec<T extends BaseInvoice>(): Specification<T, ValidationError> {
return [
validTransactionIds,
[[userMustExist], 'forId', new ValidationError('forId:')],
[[validOrUndefinedDate], 'fromDate', new ValidationError('fromDate:')],
[stringSpec(), 'description', new ValidationError('description:')],
// We have only defined a single item rule, so we use this to apply it to an array,
[[createArrayRule(invoiceEntryRequestSpec())], 'customEntries', new ValidationError('Custom entries:')],
];
}
/**
* Specification for an UpdateInvoiceParams
*/
const updateInvoiceRequestSpec: Specification<UpdateInvoiceParams, ValidationError> = [
[stringSpec(), 'description', new ValidationError('description:')],
differentState,
existsAndNotDeleted,
];
/**
* Specification for an CreateInvoiceParams
*/
const createInvoiceRequestSpec: () => Specification<CreateInvoiceParams, ValidationError> = () => [
...baseInvoiceRequestSpec<CreateInvoiceParams>(),
[[userMustExist], 'byId', new ValidationError('byId:')],
[stringSpec(), 'street', new ValidationError('street:')],
[stringSpec(), 'postalCode', new ValidationError('postalCode:')],
[stringSpec(), 'city', new ValidationError('city:')],
[stringSpec(), 'country', new ValidationError('country:')],
[stringSpec(), 'reference', new ValidationError('reference:')],
];
export default async function verifyCreateInvoiceRequest(
createInvoiceRequest: CreateInvoiceRequest,
) {
return Promise.resolve(await validateSpecification(
createInvoiceRequest, createInvoiceRequestSpec(),
));
}
export async function verifyUpdateInvoiceRequest(
updateInvoiceRequest: UpdateInvoiceParams,
) {
return Promise.resolve(await validateSpecification(
updateInvoiceRequest, updateInvoiceRequestSpec,
));
}