@endora-commerce/mod-invoices 0.109.0 → 0.110.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/admin/templates/invoice-puck-config.d.ts.map +1 -1
- package/dist/admin/templates/invoice-puck-config.js +220 -135
- package/dist/admin/templates/invoice-puck-config.js.map +1 -1
- package/dist/backend/entities/invoice-line.entity.d.ts +18 -1
- package/dist/backend/entities/invoice-line.entity.d.ts.map +1 -1
- package/dist/backend/entities/invoice-line.entity.js +20 -0
- package/dist/backend/entities/invoice-line.entity.js.map +1 -1
- package/dist/backend/index.d.ts.map +1 -1
- package/dist/backend/index.js +19 -3
- package/dist/backend/index.js.map +1 -1
- package/dist/backend/invoices-prose.d.ts +2 -0
- package/dist/backend/invoices-prose.d.ts.map +1 -1
- package/dist/backend/invoices-prose.js +2 -0
- package/dist/backend/invoices-prose.js.map +1 -1
- package/dist/backend/pdf-components/embed-logo-images.d.ts.map +1 -1
- package/dist/backend/pdf-components/embed-logo-images.js +2 -15
- package/dist/backend/pdf-components/embed-logo-images.js.map +1 -1
- package/dist/backend/pdf-components/sections.d.ts.map +1 -1
- package/dist/backend/pdf-components/sections.js +3 -1
- package/dist/backend/pdf-components/sections.js.map +1 -1
- package/dist/backend/plugin.d.ts.map +1 -1
- package/dist/backend/plugin.js +2 -1
- package/dist/backend/plugin.js.map +1 -1
- package/dist/backend/routes.customer.d.ts +3 -3
- package/dist/backend/routes.customer.d.ts.map +1 -1
- package/dist/backend/routes.customer.js +17 -9
- package/dist/backend/routes.customer.js.map +1 -1
- package/dist/backend/seeds/generic-invoice-template.d.ts +13 -7
- package/dist/backend/seeds/generic-invoice-template.d.ts.map +1 -1
- package/dist/backend/seeds/generic-invoice-template.js +34 -22
- package/dist/backend/seeds/generic-invoice-template.js.map +1 -1
- package/dist/backend/services/auto-issue-reactor.d.ts.map +1 -1
- package/dist/backend/services/auto-issue-reactor.js +6 -2
- package/dist/backend/services/auto-issue-reactor.js.map +1 -1
- package/dist/backend/services/corrective-invoice.d.ts +167 -16
- package/dist/backend/services/corrective-invoice.d.ts.map +1 -1
- package/dist/backend/services/corrective-invoice.js +389 -52
- package/dist/backend/services/corrective-invoice.js.map +1 -1
- package/dist/backend/services/invoice-copy-host.service.d.ts.map +1 -1
- package/dist/backend/services/invoice-copy-host.service.js +3 -0
- package/dist/backend/services/invoice-copy-host.service.js.map +1 -1
- package/dist/backend/services/invoice-line-builder.d.ts +4 -0
- package/dist/backend/services/invoice-line-builder.d.ts.map +1 -1
- package/dist/backend/services/invoice-line-builder.js +1 -0
- package/dist/backend/services/invoice-line-builder.js.map +1 -1
- package/dist/backend/services/invoice-service.d.ts +27 -4
- package/dist/backend/services/invoice-service.d.ts.map +1 -1
- package/dist/backend/services/invoice-service.js +69 -12
- package/dist/backend/services/invoice-service.js.map +1 -1
- package/dist/backend/services/kept-quantities.d.ts +24 -0
- package/dist/backend/services/kept-quantities.d.ts.map +1 -0
- package/dist/backend/services/kept-quantities.js +32 -0
- package/dist/backend/services/kept-quantities.js.map +1 -0
- package/dist/backend/services/order-returns-lock.d.ts +19 -0
- package/dist/backend/services/order-returns-lock.d.ts.map +1 -0
- package/dist/backend/services/order-returns-lock.js +37 -0
- package/dist/backend/services/order-returns-lock.js.map +1 -0
- package/dist/manifest.d.ts +9 -3
- package/dist/manifest.d.ts.map +1 -1
- package/dist/migrations/20261108T073244_invoices_invoice_line_kind.d.ts +21 -0
- package/dist/migrations/20261108T073244_invoices_invoice_line_kind.d.ts.map +1 -0
- package/dist/migrations/20261108T073244_invoices_invoice_line_kind.js +28 -0
- package/dist/migrations/20261108T073244_invoices_invoice_line_kind.js.map +1 -0
- package/dist/migrations/index.d.ts +2 -1
- package/dist/migrations/index.d.ts.map +1 -1
- package/dist/migrations/index.js +3 -1
- package/dist/migrations/index.js.map +1 -1
- package/docs/invoices.md +89 -3
- package/i18n/en.json +5 -2
- package/i18n/pl.json +5 -2
- package/package.json +15 -15
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { randomUUID } from 'crypto';
|
|
2
|
-
import { ERROR_CODES, compareDecimals, allocateHalfUp, decimalDifference, decimalProduct, moneyDifference, moneySum, netForGrossAtRate, netFromGrossHalfUp, quotientHalfUp, roundHalfUp, } from '@endora-commerce/contracts';
|
|
2
|
+
import { ERROR_CODES, compareDecimals, allocateHalfUp, decimalDifference, decimalProduct, lineAmountHalfUp, moneyDifference, moneySum, netForGrossAtRate, netFromGrossHalfUp, quotientHalfUp, roundHalfUp, } from '@endora-commerce/contracts';
|
|
3
3
|
import { HttpError } from '@endora-commerce/platform/http';
|
|
4
4
|
import { Invoice } from '../entities/invoice.entity.js';
|
|
5
5
|
import { InvoiceLine } from '../entities/invoice-line.entity.js';
|
|
6
6
|
import { shouldHoldForVendorNumber, } from './vendor-number-hold.js';
|
|
7
7
|
import { rethrowIfModuleDisabled } from '@endora-commerce/platform/kernel';
|
|
8
8
|
import { refuseDuplicateInvoiceNumber } from './duplicate-number-refusal.js';
|
|
9
|
+
import { supportedLanguageOf } from '@endora-commerce/contracts';
|
|
10
|
+
import { INVOICE_RENDER_LANGUAGE } from '../document/invoice-document-type.js';
|
|
11
|
+
import { invoicesProse } from '../invoices-prose.js';
|
|
9
12
|
/** The smaller of two decimals. */
|
|
10
13
|
function minDecimal(a, b) {
|
|
11
14
|
return compareDecimals(a, b) <= 0 ? a : b;
|
|
@@ -21,10 +24,71 @@ export class CorrectionTotalExceedsLinesError extends Error {
|
|
|
21
24
|
this.name = 'CorrectionTotalExceedsLinesError';
|
|
22
25
|
}
|
|
23
26
|
}
|
|
27
|
+
/**
|
|
28
|
+
* A correction asked to credit more goods at one VAT rate than the invoice
|
|
29
|
+
* still charges at that rate (issue #885). Crediting it would take back more
|
|
30
|
+
* VAT than the rate charged.
|
|
31
|
+
*/
|
|
32
|
+
export class CorrectionExceedsRateRemainingError extends Error {
|
|
33
|
+
taxRate;
|
|
34
|
+
remaining;
|
|
35
|
+
constructor(taxRate, remaining) {
|
|
36
|
+
super(`The correction credits more at ${taxRate} VAT than the invoice still charges there, ${remaining}.`);
|
|
37
|
+
this.taxRate = taxRate;
|
|
38
|
+
this.remaining = remaining;
|
|
39
|
+
this.name = 'CorrectionExceedsRateRemainingError';
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* A correction asked to credit more of an order charge — the delivery or the
|
|
44
|
+
* payment surcharge — than the invoice still charges for it (issue #876).
|
|
45
|
+
*/
|
|
46
|
+
export class CorrectionExceedsChargeRemainingError extends Error {
|
|
47
|
+
kind;
|
|
48
|
+
remaining;
|
|
49
|
+
constructor(kind, remaining) {
|
|
50
|
+
super(`The correction credits more of the ${kind} than the invoice still charges for it, ${remaining}.`);
|
|
51
|
+
this.kind = kind;
|
|
52
|
+
this.remaining = remaining;
|
|
53
|
+
this.name = 'CorrectionExceedsChargeRemainingError';
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* On a correction, a goods line (one naming an order item) stored with
|
|
58
|
+
* quantity 0 is a price reduction (issue #885): its value changed, not its
|
|
59
|
+
* quantity. Corrections written before #885 never stored a goods line with
|
|
60
|
+
* quantity 0, so the rule holds for the whole history.
|
|
61
|
+
*/
|
|
62
|
+
export function isPriceReductionLine(l) {
|
|
63
|
+
return !!l.orderItemId && Number(l.quantity) === 0;
|
|
64
|
+
}
|
|
65
|
+
/** The units a correction line credits: none for a price reduction. */
|
|
66
|
+
export function creditedQuantity(l) {
|
|
67
|
+
return isPriceReductionLine(l) ? 0 : Number(l.quantity);
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The quantity a correction line is stored with: 0 for a price reduction, the
|
|
71
|
+
* returned quantity otherwise — and never 0 for returned goods, so a returned
|
|
72
|
+
* line is never read back as a price reduction.
|
|
73
|
+
*/
|
|
74
|
+
export function storedCorrectionQuantity(basis, quantity) {
|
|
75
|
+
return basis === 'price_reduction' ? 0 : quantity || 1;
|
|
76
|
+
}
|
|
77
|
+
const ZERO = '0.00';
|
|
78
|
+
/** `round(net × rate)`, the VAT `vatByRate` charges on a net at one rate. */
|
|
79
|
+
function vatAt(net, rate) {
|
|
80
|
+
return roundHalfUp(decimalProduct(net, rate));
|
|
81
|
+
}
|
|
82
|
+
/** `net` shared over `weights` in proportion, adding up to `net` exactly. */
|
|
83
|
+
function shareOut(net, weights) {
|
|
84
|
+
const sum = moneySum(weights, 6);
|
|
85
|
+
if (compareDecimals(sum, 0) === 0)
|
|
86
|
+
return weights.map(() => ZERO);
|
|
87
|
+
return allocateHalfUp(net, weights.map((w) => quotientHalfUp(decimalProduct(net, w), sum, 6)));
|
|
88
|
+
}
|
|
24
89
|
/**
|
|
25
90
|
* A correction's amounts, in exact decimal arithmetic, under the invoice's VAT
|
|
26
|
-
* method
|
|
27
|
-
* owner ruling of 2026-10-24, review of PR #423).
|
|
91
|
+
* method (issue #417, owner ruling of 2026-10-24, review of PR #423).
|
|
28
92
|
*
|
|
29
93
|
* The credited amount is gross (a return credits what was paid, tax included),
|
|
30
94
|
* capped at what remains of the invoice after earlier corrections (FR-020),
|
|
@@ -32,25 +96,62 @@ export class CorrectionTotalExceedsLinesError extends Error {
|
|
|
32
96
|
* refused ({@link CorrectionTotalExceedsLinesError}) rather than booked as a
|
|
33
97
|
* net with no VAT and no line.
|
|
34
98
|
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
99
|
+
* **An invoice issued per rate** (issue #873) is corrected on what it keeps,
|
|
100
|
+
* rate by rate. Before the correction the invoice keeps `Nb` net and `Vb` VAT
|
|
101
|
+
* at a rate, `Gb` gross: its summary row less what earlier corrections credited
|
|
102
|
+
* there. The correction credits `G` gross at the rate. Its goods lines leave
|
|
103
|
+
* each invoiced line with a kept quantity — the invoiced quantity less every
|
|
104
|
+
* credited quantity, where a price reduction (issue #885) credits none — and
|
|
105
|
+
* the kept net `K` is those quantities at the invoiced unit prices.
|
|
106
|
+
* - **Quantity path**: when `Gb − G` is `K + round(K × rate)`, the refund is the
|
|
107
|
+
* default one; the invoice keeps `K` net and `round(K × rate)` VAT, exactly
|
|
108
|
+
* what `vatByRate` charges on the kept nets, and the correction credits the
|
|
109
|
+
* rest.
|
|
110
|
+
* - **Gross path** otherwise — an operator-reduced amount, a price reduction, a
|
|
111
|
+
* capped credit, an order placed before 0.108.0: the invoice keeps `Gb − G`
|
|
112
|
+
* gross. When a net has that gross under the rule, the invoice keeps it;
|
|
113
|
+
* otherwise, when one has `G`, the correction credits it; otherwise the
|
|
114
|
+
* invoice keeps the nearest (owner ruling E1, 2026-11-07: the money is exact,
|
|
115
|
+
* and what is left may be a cent off the rule until the next correction).
|
|
116
|
+
*
|
|
117
|
+
* In every case the credited VAT is `G` less the credited net, which lies
|
|
118
|
+
* within `[0, G]` and never above `Nb`; a `G` above `Gb` is refused
|
|
119
|
+
* ({@link CorrectionExceedsRateRemainingError}). On the quantity path a rate's
|
|
120
|
+
* net is shared over its lines by what each line's kept net fell; otherwise in
|
|
121
|
+
* proportion to their gross.
|
|
122
|
+
*
|
|
123
|
+
* **An invoice issued before 0.108.0** is credited line by line, cumulatively:
|
|
124
|
+
* the invoiced line net in proportion to the cumulative gross, less the nets
|
|
125
|
+
* earlier corrections credited.
|
|
126
|
+
*
|
|
127
|
+
* An order-level discount the goods carried is credited back as a negative
|
|
128
|
+
* 0 % amount. A price-reduction line carries none.
|
|
44
129
|
*/
|
|
45
130
|
export function correctionAmounts(input) {
|
|
46
|
-
|
|
131
|
+
// Issue #876 — the order charges first: each is credited in full at the rate
|
|
132
|
+
// of the invoice line that charged it, and never above what that line still
|
|
133
|
+
// charges. The goods share what is left of the total and of the invoice.
|
|
134
|
+
const chargeLines = (input.charges ?? [])
|
|
135
|
+
.filter((c) => compareDecimals(c.amount, 0) > 0)
|
|
136
|
+
.map((c) => {
|
|
137
|
+
const gross = roundHalfUp(c.amount);
|
|
138
|
+
if (compareDecimals(gross, c.remaining) > 0)
|
|
139
|
+
throw new CorrectionExceedsChargeRemainingError(c.kind, roundHalfUp(c.remaining));
|
|
140
|
+
const rate = roundHalfUp(c.rate, 4);
|
|
141
|
+
const net = compareDecimals(rate, 0) === 0 ? gross : netFromGrossHalfUp(gross, rate, 'fraction');
|
|
142
|
+
return { kind: c.kind, gross, net, rate };
|
|
143
|
+
});
|
|
144
|
+
const chargesTotal = moneySum(chargeLines.map((c) => c.gross));
|
|
145
|
+
const asked = input.lines.map((l) => (compareDecimals(l.amount, 0) < 0 ? ZERO : roundHalfUp(l.amount)));
|
|
47
146
|
const linesTotal = moneySum(asked);
|
|
48
|
-
const total = roundHalfUp(input.total);
|
|
147
|
+
const total = moneyDifference(roundHalfUp(input.total), chargesTotal);
|
|
49
148
|
if (compareDecimals(total, linesTotal) > 0)
|
|
50
|
-
throw new CorrectionTotalExceedsLinesError(total, linesTotal);
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
const
|
|
149
|
+
throw new CorrectionTotalExceedsLinesError(roundHalfUp(input.total), moneySum([linesTotal, chargesTotal]));
|
|
150
|
+
if (compareDecimals(total, 0) < 0)
|
|
151
|
+
throw new CorrectionTotalExceedsLinesError(roundHalfUp(input.total), chargesTotal);
|
|
152
|
+
const remainingOfInvoice = moneyDifference(moneyDifference(input.originalGross, input.creditedBefore ?? '0'), chargesTotal);
|
|
153
|
+
const credited = compareDecimals(remainingOfInvoice, 0) <= 0 ? ZERO : minDecimal(total, remainingOfInvoice);
|
|
154
|
+
const discounts = input.lines.map((l) => l.discount === undefined || compareDecimals(l.discount, 0) <= 0 ? ZERO : roundHalfUp(l.discount));
|
|
54
155
|
// An order-level discount (issue #417, review of PR #423): the invoice charged
|
|
55
156
|
// the goods at their full value and the discount on a 0 % line of its own, so
|
|
56
157
|
// the goods are credited at `amount + discount` and the discount comes back as
|
|
@@ -72,8 +173,10 @@ export function correctionAmounts(input) {
|
|
|
72
173
|
remaining = roundHalfUp(decimalDifference(remaining, gross));
|
|
73
174
|
return gross;
|
|
74
175
|
});
|
|
75
|
-
const discountCredit = withDiscount ? moneyDifference('0', moneySum(discounts)) :
|
|
76
|
-
const
|
|
176
|
+
const discountCredit = withDiscount ? moneyDifference('0', moneySum(discounts)) : ZERO;
|
|
177
|
+
const isReduction = (i) => input.lines[i].basis === 'price_reduction';
|
|
178
|
+
const rateOf = (rate) => roundHalfUp(rate, 4);
|
|
179
|
+
const groupOf = (l) => (input.perRate ? rateOf(l.rate) : l.orderItemId);
|
|
77
180
|
const byGroup = new Map();
|
|
78
181
|
input.lines.forEach((l, i) => {
|
|
79
182
|
const group = groupOf(l);
|
|
@@ -83,43 +186,121 @@ export function correctionAmounts(input) {
|
|
|
83
186
|
else
|
|
84
187
|
byGroup.set(group, [i]);
|
|
85
188
|
});
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
const
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
189
|
+
// What the invoice invoiced and earlier corrections credited, per order item.
|
|
190
|
+
const invoiced = new Map();
|
|
191
|
+
for (const o of input.originalLines) {
|
|
192
|
+
const cur = invoiced.get(o.orderItemId);
|
|
193
|
+
if (cur) {
|
|
194
|
+
cur.quantity += o.quantity;
|
|
195
|
+
cur.net.push(o.net);
|
|
196
|
+
}
|
|
197
|
+
else {
|
|
198
|
+
invoiced.set(o.orderItemId, { quantity: o.quantity, net: [o.net], unitNetPrice: o.unitNetPrice });
|
|
199
|
+
}
|
|
93
200
|
}
|
|
94
|
-
const
|
|
201
|
+
const creditedBeforeOf = (orderItemId) => {
|
|
202
|
+
const lines = input.earlierLines.filter((e) => e.orderItemId === orderItemId);
|
|
203
|
+
return { quantity: lines.reduce((a, e) => a + creditedQuantity(e), 0), net: moneySum(lines.map((e) => e.net)) };
|
|
204
|
+
};
|
|
205
|
+
const nets = input.lines.map(() => ZERO);
|
|
206
|
+
const paths = {};
|
|
95
207
|
for (const [group, indexes] of byGroup) {
|
|
96
208
|
const gross = moneySum(indexes.map((i) => grosses[i]));
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
let cumulativeNet;
|
|
209
|
+
let net;
|
|
210
|
+
let weights = indexes.map((i) => grosses[i]);
|
|
100
211
|
if (input.perRate) {
|
|
101
|
-
|
|
212
|
+
const rate = group;
|
|
213
|
+
const zeroRate = compareDecimals(rate, 0) === 0;
|
|
214
|
+
const goods = input.originalLines.filter((o) => rateOf(o.rate) === rate);
|
|
215
|
+
const row = zeroRate ? undefined : input.originalSummary?.find((r) => rateOf(r.taxRate) === rate);
|
|
216
|
+
// The invoice's own figures at the rate. At 0 % its row also holds the
|
|
217
|
+
// delivery, the surcharge and the discount, so the goods are summed.
|
|
218
|
+
const n0 = row ? roundHalfUp(row.netTotal) : moneySum(goods.map((o) => o.net));
|
|
219
|
+
const v0 = row ? roundHalfUp(row.vatAmount) : zeroRate ? ZERO : vatAt(n0, rate);
|
|
220
|
+
const before = input.earlierLines.filter((e) => rateOf(e.rate) === rate);
|
|
221
|
+
const nb = moneyDifference(n0, moneySum(before.map((e) => e.net)));
|
|
222
|
+
const vb = moneyDifference(v0, moneySum(before.map((e) => moneyDifference(e.gross, e.net))));
|
|
223
|
+
const gb = moneySum([nb, vb]);
|
|
224
|
+
// Nothing credited at the rate is never refused, whatever an earlier
|
|
225
|
+
// correction left there.
|
|
226
|
+
if (compareDecimals(gross, 0) > 0 && compareDecimals(gross, gb) > 0) {
|
|
227
|
+
throw new CorrectionExceedsRateRemainingError(rate, gb);
|
|
228
|
+
}
|
|
229
|
+
// The kept state after this correction: each invoiced line's kept
|
|
230
|
+
// quantity at its invoiced unit price, untouched when none came back.
|
|
231
|
+
const keptAfter = new Map();
|
|
232
|
+
for (const id of new Set(goods.map((o) => o.orderItemId))) {
|
|
233
|
+
const inv = invoiced.get(id);
|
|
234
|
+
const returnedNow = indexes
|
|
235
|
+
.filter((i) => input.lines[i].orderItemId === id && !isReduction(i))
|
|
236
|
+
.reduce((a, i) => a + input.lines[i].quantity, 0);
|
|
237
|
+
const q = Math.max(0, inv.quantity - creditedBeforeOf(id).quantity - returnedNow);
|
|
238
|
+
keptAfter.set(id, q === inv.quantity ? moneySum(inv.net) : lineAmountHalfUp(inv.unitNetPrice, q));
|
|
239
|
+
}
|
|
240
|
+
const k = moneySum([...keptAfter.values()]);
|
|
241
|
+
const after = moneyDifference(gb, gross);
|
|
242
|
+
if (compareDecimals(after, moneySum([k, vatAt(k, rate)])) === 0) {
|
|
243
|
+
paths[rate] = 'quantity';
|
|
244
|
+
net = moneyDifference(nb, k);
|
|
245
|
+
// Each line's share: what its kept net fell by, split by quantity
|
|
246
|
+
// among entries naming the same item. Exact when the history was all
|
|
247
|
+
// on this path; a price reduction in the history may leave a weight
|
|
248
|
+
// that is not, and then the gross shares are used.
|
|
249
|
+
const fell = indexes.map((i) => {
|
|
250
|
+
const id = input.lines[i].orderItemId;
|
|
251
|
+
const remBefore = moneyDifference(moneySum(invoiced.get(id)?.net ?? []), creditedBeforeOf(id).net);
|
|
252
|
+
const drop = moneyDifference(remBefore, keptAfter.get(id) ?? ZERO);
|
|
253
|
+
const same = indexes.filter((j) => input.lines[j].orderItemId === id);
|
|
254
|
+
const units = same.reduce((a, j) => a + input.lines[j].quantity, 0);
|
|
255
|
+
return units > 0 ? quotientHalfUp(decimalProduct(drop, input.lines[i].quantity), units, 6) : ZERO;
|
|
256
|
+
});
|
|
257
|
+
if (!indexes.some(isReduction) &&
|
|
258
|
+
fell.every((w) => compareDecimals(w, 0) >= 0) &&
|
|
259
|
+
fell.some((w) => compareDecimals(w, 0) > 0)) {
|
|
260
|
+
weights = fell;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
else {
|
|
264
|
+
const keeps = netForGrossAtRate(after, rate, 'fraction');
|
|
265
|
+
const credits = netForGrossAtRate(gross, rate, 'fraction');
|
|
266
|
+
if (keeps.exact) {
|
|
267
|
+
paths[rate] = 'gross';
|
|
268
|
+
net = moneyDifference(nb, keeps.net);
|
|
269
|
+
}
|
|
270
|
+
else if (credits.exact) {
|
|
271
|
+
paths[rate] = 'gross_credit';
|
|
272
|
+
net = credits.net;
|
|
273
|
+
}
|
|
274
|
+
else {
|
|
275
|
+
paths[rate] = 'gross_nearest';
|
|
276
|
+
net = moneyDifference(nb, keeps.net);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
if (compareDecimals(net, nb) > 0)
|
|
280
|
+
net = nb;
|
|
102
281
|
}
|
|
103
282
|
else {
|
|
283
|
+
const before = input.earlierLines.filter((e) => e.orderItemId === group);
|
|
284
|
+
const cumulativeGross = moneySum([...before.map((e) => e.gross), gross]);
|
|
104
285
|
const original = input.originalLines.find((o) => o.orderItemId === group);
|
|
105
|
-
cumulativeNet =
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
286
|
+
const cumulativeNet = original && compareDecimals(original.gross, 0) > 0
|
|
287
|
+
? quotientHalfUp(decimalProduct(original.net, cumulativeGross), original.gross)
|
|
288
|
+
: netFromGrossHalfUp(cumulativeGross, input.lines[indexes[0]].rate, 'fraction');
|
|
289
|
+
net = moneyDifference(cumulativeNet, moneySum(before.map((e) => e.net)));
|
|
109
290
|
}
|
|
110
|
-
let net = moneyDifference(cumulativeNet, moneySum(before.net));
|
|
111
291
|
if (compareDecimals(net, 0) < 0)
|
|
112
|
-
net =
|
|
292
|
+
net = ZERO;
|
|
113
293
|
if (compareDecimals(net, gross) > 0)
|
|
114
294
|
net = gross;
|
|
115
|
-
const shares = compareDecimals(gross, 0) === 0
|
|
116
|
-
? indexes.map(() => '0.00')
|
|
117
|
-
: allocateHalfUp(net, indexes.map((i) => quotientHalfUp(decimalProduct(net, grosses[i]), gross, 6)));
|
|
295
|
+
const shares = compareDecimals(gross, 0) === 0 ? indexes.map(() => ZERO) : shareOut(net, weights);
|
|
118
296
|
indexes.forEach((lineIndex, k) => {
|
|
119
297
|
nets[lineIndex] = shares[k];
|
|
120
298
|
});
|
|
121
299
|
}
|
|
122
|
-
const taxTotal = moneySum(
|
|
300
|
+
const taxTotal = moneySum([
|
|
301
|
+
...grosses.map((g, i) => moneyDifference(g, nets[i])),
|
|
302
|
+
...chargeLines.map((c) => moneyDifference(c.gross, c.net)),
|
|
303
|
+
]);
|
|
123
304
|
const rates = new Map();
|
|
124
305
|
const addToRate = (key, net, gross) => {
|
|
125
306
|
const sums = rates.get(key) ?? { net: [], gross: [] };
|
|
@@ -127,17 +308,25 @@ export function correctionAmounts(input) {
|
|
|
127
308
|
sums.gross.push(gross);
|
|
128
309
|
rates.set(key, sums);
|
|
129
310
|
};
|
|
130
|
-
input.lines.forEach((l, i) => addToRate(
|
|
311
|
+
input.lines.forEach((l, i) => addToRate(rateOf(l.rate), nets[i], grosses[i]));
|
|
131
312
|
if (compareDecimals(discountCredit, 0) !== 0)
|
|
132
313
|
addToRate('0.0000', discountCredit, discountCredit);
|
|
314
|
+
for (const c of chargeLines)
|
|
315
|
+
addToRate(c.rate, c.net, c.gross);
|
|
316
|
+
const creditedTotal = moneySum([credited, chargesTotal]);
|
|
133
317
|
return {
|
|
134
|
-
credited,
|
|
135
|
-
netTotal: roundHalfUp(decimalDifference(
|
|
318
|
+
credited: creditedTotal,
|
|
319
|
+
netTotal: roundHalfUp(decimalDifference(creditedTotal, taxTotal)),
|
|
136
320
|
taxTotal,
|
|
137
321
|
lines: input.lines.map((l, i) => ({
|
|
138
322
|
gross: grosses[i],
|
|
139
323
|
net: nets[i],
|
|
140
|
-
|
|
324
|
+
// A price reduction's unit price is the change in the line's unit net
|
|
325
|
+
// price over the units still on the invoice (issue #885): 3 × 10.0100
|
|
326
|
+
// reduced by 5.00 shows 1.6667. Informational, at four places.
|
|
327
|
+
unitNetPrice: isReduction(i)
|
|
328
|
+
? quotientHalfUp(nets[i], Math.max(1, (invoiced.get(l.orderItemId)?.quantity ?? 0) - creditedBeforeOf(l.orderItemId).quantity), 4)
|
|
329
|
+
: quotientHalfUp(nets[i], l.quantity || 1, 4),
|
|
141
330
|
})),
|
|
142
331
|
vatSummary: [...rates.entries()]
|
|
143
332
|
.sort((a, b) => compareDecimals(a[0], b[0]))
|
|
@@ -147,6 +336,37 @@ export function correctionAmounts(input) {
|
|
|
147
336
|
return { taxRate, netTotal, vatAmount: moneyDifference(grossTotal, netTotal), grossTotal };
|
|
148
337
|
}),
|
|
149
338
|
discountCredit,
|
|
339
|
+
paths,
|
|
340
|
+
chargeLines,
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* The invoice's delivery and payment-surcharge lines (issue #876), by
|
|
345
|
+
* `line_kind`. A line issued before #904 has none. Issuance has written the
|
|
346
|
+
* delivery before the surcharge, each a positive 0 % line naming no order item,
|
|
347
|
+
* since it first itemised them (`ee860569e`, "itemize delivery, payment
|
|
348
|
+
* surcharge, and discount as lines"), so with two such lines the first is the
|
|
349
|
+
* delivery and the second the surcharge. Only 0 % lines are matched (ruling Q3
|
|
350
|
+
* on PR #965): a positive line at another rate is no charge issuance wrote, so
|
|
351
|
+
* a credit asked of it is refused `no_corrected_line`. With one, it is whichever charge the order had — the settlement
|
|
352
|
+
* names only a charge that was paid, so it never asks for both — and it answers
|
|
353
|
+
* for either. On those invoices both are 0 % lines, so the rate a credit
|
|
354
|
+
* mirrors is the same either way.
|
|
355
|
+
*/
|
|
356
|
+
export function chargeLinesOf(lines) {
|
|
357
|
+
const delivery = lines.find((l) => l.lineKind === 'delivery');
|
|
358
|
+
const surcharge = lines.find((l) => l.lineKind === 'payment_surcharge');
|
|
359
|
+
if (delivery || surcharge || lines.some((l) => l.lineKind != null)) {
|
|
360
|
+
return { ...(delivery ? { delivery } : {}), ...(surcharge ? { payment_surcharge: surcharge } : {}) };
|
|
361
|
+
}
|
|
362
|
+
const legacy = lines
|
|
363
|
+
.filter((l) => !l.orderItemId && compareDecimals(l.grossValue, 0) > 0 && compareDecimals(l.taxRate, 0) === 0)
|
|
364
|
+
.sort((a, b) => a.ordinal - b.ordinal);
|
|
365
|
+
if (legacy.length === 1)
|
|
366
|
+
return { delivery: legacy[0], payment_surcharge: legacy[0] };
|
|
367
|
+
return {
|
|
368
|
+
...(legacy[0] ? { delivery: legacy[0] } : {}),
|
|
369
|
+
...(legacy[1] ? { payment_surcharge: legacy[1] } : {}),
|
|
150
370
|
};
|
|
151
371
|
}
|
|
152
372
|
/**
|
|
@@ -186,6 +406,7 @@ export class CorrectiveInvoiceProvider {
|
|
|
186
406
|
audit;
|
|
187
407
|
events;
|
|
188
408
|
ledgerRouting;
|
|
409
|
+
lineProse;
|
|
189
410
|
/**
|
|
190
411
|
* `numbers` is an accessor for the same reason `emFactory` is: the generator
|
|
191
412
|
* is a gated port, so resolving it is a question about `invoices`' effective
|
|
@@ -193,12 +414,21 @@ export class CorrectiveInvoiceProvider {
|
|
|
193
414
|
* resolved it while wiring this provider asked at boot, and an operator who
|
|
194
415
|
* had switched `invoices` off took the backend down with it.
|
|
195
416
|
*/
|
|
196
|
-
constructor(emFactory, numbers, audit, events, ledgerRouting
|
|
417
|
+
constructor(emFactory, numbers, audit, events, ledgerRouting,
|
|
418
|
+
/**
|
|
419
|
+
* The language a price-reduction line is named in, and this module's
|
|
420
|
+
* bundle to name it from (issue #885), as `InvoiceService` names the lines
|
|
421
|
+
* it itemises: the name is stored with the line, so it is written in the
|
|
422
|
+
* document's language, `INVOICE_RENDER_LANGUAGE`. Without a translator,
|
|
423
|
+
* English.
|
|
424
|
+
*/
|
|
425
|
+
lineProse = {}) {
|
|
197
426
|
this.emFactory = emFactory;
|
|
198
427
|
this.numbers = numbers;
|
|
199
428
|
this.audit = audit;
|
|
200
429
|
this.events = events;
|
|
201
430
|
this.ledgerRouting = ledgerRouting;
|
|
431
|
+
this.lineProse = lineProse;
|
|
202
432
|
}
|
|
203
433
|
/**
|
|
204
434
|
* Refuse, without writing anything, exactly what {@link createCorrection}
|
|
@@ -257,6 +487,13 @@ export class CorrectiveInvoiceProvider {
|
|
|
257
487
|
// Resolve every line before the transaction opens, so a line that cannot
|
|
258
488
|
// be mirrored refuses without having drawn a correction number.
|
|
259
489
|
const mirrored = input.lines.map((l) => mirrorFor(original, mirrorByOrderItem, l.orderItemId));
|
|
490
|
+
// A price reduction keeps the goods, and the order discount they carried
|
|
491
|
+
// with them (issue #885), so it credits none back. `returns` never sends
|
|
492
|
+
// one; a caller that does has misread the port.
|
|
493
|
+
const discounted = input.lines.find((l) => l.basis === 'price_reduction' && l.discount !== undefined && compareDecimals(l.discount, 0) > 0);
|
|
494
|
+
if (discounted) {
|
|
495
|
+
throw new HttpError(422, ERROR_CODES.VALIDATION_FAILED, 'A price reduction carries no discount: the buyer keeps the goods and the discount they carried.', { code: 'price_reduction_carries_discount', orderItemId: discounted.orderItemId });
|
|
496
|
+
}
|
|
260
497
|
// What earlier corrections of this invoice already credited: the cap and
|
|
261
498
|
// the cumulative rule both read it (review of PR #423).
|
|
262
499
|
// A cancelled correction credits nothing, so it is neither in the cap nor in
|
|
@@ -270,10 +507,39 @@ export class CorrectiveInvoiceProvider {
|
|
|
270
507
|
rate: l.taxRate,
|
|
271
508
|
net: l.netValue,
|
|
272
509
|
gross: l.grossValue,
|
|
510
|
+
// The kept quantities are read from these (issue #873); on an earlier
|
|
511
|
+
// correction, 0 is a price reduction and credits no unit (#885).
|
|
512
|
+
quantity: Number(l.quantity),
|
|
513
|
+
unitNetPrice: l.unitNetPrice,
|
|
273
514
|
});
|
|
274
515
|
// The invoice's own discount line: the discount credit mirrors its name and
|
|
275
516
|
// unit, and an invoice that itemized no discount credits none separately.
|
|
276
517
|
const discountLine = originalLines.find((l) => !l.orderItemId && compareDecimals(l.grossValue, 0) < 0);
|
|
518
|
+
// Issue #876 — the invoice's delivery and surcharge lines a consumer's
|
|
519
|
+
// withdrawal credits, each at its own rate and never above what it still
|
|
520
|
+
// charges after earlier corrections.
|
|
521
|
+
const chargeLineOf = chargeLinesOf(originalLines);
|
|
522
|
+
const charges = [
|
|
523
|
+
['delivery', input.charges?.delivery],
|
|
524
|
+
['payment_surcharge', input.charges?.surcharge],
|
|
525
|
+
].flatMap(([kind, amount]) => {
|
|
526
|
+
if (amount === undefined || compareDecimals(amount, 0) <= 0)
|
|
527
|
+
return [];
|
|
528
|
+
const charged = chargeLineOf[kind];
|
|
529
|
+
if (!charged) {
|
|
530
|
+
throw new HttpError(422, ERROR_CODES.VALIDATION_FAILED, 'The corrected charge has no line on the original invoice, so its VAT rate is unknown.', { code: 'no_corrected_line', chargeKind: kind, originalInvoiceId: original.id });
|
|
531
|
+
}
|
|
532
|
+
const creditedOfIt = earlierLines.filter((l) => l.lineKind === kind).map((l) => l.grossValue);
|
|
533
|
+
return [
|
|
534
|
+
{
|
|
535
|
+
kind,
|
|
536
|
+
amount,
|
|
537
|
+
rate: charged.taxRate,
|
|
538
|
+
remaining: moneyDifference(charged.grossValue, moneySum(creditedOfIt)),
|
|
539
|
+
line: charged,
|
|
540
|
+
},
|
|
541
|
+
];
|
|
542
|
+
});
|
|
277
543
|
let amounts;
|
|
278
544
|
try {
|
|
279
545
|
amounts = correctionAmounts({
|
|
@@ -282,6 +548,7 @@ export class CorrectiveInvoiceProvider {
|
|
|
282
548
|
creditedBefore: moneySum(earlierCorrections.map((c) => c.total)),
|
|
283
549
|
// Issued under the per-rate method exactly when it stored its summary.
|
|
284
550
|
perRate: original.vatSummary != null,
|
|
551
|
+
originalSummary: original.vatSummary ?? null,
|
|
285
552
|
// Goods lines only: a delivery, surcharge or discount line names no order
|
|
286
553
|
// item, and an earlier correction's discount credit is not goods.
|
|
287
554
|
originalLines: originalLines.filter((l) => l.orderItemId).map(asCredited),
|
|
@@ -292,10 +559,28 @@ export class CorrectiveInvoiceProvider {
|
|
|
292
559
|
quantity: l.quantity,
|
|
293
560
|
rate: mirrored[index].rate,
|
|
294
561
|
orderItemId: l.orderItemId,
|
|
562
|
+
basis: l.basis ?? 'returned_goods',
|
|
295
563
|
})),
|
|
564
|
+
charges: charges.map(({ kind, amount, rate, remaining }) => ({ kind, amount, rate, remaining })),
|
|
296
565
|
});
|
|
297
566
|
}
|
|
298
567
|
catch (err) {
|
|
568
|
+
if (err instanceof CorrectionExceedsChargeRemainingError) {
|
|
569
|
+
throw new HttpError(422, ERROR_CODES.VALIDATION_FAILED, err.message, {
|
|
570
|
+
code: 'correction_exceeds_charge_remaining',
|
|
571
|
+
chargeKind: err.kind,
|
|
572
|
+
remaining: err.remaining,
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
if (err instanceof CorrectionExceedsRateRemainingError) {
|
|
576
|
+
throw new HttpError(422, ERROR_CODES.VALIDATION_FAILED, err.message, {
|
|
577
|
+
code: 'correction_exceeds_rate_remaining',
|
|
578
|
+
taxRate: err.taxRate,
|
|
579
|
+
remaining: err.remaining,
|
|
580
|
+
// For the operator's sentence: 23, not 0.2300.
|
|
581
|
+
vatRatePercent: String(Number(decimalProduct(err.taxRate, 100))),
|
|
582
|
+
});
|
|
583
|
+
}
|
|
299
584
|
if (!(err instanceof CorrectionTotalExceedsLinesError))
|
|
300
585
|
throw err;
|
|
301
586
|
throw new HttpError(400, ERROR_CODES.VALIDATION_FAILED, err.message, {
|
|
@@ -304,16 +589,47 @@ export class CorrectiveInvoiceProvider {
|
|
|
304
589
|
linesTotal: err.linesTotal,
|
|
305
590
|
});
|
|
306
591
|
}
|
|
592
|
+
// One at a time, as `invoicesProseTable` reads the bundle.
|
|
593
|
+
const names = [];
|
|
594
|
+
for (const l of input.lines)
|
|
595
|
+
names.push(await this.#lineName(l, input.caseReference));
|
|
307
596
|
const snapshots = input.lines.map((l, index) => ({
|
|
308
597
|
ordinal: index + 1,
|
|
309
598
|
orderItemId: l.orderItemId,
|
|
310
|
-
name:
|
|
311
|
-
|
|
599
|
+
name: names[index],
|
|
600
|
+
// A price reduction is stored with quantity 0 (issue #885); returned
|
|
601
|
+
// goods keep their quantity, and never 0.
|
|
602
|
+
quantity: storedCorrectionQuantity(l.basis, l.quantity),
|
|
312
603
|
rate: roundHalfUp(mirrored[index].rate, 4),
|
|
313
604
|
unit: mirrored[index].unit,
|
|
314
605
|
...amounts.lines[index],
|
|
315
606
|
}));
|
|
316
|
-
|
|
607
|
+
// Each credited charge mirrors the name and the unit of the line it credits.
|
|
608
|
+
const chargeSnapshots = amounts.chargeLines.map((c) => {
|
|
609
|
+
const line = charges.find((x) => x.kind === c.kind).line;
|
|
610
|
+
return { ...c, name: line.name, unit: line.unit };
|
|
611
|
+
});
|
|
612
|
+
return { original, salesChannelId, amounts, snapshots, discountLine, chargeSnapshots };
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* A returned-goods line is named after its product. A price reduction is
|
|
616
|
+
* named as one, in the document's language, with the case it settles
|
|
617
|
+
* (issue #885): "Obniżka ceny (reklamacja RMA-…): Widget".
|
|
618
|
+
*/
|
|
619
|
+
async #lineName(line, caseReference) {
|
|
620
|
+
if (line.basis !== 'price_reduction')
|
|
621
|
+
return line.productName;
|
|
622
|
+
const language = this.lineProse.language ?? supportedLanguageOf(INVOICE_RENDER_LANGUAGE);
|
|
623
|
+
const name = caseReference
|
|
624
|
+
? await invoicesProse(this.lineProse.translate, 'lines.priceReduction', language, {
|
|
625
|
+
rma: caseReference,
|
|
626
|
+
product: line.productName,
|
|
627
|
+
})
|
|
628
|
+
: await invoicesProse(this.lineProse.translate, 'lines.priceReductionUnreferenced', language, {
|
|
629
|
+
product: line.productName,
|
|
630
|
+
});
|
|
631
|
+
// The column's width.
|
|
632
|
+
return name.slice(0, 512);
|
|
317
633
|
}
|
|
318
634
|
async createCorrection(input) {
|
|
319
635
|
const em = this.emFactory();
|
|
@@ -341,7 +657,7 @@ export class CorrectiveInvoiceProvider {
|
|
|
341
657
|
// No original, no correction (#135).
|
|
342
658
|
if (!plan)
|
|
343
659
|
return { issued: false, reason: 'order_not_invoiced' };
|
|
344
|
-
const { original, salesChannelId, amounts, snapshots, discountLine } = plan;
|
|
660
|
+
const { original, salesChannelId, amounts, snapshots, discountLine, chargeSnapshots } = plan;
|
|
345
661
|
const { credited: creditedTotal, netTotal, taxTotal } = amounts;
|
|
346
662
|
const issuedAt = new Date();
|
|
347
663
|
const holdForVendor = await shouldHoldForVendorNumber(this.ledgerRouting, salesChannelId);
|
|
@@ -401,12 +717,29 @@ export class CorrectiveInvoiceProvider {
|
|
|
401
717
|
orderItemId: s.orderItemId,
|
|
402
718
|
});
|
|
403
719
|
}
|
|
720
|
+
// Issue #876 — the delivery and the surcharge a consumer's withdrawal
|
|
721
|
+
// refunds, each on a line of its own kind at the rate it was charged at.
|
|
722
|
+
chargeSnapshots.forEach((c, i) => {
|
|
723
|
+
tx.create(InvoiceLine, {
|
|
724
|
+
invoiceId: inv.id,
|
|
725
|
+
ordinal: snapshots.length + i + 1,
|
|
726
|
+
name: c.name,
|
|
727
|
+
unit: c.unit,
|
|
728
|
+
quantity: '1',
|
|
729
|
+
unitNetPrice: roundHalfUp(c.net, 4),
|
|
730
|
+
taxRate: c.rate,
|
|
731
|
+
netValue: c.net,
|
|
732
|
+
grossValue: c.gross,
|
|
733
|
+
orderItemId: null,
|
|
734
|
+
lineKind: c.kind,
|
|
735
|
+
});
|
|
736
|
+
});
|
|
404
737
|
// The order-level discount the returned goods carried, credited back on
|
|
405
738
|
// a 0 % line of its own, as the invoice charged it (issue #417).
|
|
406
739
|
if (discountLine && compareDecimals(amounts.discountCredit, 0) !== 0) {
|
|
407
740
|
tx.create(InvoiceLine, {
|
|
408
741
|
invoiceId: inv.id,
|
|
409
|
-
ordinal: snapshots.length + 1,
|
|
742
|
+
ordinal: snapshots.length + chargeSnapshots.length + 1,
|
|
410
743
|
name: discountLine.name,
|
|
411
744
|
unit: discountLine.unit,
|
|
412
745
|
quantity: '1',
|
|
@@ -450,6 +783,10 @@ export class CorrectiveInvoiceProvider {
|
|
|
450
783
|
orderId: input.orderId,
|
|
451
784
|
originalInvoiceId: original.id,
|
|
452
785
|
credited: Number(creditedTotal),
|
|
786
|
+
priceReductionLines: input.lines.filter((l) => l.basis === 'price_reduction').length,
|
|
787
|
+
...(chargeSnapshots.length > 0
|
|
788
|
+
? { charges: Object.fromEntries(chargeSnapshots.map((c) => [c.kind, Number(c.gross)])) }
|
|
789
|
+
: {}),
|
|
453
790
|
},
|
|
454
791
|
})
|
|
455
792
|
.catch(() => undefined);
|