@endora-commerce/mod-invoices 0.109.0 → 0.111.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.
Files changed (179) hide show
  1. package/dist/admin/lib/invoice-list-path.d.ts +20 -0
  2. package/dist/admin/lib/invoice-list-path.js +36 -0
  3. package/dist/admin/pages/InvoicesList.js +46 -21
  4. package/dist/admin/templates/invoice-puck-config.js +220 -135
  5. package/dist/backend/admin-list-cursor.d.ts +20 -0
  6. package/dist/backend/admin-list-cursor.js +27 -0
  7. package/dist/backend/entities/invoice-line.entity.d.ts +18 -1
  8. package/dist/backend/entities/invoice-line.entity.js +20 -0
  9. package/dist/backend/index.js +19 -3
  10. package/dist/backend/invoices-prose.d.ts +2 -0
  11. package/dist/backend/invoices-prose.js +2 -0
  12. package/dist/backend/pdf-components/embed-logo-images.js +2 -15
  13. package/dist/backend/pdf-components/sections.js +3 -1
  14. package/dist/backend/plugin.js +2 -1
  15. package/dist/backend/routes.admin.js +55 -15
  16. package/dist/backend/routes.customer.d.ts +3 -3
  17. package/dist/backend/routes.customer.js +17 -9
  18. package/dist/backend/seeds/generic-invoice-template.d.ts +13 -7
  19. package/dist/backend/seeds/generic-invoice-template.js +34 -22
  20. package/dist/backend/services/auto-issue-reactor.js +6 -2
  21. package/dist/backend/services/corrective-invoice.d.ts +167 -16
  22. package/dist/backend/services/corrective-invoice.js +402 -58
  23. package/dist/backend/services/erp-sale-document-write-port.js +2 -2
  24. package/dist/backend/services/invoice-copy-host.service.js +3 -0
  25. package/dist/backend/services/invoice-line-builder.d.ts +4 -0
  26. package/dist/backend/services/invoice-line-builder.js +1 -0
  27. package/dist/backend/services/invoice-service.d.ts +27 -4
  28. package/dist/backend/services/invoice-service.js +75 -17
  29. package/dist/backend/services/kept-quantities.d.ts +24 -0
  30. package/dist/backend/services/kept-quantities.js +32 -0
  31. package/dist/backend/services/order-returns-lock.d.ts +19 -0
  32. package/dist/backend/services/order-returns-lock.js +37 -0
  33. package/dist/backend/services/seller-settings.js +1 -1
  34. package/dist/manifest.d.ts +15 -3
  35. package/dist/manifest.js +17 -2
  36. package/dist/migrations/20261108T073244_invoices_invoice_line_kind.d.ts +21 -0
  37. package/dist/migrations/20261108T073244_invoices_invoice_line_kind.js +28 -0
  38. package/dist/migrations/index.d.ts +2 -1
  39. package/dist/migrations/index.js +3 -1
  40. package/docs/invoices.md +143 -16
  41. package/i18n/en.json +13 -2
  42. package/i18n/pl.json +13 -2
  43. package/package.json +17 -16
  44. package/dist/admin/components/InvoiceSectionTabs.d.ts.map +0 -1
  45. package/dist/admin/components/InvoiceSectionTabs.js.map +0 -1
  46. package/dist/admin/document-blocks/InvoiceDivider.d.ts.map +0 -1
  47. package/dist/admin/document-blocks/InvoiceDivider.js.map +0 -1
  48. package/dist/admin/document-blocks/InvoiceFooter.d.ts.map +0 -1
  49. package/dist/admin/document-blocks/InvoiceFooter.js.map +0 -1
  50. package/dist/admin/document-blocks/InvoiceHeader.d.ts.map +0 -1
  51. package/dist/admin/document-blocks/InvoiceHeader.js.map +0 -1
  52. package/dist/admin/document-blocks/InvoiceLineItems.d.ts.map +0 -1
  53. package/dist/admin/document-blocks/InvoiceLineItems.js.map +0 -1
  54. package/dist/admin/document-blocks/InvoiceLogo.d.ts.map +0 -1
  55. package/dist/admin/document-blocks/InvoiceLogo.js.map +0 -1
  56. package/dist/admin/document-blocks/InvoiceNotes.d.ts.map +0 -1
  57. package/dist/admin/document-blocks/InvoiceNotes.js.map +0 -1
  58. package/dist/admin/document-blocks/InvoiceParties.d.ts.map +0 -1
  59. package/dist/admin/document-blocks/InvoiceParties.js.map +0 -1
  60. package/dist/admin/document-blocks/InvoiceSpacer.d.ts.map +0 -1
  61. package/dist/admin/document-blocks/InvoiceSpacer.js.map +0 -1
  62. package/dist/admin/document-blocks/InvoiceTotals.d.ts.map +0 -1
  63. package/dist/admin/document-blocks/InvoiceTotals.js.map +0 -1
  64. package/dist/admin/document-blocks/InvoiceVatSummary.d.ts.map +0 -1
  65. package/dist/admin/document-blocks/InvoiceVatSummary.js.map +0 -1
  66. package/dist/admin/index.d.ts.map +0 -1
  67. package/dist/admin/index.js.map +0 -1
  68. package/dist/admin/pages/InvoiceDetail.d.ts.map +0 -1
  69. package/dist/admin/pages/InvoiceDetail.js.map +0 -1
  70. package/dist/admin/pages/InvoiceTemplatesRedirect.d.ts.map +0 -1
  71. package/dist/admin/pages/InvoiceTemplatesRedirect.js.map +0 -1
  72. package/dist/admin/pages/InvoicesList.d.ts.map +0 -1
  73. package/dist/admin/pages/InvoicesList.js.map +0 -1
  74. package/dist/admin/templates/invoice-puck-config.d.ts.map +0 -1
  75. package/dist/admin/templates/invoice-puck-config.js.map +0 -1
  76. package/dist/backend/document/block-descriptions.d.ts.map +0 -1
  77. package/dist/backend/document/block-descriptions.js.map +0 -1
  78. package/dist/backend/document/document-templates-grant.d.ts.map +0 -1
  79. package/dist/backend/document/document-templates-grant.js.map +0 -1
  80. package/dist/backend/document/invoice-document-type.d.ts.map +0 -1
  81. package/dist/backend/document/invoice-document-type.js.map +0 -1
  82. package/dist/backend/document/render-invoice.d.ts.map +0 -1
  83. package/dist/backend/document/render-invoice.js.map +0 -1
  84. package/dist/backend/email-templates/invoice-issued.default.d.ts.map +0 -1
  85. package/dist/backend/email-templates/invoice-issued.default.js.map +0 -1
  86. package/dist/backend/entities/invoice-external-attachment.entity.d.ts.map +0 -1
  87. package/dist/backend/entities/invoice-external-attachment.entity.js.map +0 -1
  88. package/dist/backend/entities/invoice-line.entity.d.ts.map +0 -1
  89. package/dist/backend/entities/invoice-line.entity.js.map +0 -1
  90. package/dist/backend/entities/invoice-number-counter.entity.d.ts.map +0 -1
  91. package/dist/backend/entities/invoice-number-counter.entity.js.map +0 -1
  92. package/dist/backend/entities/invoice.entity.d.ts.map +0 -1
  93. package/dist/backend/entities/invoice.entity.js.map +0 -1
  94. package/dist/backend/index.d.ts.map +0 -1
  95. package/dist/backend/index.js.map +0 -1
  96. package/dist/backend/invoices-prose.d.ts.map +0 -1
  97. package/dist/backend/invoices-prose.js.map +0 -1
  98. package/dist/backend/pdf-components/embed-logo-images.d.ts.map +0 -1
  99. package/dist/backend/pdf-components/embed-logo-images.js.map +0 -1
  100. package/dist/backend/pdf-components/sample.d.ts.map +0 -1
  101. package/dist/backend/pdf-components/sample.js.map +0 -1
  102. package/dist/backend/pdf-components/sections.d.ts.map +0 -1
  103. package/dist/backend/pdf-components/sections.js.map +0 -1
  104. package/dist/backend/pdf-components/tree-mapper.d.ts.map +0 -1
  105. package/dist/backend/pdf-components/tree-mapper.js.map +0 -1
  106. package/dist/backend/plugin.d.ts.map +0 -1
  107. package/dist/backend/plugin.js.map +0 -1
  108. package/dist/backend/routes.admin.d.ts.map +0 -1
  109. package/dist/backend/routes.admin.js.map +0 -1
  110. package/dist/backend/routes.customer.d.ts.map +0 -1
  111. package/dist/backend/routes.customer.js.map +0 -1
  112. package/dist/backend/seeds/generic-invoice-template.d.ts.map +0 -1
  113. package/dist/backend/seeds/generic-invoice-template.js.map +0 -1
  114. package/dist/backend/services/amount-to-words.d.ts.map +0 -1
  115. package/dist/backend/services/amount-to-words.js.map +0 -1
  116. package/dist/backend/services/auto-issue-reactor.d.ts.map +0 -1
  117. package/dist/backend/services/auto-issue-reactor.js.map +0 -1
  118. package/dist/backend/services/corrective-invoice.d.ts.map +0 -1
  119. package/dist/backend/services/corrective-invoice.js.map +0 -1
  120. package/dist/backend/services/cross-module-context.d.ts.map +0 -1
  121. package/dist/backend/services/cross-module-context.js.map +0 -1
  122. package/dist/backend/services/duplicate-number-refusal.d.ts.map +0 -1
  123. package/dist/backend/services/duplicate-number-refusal.js.map +0 -1
  124. package/dist/backend/services/erp-sale-document-write-port.d.ts.map +0 -1
  125. package/dist/backend/services/erp-sale-document-write-port.js.map +0 -1
  126. package/dist/backend/services/invoice-attachment-fetch-registry.d.ts.map +0 -1
  127. package/dist/backend/services/invoice-attachment-fetch-registry.js.map +0 -1
  128. package/dist/backend/services/invoice-copy-host.service.d.ts.map +0 -1
  129. package/dist/backend/services/invoice-copy-host.service.js.map +0 -1
  130. package/dist/backend/services/invoice-email-dispatch.d.ts.map +0 -1
  131. package/dist/backend/services/invoice-email-dispatch.js.map +0 -1
  132. package/dist/backend/services/invoice-line-builder.d.ts.map +0 -1
  133. package/dist/backend/services/invoice-line-builder.js.map +0 -1
  134. package/dist/backend/services/invoice-number-collisions.d.ts.map +0 -1
  135. package/dist/backend/services/invoice-number-collisions.js.map +0 -1
  136. package/dist/backend/services/invoice-number-generator.d.ts.map +0 -1
  137. package/dist/backend/services/invoice-number-generator.js.map +0 -1
  138. package/dist/backend/services/invoice-paid.d.ts.map +0 -1
  139. package/dist/backend/services/invoice-paid.js.map +0 -1
  140. package/dist/backend/services/invoice-pdf-block-registry.d.ts.map +0 -1
  141. package/dist/backend/services/invoice-pdf-block-registry.js.map +0 -1
  142. package/dist/backend/services/invoice-pdf.d.ts.map +0 -1
  143. package/dist/backend/services/invoice-pdf.js.map +0 -1
  144. package/dist/backend/services/invoice-placement-apply-port.d.ts.map +0 -1
  145. package/dist/backend/services/invoice-placement-apply-port.js.map +0 -1
  146. package/dist/backend/services/invoice-read-port.d.ts.map +0 -1
  147. package/dist/backend/services/invoice-read-port.js.map +0 -1
  148. package/dist/backend/services/invoice-service.d.ts.map +0 -1
  149. package/dist/backend/services/invoice-service.js.map +0 -1
  150. package/dist/backend/services/numbering-configuration.d.ts.map +0 -1
  151. package/dist/backend/services/numbering-configuration.js.map +0 -1
  152. package/dist/backend/services/numbering-write-validator.d.ts.map +0 -1
  153. package/dist/backend/services/numbering-write-validator.js.map +0 -1
  154. package/dist/backend/services/seller-settings.d.ts.map +0 -1
  155. package/dist/backend/services/seller-settings.js.map +0 -1
  156. package/dist/backend/services/vendor-number-hold.d.ts.map +0 -1
  157. package/dist/backend/services/vendor-number-hold.js.map +0 -1
  158. package/dist/manifest.d.ts.map +0 -1
  159. package/dist/manifest.js.map +0 -1
  160. package/dist/migrations/20260629T125121_invoices_module.d.ts.map +0 -1
  161. package/dist/migrations/20260629T125121_invoices_module.js.map +0 -1
  162. package/dist/migrations/20260801T111000_invoices_generic_template_reseed.d.ts.map +0 -1
  163. package/dist/migrations/20260801T111000_invoices_generic_template_reseed.js.map +0 -1
  164. package/dist/migrations/20260817T201110_invoices_correction_idempotency_key.d.ts.map +0 -1
  165. package/dist/migrations/20260817T201110_invoices_correction_idempotency_key.js.map +0 -1
  166. package/dist/migrations/20260903T101756_invoices_namespace_block_names.d.ts.map +0 -1
  167. package/dist/migrations/20260903T101756_invoices_namespace_block_names.js.map +0 -1
  168. package/dist/migrations/20260914T133603_invoices_erp_imported_sale_documents.d.ts.map +0 -1
  169. package/dist/migrations/20260914T133603_invoices_erp_imported_sale_documents.js.map +0 -1
  170. package/dist/migrations/20260926T230239_invoices_import_identity.d.ts.map +0 -1
  171. package/dist/migrations/20260926T230239_invoices_import_identity.js.map +0 -1
  172. package/dist/migrations/20261017T075839_invoices_drop_invoice_templates.d.ts.map +0 -1
  173. package/dist/migrations/20261017T075839_invoices_drop_invoice_templates.js.map +0 -1
  174. package/dist/migrations/20261024T145631_invoices_vat_summary.d.ts.map +0 -1
  175. package/dist/migrations/20261024T145631_invoices_vat_summary.js.map +0 -1
  176. package/dist/migrations/index.d.ts.map +0 -1
  177. package/dist/migrations/index.js.map +0 -1
  178. package/dist/ports/index.d.ts.map +0 -1
  179. package/dist/ports/index.js.map +0 -1
@@ -0,0 +1,27 @@
1
+ import { ERROR_CODES, isUuidShape } from '@endora-commerce/contracts';
2
+ import { HttpError, decodeCursor, encodeCursor } from '@endora-commerce/platform/http';
3
+ const SEPARATOR = '|';
4
+ export function encodeInvoiceListCursor(position) {
5
+ return encodeCursor(`${position.issuedAt.toISOString()}${SEPARATOR}${position.id}`);
6
+ }
7
+ /** The position a cursor names; a value this route did not issue is a 400. */
8
+ export function decodeInvoiceListCursor(raw) {
9
+ const key = decodeCursor(raw);
10
+ const at = key?.indexOf(SEPARATOR) ?? -1;
11
+ if (key !== undefined && at > 0) {
12
+ const issuedAt = new Date(key.slice(0, at));
13
+ const id = key.slice(at + 1);
14
+ if (!Number.isNaN(issuedAt.getTime()) && isUuidShape(id))
15
+ return { issuedAt, id };
16
+ }
17
+ throw new HttpError(400, ERROR_CODES.VALIDATION_FAILED, 'The cursor is not one this API issued.', [
18
+ { path: 'cursor', issue: 'Expected a cursor from a previous page' },
19
+ ]);
20
+ }
21
+ /** The rows strictly after `position` in `(issuedAt desc, id desc)` order. */
22
+ export function afterPosition(position) {
23
+ return {
24
+ $or: [{ issuedAt: { $lt: position.issuedAt } }, { issuedAt: position.issuedAt, id: { $lt: position.id } }],
25
+ };
26
+ }
27
+ //# sourceMappingURL=admin-list-cursor.js.map
@@ -1,10 +1,17 @@
1
1
  import { OptionalProps } from '@mikro-orm/core';
2
+ /**
3
+ * Issue #904 — what an invoice line is (`invoice_lines.line_kind`). A
4
+ * `price_reduction` is a correction's line; the others are an issued
5
+ * document's.
6
+ */
7
+ export declare const INVOICE_LINE_KINDS: readonly ["goods", "delivery", "payment_surcharge", "discount", "price_reduction"];
8
+ export type InvoiceLineKind = (typeof INVOICE_LINE_KINDS)[number];
2
9
  /**
3
10
  * Immutable snapshot of one invoice line at issuance (feature 047). Independent
4
11
  * of later order edits. For corrections, holds the corrected delta lines.
5
12
  */
6
13
  export declare class InvoiceLine {
7
- [OptionalProps]?: 'id' | 'orderItemId';
14
+ [OptionalProps]?: 'id' | 'orderItemId' | 'lineKind';
8
15
  id: string;
9
16
  invoiceId: string;
10
17
  ordinal: number;
@@ -16,5 +23,15 @@ export declare class InvoiceLine {
16
23
  netValue: string;
17
24
  grossValue: string;
18
25
  orderItemId?: string | null;
26
+ /**
27
+ * Issue #904 — the line's kind, written for every line of an invoice or a
28
+ * proforma issued from now on, the 0 % delivery and surcharge lines included.
29
+ * `null`: a line issued before, or one no writer names yet (a correction's
30
+ * goods and discount lines), told apart as it always was — by its
31
+ * `orderItemId` and its sign. A correction's credited delivery or surcharge
32
+ * (issue #876) is written with its kind: it names no order item and is
33
+ * positive, so nothing else would tell the two apart.
34
+ */
35
+ lineKind?: InvoiceLineKind | null;
19
36
  }
20
37
  //# sourceMappingURL=invoice-line.entity.d.ts.map
@@ -10,6 +10,12 @@ var __metadata = (this && this.__metadata) || function (k, v) {
10
10
  import { Entity, Index, OptionalProps, PrimaryKey, Property } from '@mikro-orm/core';
11
11
  import { GlobalEntity } from '@endora-commerce/platform/tenancy';
12
12
  import { randomUUID } from 'crypto';
13
+ /**
14
+ * Issue #904 — what an invoice line is (`invoice_lines.line_kind`). A
15
+ * `price_reduction` is a correction's line; the others are an issued
16
+ * document's.
17
+ */
18
+ export const INVOICE_LINE_KINDS = ['goods', 'delivery', 'payment_surcharge', 'discount', 'price_reduction'];
13
19
  /**
14
20
  * Immutable snapshot of one invoice line at issuance (feature 047). Independent
15
21
  * of later order edits. For corrections, holds the corrected delta lines.
@@ -27,6 +33,16 @@ let InvoiceLine = class InvoiceLine {
27
33
  netValue;
28
34
  grossValue;
29
35
  orderItemId;
36
+ /**
37
+ * Issue #904 — the line's kind, written for every line of an invoice or a
38
+ * proforma issued from now on, the 0 % delivery and surcharge lines included.
39
+ * `null`: a line issued before, or one no writer names yet (a correction's
40
+ * goods and discount lines), told apart as it always was — by its
41
+ * `orderItemId` and its sign. A correction's credited delivery or surcharge
42
+ * (issue #876) is written with its kind: it names no order item and is
43
+ * positive, so nothing else would tell the two apart.
44
+ */
45
+ lineKind = null;
30
46
  };
31
47
  __decorate([
32
48
  PrimaryKey({ type: 'uuid' }),
@@ -73,6 +89,10 @@ __decorate([
73
89
  Property({ type: 'uuid', nullable: true }),
74
90
  __metadata("design:type", Object)
75
91
  ], InvoiceLine.prototype, "orderItemId", void 0);
92
+ __decorate([
93
+ Property({ type: 'string', length: 24, nullable: true }),
94
+ __metadata("design:type", Object)
95
+ ], InvoiceLine.prototype, "lineKind", void 0);
76
96
  InvoiceLine = __decorate([
77
97
  GlobalEntity(),
78
98
  Entity({ tableName: 'invoice_lines' }),
@@ -1,4 +1,4 @@
1
- import { moneySum } from '@endora-commerce/contracts';
1
+ import { moneySum, supportedLanguageOf } from '@endora-commerce/contracts';
2
2
  /**
3
3
  * A payment attempt whose amount was captured: paid, or paid and since
4
4
  * refunded in part or in full (a refund is the return's to record, not the
@@ -22,7 +22,7 @@ import { INVOICE_ISSUED_DEFAULT } from './email-templates/invoice-issued.default
22
22
  import { InvoiceExternalAttachment } from './entities/invoice-external-attachment.entity.js';
23
23
  import { InvoiceLine } from './entities/invoice-line.entity.js';
24
24
  import { InvoiceNumberCounter } from './entities/invoice-number-counter.entity.js';
25
- import { createInvoiceDocumentType } from './document/invoice-document-type.js';
25
+ import { createInvoiceDocumentType, INVOICE_RENDER_LANGUAGE } from './document/invoice-document-type.js';
26
26
  import { GRANT_DONE_SETTING, grantDocumentTemplatesAccess } from './document/document-templates-grant.js';
27
27
  import { Invoice } from './entities/invoice.entity.js';
28
28
  export function registerModule(ctx) {
@@ -142,6 +142,20 @@ export function registerModule(ctx) {
142
142
  return [];
143
143
  return lazyPort(ctx, 'returnRefundReadPort').listForOrder(orderId);
144
144
  },
145
+ // Issue #435 — what of the order came back, so an invoice issued
146
+ // after a return lists only the kept lines.
147
+ returnedQuantitiesFor: async (orderId) => {
148
+ if (!effectiveState.isPresent('returns'))
149
+ return [];
150
+ return lazyPort(ctx, 'returnRefundReadPort').listReturnedQuantities(orderId);
151
+ },
152
+ // Issue #876 — what of the delivery and the surcharge a consumer's
153
+ // withdrawal refunded, so the invoice charges only what is left.
154
+ refundedChargesFor: async (orderId) => {
155
+ if (!effectiveState.isPresent('returns'))
156
+ return { delivery: '0.00', surcharge: '0.00' };
157
+ return lazyPort(ctx, 'returnRefundReadPort').listRefundedCharges(orderId);
158
+ },
145
159
  },
146
160
  ledgerRouting: {
147
161
  numberingModeFor: async (salesChannelId) => {
@@ -237,7 +251,9 @@ export function registerModule(ctx) {
237
251
  return null;
238
252
  return lazyPort(ctx, 'invoiceLedgerRoutingPort').activeVendorModuleId();
239
253
  },
240
- }))
254
+ },
255
+ // A price-reduction line is named in the document's language (issue #885).
256
+ { translate, language: supportedLanguageOf(INVOICE_RENDER_LANGUAGE) }))
241
257
  .singleton());
242
258
  /**
243
259
  * FR-002 — auto-issue on an order status change (issue #107).
@@ -47,6 +47,8 @@ export declare const INVOICES_PROSE_EN: {
47
47
  readonly 'lines.delivery': "Delivery";
48
48
  readonly 'lines.paymentSurcharge': "Payment method surcharge";
49
49
  readonly 'lines.discount': "Discount";
50
+ readonly 'lines.priceReduction': "Price reduction (complaint {rma}): {product}";
51
+ readonly 'lines.priceReductionUnreferenced': "Price reduction (complaint): {product}";
50
52
  };
51
53
  export type InvoicesProseKey = keyof typeof INVOICES_PROSE_EN;
52
54
  export type ProseParams = Record<string, string | number>;
@@ -46,6 +46,8 @@ export const INVOICES_PROSE_EN = {
46
46
  'lines.delivery': 'Delivery',
47
47
  'lines.paymentSurcharge': 'Payment method surcharge',
48
48
  'lines.discount': 'Discount',
49
+ 'lines.priceReduction': 'Price reduction (complaint {rma}): {product}',
50
+ 'lines.priceReductionUnreferenced': 'Price reduction (complaint): {product}',
49
51
  };
50
52
  /** One sentence of this module's prose in `language`, English when the bundle cannot answer. */
51
53
  export async function invoicesProse(translate, key, language, params) {
@@ -1,18 +1,5 @@
1
- /**
2
- * Pre-resolve InvoiceLogo images to data URIs before pdfmake runs.
3
- *
4
- * pdfmake fetches `image: <http url>` over the network. When the admin embeds a
5
- * library asset, `resolveData` bakes an absolute API URL
6
- * (`http://localhost:3001/assets/file/<id>`). Fetching that URL from inside the
7
- * same Node process that is still serving the preview request deadlocks or
8
- * 403s (private assets), which surfaces as INTERNAL on Preview PDF.
9
- *
10
- * Loading bytes via the Assets Library storage adapter (or a short external
11
- * fetch for true remote URLs) and inlining `data:image/…;base64,…` avoids the
12
- * self-HTTP path. Unsupported formats (SVG, WebP, …) are omitted so the PDF
13
- * still renders.
14
- */
15
- const ASSET_FILE_RE = /\/assets\/file\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i;
1
+ import { UUID_SHAPE_PATTERN } from '@endora-commerce/contracts';
2
+ const ASSET_FILE_RE = new RegExp(`/assets/file/(${UUID_SHAPE_PATTERN})`);
16
3
  /** pdfmake reliably embeds JPEG/PNG; other types are skipped. */
17
4
  const PDFMAKE_IMAGE_MIME = new Set(['image/jpeg', 'image/jpg', 'image/png']);
18
5
  function normalizeMime(mime) {
@@ -419,7 +419,9 @@ export function notesSection(props, inv) {
419
419
  return textBlock(raw, inv, props, { fontSize: 11, showTopDivider: false, marginBottom: 8 });
420
420
  }
421
421
  export function footerSection(props, inv, labels = INVOICE_PDF_LABELS_EN) {
422
- const raw = typeof props['text'] === 'string' ? props['text'] : labels['pdf.footer.default'];
422
+ // An empty footer text prints the default one in the document's language,
423
+ // as an empty label does (issue #437); the built-in layout leaves it empty.
424
+ const raw = optStr(props, 'text') ?? labels['pdf.footer.default'];
423
425
  return textBlock(raw, inv, props, { fontSize: 9, showTopDivider: true, marginBottom: 8 });
424
426
  }
425
427
  export function spacerSection(props = {}) {
@@ -3,6 +3,7 @@ import { InvoiceNumberGenerator, createSettingsPatternResolver } from './service
3
3
  import { SellerSettingsResolver } from './services/seller-settings.js';
4
4
  import { InvoiceEmailDispatcher } from './services/invoice-email-dispatch.js';
5
5
  import { createAutoIssueReactor } from './services/auto-issue-reactor.js';
6
+ import { createOrderReturnsLock } from './services/order-returns-lock.js';
6
7
  import { registerInvoicesAdminRoutes } from './routes.admin.js';
7
8
  import { registerInvoicesCustomerRoutes } from './routes.customer.js';
8
9
  export function invoicesModule(options) {
@@ -15,7 +16,7 @@ export function invoicesModule(options) {
15
16
  }
16
17
  : undefined, async (invoiceId) => {
17
18
  await emailOnReadyHolder.dispatch?.(invoiceId);
18
- }, options.ledgerRouting, options.capturedPayments, options.returnRefunds, { translate: options.translate });
19
+ }, options.ledgerRouting, options.capturedPayments, options.returnRefunds, { translate: options.translate }, createOrderReturnsLock(options.emFactory));
19
20
  // T118c — built unconditionally. The three inputs used to be optional bridge
20
21
  // members, so a composition that supplied two of the three got no dispatcher
21
22
  // at all and every issued invoice answered `not_sent` / `no_sender` — a
@@ -1,12 +1,19 @@
1
1
  import { issueInvoiceRequestSchema, sendInvoiceEmailRequestSchema, } from '@endora-commerce/contracts';
2
2
  import { Invoice } from './entities/invoice.entity.js';
3
- import { isOrgInScope } from '@endora-commerce/platform/tenancy';
3
+ import { orgInScope } from '@endora-commerce/platform/tenancy';
4
4
  import { renderInvoicePdf } from './document/render-invoice.js';
5
+ import { afterPosition, decodeInvoiceListCursor, encodeInvoiceListCursor, } from './admin-list-cursor.js';
5
6
  export async function registerInvoicesAdminRoutes(app, deps) {
6
7
  const { emFactory, orderReadPort, requireAdmin, invoiceService, documents } = deps;
7
8
  // List ------------------------------------------------------------------
8
9
  app.get('/api/v1/admin/invoices', { preHandler: requireAdmin('invoices:read') }, async (request) => {
9
10
  const q = (request.query ?? {});
11
+ // The page size asked for — what `pagination.limit` answers, an empty
12
+ // page included (`paginationSchema`: 1–200; issue #599).
13
+ const limit = Math.min(Math.max(Number.parseInt(q['limit'] ?? '50', 10) || 50, 1), 200);
14
+ // Issue #1120 — decoded before any read, so a forged cursor is a 400 and
15
+ // not an empty page.
16
+ const after = q['cursor'] ? decodeInvoiceListCursor(q['cursor']) : null;
10
17
  const where = {};
11
18
  if (q['filter[status]'])
12
19
  where['status'] = q['filter[status]'];
@@ -44,31 +51,63 @@ export async function registerInvoicesAdminRoutes(app, deps) {
44
51
  if (orderNumber) {
45
52
  const matchingOrderIds = await orderReadPort.findIdsByBusinessIdLike(orderNumber, 500);
46
53
  if (matchingOrderIds.length === 0) {
47
- return { data: [], pagination: { cursor: null, hasMore: false, limit: 0 } };
54
+ return { data: [], pagination: { cursor: null, hasMore: false, limit } };
48
55
  }
49
56
  where['orderId'] = { $in: matchingOrderIds };
50
57
  }
51
- const limit = Math.min(Math.max(Number.parseInt(q['limit'] ?? '50', 10), 1), 200);
52
- const rows = await em.find(Invoice, where, { orderBy: { issuedAt: 'desc' }, limit });
58
+ // Issue #1120 — a page is `limit` rows the caller may see, newest first,
59
+ // and `hasMore` says whether one more exists. The tenant scope below is
60
+ // applied after the read (an invoice is scoped through its order's
61
+ // organisation, which `orders` owns), so the read walks forward in
62
+ // batches until it holds one visible row beyond the page or runs out: an
63
+ // out-of-scope row never shortens a page, never ends the walk early, and
64
+ // never becomes the cursor, which is always the last row answered.
65
+ const batch = limit + 1;
66
+ const visible = [];
67
+ const businessIdByOrder = new Map();
68
+ let position = after;
69
+ for (;;) {
70
+ const rows = await em.find(Invoice, position ? { $and: [where, afterPosition(position)] } : where, { orderBy: { issuedAt: 'desc', id: 'desc' }, limit: batch });
71
+ visible.push(...(await scoped(rows, businessIdByOrder)));
72
+ const last = rows[rows.length - 1];
73
+ if (visible.length > limit || rows.length < batch || !last)
74
+ break;
75
+ position = { issuedAt: last.issuedAt, id: last.id };
76
+ }
77
+ const page = visible.slice(0, limit);
78
+ const hasMore = visible.length > limit;
79
+ const end = page[page.length - 1];
80
+ return {
81
+ data: page.map((i) => serialize(i, i.orderId ? (businessIdByOrder.get(i.orderId) ?? null) : null)),
82
+ pagination: {
83
+ cursor: hasMore && end ? encodeInvoiceListCursor({ issuedAt: end.issuedAt, id: end.id }) : null,
84
+ hasMore,
85
+ limit,
86
+ },
87
+ };
88
+ });
89
+ /**
90
+ * The rows of `rows` in the ambient tenant scope, in order. Records each
91
+ * order's business id into `businessIdByOrder` for the serializer.
92
+ */
93
+ async function scoped(rows, businessIdByOrder) {
53
94
  const orderIds = [
54
95
  ...new Set(rows.map((r) => r.orderId).filter((id) => id != null)),
55
96
  ];
56
97
  // Feature 075, Phase C — the order number and the owning organisation are
57
98
  // `orders`' fields, read over its port rather than out of its table.
58
- const orders = await orderReadPort.findByIds(orderIds);
59
- const byOrder = new Map(orders.map((o) => [o.id, o.businessId]));
99
+ const orders = orderIds.length > 0 ? await orderReadPort.findByIds(orderIds) : [];
100
+ for (const o of orders)
101
+ businessIdByOrder.set(o.id, o.businessId);
60
102
  const orgByOrder = new Map(orders.map((o) => [o.id, o.organizationId]));
61
103
  // Feature 050 — Invoice is transitively scoped via its Order's org; hide
62
104
  // invoices whose order is out of the ambient tenant scope. ERP-imported
63
105
  // rows without an order scope directly on `organizationId` (feature 119).
64
- const scoped = rows.filter((i) => i.origin === 'erp_import'
65
- ? isOrgInScope(i.organizationId ?? '')
66
- : isOrgInScope(orgByOrder.get(i.orderId ?? '') ?? ''));
67
- return {
68
- data: scoped.map((i) => serialize(i, i.orderId ? (byOrder.get(i.orderId) ?? null) : null)),
69
- pagination: { cursor: null, hasMore: false, limit: scoped.length },
70
- };
71
- });
106
+ const inScope = await Promise.all(rows.map((i) => i.origin === 'erp_import'
107
+ ? orgInScope(i.organizationId ?? '')
108
+ : orgInScope(orgByOrder.get(i.orderId ?? '') ?? '')));
109
+ return rows.filter((_, index) => inScope[index]);
110
+ }
72
111
  // Detail ----------------------------------------------------------------
73
112
  app.get('/api/v1/admin/invoices/:id', { preHandler: requireAdmin('invoices:read') }, async (request) => {
74
113
  return { data: await invoiceService.buildDetail(request.params.id) };
@@ -157,7 +196,8 @@ async function sendOnIssue(deps, invoiceId, salesChannelId, invoiceStatus) {
157
196
  function serialize(i, orderBusinessId) {
158
197
  return {
159
198
  id: i.id,
160
- orderId: i.orderId,
199
+ // An ERP-imported sale document may have no order: `null`, never an absent key (issue #599).
200
+ orderId: i.orderId ?? null,
161
201
  orderBusinessId,
162
202
  salesChannelId: i.salesChannelId ?? null,
163
203
  kind: i.kind,
@@ -4,7 +4,7 @@ import { type AssetsLibraryPort, type DocumentRenderPort, type InvoiceAttachment
4
4
  import type { InvoiceService } from './services/invoice-service.js';
5
5
  export interface InvoicesCustomerDeps {
6
6
  emFactory: () => EntityManager;
7
- /** `orders`' published read model — the ownership check (feature 075, Phase C). */
7
+ /** `orders`' published read model — the customer-scoped order read (issue #669). */
8
8
  orderReadPort: OrderReadPort;
9
9
  /** `assets_library` — resolves signed URLs for private attachment bytes. */
10
10
  assetsLibrary: AssetsLibraryPort;
@@ -24,8 +24,8 @@ export interface InvoicesCustomerDeps {
24
24
  }
25
25
  /**
26
26
  * Storefront customer invoice routes (feature 047, US4). A customer lists and
27
- * downloads invoices for an order they (or their organization) own. Only
28
- * `ready` invoices are exposed.
27
+ * downloads invoices for an order they may read under the order read scope
28
+ * (issue #669). Only `ready` invoices are exposed.
29
29
  */
30
30
  export declare function registerInvoicesCustomerRoutes(app: FastifyInstance, deps: InvoicesCustomerDeps): Promise<void>;
31
31
  //# sourceMappingURL=routes.customer.d.ts.map
@@ -1,23 +1,25 @@
1
1
  import { HttpError } from '@endora-commerce/platform/http';
2
- import { ERROR_CODES, } from '@endora-commerce/contracts';
2
+ import { ERROR_CODES, isUuidShape, } from '@endora-commerce/contracts';
3
3
  import { InvoiceExternalAttachment } from './entities/invoice-external-attachment.entity.js';
4
4
  import { Invoice } from './entities/invoice.entity.js';
5
5
  import { renderInvoicePdf } from './document/render-invoice.js';
6
6
  /**
7
7
  * Storefront customer invoice routes (feature 047, US4). A customer lists and
8
- * downloads invoices for an order they (or their organization) own. Only
9
- * `ready` invoices are exposed.
8
+ * downloads invoices for an order they may read under the order read scope
9
+ * (issue #669). Only `ready` invoices are exposed.
10
10
  */
11
11
  export async function registerInvoicesCustomerRoutes(app, deps) {
12
12
  const { emFactory, orderReadPort, assetsLibrary, saleDocumentAttachments, requireCustomer, resolveCustomerContext, invoiceService, documents, } = deps;
13
+ /**
14
+ * The order, if the caller may read it — decided by `orders` itself, so these
15
+ * routes and `GET /api/v1/orders/:id` share one rule: a regular member reaches
16
+ * only the orders they placed, a holder of `orders.view_organization` every
17
+ * order of the Organization (issue #669, `specs/170-organization-roles/` FR-049). Anything else answers 404.
18
+ */
13
19
  async function ownedOrderOr404(req, orderId) {
14
- const ctx = resolveCustomerContext(req);
15
- const order = await orderReadPort.findById(orderId);
16
- if (!order ||
17
- (order.placedByCustomerAccountId !== ctx.customerAccountId &&
18
- order.organizationId !== ctx.organizationId)) {
20
+ const order = await orderReadPort.findByIdForCustomer(orderId, resolveCustomerContext(req));
21
+ if (!order)
19
22
  throw new HttpError(404, ERROR_CODES.NOT_FOUND, 'Order not found.');
20
- }
21
23
  return order;
22
24
  }
23
25
  app.get('/api/v1/orders/:id/invoices', { preHandler: requireCustomer }, async (request) => {
@@ -90,6 +92,9 @@ export async function registerInvoicesCustomerRoutes(app, deps) {
90
92
  app.get('/api/v1/account/organization/invoices/:invoiceId/attachments/:attachmentId', { preHandler: requireCustomer, config: { streamingResponse: true } }, async (request, reply) => {
91
93
  const ctx = resolveCustomerContext(request);
92
94
  const em = emFactory();
95
+ if (!isUuidShape(request.params.invoiceId)) {
96
+ throw new HttpError(404, ERROR_CODES.NOT_FOUND, 'Sale document not found.');
97
+ }
93
98
  const invoice = await em.findOne(Invoice, {
94
99
  id: request.params.invoiceId,
95
100
  origin: 'erp_import',
@@ -99,6 +104,9 @@ export async function registerInvoicesCustomerRoutes(app, deps) {
99
104
  if (!invoice) {
100
105
  throw new HttpError(404, ERROR_CODES.NOT_FOUND, 'Sale document not found.');
101
106
  }
107
+ if (!isUuidShape(request.params.attachmentId)) {
108
+ throw new HttpError(404, ERROR_CODES.NOT_FOUND, 'Attachment not found.');
109
+ }
102
110
  const attachment = await em.findOne(InvoiceExternalAttachment, {
103
111
  id: request.params.attachmentId,
104
112
  invoiceId: invoice.id,
@@ -2,17 +2,23 @@
2
2
  * Seeded generic invoice template (feature 047, US6 / T027). A Puck content
3
3
  * envelope composed of the bounded invoice component set.
4
4
  *
5
- * Props on each node MUST mirror `defaultProps` in
6
- * `admin/.../invoice-puck-config.tsx` so the editor sidebar shows selected
7
- * radios/selects when a template is created from this seed (Puck does not
8
- * re-apply defaultProps onto already-persisted nodes).
5
+ * It is the *Invoice* document type's built-in layout
6
+ * (`document/invoice-document-type.ts`), and the content a template started
7
+ * from it copies. Every prop is spelled out so the editor sidebar shows
8
+ * selected radios/selects (Puck does not re-apply defaultProps onto
9
+ * already-persisted nodes). **Label props are empty** (issues #428, #437): an
10
+ * empty label is drawn in the document's language, and a literal here would
11
+ * be a template prop that wins over it.
9
12
  */
10
13
  export declare const GENERIC_INVOICE_TEMPLATE_CODE = "generic";
11
14
  export declare const GENERIC_INVOICE_TEMPLATE_LANGUAGES: string[];
12
15
  /**
13
- * Bump when the seeded Puck tree shape changes so `ensureGenericSeed` (and the
14
- * matching data migration) refresh the system `generic` row on existing DBs.
16
+ * Bump when the seeded Puck tree changes. It is the envelope's
17
+ * `schema_version`; no stored row is rewritten on it since the seeded
18
+ * `generic` row went with `invoice_templates` (`specs/152-compare-pdf-template/`).
19
+ * Templates already stored are corrected by a migration of the module that
20
+ * owns them, as `document_templates` does for issue #437 (revision 3).
15
21
  */
16
- export declare const GENERIC_INVOICE_TEMPLATE_SEED_REVISION = 2;
22
+ export declare const GENERIC_INVOICE_TEMPLATE_SEED_REVISION = 3;
17
23
  export declare const GENERIC_INVOICE_TEMPLATE_CONTENT: Record<string, unknown>;
18
24
  //# sourceMappingURL=generic-invoice-template.d.ts.map
@@ -2,19 +2,31 @@
2
2
  * Seeded generic invoice template (feature 047, US6 / T027). A Puck content
3
3
  * envelope composed of the bounded invoice component set.
4
4
  *
5
- * Props on each node MUST mirror `defaultProps` in
6
- * `admin/.../invoice-puck-config.tsx` so the editor sidebar shows selected
7
- * radios/selects when a template is created from this seed (Puck does not
8
- * re-apply defaultProps onto already-persisted nodes).
5
+ * It is the *Invoice* document type's built-in layout
6
+ * (`document/invoice-document-type.ts`), and the content a template started
7
+ * from it copies. Every prop is spelled out so the editor sidebar shows
8
+ * selected radios/selects (Puck does not re-apply defaultProps onto
9
+ * already-persisted nodes). **Label props are empty** (issues #428, #437): an
10
+ * empty label is drawn in the document's language, and a literal here would
11
+ * be a template prop that wins over it.
9
12
  */
10
13
  export const GENERIC_INVOICE_TEMPLATE_CODE = 'generic';
11
14
  export const GENERIC_INVOICE_TEMPLATE_LANGUAGES = ['pl-PL', 'en-US'];
12
15
  /**
13
- * Bump when the seeded Puck tree shape changes so `ensureGenericSeed` (and the
14
- * matching data migration) refresh the system `generic` row on existing DBs.
16
+ * Bump when the seeded Puck tree changes. It is the envelope's
17
+ * `schema_version`; no stored row is rewritten on it since the seeded
18
+ * `generic` row went with `invoice_templates` (`specs/152-compare-pdf-template/`).
19
+ * Templates already stored are corrected by a migration of the module that
20
+ * owns them, as `document_templates` does for issue #437 (revision 3).
15
21
  */
16
- export const GENERIC_INVOICE_TEMPLATE_SEED_REVISION = 2;
17
- const DEFAULT_FOOTER_TEXT = 'Thank you for your business.\n{{var seller.legalName}} · Tax ID {{var seller.taxId}}';
22
+ export const GENERIC_INVOICE_TEMPLATE_SEED_REVISION = 3;
23
+ /**
24
+ * Empty on purpose (issue #437), like every label below: an empty footer text
25
+ * prints `pdf.footer.default` in the document's language. A literal here is a
26
+ * template prop, and a template prop wins over the translation — which is how
27
+ * a Polish invoice came to say "Thank you for your business."
28
+ */
29
+ const DEFAULT_FOOTER_TEXT = '';
18
30
  function genericTree() {
19
31
  return {
20
32
  root: { props: {} },
@@ -44,10 +56,13 @@ function genericTree() {
44
56
  showSaleDate: true,
45
57
  showPaymentDue: true,
46
58
  showPaymentMethod: true,
47
- labelIssuedAt: 'Issue date',
48
- labelSaleDate: 'Sale date',
49
- labelPaymentDue: 'Payment due',
50
- labelPaymentMethod: 'Payment method',
59
+ // Every label of the layout is empty (issue #437, after #428): the
60
+ // block prints it in the document's language unless a template
61
+ // sets its own.
62
+ labelIssuedAt: '',
63
+ labelSaleDate: '',
64
+ labelPaymentDue: '',
65
+ labelPaymentMethod: '',
51
66
  marginTop: 0,
52
67
  marginBottom: 12,
53
68
  },
@@ -60,8 +75,8 @@ function genericTree() {
60
75
  type: 'invoices.InvoiceParties',
61
76
  props: {
62
77
  id: 'inv-parties',
63
- sellerLabel: 'Seller',
64
- buyerLabel: 'Buyer',
78
+ sellerLabel: '',
79
+ buyerLabel: '',
65
80
  showSellerBank: true,
66
81
  showSellerSwift: true,
67
82
  showBuyerTaxId: true,
@@ -103,7 +118,7 @@ function genericTree() {
103
118
  headerColor: '',
104
119
  borderColor: '#cbd5e1',
105
120
  showTotalRow: true,
106
- totalLabel: 'Total',
121
+ totalLabel: '',
107
122
  marginTop: 0,
108
123
  marginBottom: 12,
109
124
  },
@@ -123,14 +138,11 @@ function genericTree() {
123
138
  showOverpayment: true,
124
139
  showGross: true,
125
140
  showAmountInWords: true,
126
- labelPaid: 'Paid',
127
- labelAmountDue: 'Amount due',
128
- // Empty on purpose (issue #428): the row is labelled in the language
129
- // the amounts are written in — Polish on a Polish invoice —
130
- // unless a template sets its own label.
141
+ labelPaid: '',
142
+ labelAmountDue: '',
131
143
  labelOverpayment: '',
132
- labelGross: 'Total',
133
- labelInWords: 'In words',
144
+ labelGross: '',
145
+ labelInWords: '',
134
146
  marginTop: 0,
135
147
  marginBottom: 16,
136
148
  },
@@ -85,11 +85,15 @@ export function createAutoIssueReactor(deps) {
85
85
  // is a presence answer about the whole operation and is re-thrown.
86
86
  rethrowIfModuleDisabled(error);
87
87
  // An order refunded in full before it was invoiced is not invoiced at
88
- // all (owner ruling of 2026-10-24): skipped, and the log says why.
88
+ // all (owner ruling of 2026-10-24), nor is one returned in full
89
+ // (product-owner ruling on F4, review of PR #865): skipped, and the log
90
+ // says why, and which of the two.
89
91
  if (error instanceof HttpError && error.code === ERROR_CODES.INVOICE_ORDER_REFUNDED) {
90
- log('[invoices] the order was not auto-invoiced: its payments were refunded in full', {
92
+ const cause = error.details?.reason;
93
+ log('[invoices] the order was not auto-invoiced: it was refunded or returned in full', {
91
94
  orderId: p.orderId,
92
95
  reason: ERROR_CODES.INVOICE_ORDER_REFUNDED,
96
+ ...(typeof cause === 'string' ? { cause } : {}),
93
97
  });
94
98
  return;
95
99
  }