@stamhoofd/models 2.152.0 → 2.153.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/factories/UserFactory.d.ts +1 -0
- package/dist/factories/UserFactory.d.ts.map +1 -1
- package/dist/factories/UserFactory.js +3 -1
- package/dist/factories/UserFactory.js.map +1 -1
- package/dist/helpers/Handlebars.d.ts.map +1 -1
- package/dist/helpers/Handlebars.js +2 -10
- package/dist/helpers/Handlebars.js.map +1 -1
- package/dist/helpers/countDays.d.ts +5 -0
- package/dist/helpers/countDays.d.ts.map +1 -0
- package/dist/helpers/countDays.js +15 -0
- package/dist/helpers/countDays.js.map +1 -0
- package/dist/migrations/1788509800-invoiced-balance-items-details.sql +5 -0
- package/dist/migrations/1788900000-document-parent-id.sql +2 -0
- package/dist/models/Document.d.ts +4 -0
- package/dist/models/Document.d.ts.map +1 -1
- package/dist/models/Document.js +7 -0
- package/dist/models/Document.js.map +1 -1
- package/dist/models/DocumentTemplate.d.ts +66 -3
- package/dist/models/DocumentTemplate.d.ts.map +1 -1
- package/dist/models/DocumentTemplate.js +234 -47
- package/dist/models/DocumentTemplate.js.map +1 -1
- package/dist/models/Invoice.d.ts.map +1 -1
- package/dist/models/Invoice.js +2 -2
- package/dist/models/Invoice.js.map +1 -1
- package/dist/models/InvoicedBalanceItem.d.ts +8 -0
- package/dist/models/InvoicedBalanceItem.d.ts.map +1 -1
- package/dist/models/InvoicedBalanceItem.js +21 -0
- package/dist/models/InvoicedBalanceItem.js.map +1 -1
- package/dist/models/Member.d.ts +2 -1
- package/dist/models/Member.d.ts.map +1 -1
- package/dist/models/Member.js +7 -1
- package/dist/models/Member.js.map +1 -1
- package/dist/tsconfig.test.tsbuildinfo +1 -0
- package/package.json +66 -66
- package/src/factories/UserFactory.ts +3 -1
- package/src/helpers/Handlebars.ts +2 -10
- package/src/helpers/countDays.ts +15 -0
- package/src/migrations/1788509800-invoiced-balance-items-details.sql +5 -0
- package/src/migrations/1788900000-document-parent-id.sql +2 -0
- package/src/models/Document.ts +6 -0
- package/src/models/DocumentTemplate.test.ts +75 -1
- package/src/models/DocumentTemplate.ts +295 -50
- package/src/models/Invoice.ts +2 -2
- package/src/models/InvoicedBalanceItem.ts +17 -0
- package/src/models/Member.ts +8 -1
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { column } from '@simonbackx/simple-database';
|
|
2
2
|
import { SimpleError } from '@simonbackx/simple-errors';
|
|
3
3
|
import { QueueHandler } from '@stamhoofd/queues';
|
|
4
|
-
import type { Parent, RecordAnswer } from '@stamhoofd/structures';
|
|
4
|
+
import type { MemberDetails, Parent, RecordAnswer } from '@stamhoofd/structures';
|
|
5
5
|
import { BalanceItemStatus, DocumentData, DocumentPrivateSettings, DocumentSettings, DocumentStatus, DocumentTemplatePrivate, GroupType, NationalRegisterNumberOptOut, RecordAddressAnswer, RecordAnswerDecoder, RecordDateAnswer, RecordPriceAnswer, RecordSettings, RecordTextAnswer, RecordType } from '@stamhoofd/structures';
|
|
6
6
|
import { Formatter, Sorter } from '@stamhoofd/utility';
|
|
7
7
|
import { v4 as uuidv4 } from 'uuid';
|
|
8
8
|
|
|
9
9
|
import { QueryableModel } from '@stamhoofd/sql';
|
|
10
|
+
import { countDays } from '../helpers/countDays.js';
|
|
10
11
|
import { BalanceItem } from './BalanceItem.js';
|
|
11
12
|
import { Document } from './Document.js';
|
|
12
13
|
import { Group } from './Group.js';
|
|
@@ -15,6 +16,64 @@ import { Member } from './Member.js';
|
|
|
15
16
|
import { Registration } from './Registration.js';
|
|
16
17
|
import { User } from './User.js';
|
|
17
18
|
|
|
19
|
+
export interface DocumentDebtor {
|
|
20
|
+
debtor: Parent;
|
|
21
|
+
missingData: boolean;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* One of the documents of a certificate that is split between multiple debtors
|
|
26
|
+
*/
|
|
27
|
+
export interface DocumentSplit {
|
|
28
|
+
debtor: DocumentDebtor;
|
|
29
|
+
count: number;
|
|
30
|
+
index: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
type RegistrationBalance = Awaited<ReturnType<typeof BalanceItem.getForRegistration>>;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The days a registration is certified for; `certifiedDays` is only set when that is less than the whole registration
|
|
37
|
+
*/
|
|
38
|
+
interface CertifiedPeriod {
|
|
39
|
+
startDate: Date | null;
|
|
40
|
+
endDate: Date | null;
|
|
41
|
+
certifiedDays: number | null;
|
|
42
|
+
totalDays: number | null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function roundToCent(price: number): number {
|
|
46
|
+
return Math.round(price / 100) * 100;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The family points at the parents whose name the certificate has to carry, so once any parent is
|
|
51
|
+
* marked we never fall back to a parent they did not choose - not even when that parent opted out
|
|
52
|
+
* of giving a national register number. Every marked parent receives their own document.
|
|
53
|
+
* Returns an empty list when the family has not answered at all.
|
|
54
|
+
*/
|
|
55
|
+
export function getTaxDependentDebtors(parents: Parent[]): DocumentDebtor[] {
|
|
56
|
+
return parents
|
|
57
|
+
.filter(p => p.isMemberTaxDependent === true)
|
|
58
|
+
.map(debtor => ({
|
|
59
|
+
debtor,
|
|
60
|
+
missingData: !debtor.nationalRegisterNumber || debtor.nationalRegisterNumber === NationalRegisterNumberOptOut,
|
|
61
|
+
}));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Splits an amount over `count` documents in whole cents (prices carry two extra decimals);
|
|
66
|
+
* the remaining cents and any sub-cent rest go to the first documents so the shares add up to the total.
|
|
67
|
+
*/
|
|
68
|
+
export function splitPrice(total: number, count: number, index: number): number {
|
|
69
|
+
const cent = 100;
|
|
70
|
+
const cents = Math.floor(total / cent);
|
|
71
|
+
const base = Math.floor(cents / count);
|
|
72
|
+
const remainder = cents - base * count;
|
|
73
|
+
const share = (base + (index < remainder ? 1 : 0)) * cent;
|
|
74
|
+
return index === 0 ? share + (total - cents * cent) : share;
|
|
75
|
+
}
|
|
76
|
+
|
|
18
77
|
export class DocumentTemplate extends QueryableModel {
|
|
19
78
|
static table = 'document_templates';
|
|
20
79
|
|
|
@@ -116,19 +175,117 @@ export class DocumentTemplate extends QueryableModel {
|
|
|
116
175
|
}
|
|
117
176
|
}
|
|
118
177
|
|
|
178
|
+
hasDebtorFields() {
|
|
179
|
+
return this.privateSettings.templateDefinition.documentFieldCategories.flatMap(c => c.getAllRecords()).some(s => s.id.startsWith('debtor.'));
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* The parents the certificate has to be issued to. Empty when the template has no debtor fields,
|
|
184
|
+
* multiple when the family marked more than one parent as having the member tax dependent.
|
|
185
|
+
*/
|
|
186
|
+
async getDebtors(registration: RegistrationWithMember, balanceItems: BalanceItem[]): Promise<DocumentDebtor[]> {
|
|
187
|
+
if (!this.hasDebtorFields()) {
|
|
188
|
+
return [];
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const parents = registration.member.details.parents;
|
|
192
|
+
const taxDependentDebtors = getTaxDependentDebtors(parents);
|
|
193
|
+
if (taxDependentDebtors.length > 0) {
|
|
194
|
+
return taxDependentDebtors;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const parentsWithNRN = parents.filter(p => p.nationalRegisterNumber !== NationalRegisterNumberOptOut && p.nationalRegisterNumber);
|
|
198
|
+
let debtor: Parent | undefined = parentsWithNRN[0] ?? parents[0];
|
|
199
|
+
if (parentsWithNRN.length > 1) {
|
|
200
|
+
for (const balanceItem of balanceItems) {
|
|
201
|
+
if (balanceItem && balanceItem.userId && balanceItem.priceOpen === 0 && balanceItem.status === BalanceItemStatus.Due) {
|
|
202
|
+
const user = await User.getByID(balanceItem.userId);
|
|
203
|
+
if (user) {
|
|
204
|
+
const parent = parentsWithNRN.find(p => p.hasEmail(user.email));
|
|
205
|
+
|
|
206
|
+
if (parent) {
|
|
207
|
+
debtor = parent;
|
|
208
|
+
break;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
if (!debtor.nationalRegisterNumber) {
|
|
212
|
+
const parent = parents.find(p => p.hasEmail(user.email));
|
|
213
|
+
if (parent) {
|
|
214
|
+
debtor = parent;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
return debtor ? [{ debtor, missingData: false }] : [];
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
private getMaxAgeFor(details: MemberDetails): number | null {
|
|
226
|
+
if (this.settings.maxAge === null) {
|
|
227
|
+
return null;
|
|
228
|
+
}
|
|
229
|
+
if (this.settings.maxAgeSevereDisability && details.severeDisability?.value) {
|
|
230
|
+
return this.settings.maxAgeSevereDisability;
|
|
231
|
+
}
|
|
232
|
+
return this.settings.maxAge;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* A certificate only covers the days the member is young enough: when the birthday that makes the member
|
|
237
|
+
* too old falls inside the registration, the certified period ends the day before that birthday.
|
|
238
|
+
*/
|
|
239
|
+
getCertifiedPeriod(registration: RegistrationWithMember, group: Group | undefined): CertifiedPeriod {
|
|
240
|
+
const startDate = registration.startDate ?? group?.settings?.startDate ?? null;
|
|
241
|
+
const endDate = registration.endDate ?? group?.settings?.endDate ?? null;
|
|
242
|
+
const untrimmed: CertifiedPeriod = { startDate, endDate, certifiedDays: null, totalDays: null };
|
|
243
|
+
|
|
244
|
+
const maxAge = this.getMaxAgeFor(registration.member.details);
|
|
245
|
+
const birthDay = registration.member.details.birthDay;
|
|
246
|
+
if (maxAge === null || !birthDay || !startDate || !endDate) {
|
|
247
|
+
return untrimmed;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const tooOldFrom = Formatter.luxon(birthDay).plus({ years: maxAge + 1 }).startOf('day');
|
|
251
|
+
if (tooOldFrom <= Formatter.luxon(startDate).startOf('day') || tooOldFrom > Formatter.luxon(endDate).startOf('day')) {
|
|
252
|
+
return untrimmed;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const lastDay = tooOldFrom.minus({ days: 1 });
|
|
256
|
+
const certifiedEndDate = Formatter.luxon(endDate).set({ year: lastDay.year, month: lastDay.month, day: lastDay.day }).toJSDate();
|
|
257
|
+
return {
|
|
258
|
+
startDate,
|
|
259
|
+
endDate: certifiedEndDate,
|
|
260
|
+
certifiedDays: countDays(startDate, certifiedEndDate),
|
|
261
|
+
totalDays: countDays(startDate, endDate),
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
|
|
119
265
|
/**
|
|
120
|
-
* Returns the default answers for a given registration
|
|
266
|
+
* Returns the default answers for a given registration. With a split, the prices are the share of that debtor.
|
|
121
267
|
*/
|
|
122
|
-
async buildAnswers(registration: RegistrationWithMember): Promise<{ fieldAnswers: Map<string, RecordAnswer>; missingData: boolean }> {
|
|
268
|
+
async buildAnswers(registration: RegistrationWithMember, options: { balance?: RegistrationBalance; debtors?: DocumentDebtor[]; split?: DocumentSplit } = {}): Promise<{ fieldAnswers: Map<string, RecordAnswer>; missingData: boolean }> {
|
|
123
269
|
const fieldAnswers = new Map<string, RecordAnswer>();
|
|
124
270
|
let missingData = false;
|
|
125
271
|
|
|
126
272
|
const group = 'group' in registration ? registration.group as Group : await Group.getByID(registration.groupId);
|
|
127
|
-
const { items: balanceItems, payments } = await BalanceItem.getForRegistration(registration.id, this.organizationId);
|
|
273
|
+
const { items: balanceItems, payments } = options.balance ?? await BalanceItem.getForRegistration(registration.id, this.organizationId);
|
|
128
274
|
|
|
129
275
|
const paidAtDates = payments.flatMap(p => p.paidAt ? [p.paidAt?.getTime()] : []);
|
|
130
|
-
|
|
131
|
-
|
|
276
|
+
let totalPrice = balanceItems.reduce((sum, item) => sum + (item.priceOpen + item.pricePaid + item.pricePending), 0);
|
|
277
|
+
let totalPricePaid = balanceItems.reduce((sum, item) => sum + item.pricePaid, 0);
|
|
278
|
+
|
|
279
|
+
// A trimmed period keeps the daily rate, so the certified amount shrinks with the days
|
|
280
|
+
const period = this.getCertifiedPeriod(registration, group);
|
|
281
|
+
if (period.certifiedDays !== null && period.totalDays !== null && period.totalDays > 0) {
|
|
282
|
+
totalPrice = roundToCent(totalPrice / period.totalDays) * period.certifiedDays;
|
|
283
|
+
totalPricePaid = Math.min(totalPricePaid, totalPrice);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const split = options.split;
|
|
287
|
+
const price = split ? splitPrice(totalPrice, split.count, split.index) : totalPrice;
|
|
288
|
+
const pricePaid = split ? splitPrice(totalPricePaid, split.count, split.index) : totalPricePaid;
|
|
132
289
|
|
|
133
290
|
// We take the minimum date here, because there is a highter change of later paymetns to be for other things than the registration itself
|
|
134
291
|
const paidAt = paidAtDates.length ? new Date(Math.min(...paidAtDates)) : null;
|
|
@@ -154,14 +311,14 @@ export class DocumentTemplate extends QueryableModel {
|
|
|
154
311
|
id: 'registration.startDate',
|
|
155
312
|
type: RecordType.Date,
|
|
156
313
|
}), // settings will be overwritten
|
|
157
|
-
dateValue:
|
|
314
|
+
dateValue: period.startDate,
|
|
158
315
|
}),
|
|
159
316
|
'registration.endDate': RecordDateAnswer.create({
|
|
160
317
|
settings: RecordSettings.create({
|
|
161
318
|
id: 'registration.endDate',
|
|
162
319
|
type: RecordType.Date,
|
|
163
320
|
}), // settings will be overwritten
|
|
164
|
-
dateValue:
|
|
321
|
+
dateValue: period.endDate,
|
|
165
322
|
}),
|
|
166
323
|
'registration.price':
|
|
167
324
|
RecordPriceAnswer.create({
|
|
@@ -171,23 +328,23 @@ export class DocumentTemplate extends QueryableModel {
|
|
|
171
328
|
}), // settings will be overwritten
|
|
172
329
|
value: price,
|
|
173
330
|
}),
|
|
174
|
-
// This one is duplicated in case it got disabled (we need to use it to check if document is included)
|
|
331
|
+
// This one is duplicated in case it got disabled (we need to use it to check if document is included), so it is never split
|
|
175
332
|
'registration.priceOriginal':
|
|
176
333
|
RecordPriceAnswer.create({
|
|
177
334
|
settings: RecordSettings.create({
|
|
178
335
|
id: 'registration.priceOriginal',
|
|
179
336
|
type: RecordType.Price,
|
|
180
337
|
}), // settings will be overwritten
|
|
181
|
-
value:
|
|
338
|
+
value: totalPrice,
|
|
182
339
|
}),
|
|
183
|
-
// This one is duplicated in case it got disabled (we need to use it to check if document is included)
|
|
340
|
+
// This one is duplicated in case it got disabled (we need to use it to check if document is included), so it is never split
|
|
184
341
|
'registration.pricePaidOriginal':
|
|
185
342
|
RecordPriceAnswer.create({
|
|
186
343
|
settings: RecordSettings.create({
|
|
187
344
|
id: 'registration.pricePaidOriginal',
|
|
188
345
|
type: RecordType.Price,
|
|
189
346
|
}), // settings will be overwritten
|
|
190
|
-
value:
|
|
347
|
+
value: totalPricePaid,
|
|
191
348
|
}),
|
|
192
349
|
'registration.pricePaid':
|
|
193
350
|
RecordPriceAnswer.create({
|
|
@@ -273,32 +430,13 @@ export class DocumentTemplate extends QueryableModel {
|
|
|
273
430
|
};
|
|
274
431
|
|
|
275
432
|
const allRecords = this.privateSettings.templateDefinition.documentFieldCategories.flatMap(c => c.getAllRecords());
|
|
276
|
-
const hasDebtor = allRecords.find(s => s.id.startsWith('debtor.'));
|
|
277
|
-
|
|
278
|
-
if (hasDebtor) {
|
|
279
|
-
const parentsWithNRN = registration.member.details.parents.filter(p => p.nationalRegisterNumber !== NationalRegisterNumberOptOut && p.nationalRegisterNumber);
|
|
280
|
-
let debtor: Parent | undefined = parentsWithNRN[0] ?? registration.member.details.parents[0];
|
|
281
|
-
if (parentsWithNRN.length > 1) {
|
|
282
|
-
for (const balanceItem of balanceItems) {
|
|
283
|
-
if (balanceItem && balanceItem.userId && balanceItem.priceOpen === 0 && balanceItem.status === BalanceItemStatus.Due) {
|
|
284
|
-
const user = await User.getByID(balanceItem.userId);
|
|
285
|
-
if (user) {
|
|
286
|
-
const parent = parentsWithNRN.find(p => p.hasEmail(user.email));
|
|
287
433
|
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
}
|
|
434
|
+
if (this.hasDebtorFields()) {
|
|
435
|
+
const documentDebtor = split ? split.debtor : (options.debtors ?? await this.getDebtors(registration, balanceItems))[0];
|
|
436
|
+
const debtor = documentDebtor?.debtor;
|
|
292
437
|
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
if (parent) {
|
|
296
|
-
debtor = parent;
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
}
|
|
438
|
+
if (documentDebtor?.missingData) {
|
|
439
|
+
missingData = true;
|
|
302
440
|
}
|
|
303
441
|
|
|
304
442
|
Object.assign(defaultData, {
|
|
@@ -482,7 +620,9 @@ export class DocumentTemplate extends QueryableModel {
|
|
|
482
620
|
return [];
|
|
483
621
|
}
|
|
484
622
|
|
|
485
|
-
const
|
|
623
|
+
const balance = await BalanceItem.getForRegistration(registration.id, this.organizationId);
|
|
624
|
+
const debtors = await this.getDebtors(registration, balance.items);
|
|
625
|
+
const { fieldAnswers, missingData } = await this.buildAnswers(registration, { balance, debtors });
|
|
486
626
|
|
|
487
627
|
if (!this.checkAnswersIncluded(registration, fieldAnswers)) {
|
|
488
628
|
for (const document of existingDocuments) {
|
|
@@ -494,11 +634,32 @@ export class DocumentTemplate extends QueryableModel {
|
|
|
494
634
|
const group = 'group' in registration ? registration.group as Group : await Group.getByID(registration.groupId);
|
|
495
635
|
const description = `${registration.member.details.name}, ${group ? group.settings.name.toString() : ''}${group && group.settings.period && group.type === GroupType.Membership ? ' ' + group.settings.period?.nameShort : ''}`;
|
|
496
636
|
|
|
497
|
-
|
|
498
|
-
|
|
637
|
+
const activeDocuments = existingDocuments.filter(d => d.status !== DocumentStatus.Deleted);
|
|
638
|
+
const manualDocuments = activeDocuments.filter(d => d.parentId === null);
|
|
639
|
+
const splitDocuments = activeDocuments.filter(d => d.parentId !== null);
|
|
640
|
+
|
|
641
|
+
// Multiple documents without a parent were split by hand (duplicated in the dashboard): never touch those
|
|
642
|
+
if (debtors.length >= 2 && manualDocuments.length < 2) {
|
|
643
|
+
return await this.updateSplitDocuments(registration, { balance, debtors, existingDocuments, splitDocuments, manualDocuments, unsplitAnswers: fieldAnswers, description });
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
// Merge documents that were split before, by keeping the one of the remaining debtor
|
|
647
|
+
const keep = splitDocuments.length > 0 ? this.pickDocumentToKeep(splitDocuments, debtors[0]?.debtor.id ?? null) : null;
|
|
648
|
+
const documents: Document[] = [];
|
|
649
|
+
for (const document of existingDocuments) {
|
|
650
|
+
if (document.parentId !== null && document.status !== DocumentStatus.Deleted && document !== keep) {
|
|
651
|
+
await this.removeDocument(document);
|
|
652
|
+
continue;
|
|
653
|
+
}
|
|
654
|
+
documents.push(document);
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
if (documents.length > 0) {
|
|
658
|
+
for (const document of documents) {
|
|
659
|
+
document.parentId = null;
|
|
499
660
|
await this.updateDocumentWithAnswers(document, fieldAnswers);
|
|
500
661
|
document.data.name = this.settings.name;
|
|
501
|
-
if (
|
|
662
|
+
if (documents.length === 1) {
|
|
502
663
|
document.data.description = description;
|
|
503
664
|
}
|
|
504
665
|
if (document.status === DocumentStatus.Draft || document.status === DocumentStatus.Published) {
|
|
@@ -506,9 +667,73 @@ export class DocumentTemplate extends QueryableModel {
|
|
|
506
667
|
}
|
|
507
668
|
await document.save();
|
|
508
669
|
}
|
|
509
|
-
return
|
|
670
|
+
return documents;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
return [await this.createDocument(registration, { fieldAnswers, missingData, description, parentId: null })];
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
/**
|
|
677
|
+
* One document per debtor, each with its share of the price
|
|
678
|
+
*/
|
|
679
|
+
private async updateSplitDocuments(registration: RegistrationWithMember, { balance, debtors, existingDocuments, splitDocuments, manualDocuments, unsplitAnswers, description }: { balance: RegistrationBalance; debtors: DocumentDebtor[]; existingDocuments: Document[]; splitDocuments: Document[]; manualDocuments: Document[]; unsplitAnswers: Map<string, RecordAnswer>; description: string }): Promise<Document[]> {
|
|
680
|
+
const documents: Document[] = [];
|
|
681
|
+
|
|
682
|
+
// The document from before the split is kept for the first debtor, so it keeps its number
|
|
683
|
+
const claimable = splitDocuments.length === 0 && manualDocuments.length === 1 ? manualDocuments[0] : null;
|
|
684
|
+
const unmatched = new Set(splitDocuments);
|
|
685
|
+
|
|
686
|
+
for (const [index, debtor] of debtors.entries()) {
|
|
687
|
+
const split: DocumentSplit = { debtor, count: debtors.length, index };
|
|
688
|
+
const { fieldAnswers, missingData } = await this.buildAnswers(registration, { balance, split });
|
|
689
|
+
const splitDescription = `${description} (${debtor.debtor.name})`;
|
|
690
|
+
|
|
691
|
+
const document = splitDocuments.find(d => d.parentId === debtor.debtor.id) ?? (index === 0 ? claimable : null);
|
|
692
|
+
if (!document) {
|
|
693
|
+
documents.push(await this.createDocument(registration, { fieldAnswers, missingData, description: splitDescription, parentId: debtor.debtor.id }));
|
|
694
|
+
continue;
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
unmatched.delete(document);
|
|
698
|
+
document.parentId = debtor.debtor.id;
|
|
699
|
+
await this.updateDocumentWithAnswers(document, fieldAnswers);
|
|
700
|
+
document.data.name = this.settings.name;
|
|
701
|
+
document.data.description = splitDescription;
|
|
702
|
+
if (document.status === DocumentStatus.Draft || document.status === DocumentStatus.Published) {
|
|
703
|
+
document.status = this.status;
|
|
704
|
+
}
|
|
705
|
+
await document.save();
|
|
706
|
+
documents.push(document);
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
for (const document of unmatched) {
|
|
710
|
+
await this.removeDocument(document);
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
// Documents created by hand keep the answers of an unsplit certificate, their own edits win because they are reviewed
|
|
714
|
+
for (const document of existingDocuments) {
|
|
715
|
+
if (documents.includes(document) || unmatched.has(document)) {
|
|
716
|
+
continue;
|
|
717
|
+
}
|
|
718
|
+
await this.updateDocumentWithAnswers(document, unsplitAnswers);
|
|
719
|
+
document.data.name = this.settings.name;
|
|
720
|
+
if (document.status === DocumentStatus.Draft || document.status === DocumentStatus.Published) {
|
|
721
|
+
document.status = this.status;
|
|
722
|
+
}
|
|
723
|
+
await document.save();
|
|
724
|
+
documents.push(document);
|
|
510
725
|
}
|
|
511
726
|
|
|
727
|
+
return documents;
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
private pickDocumentToKeep(splitDocuments: Document[], parentId: string | null): Document {
|
|
731
|
+
return splitDocuments.find(d => d.parentId === parentId)
|
|
732
|
+
?? splitDocuments.find(d => d.number !== null)
|
|
733
|
+
?? [...splitDocuments].sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime())[0];
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
private async createDocument(registration: RegistrationWithMember, { fieldAnswers, missingData, description, parentId }: { fieldAnswers: Map<string, RecordAnswer>; missingData: boolean; description: string; parentId: string | null }): Promise<Document> {
|
|
512
737
|
const document = new Document();
|
|
513
738
|
document.organizationId = this.organizationId;
|
|
514
739
|
document.templateId = this.id;
|
|
@@ -520,8 +745,26 @@ export class DocumentTemplate extends QueryableModel {
|
|
|
520
745
|
});
|
|
521
746
|
document.memberId = registration.member.id;
|
|
522
747
|
document.registrationId = registration.id;
|
|
748
|
+
document.parentId = parentId;
|
|
749
|
+
await document.save();
|
|
750
|
+
return document;
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
/**
|
|
754
|
+
* Same rule as buildAll: a document that already received a number stays visible as deleted
|
|
755
|
+
*/
|
|
756
|
+
private async removeDocument(document: Document) {
|
|
757
|
+
if (document.isLocked) {
|
|
758
|
+
return;
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
if (document.number === null) {
|
|
762
|
+
await document.delete();
|
|
763
|
+
return;
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
document.status = DocumentStatus.Deleted;
|
|
523
767
|
await document.save();
|
|
524
|
-
return [document];
|
|
525
768
|
}
|
|
526
769
|
|
|
527
770
|
checkRegistrationIncluded(registration: Registration) {
|
|
@@ -558,19 +801,16 @@ export class DocumentTemplate extends QueryableModel {
|
|
|
558
801
|
}
|
|
559
802
|
|
|
560
803
|
if (startDate) {
|
|
561
|
-
|
|
804
|
+
// ageOnDate reads the local calendar day, so hand it the Brussels day the registration starts on
|
|
805
|
+
const startDay = Formatter.luxon(startDate);
|
|
806
|
+
const age = registration.member.details.ageOnDate(new Date(startDay.year, startDay.month - 1, startDay.day));
|
|
562
807
|
|
|
563
808
|
if (age === null) {
|
|
564
809
|
console.warn('Missing member age checking maxAge');
|
|
565
810
|
return false;
|
|
566
811
|
}
|
|
567
812
|
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
if (this.settings.maxAgeSevereDisability && registration.member.details.severeDisability?.value) {
|
|
571
|
-
maxAge = this.settings.maxAgeSevereDisability;
|
|
572
|
-
}
|
|
573
|
-
if (age > maxAge) {
|
|
813
|
+
if (age > this.getMaxAgeFor(registration.member.details)!) {
|
|
574
814
|
return false;
|
|
575
815
|
}
|
|
576
816
|
} else {
|
|
@@ -770,7 +1010,12 @@ export class DocumentTemplate extends QueryableModel {
|
|
|
770
1010
|
}
|
|
771
1011
|
|
|
772
1012
|
async updateDocumentFor(document: Document, registration: RegistrationWithMember) {
|
|
773
|
-
const
|
|
1013
|
+
const balance = await BalanceItem.getForRegistration(registration.id, this.organizationId);
|
|
1014
|
+
const debtors = await this.getDebtors(registration, balance.items);
|
|
1015
|
+
const index = document.parentId === null ? -1 : debtors.findIndex(d => d.debtor.id === document.parentId);
|
|
1016
|
+
const split: DocumentSplit | undefined = debtors.length >= 2 && index !== -1 ? { debtor: debtors[index], count: debtors.length, index } : undefined;
|
|
1017
|
+
|
|
1018
|
+
const { fieldAnswers } = await this.buildAnswers(registration, { balance, debtors, split });
|
|
774
1019
|
await this.updateDocumentWithAnswers(document, fieldAnswers);
|
|
775
1020
|
}
|
|
776
1021
|
}
|
package/src/models/Invoice.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { column } from '@simonbackx/simple-database';
|
|
2
|
-
import { Company, File, PaymentCustomer, VATSubtotal } from '@stamhoofd/structures';
|
|
2
|
+
import { Company, File, InvoicedBalanceItem as InvoicedBalanceItemStruct, PaymentCustomer, VATSubtotal } from '@stamhoofd/structures';
|
|
3
3
|
import { v4 as uuidv4 } from 'uuid';
|
|
4
4
|
|
|
5
5
|
import { ArrayDecoder } from '@simonbackx/simple-encoding';
|
|
@@ -160,7 +160,7 @@ export class Invoice extends QueryableModel {
|
|
|
160
160
|
return { invoicedBalanceItems: [] };
|
|
161
161
|
}
|
|
162
162
|
// Load all the related models from the database so we can build the structures
|
|
163
|
-
const invoicedBalanceItems = await InvoicedBalanceItem.select().where('invoiceId', invoices.map(i => i.id)).fetch();
|
|
163
|
+
const invoicedBalanceItems = InvoicedBalanceItemStruct.sort(await InvoicedBalanceItem.select().where('invoiceId', invoices.map(i => i.id)).fetch());
|
|
164
164
|
return { invoicedBalanceItems };
|
|
165
165
|
}
|
|
166
166
|
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import type { ManyToOneRelation } from '@simonbackx/simple-database';
|
|
2
2
|
import { column } from '@simonbackx/simple-database';
|
|
3
|
+
import { EnumDecoder, MapDecoder } from '@simonbackx/simple-encoding';
|
|
3
4
|
import { v4 as uuidv4 } from 'uuid';
|
|
4
5
|
|
|
5
6
|
import { QueryableModel } from '@stamhoofd/sql';
|
|
6
7
|
import type {Invoice} from './Invoice.js';
|
|
7
8
|
import type {BalanceItem} from './BalanceItem.js';
|
|
8
9
|
import type { VATExcemptReason } from '@stamhoofd/structures';
|
|
10
|
+
import { BalanceItemRelation, BalanceItemRelationType, BalanceItemType } from '@stamhoofd/structures';
|
|
9
11
|
|
|
10
12
|
/**
|
|
11
13
|
* Keeps track of all the created invoices of a balance item, which contains how many balance was invoiced (including VAT)
|
|
@@ -30,12 +32,27 @@ export class InvoicedBalanceItem extends QueryableModel {
|
|
|
30
32
|
@column({ type: 'string' })
|
|
31
33
|
balanceItemId: string;
|
|
32
34
|
|
|
35
|
+
@column({ type: 'string', decoder: new EnumDecoder(BalanceItemType) })
|
|
36
|
+
type = BalanceItemType.Other;
|
|
37
|
+
|
|
33
38
|
@column({ type: 'string' })
|
|
34
39
|
name = '';
|
|
35
40
|
|
|
36
41
|
@column({ type: 'string' })
|
|
37
42
|
description = '';
|
|
38
43
|
|
|
44
|
+
/**
|
|
45
|
+
* Copied from the balance item at the time of invoicing, so invoices can be ordered and grouped without loading the balance items.
|
|
46
|
+
*/
|
|
47
|
+
@column({ decoder: new MapDecoder(new EnumDecoder(BalanceItemRelationType), BalanceItemRelation), type: 'json' })
|
|
48
|
+
relations: Map<BalanceItemRelationType, BalanceItemRelation> = new Map();
|
|
49
|
+
|
|
50
|
+
@column({ type: 'datetime', nullable: true })
|
|
51
|
+
startDate: Date | null = null;
|
|
52
|
+
|
|
53
|
+
@column({ type: 'datetime', nullable: true })
|
|
54
|
+
endDate: Date | null = null;
|
|
55
|
+
|
|
39
56
|
/**
|
|
40
57
|
* Price of the balance that was actually invoiced. Always includes VAT.
|
|
41
58
|
*
|
package/src/models/Member.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { column, ManyToManyRelation, ManyToOneRelation, OneToManyRelation } from '@simonbackx/simple-database';
|
|
2
2
|
import { QueryableModel, SQL } from '@stamhoofd/sql';
|
|
3
|
-
import { MemberDetails, NationalRegisterNumberOptOut, RegistrationWithTinyMember, TinyMember } from '@stamhoofd/structures';
|
|
3
|
+
import { MemberDetails, NationalRegisterNumberOptOut, PlatformMembershipMemberDetails, RegistrationWithTinyMember, TinyMember } from '@stamhoofd/structures';
|
|
4
4
|
import { Formatter } from '@stamhoofd/utility';
|
|
5
5
|
import basex from 'base-x';
|
|
6
6
|
import crypto from 'crypto';
|
|
@@ -490,6 +490,13 @@ export class Member extends QueryableModel {
|
|
|
490
490
|
return this.getBlobByIds(...(await this.getMemberIdsForUser(user)));
|
|
491
491
|
}
|
|
492
492
|
|
|
493
|
+
getPlatformMembershipDetails() {
|
|
494
|
+
return PlatformMembershipMemberDetails.create({
|
|
495
|
+
...this,
|
|
496
|
+
birthDay: this.details.birthDay,
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
|
|
493
500
|
static getRegistrationWithTinyMemberStructure(registration: RegistrationWithMember & { group: Group }): RegistrationWithTinyMember {
|
|
494
501
|
return RegistrationWithTinyMember.create({
|
|
495
502
|
...registration.getStructure(),
|