@aglyn/plugins-commerce 1.10.0 → 1.12.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/package.json +13 -13
- package/src/lib/components/console/host-quotes-card.component.js +20 -11
- package/src/lib/components/console/host-quotes-card.component.js.map +1 -1
- package/src/lib/components/console/invoice-send.component.d.ts +9 -2
- package/src/lib/components/console/invoice-send.component.js +58 -30
- package/src/lib/components/console/invoice-send.component.js.map +1 -1
- package/src/lib/components/console/pay-link-readiness-notice.component.d.ts +84 -0
- package/src/lib/components/console/pay-link-readiness-notice.component.js +164 -0
- package/src/lib/components/console/pay-link-readiness-notice.component.js.map +1 -0
- package/src/lib/components/console/pos-kiosk/kiosk-menu.d.ts +10 -3
- package/src/lib/components/console/pos-kiosk/kiosk-menu.js +29 -8
- package/src/lib/components/console/pos-kiosk/kiosk-menu.js.map +1 -1
- package/src/lib/components/console/pos-kiosk/pos-kiosk-api.d.ts +2 -0
- package/src/lib/components/console/pos-kiosk/pos-kiosk-api.js +7 -0
- package/src/lib/components/console/pos-kiosk/pos-kiosk-api.js.map +1 -1
- package/src/lib/components/console/pos-kiosk-page.component.d.ts +2 -0
- package/src/lib/components/console/pos-kiosk-page.component.js +54 -3
- package/src/lib/components/console/pos-kiosk-page.component.js.map +1 -1
- package/src/lib/components/console/product-add-ons-fields.component.d.ts +0 -2
- package/src/lib/components/console/product-add-ons-fields.component.js +1 -6
- package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
- package/src/lib/components/console/quote-editor-dialog.component.d.ts +2 -0
- package/src/lib/components/console/quote-editor-dialog.component.js +35 -27
- package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/quote-pay-link.component.d.ts +3 -0
- package/src/lib/components/console/quote-pay-link.component.js +9 -0
- package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
- package/src/lib/components/console/quote-send.component.d.ts +3 -0
- package/src/lib/components/console/quote-send.component.js +9 -0
- package/src/lib/components/console/quote-send.component.js.map +1 -1
- package/src/lib/components/product-detail.js +1 -1
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/product-grid.js +5 -3
- package/src/lib/components/product-grid.js.map +1 -1
- package/src/lib/components/product-reviews.js +17 -12
- package/src/lib/components/product-reviews.js.map +1 -1
- package/src/lib/components/quote-page-body.js +5 -3
- package/src/lib/components/quote-page-body.js.map +1 -1
- package/src/lib/components/related-products.js +2 -1
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/model/commerce-invoices.d.ts +45 -5
- package/src/lib/model/commerce-invoices.js +46 -9
- package/src/lib/model/commerce-invoices.js.map +1 -1
- package/src/lib/model/commerce-kiosk-search.d.ts +22 -0
- package/src/lib/model/commerce-kiosk-search.js +32 -0
- package/src/lib/model/commerce-kiosk-search.js.map +1 -0
- package/src/lib/model/commerce-pos-kiosk.d.ts +7 -1
- package/src/lib/model/commerce-pos-kiosk.js +1 -1
- package/src/lib/model/commerce-pos-kiosk.js.map +1 -1
- package/src/lib/model/commerce-quote-pay.d.ts +110 -6
- package/src/lib/model/commerce-quote-pay.js +182 -23
- package/src/lib/model/commerce-quote-pay.js.map +1 -1
- package/src/lib/model/product-modifiers.d.ts +4 -0
- package/src/lib/model/product-modifiers.js +5 -0
- package/src/lib/model/product-modifiers.js.map +1 -1
- package/src/lib/server/billing-webhook.js +4 -1
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/commerce-pdf.js +2 -1
- package/src/lib/server/commerce-pdf.js.map +1 -1
- package/src/lib/server/invoice-email.js +2 -1
- package/src/lib/server/invoice-email.js.map +1 -1
- package/src/lib/server/order-invoice-send.js +1 -1
- package/src/lib/server/order-invoice-send.js.map +1 -1
- package/src/lib/server/order-status.d.ts +5 -1
- package/src/lib/server/order-status.js +19 -5
- package/src/lib/server/order-status.js.map +1 -1
- package/src/lib/server/pos-kiosk.js +70 -15
- package/src/lib/server/pos-kiosk.js.map +1 -1
- package/src/lib/server/quote-email.js +2 -1
- package/src/lib/server/quote-email.js.map +1 -1
- package/src/lib/server/quote-pay.d.ts +39 -0
- package/src/lib/server/quote-pay.js +103 -43
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/quote-proofs.js +20 -11
- package/src/lib/server/quote-proofs.js.map +1 -1
- package/src/lib/server/site-page-enricher.js +5 -1
- package/src/lib/server/site-page-enricher.js.map +1 -1
- package/src/lib/testing/fake-firestore.js +34 -5
- package/src/lib/testing/fake-firestore.js.map +1 -1
- package/src/lib/transfer/product-register-cells.d.ts +75 -0
- package/src/lib/transfer/product-register-cells.js +487 -0
- package/src/lib/transfer/product-register-cells.js.map +1 -0
- package/src/lib/transfer/product-transfer.d.ts +12 -0
- package/src/lib/transfer/product-transfer.js +174 -10
- package/src/lib/transfer/product-transfer.js.map +1 -1
- package/src/lib/transfer/products.server.js +24 -9
- package/src/lib/transfer/products.server.js.map +1 -1
- package/src/lib/utils/invoice-email-content.d.ts +3 -1
- package/src/lib/utils/invoice-email-content.js +1 -1
- package/src/lib/utils/invoice-email-content.js.map +1 -1
- package/src/lib/utils/quote-email-content.d.ts +3 -1
- package/src/lib/utils/quote-email-content.js +3 -3
- package/src/lib/utils/quote-email-content.js.map +1 -1
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
17
|
import { type HostOrder, type OrderTimelineEvent } from './commerce-orders';
|
|
18
|
-
import { type QuoteCheckoutCharge, type QuotePageView, type QuotePayRefusal } from './commerce-quote-pay';
|
|
18
|
+
import { type PayLinkStore, type QuoteCheckoutCharge, type QuotePageView, type QuotePayRefusal } from './commerce-quote-pay';
|
|
19
19
|
import { type OrderInvoiceSendRecord, type QuoteEmailThread, type QuoteTaxBasis } from './commerce-quotes';
|
|
20
20
|
import type { ResolvedShippingRate } from './commerce-shipping';
|
|
21
21
|
/** Which page a pay link opens for an order: a quote, an invoice, or none. */
|
|
@@ -60,7 +60,9 @@ export declare function invoiceTaxBasis(order: Pick<HostOrder, 'taxMode' | 'tota
|
|
|
60
60
|
* rates it offered when it was made (Stripe asks for the address and the
|
|
61
61
|
* buyer picks one, as on the draft's first link).
|
|
62
62
|
*/
|
|
63
|
-
export declare function invoiceCheckoutCharge(order: Pick<HostOrder, 'number' | 'lineItems' | 'quote' | 'totals' | 'taxMode'> & Partial<Pick<HostOrder, 'draftShipping'>>, orderId: string
|
|
63
|
+
export declare function invoiceCheckoutCharge(order: Pick<HostOrder, 'number' | 'lineItems' | 'quote' | 'totals' | 'taxMode'> & Partial<Pick<HostOrder, 'draftShipping'>>, orderId: string,
|
|
64
|
+
/** The store's sales tax choice, which a quote saved before it was made takes (`quotePayTax`). */
|
|
65
|
+
store?: PayLinkStore | null): InvoiceCheckoutCharge;
|
|
64
66
|
/**
|
|
65
67
|
* Why an order cannot be paid through its pay link now: a quote's reasons,
|
|
66
68
|
* and two of an invoice's own. `not-payable` is an order the link does not
|
|
@@ -68,9 +70,41 @@ export declare function invoiceCheckoutCharge(order: Pick<HostOrder, 'number' |
|
|
|
68
70
|
* before drafts kept their shipping rates, whose shipping cannot be charged.
|
|
69
71
|
*/
|
|
70
72
|
export type InvoicePayRefusal = QuotePayRefusal | 'not-payable' | 'shipping-unknown';
|
|
71
|
-
export declare function invoicePayRefusal(order: Pick<HostOrder, 'number' | 'status' | 'lineItems' | 'quote' | 'totals' | 'taxMode' | 'channel'> & Partial<Pick<HostOrder, 'draftShipping'>>, orderId: string
|
|
73
|
+
export declare function invoicePayRefusal(order: Pick<HostOrder, 'number' | 'status' | 'lineItems' | 'quote' | 'totals' | 'taxMode' | 'channel'> & Partial<Pick<HostOrder, 'draftShipping'>>, orderId: string,
|
|
74
|
+
/** The store's sales tax choice; with it, a store that has not chosen refuses (AGL-1999). */
|
|
75
|
+
store?: PayLinkStore | null): InvoicePayRefusal | null;
|
|
72
76
|
/** What the customer is told for a refusal, in the page's words: "quote" or "invoice". */
|
|
73
77
|
export declare function invoicePayRefusalMessage(reason: InvoicePayRefusal, storeName: string, kind: OrderPayLinkKind): string;
|
|
78
|
+
/**
|
|
79
|
+
* What stands between a pay link and a payment that the business fixes in
|
|
80
|
+
* the console (AGL-4162):
|
|
81
|
+
*
|
|
82
|
+
* - `payments`: the workspace can't take card payments yet.
|
|
83
|
+
* - `tax-undecided`: the store has not chosen how it handles sales tax.
|
|
84
|
+
* - `tax-save`: the quote was saved before the store chose, and the store's
|
|
85
|
+
* choice now prices it only on a save (`quotePayTax`'s `save`).
|
|
86
|
+
*/
|
|
87
|
+
export type PayLinkGap = 'payments' | 'tax-undecided' | 'tax-save';
|
|
88
|
+
/**
|
|
89
|
+
* What the console's "Customers can't pay this … online yet" notice names,
|
|
90
|
+
* for an unpaid quote or a draft order's invoice, or a quote not saved yet
|
|
91
|
+
* (`order: null`), which will be saved under the store's choice as it stands.
|
|
92
|
+
* The same answers Pay refuses on: `invoicePayRefusal` with the store, and
|
|
93
|
+
* the payment account check the page and Pay share.
|
|
94
|
+
*
|
|
95
|
+
* Null while either answer is unknown, so the notice waits rather than tell a
|
|
96
|
+
* store that is set up to set up. Empty for anything the pay link does not
|
|
97
|
+
* charge (a paid, closed or unlinked order) or that nothing stands in front of.
|
|
98
|
+
* A refusal that is not the business's setup (approval, an amount too small)
|
|
99
|
+
* is said where it is decided, not here.
|
|
100
|
+
*/
|
|
101
|
+
export declare function payLinkGaps(input: {
|
|
102
|
+
order: (Pick<HostOrder, 'status' | 'channel'> & Partial<Pick<HostOrder, 'quote'>>) | null;
|
|
103
|
+
/** The workspace can take card payments; null while that is unknown. */
|
|
104
|
+
paymentsReady: boolean | null;
|
|
105
|
+
/** The store's sales tax choice; undefined while it is being read. */
|
|
106
|
+
store: PayLinkStore | undefined;
|
|
107
|
+
}): PayLinkGap[] | null;
|
|
74
108
|
/**
|
|
75
109
|
* The pay link's page for an order that is not a quote: "Invoice #N", its
|
|
76
110
|
* lines and totals, the customer's addresses, and Pay while it is unpaid. No
|
|
@@ -87,6 +121,10 @@ export declare function buildInvoicePageView(input: {
|
|
|
87
121
|
currency: string;
|
|
88
122
|
/** The order's status page, once paid. */
|
|
89
123
|
receiptUrl?: string | null;
|
|
124
|
+
/** The store's sales tax choice; with it, a store that has not chosen refuses Pay (AGL-1999). */
|
|
125
|
+
store?: PayLinkStore | null;
|
|
126
|
+
/** Whether the business can take a card payment now; absent, it is not judged here. */
|
|
127
|
+
paymentsReady?: boolean;
|
|
90
128
|
}): QuotePageView;
|
|
91
129
|
/** The order's invoice sends on record, oldest first. */
|
|
92
130
|
export declare function invoiceSends(order: Pick<HostOrder, 'invoiceSends'> | null | undefined): OrderInvoiceSendRecord[];
|
|
@@ -113,13 +151,15 @@ export declare function invoiceEmailThread(order: Pick<HostOrder, 'quote' | 'ema
|
|
|
113
151
|
*/
|
|
114
152
|
export declare function invoiceEmailDefaultSubject(order: Pick<HostOrder, 'number' | 'quote' | 'emailThread'>, businessName: string, orderId?: string): string;
|
|
115
153
|
/** Why an invoice cannot be emailed now, and what the console says. */
|
|
116
|
-
export type InvoiceSendRefusal = 'unknown' | 'closed' | 'empty' | 'not-payable' | 'approval-required' | 'tax-undecided' | 'nothing-to-pay' | 'shipping-unknown' | 'no-address' | 'bad-address';
|
|
154
|
+
export type InvoiceSendRefusal = 'unknown' | 'closed' | 'empty' | 'not-payable' | 'approval-required' | 'tax-undecided' | 'tax-save' | 'nothing-to-pay' | 'shipping-unknown' | 'no-address' | 'bad-address';
|
|
117
155
|
/**
|
|
118
156
|
* Why the order's invoice cannot be emailed to `to` now, if it cannot:
|
|
119
157
|
* a canceled or refunded order, one with nothing on it, an unpaid order its
|
|
120
158
|
* pay link cannot take payment for (and why), and the address.
|
|
121
159
|
*/
|
|
122
|
-
export declare function invoiceSendRefusal(order: (Pick<HostOrder, 'number' | 'status' | 'channel' | 'lineItems' | 'totals' | 'quote' | 'taxMode'> & Partial<Pick<HostOrder, 'draftShipping'>>) | null | undefined, orderId: string, to: string
|
|
160
|
+
export declare function invoiceSendRefusal(order: (Pick<HostOrder, 'number' | 'status' | 'channel' | 'lineItems' | 'totals' | 'quote' | 'taxMode'> & Partial<Pick<HostOrder, 'draftShipping'>>) | null | undefined, orderId: string, to: string,
|
|
161
|
+
/** The store's sales tax choice, as the pay link reads it (`invoicePayRefusal`). */
|
|
162
|
+
store?: PayLinkStore | null): InvoiceSendRefusal | null;
|
|
123
163
|
/** What the console says for a refused invoice send. */
|
|
124
164
|
export declare function invoiceSendRefusalMessage(reason: InvoiceSendRefusal): string;
|
|
125
165
|
/** The HTTP status a refused send answers with. */
|
|
@@ -15,9 +15,10 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
15
15
|
* See the License for the specific language governing permissions and
|
|
16
16
|
* limitations under the License.
|
|
17
17
|
*/ import { appendOrderEvent, formatOrderNumber, orderCreatedAtMs } from "./commerce-orders.js";
|
|
18
|
-
import { QUOTE_MIN_CHARGE_CENTS, payLinkCheckoutCharge, quoteCheckoutCharge, quotePageAddress, quotePageLines, quotePageStatus, quotePayRefusal, quotePayRefusalMessage } from "./commerce-quote-pay.js";
|
|
18
|
+
import { QUOTE_MIN_CHARGE_CENTS, payLinkCheckoutCharge, payLinkPaymentsUnavailableMessage, payLinkRefusalWithPayments, quoteCheckoutCharge, quotePageAddress, quotePageLines, quotePageStatus, quotePayRefusal, quotePayRefusalMessage, quotePayTax } from "./commerce-quote-pay.js";
|
|
19
19
|
import { lastQuoteSend } from "./commerce-quote-email.js";
|
|
20
20
|
import { isQuote } from "./commerce-quotes.js";
|
|
21
|
+
import { storefrontTaxDecision } from "./commerce-tax-decision.js";
|
|
21
22
|
import { lineRequiresShipping } from "./order-fulfillment.js";
|
|
22
23
|
/** The most invoice sends an order keeps on record; the oldest go first. */ export const INVOICE_MAX_SENDS = 50;
|
|
23
24
|
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
@@ -104,10 +105,10 @@ const PAID_STATUSES = new Set([
|
|
|
104
105
|
* discount, its tax ({@link invoiceTaxBasis}) and, for a draft, the shipping
|
|
105
106
|
* rates it offered when it was made (Stripe asks for the address and the
|
|
106
107
|
* buyer picks one, as on the draft's first link).
|
|
107
|
-
*/ export function invoiceCheckoutCharge(order, orderId) {
|
|
108
|
+
*/ export function invoiceCheckoutCharge(order, orderId, /** The store's sales tax choice, which a quote saved before it was made takes (`quotePayTax`). */ store) {
|
|
108
109
|
var _order_lineItems, _ref, _ref1;
|
|
109
110
|
var _order_totals, _order_draftShipping, _order_draftShipping1;
|
|
110
|
-
if (order.quote) return _extends({}, quoteCheckoutCharge(order, orderId), {
|
|
111
|
+
if (order.quote) return _extends({}, quoteCheckoutCharge(order, orderId, store), {
|
|
111
112
|
shippingOptions: [],
|
|
112
113
|
shippingCountries: []
|
|
113
114
|
});
|
|
@@ -129,13 +130,16 @@ const PAID_STATUSES = new Set([
|
|
|
129
130
|
shippingCountries: options.length ? countries : []
|
|
130
131
|
});
|
|
131
132
|
}
|
|
132
|
-
export function invoicePayRefusal(order, orderId) {
|
|
133
|
+
export function invoicePayRefusal(order, orderId, /** The store's sales tax choice; with it, a store that has not chosen refuses (AGL-1999). */ store) {
|
|
133
134
|
var _order_lineItems;
|
|
134
135
|
const kind = orderPayLinkKind(order);
|
|
135
|
-
if (kind === 'quote') return quotePayRefusal(order, orderId);
|
|
136
|
+
if (kind === 'quote') return quotePayRefusal(order, orderId, store);
|
|
136
137
|
if (order.status === 'cancelled' || order.status === 'refunded') return 'closed';
|
|
137
138
|
if (order.status !== 'pending') return 'paid';
|
|
138
139
|
if (kind !== 'invoice') return 'not-payable';
|
|
140
|
+
if (store && storefrontTaxDecision({
|
|
141
|
+
settings: store.tax
|
|
142
|
+
}).kind === 'undecided') return 'tax-undecided';
|
|
139
143
|
const ships = ((_order_lineItems = order.lineItems) != null ? _order_lineItems : []).some((line)=>line && !line.included && lineRequiresShipping(line));
|
|
140
144
|
if (ships && !order.draftShipping) return 'shipping-unknown';
|
|
141
145
|
if (invoiceCheckoutCharge(order, orderId).totalCents < QUOTE_MIN_CHARGE_CENTS) return 'nothing-to-pay';
|
|
@@ -162,6 +166,30 @@ export function invoicePayRefusal(order, orderId) {
|
|
|
162
166
|
return `This invoice can’t be paid online. Contact ${business} to pay it.`;
|
|
163
167
|
}
|
|
164
168
|
}
|
|
169
|
+
/**
|
|
170
|
+
* What the console's "Customers can't pay this … online yet" notice names,
|
|
171
|
+
* for an unpaid quote or a draft order's invoice, or a quote not saved yet
|
|
172
|
+
* (`order: null`), which will be saved under the store's choice as it stands.
|
|
173
|
+
* The same answers Pay refuses on: `invoicePayRefusal` with the store, and
|
|
174
|
+
* the payment account check the page and Pay share.
|
|
175
|
+
*
|
|
176
|
+
* Null while either answer is unknown, so the notice waits rather than tell a
|
|
177
|
+
* store that is set up to set up. Empty for anything the pay link does not
|
|
178
|
+
* charge (a paid, closed or unlinked order) or that nothing stands in front of.
|
|
179
|
+
* A refusal that is not the business's setup (approval, an amount too small)
|
|
180
|
+
* is said where it is decided, not here.
|
|
181
|
+
*/ export function payLinkGaps(input) {
|
|
182
|
+
const { order, store } = input;
|
|
183
|
+
if (input.paymentsReady === null || store === undefined) return null;
|
|
184
|
+
if (order && (order.status !== 'pending' || orderPayLinkKind(order) === null)) return [];
|
|
185
|
+
const gaps = [];
|
|
186
|
+
if (!input.paymentsReady) gaps.push('payments');
|
|
187
|
+
if (storefrontTaxDecision({
|
|
188
|
+
settings: store.tax
|
|
189
|
+
}).kind === 'undecided') gaps.push('tax-undecided');
|
|
190
|
+
else if ((order == null ? void 0 : order.quote) && quotePayTax(order.quote, store).source === 'save') gaps.push('tax-save');
|
|
191
|
+
return gaps;
|
|
192
|
+
}
|
|
165
193
|
/*==========================================
|
|
166
194
|
* THE CUSTOMER'S PAGE FOR AN INVOICE
|
|
167
195
|
*=========================================*/ /**
|
|
@@ -175,7 +203,8 @@ export function invoicePayRefusal(order, orderId) {
|
|
|
175
203
|
const { order } = input;
|
|
176
204
|
const status = quotePageStatus(order.status);
|
|
177
205
|
const unpaid = status.status === 'unpaid';
|
|
178
|
-
const charge = invoiceCheckoutCharge(order, input.orderId);
|
|
206
|
+
const charge = invoiceCheckoutCharge(order, input.orderId, input.store);
|
|
207
|
+
const refused = unpaid ? payLinkRefusalWithPayments(invoicePayRefusal(order, input.orderId, input.store), input.paymentsReady) : null;
|
|
179
208
|
const stored = order.totals;
|
|
180
209
|
const totals = unpaid || !stored ? {
|
|
181
210
|
itemsCents: charge.itemsCents,
|
|
@@ -218,7 +247,9 @@ export function invoicePayRefusal(order, orderId) {
|
|
|
218
247
|
paidAtMs: orderPaidAtMs(order),
|
|
219
248
|
receiptUrl: unpaid ? null : (_input_receiptUrl = input.receiptUrl) != null ? _input_receiptUrl : null,
|
|
220
249
|
approvalRequired: false,
|
|
221
|
-
payable: unpaid &&
|
|
250
|
+
payable: unpaid && refused === null,
|
|
251
|
+
notPayableMessage: refused === 'payments-unavailable' ? payLinkPaymentsUnavailableMessage(input.storeName, 'invoice') : null,
|
|
252
|
+
taxKey: null,
|
|
222
253
|
revision: 1,
|
|
223
254
|
proofs: [],
|
|
224
255
|
response: null,
|
|
@@ -274,7 +305,7 @@ export function invoicePayRefusal(order, orderId) {
|
|
|
274
305
|
* Why the order's invoice cannot be emailed to `to` now, if it cannot:
|
|
275
306
|
* a canceled or refunded order, one with nothing on it, an unpaid order its
|
|
276
307
|
* pay link cannot take payment for (and why), and the address.
|
|
277
|
-
*/ export function invoiceSendRefusal(order, orderId, to) {
|
|
308
|
+
*/ export function invoiceSendRefusal(order, orderId, to, /** The store's sales tax choice, as the pay link reads it (`invoicePayRefusal`). */ store) {
|
|
278
309
|
var _order_lineItems;
|
|
279
310
|
var _order_totals;
|
|
280
311
|
if (!order) return 'unknown';
|
|
@@ -282,8 +313,12 @@ export function invoicePayRefusal(order, orderId) {
|
|
|
282
313
|
const lines = ((_order_lineItems = order.lineItems) != null ? _order_lineItems : []).filter(Boolean);
|
|
283
314
|
if (!lines.length && cents((_order_totals = order.totals) == null ? void 0 : _order_totals.totalCents) <= 0) return 'empty';
|
|
284
315
|
if (!invoiceIsPaid(order)) {
|
|
285
|
-
const refused = invoicePayRefusal(order, orderId);
|
|
316
|
+
const refused = invoicePayRefusal(order, orderId, store);
|
|
286
317
|
if (refused === 'closed') return 'closed';
|
|
318
|
+
// A quote saved before the store chose: the store has chosen, and a save prices it.
|
|
319
|
+
if (refused === 'tax-undecided' && order.quote && quotePayTax(order.quote, store).source === 'save') {
|
|
320
|
+
return 'tax-save';
|
|
321
|
+
}
|
|
287
322
|
if (refused && refused !== 'paid') return refused;
|
|
288
323
|
}
|
|
289
324
|
if (!to) return 'no-address';
|
|
@@ -304,6 +339,8 @@ export function invoicePayRefusal(order, orderId) {
|
|
|
304
339
|
return 'This quote asks your customer to approve the proof before they pay, and they haven’t yet. Send the quote so they can approve it, then send the invoice.';
|
|
305
340
|
case 'tax-undecided':
|
|
306
341
|
return 'Sales tax isn’t set up for this store yet, so the invoice can’t be paid online. Finish the tax settings, then send it.';
|
|
342
|
+
case 'tax-save':
|
|
343
|
+
return 'This quote was saved before your store chose how it handles sales tax. Save the quote again, then send the invoice.';
|
|
307
344
|
case 'nothing-to-pay':
|
|
308
345
|
return 'This invoice totals less than $0.50, so it can’t be paid by card.';
|
|
309
346
|
case 'shipping-unknown':
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-invoices.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n appendOrderEvent,\n formatOrderNumber,\n orderCreatedAtMs,\n type HostOrder,\n type OrderStatus,\n type OrderTimelineEvent,\n} from './commerce-orders'\nimport {\n QUOTE_MIN_CHARGE_CENTS,\n payLinkCheckoutCharge,\n quoteCheckoutCharge,\n quotePageAddress,\n quotePageLines,\n quotePageStatus,\n quotePayRefusal,\n quotePayRefusalMessage,\n type QuoteCheckoutCharge,\n type QuotePageView,\n type QuotePayRefusal,\n} from './commerce-quote-pay'\nimport { lastQuoteSend } from './commerce-quote-email'\nimport {\n isQuote,\n type OrderInvoiceSendRecord,\n type QuoteEmailThread,\n type QuoteTaxBasis,\n} from './commerce-quotes'\nimport type { ResolvedShippingRate } from './commerce-shipping'\nimport { lineRequiresShipping } from './order-fulfillment'\n\n/*==========================================\n * INVOICES FOR ORDERS AND QUOTES (AGL-4099).\n *\n * The business emails an invoice for an order or a quote: unpaid, it asks\n * for payment through ONE lasting pay link; paid, it is the record. The link\n * is slice 2's (`/pay-quote?q=&t=`, AGL-4094), generalized rather than made\n * twice:\n *\n * - THE TOKEN is unchanged: `<version>.<HMAC(quote-link:hostId:orderId:version)>`,\n * no expiry. An order id names one document under `hosts/{hostId}/orders`\n * whatever its channel, so the same signature serves any order.\n * - THE VERSION is the quote's `quote.linkVersion` for a quote, as before,\n * so every link already sent keeps verifying; any other order keeps its own\n * as `payLink.version` (`orderPayLinkVersion`). Absent reads as 1.\n * - WHICH ORDERS the link opens ({@link orderPayLinkKind}): a quote, and a\n * draft order (`channel: 'draft'`), the two a business composes for a\n * customer to pay online. A register sale still open takes its payment at\n * the register, an online order was paid at checkout, and a marketplace\n * order on its channel, so none of them is linked; their invoices go out\n * paid, as the record.\n * - THE PAGE shows a non-quote order as \"Invoice #N\", with no proofs and no\n * approval ({@link buildInvoicePageView}).\n * - THE CHARGE is priced from the stored lines and totals on every press\n * ({@link invoiceCheckoutCharge}): the draft's discount, its frozen tax (or\n * Stripe Tax at payment where the draft used it), and the shipping rates\n * the draft offered when it was made (`draftShipping`).\n *\n * Pure: the console, the routes and the webhook read the same answers.\n *=========================================*/\n\n/** Which page a pay link opens for an order: a quote, an invoice, or none. */\nexport type OrderPayLinkKind = 'quote' | 'invoice'\n\n/** The most invoice sends an order keeps on record; the oldest go first. */\nexport const INVOICE_MAX_SENDS = 50\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\nconst cents = (value: unknown): number => {\n const number = Math.round(Number(value))\n return Number.isFinite(number) ? number : 0\n}\n\nconst text = (value: unknown): string | null => {\n const trimmed = typeof value === 'string' ? value.trim() : ''\n return trimmed ? trimmed : null\n}\n\n/**\n * Which page the lasting pay link opens for an order, or null when it opens\n * none: a quote (with its quote section), or a draft order as an invoice.\n */\nexport function orderPayLinkKind(\n order: Pick<HostOrder, 'channel'> & Partial<Pick<HostOrder, 'quote'>> | null | undefined,\n): OrderPayLinkKind | null {\n if (!order) return null\n if (isQuote(order)) return order.quote ? 'quote' : null\n return order.channel === 'draft' ? 'invoice' : null\n}\n\n/** `Invoice #1042`: the order's own number, which a paid quote keeps too. */\nexport function formatInvoiceNumber(order: Pick<HostOrder, 'number'>, orderId?: string): string {\n return `Invoice ${formatOrderNumber(order, orderId)}`\n}\n\nconst PAID_STATUSES: ReadonlySet<OrderStatus | string> = new Set([\n 'paid',\n 'partially_fulfilled',\n 'fulfilled',\n 'delivered',\n])\n\n/** The order is paid (and not refunded or canceled): its invoice is the record. */\nexport function invoiceIsPaid(order: Pick<HostOrder, 'status'> | null | undefined): boolean {\n return PAID_STATUSES.has(String(order?.status ?? ''))\n}\n\n/**\n * When the order was paid: a quote's stamp, else the timeline's `paid`\n * event, else (an order created paid, as checkout's are) when it was made.\n * Null for an order not paid.\n */\nexport function orderPaidAtMs(\n order: Pick<HostOrder, 'status' | 'quote' | 'timeline'> & { createdAtMs?: number } | null | undefined,\n): number | null {\n if (!order || order.status === 'pending') return null\n const stamped = Number(order.quote?.paidAtMs)\n if (Number.isFinite(stamped) && stamped > 0) return stamped\n const event = (order.timeline ?? []).find((entry) => entry?.event === 'paid')\n if (event && Number(event.atMs) > 0) return Number(event.atMs)\n const created = orderCreatedAtMs(order as never)\n return created > 0 ? created : null\n}\n\n/*==========================================\n * WHAT AN INVOICE'S PAY LINK CHARGES\n *=========================================*/\n\n/** What an invoice's Checkout Session charges, with the rates a draft lets the buyer pick from. */\nexport interface InvoiceCheckoutCharge extends QuoteCheckoutCharge {\n /** The draft's shipping rates, picked at payment; empty when shipping is fixed or there is none. */\n shippingOptions: ResolvedShippingRate[]\n /** Where those rates ship; empty with none. */\n shippingCountries: string[]\n}\n\n/**\n * The tax basis an order's stored figures give its invoice: Stripe Tax at\n * payment where the order was composed under it, its frozen tax as a fixed\n * figure (charged as the rate that yields it on the taxed line, the way a tax\n * service's quote is), else none.\n */\nexport function invoiceTaxBasis(order: Pick<HostOrder, 'taxMode' | 'totals'>): QuoteTaxBasis {\n if (order.taxMode === 'stripe-automatic') return { kind: 'at-payment' }\n const taxCents = Math.max(0, cents(order.totals?.taxCents))\n if (taxCents > 0) return { kind: 'service', taxCents }\n return { kind: 'none', reason: 'not-collected' }\n}\n\n/** A stored draft rate, as Stripe is given it, or null for one that is not a rate. */\nfunction draftRate(option: unknown): ResolvedShippingRate | null {\n if (!option || typeof option !== 'object') return null\n const source = option as Record<string, unknown>\n const name = text(source['name'])\n const amountCents = cents(source['amountCents'])\n if (!name || amountCents < 0) return null\n return { rateId: String(source['rateId'] ?? '') || name, name, amountCents }\n}\n\n/**\n * What an invoice's pay link charges, from the stored order alone. A quote is\n * charged as slice 2 charges it; any other order from its lines, its\n * discount, its tax ({@link invoiceTaxBasis}) and, for a draft, the shipping\n * rates it offered when it was made (Stripe asks for the address and the\n * buyer picks one, as on the draft's first link).\n */\nexport function invoiceCheckoutCharge(\n order: Pick<HostOrder, 'number' | 'lineItems' | 'quote' | 'totals' | 'taxMode'> &\n Partial<Pick<HostOrder, 'draftShipping'>>,\n orderId: string,\n): InvoiceCheckoutCharge {\n if (order.quote) return { ...quoteCheckoutCharge(order, orderId), shippingOptions: [], shippingCountries: [] }\n const discountCents = Math.max(0, cents(order.totals?.discountCents))\n const charge = payLinkCheckoutCharge({\n lineItems: order.lineItems ?? [],\n tax: invoiceTaxBasis(order),\n discount: discountCents > 0 ? { kind: 'amount', amountCents: discountCents } : null,\n shippingCents: 0,\n label: formatInvoiceNumber(order, orderId),\n })\n const options = (order.draftShipping?.options ?? [])\n .map(draftRate)\n .filter((rate): rate is ResolvedShippingRate => rate !== null)\n .slice(0, 5)\n const countries = (order.draftShipping?.countries ?? [])\n .map((country) => String(country ?? '').trim().toUpperCase())\n .filter((country) => /^[A-Z]{2}$/.test(country))\n return { ...charge, shippingOptions: options, shippingCountries: options.length ? countries : [] }\n}\n\n/*==========================================\n * WHETHER AN INVOICE CAN BE PAID NOW\n *=========================================*/\n\n/**\n * Why an order cannot be paid through its pay link now: a quote's reasons,\n * and two of an invoice's own. `not-payable` is an order the link does not\n * open (a register sale still open, say); `shipping-unknown` is a draft made\n * before drafts kept their shipping rates, whose shipping cannot be charged.\n */\nexport type InvoicePayRefusal = QuotePayRefusal | 'not-payable' | 'shipping-unknown'\n\nexport function invoicePayRefusal(\n order: Pick<HostOrder, 'number' | 'status' | 'lineItems' | 'quote' | 'totals' | 'taxMode' | 'channel'> &\n Partial<Pick<HostOrder, 'draftShipping'>>,\n orderId: string,\n): InvoicePayRefusal | null {\n const kind = orderPayLinkKind(order)\n if (kind === 'quote') return quotePayRefusal(order, orderId)\n if (order.status === 'cancelled' || order.status === 'refunded') return 'closed'\n if (order.status !== 'pending') return 'paid'\n if (kind !== 'invoice') return 'not-payable'\n const ships = (order.lineItems ?? []).some((line) => line && !line.included && lineRequiresShipping(line))\n if (ships && !order.draftShipping) return 'shipping-unknown'\n if (invoiceCheckoutCharge(order, orderId).totalCents < QUOTE_MIN_CHARGE_CENTS) return 'nothing-to-pay'\n return null\n}\n\n/** What the customer is told for a refusal, in the page's words: \"quote\" or \"invoice\". */\nexport function invoicePayRefusalMessage(\n reason: InvoicePayRefusal,\n storeName: string,\n kind: OrderPayLinkKind,\n): string {\n const business = storeName.trim() || 'the business'\n if (kind === 'quote' && reason !== 'not-payable' && reason !== 'shipping-unknown') {\n return quotePayRefusalMessage(reason, storeName)\n }\n switch (reason) {\n case 'paid':\n return 'This invoice has been paid.'\n case 'closed':\n return `This invoice is closed. Contact ${business} with any questions.`\n case 'approval-required':\n return `${business} asks you to approve the proof before you pay.`\n case 'tax-undecided':\n return `${business} has not finished setting up payments. Contact them to pay this invoice.`\n case 'nothing-to-pay':\n return `This invoice has nothing to pay by card. Contact ${business} with any questions.`\n case 'not-payable':\n case 'shipping-unknown':\n return `This invoice can’t be paid online. Contact ${business} to pay it.`\n }\n}\n\n/*==========================================\n * THE CUSTOMER'S PAGE FOR AN INVOICE\n *=========================================*/\n\n/**\n * The pay link's page for an order that is not a quote: \"Invoice #N\", its\n * lines and totals, the customer's addresses, and Pay while it is unpaid. No\n * proofs, no approval, no notes or terms (an order carries none). Allow-listed\n * as the quote's view is: the order's email, phone, Stripe ids and timeline\n * never leave the server.\n */\nexport function buildInvoicePageView(input: {\n order: Pick<\n HostOrder,\n | 'number'\n | 'status'\n | 'channel'\n | 'lineItems'\n | 'totals'\n | 'quote'\n | 'timeline'\n | 'taxMode'\n | 'customerName'\n | 'billingAddress'\n | 'shippingAddress'\n > &\n Partial<Pick<HostOrder, 'draftShipping'>> & { createdAtMs?: number }\n orderId: string\n storeName: string\n currency: string\n /** The order's status page, once paid. */\n receiptUrl?: string | null\n}): QuotePageView {\n const { order } = input\n const status = quotePageStatus(order.status)\n const unpaid = status.status === 'unpaid'\n const charge = invoiceCheckoutCharge(order, input.orderId)\n const stored = order.totals\n const totals =\n unpaid || !stored\n ? {\n itemsCents: charge.itemsCents,\n discountCents: charge.discountCents,\n shippingCents: charge.shippingCents,\n taxCents: charge.taxCents,\n totalCents: charge.totalCents,\n }\n : {\n itemsCents: cents(stored.itemsCents),\n discountCents: cents(stored.discountCents),\n shippingCents: cents(stored.shippingCents),\n taxCents: cents(stored.taxCents),\n totalCents: cents(stored.totalCents),\n }\n const taxAtPayment = unpaid && charge.taxAtPayment\n const created = orderCreatedAtMs(order as never)\n return {\n state: 'quote',\n kind: 'invoice',\n storeName: input.storeName,\n number: formatInvoiceNumber(order, input.orderId),\n dateMs: created > 0 ? created : null,\n // An invoice is not edited; the page has no version to send back.\n version: 0,\n currency: input.currency || 'USD',\n customerName: text(order.customerName),\n company: null,\n billTo: quotePageAddress(order.billingAddress),\n shipTo: quotePageAddress(order.shippingAddress),\n lines: quotePageLines(order.lineItems ?? []),\n totals,\n discountLabel: null,\n taxLabel: taxAtPayment ? 'Tax is added at payment' : 'Tax',\n taxAtPayment,\n shippingAtPayment: unpaid && charge.shippingOptions.length > 0,\n notes: null,\n terms: null,\n status: status.status,\n statusLabel: status.label,\n paidAtMs: orderPaidAtMs(order),\n receiptUrl: unpaid ? null : (input.receiptUrl ?? null),\n approvalRequired: false,\n payable: unpaid && invoicePayRefusal(order, input.orderId) === null,\n revision: 1,\n proofs: [],\n response: null,\n respondable: false,\n }\n}\n\n/*==========================================\n * EMAILING AN INVOICE\n *=========================================*/\n\n/** The order's invoice sends on record, oldest first. */\nexport function invoiceSends(order: Pick<HostOrder, 'invoiceSends'> | null | undefined): OrderInvoiceSendRecord[] {\n return Array.isArray(order?.invoiceSends)\n ? order.invoiceSends.filter((send) => send && typeof send === 'object')\n : []\n}\n\n/** The last time the order's invoice was emailed, or null. */\nexport function lastInvoiceSend(order: Pick<HostOrder, 'invoiceSends'> | null | undefined): OrderInvoiceSendRecord | null {\n const sends = invoiceSends(order)\n return sends.length ? sends[sends.length - 1] : null\n}\n\n/** Where the invoice goes: what was typed, else the order's customer, else a quote's. */\nexport function invoiceSendRecipient(\n order: Pick<HostOrder, 'customerEmail' | 'quote'> | null | undefined,\n typed: string | null | undefined,\n): string {\n return (\n String(typed ?? '').trim() ||\n String(order?.customerEmail ?? '').trim() ||\n String(order?.quote?.customer?.email ?? '').trim()\n )\n}\n\n/**\n * Who the console's Send invoice form starts addressed to: the customer's\n * email, else where the last invoice went, else (for a quote) where the quote\n * was last emailed, so an order or quote that names no email still opens\n * addressed to the customer it was already sent to.\n */\nexport function invoiceSendPrefill(order: Pick<HostOrder, 'customerEmail' | 'quote' | 'invoiceSends'> | null | undefined): string {\n return (\n invoiceSendRecipient(order, null) ||\n String(lastInvoiceSend(order)?.to ?? '').trim() ||\n String(lastQuoteSend(order?.quote)?.to ?? '').trim()\n )\n}\n\n/**\n * The conversation an invoice replies into: a quote's own (its emails, and a\n * request's confirmation before them), else the order's, which the first\n * invoice starts.\n */\nexport function invoiceEmailThread(\n order: Pick<HostOrder, 'quote' | 'emailThread'> | null | undefined,\n): QuoteEmailThread | null {\n if (order?.quote) return order.quote.emailThread ?? null\n return order?.emailThread ?? null\n}\n\n/**\n * The subject an invoice defaults to: the conversation's, so it stays one\n * conversation in the customer's mailbox, else `Invoice #1042 from Acme Signs`.\n */\nexport function invoiceEmailDefaultSubject(\n order: Pick<HostOrder, 'number' | 'quote' | 'emailThread'>,\n businessName: string,\n orderId?: string,\n): string {\n const thread = String(invoiceEmailThread(order)?.subject ?? '').trim()\n if (thread) return thread\n const name = String(businessName ?? '').trim()\n const number = formatInvoiceNumber(order, orderId)\n return name ? `${number} from ${name}` : number\n}\n\n/** Why an invoice cannot be emailed now, and what the console says. */\nexport type InvoiceSendRefusal =\n | 'unknown'\n | 'closed'\n | 'empty'\n | 'not-payable'\n | 'approval-required'\n | 'tax-undecided'\n | 'nothing-to-pay'\n | 'shipping-unknown'\n | 'no-address'\n | 'bad-address'\n\n/**\n * Why the order's invoice cannot be emailed to `to` now, if it cannot:\n * a canceled or refunded order, one with nothing on it, an unpaid order its\n * pay link cannot take payment for (and why), and the address.\n */\nexport function invoiceSendRefusal(\n order:\n | (Pick<HostOrder, 'number' | 'status' | 'channel' | 'lineItems' | 'totals' | 'quote' | 'taxMode'> &\n Partial<Pick<HostOrder, 'draftShipping'>>)\n | null\n | undefined,\n orderId: string,\n to: string,\n): InvoiceSendRefusal | null {\n if (!order) return 'unknown'\n if (order.status === 'cancelled' || order.status === 'refunded') return 'closed'\n const lines = (order.lineItems ?? []).filter(Boolean)\n if (!lines.length && cents(order.totals?.totalCents) <= 0) return 'empty'\n if (!invoiceIsPaid(order)) {\n const refused = invoicePayRefusal(order, orderId)\n if (refused === 'closed') return 'closed'\n if (refused && refused !== 'paid') return refused\n }\n if (!to) return 'no-address'\n if (to.length > 320 || !EMAIL.test(to)) return 'bad-address'\n return null\n}\n\n/** What the console says for a refused invoice send. */\nexport function invoiceSendRefusalMessage(reason: InvoiceSendRefusal): string {\n switch (reason) {\n case 'unknown':\n return 'Unknown order'\n case 'closed':\n return 'This order was canceled or refunded, so it has no invoice to send.'\n case 'empty':\n return 'This order has no items and no total, so there is nothing to put on an invoice.'\n case 'not-payable':\n return 'This order isn’t paid yet, and it can’t be paid online from an invoice. Take its payment where the sale was made, then send the invoice.'\n case 'approval-required':\n return 'This quote asks your customer to approve the proof before they pay, and they haven’t yet. Send the quote so they can approve it, then send the invoice.'\n case 'tax-undecided':\n return 'Sales tax isn’t set up for this store yet, so the invoice can’t be paid online. Finish the tax settings, then send it.'\n case 'nothing-to-pay':\n return 'This invoice totals less than $0.50, so it can’t be paid by card.'\n case 'shipping-unknown':\n return 'This draft order was made before invoices could charge its shipping, so its invoice can’t be paid online. Make a new draft order and send its invoice.'\n case 'no-address':\n return 'This order has no email for the customer. Type where to send the invoice.'\n case 'bad-address':\n return 'Enter a valid email address to send the invoice to.'\n }\n}\n\n/** The HTTP status a refused send answers with. */\nexport function invoiceSendRefusalStatus(reason: InvoiceSendRefusal): number {\n if (reason === 'unknown') return 404\n if (reason === 'no-address' || reason === 'bad-address') return 400\n return 409\n}\n\n/**\n * What an invoice email changes on the order, as a merge: the send on\n * record, a line on the timeline, and the conversation moved on, on the\n * quote for a quote and on the order otherwise.\n */\nexport function invoiceSendPatch(\n order: Pick<HostOrder, 'timeline' | 'invoiceSends' | 'quote'>,\n send: OrderInvoiceSendRecord,\n thread: QuoteEmailThread,\n): {\n timeline: OrderTimelineEvent[]\n invoiceSends: OrderInvoiceSendRecord[]\n emailThread?: QuoteEmailThread\n quote?: { emailThread: QuoteEmailThread }\n} {\n return {\n timeline: appendOrderEvent(\n order,\n 'invoice-sent',\n // The address is on the send record, which erasure clears; the timeline keeps none.\n `${send.paid ? 'Paid invoice' : 'Invoice'} emailed to the customer by ${send.by}`,\n send.atMs,\n ),\n invoiceSends: [...invoiceSends(order), send].slice(-INVOICE_MAX_SENDS),\n ...(order.quote ? { quote: { emailThread: thread } } : { emailThread: thread }),\n }\n}\n"],"names":["appendOrderEvent","formatOrderNumber","orderCreatedAtMs","QUOTE_MIN_CHARGE_CENTS","payLinkCheckoutCharge","quoteCheckoutCharge","quotePageAddress","quotePageLines","quotePageStatus","quotePayRefusal","quotePayRefusalMessage","lastQuoteSend","isQuote","lineRequiresShipping","INVOICE_MAX_SENDS","EMAIL","cents","value","number","Math","round","Number","isFinite","text","trimmed","trim","orderPayLinkKind","order","quote","channel","formatInvoiceNumber","orderId","PAID_STATUSES","Set","invoiceIsPaid","has","String","status","orderPaidAtMs","stamped","paidAtMs","event","timeline","find","entry","atMs","created","invoiceTaxBasis","taxMode","kind","taxCents","max","totals","reason","draftRate","option","source","name","amountCents","rateId","invoiceCheckoutCharge","shippingOptions","shippingCountries","discountCents","charge","lineItems","tax","discount","shippingCents","label","options","draftShipping","map","filter","rate","slice","countries","country","toUpperCase","test","length","invoicePayRefusal","ships","some","line","included","totalCents","invoicePayRefusalMessage","storeName","business","buildInvoicePageView","input","unpaid","stored","itemsCents","taxAtPayment","state","dateMs","version","currency","customerName","company","billTo","billingAddress","shipTo","shippingAddress","lines","discountLabel","taxLabel","shippingAtPayment","notes","terms","statusLabel","receiptUrl","approvalRequired","payable","revision","proofs","response","respondable","invoiceSends","Array","isArray","send","lastInvoiceSend","sends","invoiceSendRecipient","typed","customerEmail","customer","email","invoiceSendPrefill","to","invoiceEmailThread","emailThread","invoiceEmailDefaultSubject","businessName","thread","subject","invoiceS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ACqD,KAAK,OAAO;IAC/C,OAAO;AACT;AAEA,sDAAsD,GACtD,OAAO,SAASU,0BAA0BzF,MAA0B;IAClE,OAAQA;QACN,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;IACX;AACF;AAEA,iDAAiD,GACjD,OAAO,SAAS0F,yBAAyB1F,MAA0B;IACjE,IAAIA,WAAW,WAAW,OAAO;IACjC,IAAIA,WAAW,gBAAgBA,WAAW,eAAe,OAAO;IAChE,OAAO;AACT;AAEA;;;;CAIC,GACD,OAAO,SAAS2F,iBACdrH,KAA6D,EAC7DgG,IAA4B,EAC5Bc,MAAwB;IAOxB,OAAO;QACL/F,UAAU1C,iBACR2B,OACA,gBACA,oFAAoF;QACpF,GAAGgG,KAAKsB,IAAI,GAAG,iBAAiB,UAAU,4BAA4B,EAAEtB,KAAKuB,EAAE,EAAE,EACjFvB,KAAK9E,IAAI;QAEX2E,cAAc;eAAIA,aAAa7F;YAAQgG;SAAK,CAAChD,KAAK,CAAC,CAAC7D;OAChDa,MAAMC,KAAK,GAAG;QAAEA,OAAO;YAAE0G,aAAaG;QAAO;IAAE,IAAI;QAAEH,aAAaG;IAAO;AAEjF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-invoices.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n appendOrderEvent,\n formatOrderNumber,\n orderCreatedAtMs,\n type HostOrder,\n type OrderStatus,\n type OrderTimelineEvent,\n} from './commerce-orders'\nimport {\n QUOTE_MIN_CHARGE_CENTS,\n payLinkCheckoutCharge,\n payLinkPaymentsUnavailableMessage,\n payLinkRefusalWithPayments,\n quoteCheckoutCharge,\n quotePageAddress,\n quotePageLines,\n quotePageStatus,\n quotePayRefusal,\n quotePayRefusalMessage,\n quotePayTax,\n type PayLinkStore,\n type QuoteCheckoutCharge,\n type QuotePageView,\n type QuotePayRefusal,\n} from './commerce-quote-pay'\nimport { lastQuoteSend } from './commerce-quote-email'\nimport {\n isQuote,\n type OrderInvoiceSendRecord,\n type QuoteEmailThread,\n type QuoteTaxBasis,\n} from './commerce-quotes'\nimport type { ResolvedShippingRate } from './commerce-shipping'\nimport { storefrontTaxDecision } from './commerce-tax-decision'\nimport { lineRequiresShipping } from './order-fulfillment'\n\n/*==========================================\n * INVOICES FOR ORDERS AND QUOTES (AGL-4099).\n *\n * The business emails an invoice for an order or a quote: unpaid, it asks\n * for payment through ONE lasting pay link; paid, it is the record. The link\n * is slice 2's (`/pay-quote?q=&t=`, AGL-4094), generalized rather than made\n * twice:\n *\n * - THE TOKEN is unchanged: `<version>.<HMAC(quote-link:hostId:orderId:version)>`,\n * no expiry. An order id names one document under `hosts/{hostId}/orders`\n * whatever its channel, so the same signature serves any order.\n * - THE VERSION is the quote's `quote.linkVersion` for a quote, as before,\n * so every link already sent keeps verifying; any other order keeps its own\n * as `payLink.version` (`orderPayLinkVersion`). Absent reads as 1.\n * - WHICH ORDERS the link opens ({@link orderPayLinkKind}): a quote, and a\n * draft order (`channel: 'draft'`), the two a business composes for a\n * customer to pay online. A register sale still open takes its payment at\n * the register, an online order was paid at checkout, and a marketplace\n * order on its channel, so none of them is linked; their invoices go out\n * paid, as the record.\n * - THE PAGE shows a non-quote order as \"Invoice #N\", with no proofs and no\n * approval ({@link buildInvoicePageView}).\n * - THE CHARGE is priced from the stored lines and totals on every press\n * ({@link invoiceCheckoutCharge}): the draft's discount, its frozen tax (or\n * Stripe Tax at payment where the draft used it), and the shipping rates\n * the draft offered when it was made (`draftShipping`).\n *\n * Pure: the console, the routes and the webhook read the same answers.\n *=========================================*/\n\n/** Which page a pay link opens for an order: a quote, an invoice, or none. */\nexport type OrderPayLinkKind = 'quote' | 'invoice'\n\n/** The most invoice sends an order keeps on record; the oldest go first. */\nexport const INVOICE_MAX_SENDS = 50\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\nconst cents = (value: unknown): number => {\n const number = Math.round(Number(value))\n return Number.isFinite(number) ? number : 0\n}\n\nconst text = (value: unknown): string | null => {\n const trimmed = typeof value === 'string' ? value.trim() : ''\n return trimmed ? trimmed : null\n}\n\n/**\n * Which page the lasting pay link opens for an order, or null when it opens\n * none: a quote (with its quote section), or a draft order as an invoice.\n */\nexport function orderPayLinkKind(\n order: Pick<HostOrder, 'channel'> & Partial<Pick<HostOrder, 'quote'>> | null | undefined,\n): OrderPayLinkKind | null {\n if (!order) return null\n if (isQuote(order)) return order.quote ? 'quote' : null\n return order.channel === 'draft' ? 'invoice' : null\n}\n\n/** `Invoice #1042`: the order's own number, which a paid quote keeps too. */\nexport function formatInvoiceNumber(order: Pick<HostOrder, 'number'>, orderId?: string): string {\n return `Invoice ${formatOrderNumber(order, orderId)}`\n}\n\nconst PAID_STATUSES: ReadonlySet<OrderStatus | string> = new Set([\n 'paid',\n 'partially_fulfilled',\n 'fulfilled',\n 'delivered',\n])\n\n/** The order is paid (and not refunded or canceled): its invoice is the record. */\nexport function invoiceIsPaid(order: Pick<HostOrder, 'status'> | null | undefined): boolean {\n return PAID_STATUSES.has(String(order?.status ?? ''))\n}\n\n/**\n * When the order was paid: a quote's stamp, else the timeline's `paid`\n * event, else (an order created paid, as checkout's are) when it was made.\n * Null for an order not paid.\n */\nexport function orderPaidAtMs(\n order: Pick<HostOrder, 'status' | 'quote' | 'timeline'> & { createdAtMs?: number } | null | undefined,\n): number | null {\n if (!order || order.status === 'pending') return null\n const stamped = Number(order.quote?.paidAtMs)\n if (Number.isFinite(stamped) && stamped > 0) return stamped\n const event = (order.timeline ?? []).find((entry) => entry?.event === 'paid')\n if (event && Number(event.atMs) > 0) return Number(event.atMs)\n const created = orderCreatedAtMs(order as never)\n return created > 0 ? created : null\n}\n\n/*==========================================\n * WHAT AN INVOICE'S PAY LINK CHARGES\n *=========================================*/\n\n/** What an invoice's Checkout Session charges, with the rates a draft lets the buyer pick from. */\nexport interface InvoiceCheckoutCharge extends QuoteCheckoutCharge {\n /** The draft's shipping rates, picked at payment; empty when shipping is fixed or there is none. */\n shippingOptions: ResolvedShippingRate[]\n /** Where those rates ship; empty with none. */\n shippingCountries: string[]\n}\n\n/**\n * The tax basis an order's stored figures give its invoice: Stripe Tax at\n * payment where the order was composed under it, its frozen tax as a fixed\n * figure (charged as the rate that yields it on the taxed line, the way a tax\n * service's quote is), else none.\n */\nexport function invoiceTaxBasis(order: Pick<HostOrder, 'taxMode' | 'totals'>): QuoteTaxBasis {\n if (order.taxMode === 'stripe-automatic') return { kind: 'at-payment' }\n const taxCents = Math.max(0, cents(order.totals?.taxCents))\n if (taxCents > 0) return { kind: 'service', taxCents }\n return { kind: 'none', reason: 'not-collected' }\n}\n\n/** A stored draft rate, as Stripe is given it, or null for one that is not a rate. */\nfunction draftRate(option: unknown): ResolvedShippingRate | null {\n if (!option || typeof option !== 'object') return null\n const source = option as Record<string, unknown>\n const name = text(source['name'])\n const amountCents = cents(source['amountCents'])\n if (!name || amountCents < 0) return null\n return { rateId: String(source['rateId'] ?? '') || name, name, amountCents }\n}\n\n/**\n * What an invoice's pay link charges, from the stored order alone. A quote is\n * charged as slice 2 charges it; any other order from its lines, its\n * discount, its tax ({@link invoiceTaxBasis}) and, for a draft, the shipping\n * rates it offered when it was made (Stripe asks for the address and the\n * buyer picks one, as on the draft's first link).\n */\nexport function invoiceCheckoutCharge(\n order: Pick<HostOrder, 'number' | 'lineItems' | 'quote' | 'totals' | 'taxMode'> &\n Partial<Pick<HostOrder, 'draftShipping'>>,\n orderId: string,\n /** The store's sales tax choice, which a quote saved before it was made takes (`quotePayTax`). */\n store?: PayLinkStore | null,\n): InvoiceCheckoutCharge {\n if (order.quote) return { ...quoteCheckoutCharge(order, orderId, store), shippingOptions: [], shippingCountries: [] }\n const discountCents = Math.max(0, cents(order.totals?.discountCents))\n const charge = payLinkCheckoutCharge({\n lineItems: order.lineItems ?? [],\n tax: invoiceTaxBasis(order),\n discount: discountCents > 0 ? { kind: 'amount', amountCents: discountCents } : null,\n shippingCents: 0,\n label: formatInvoiceNumber(order, orderId),\n })\n const options = (order.draftShipping?.options ?? [])\n .map(draftRate)\n .filter((rate): rate is ResolvedShippingRate => rate !== null)\n .slice(0, 5)\n const countries = (order.draftShipping?.countries ?? [])\n .map((country) => String(country ?? '').trim().toUpperCase())\n .filter((country) => /^[A-Z]{2}$/.test(country))\n return { ...charge, shippingOptions: options, shippingCountries: options.length ? countries : [] }\n}\n\n/*==========================================\n * WHETHER AN INVOICE CAN BE PAID NOW\n *=========================================*/\n\n/**\n * Why an order cannot be paid through its pay link now: a quote's reasons,\n * and two of an invoice's own. `not-payable` is an order the link does not\n * open (a register sale still open, say); `shipping-unknown` is a draft made\n * before drafts kept their shipping rates, whose shipping cannot be charged.\n */\nexport type InvoicePayRefusal = QuotePayRefusal | 'not-payable' | 'shipping-unknown'\n\nexport function invoicePayRefusal(\n order: Pick<HostOrder, 'number' | 'status' | 'lineItems' | 'quote' | 'totals' | 'taxMode' | 'channel'> &\n Partial<Pick<HostOrder, 'draftShipping'>>,\n orderId: string,\n /** The store's sales tax choice; with it, a store that has not chosen refuses (AGL-1999). */\n store?: PayLinkStore | null,\n): InvoicePayRefusal | null {\n const kind = orderPayLinkKind(order)\n if (kind === 'quote') return quotePayRefusal(order, orderId, store)\n if (order.status === 'cancelled' || order.status === 'refunded') return 'closed'\n if (order.status !== 'pending') return 'paid'\n if (kind !== 'invoice') return 'not-payable'\n if (store && storefrontTaxDecision({ settings: store.tax }).kind === 'undecided') return 'tax-undecided'\n const ships = (order.lineItems ?? []).some((line) => line && !line.included && lineRequiresShipping(line))\n if (ships && !order.draftShipping) return 'shipping-unknown'\n if (invoiceCheckoutCharge(order, orderId).totalCents < QUOTE_MIN_CHARGE_CENTS) return 'nothing-to-pay'\n return null\n}\n\n/** What the customer is told for a refusal, in the page's words: \"quote\" or \"invoice\". */\nexport function invoicePayRefusalMessage(\n reason: InvoicePayRefusal,\n storeName: string,\n kind: OrderPayLinkKind,\n): string {\n const business = storeName.trim() || 'the business'\n if (kind === 'quote' && reason !== 'not-payable' && reason !== 'shipping-unknown') {\n return quotePayRefusalMessage(reason, storeName)\n }\n switch (reason) {\n case 'paid':\n return 'This invoice has been paid.'\n case 'closed':\n return `This invoice is closed. Contact ${business} with any questions.`\n case 'approval-required':\n return `${business} asks you to approve the proof before you pay.`\n case 'tax-undecided':\n return `${business} has not finished setting up payments. Contact them to pay this invoice.`\n case 'nothing-to-pay':\n return `This invoice has nothing to pay by card. Contact ${business} with any questions.`\n case 'not-payable':\n case 'shipping-unknown':\n return `This invoice can’t be paid online. Contact ${business} to pay it.`\n }\n}\n\n/*==========================================\n * WHAT THE CONSOLE TELLS THE BUSINESS\n *=========================================*/\n\n/**\n * What stands between a pay link and a payment that the business fixes in\n * the console (AGL-4162):\n *\n * - `payments`: the workspace can't take card payments yet.\n * - `tax-undecided`: the store has not chosen how it handles sales tax.\n * - `tax-save`: the quote was saved before the store chose, and the store's\n * choice now prices it only on a save (`quotePayTax`'s `save`).\n */\nexport type PayLinkGap = 'payments' | 'tax-undecided' | 'tax-save'\n\n/**\n * What the console's \"Customers can't pay this … online yet\" notice names,\n * for an unpaid quote or a draft order's invoice, or a quote not saved yet\n * (`order: null`), which will be saved under the store's choice as it stands.\n * The same answers Pay refuses on: `invoicePayRefusal` with the store, and\n * the payment account check the page and Pay share.\n *\n * Null while either answer is unknown, so the notice waits rather than tell a\n * store that is set up to set up. Empty for anything the pay link does not\n * charge (a paid, closed or unlinked order) or that nothing stands in front of.\n * A refusal that is not the business's setup (approval, an amount too small)\n * is said where it is decided, not here.\n */\nexport function payLinkGaps(input: {\n order: (Pick<HostOrder, 'status' | 'channel'> & Partial<Pick<HostOrder, 'quote'>>) | null\n /** The workspace can take card payments; null while that is unknown. */\n paymentsReady: boolean | null\n /** The store's sales tax choice; undefined while it is being read. */\n store: PayLinkStore | undefined\n}): PayLinkGap[] | null {\n const { order, store } = input\n if (input.paymentsReady === null || store === undefined) return null\n if (order && (order.status !== 'pending' || orderPayLinkKind(order) === null)) return []\n const gaps: PayLinkGap[] = []\n if (!input.paymentsReady) gaps.push('payments')\n if (storefrontTaxDecision({ settings: store.tax }).kind === 'undecided') gaps.push('tax-undecided')\n else if (order?.quote && quotePayTax(order.quote, store).source === 'save') gaps.push('tax-save')\n return gaps\n}\n\n/*==========================================\n * THE CUSTOMER'S PAGE FOR AN INVOICE\n *=========================================*/\n\n/**\n * The pay link's page for an order that is not a quote: \"Invoice #N\", its\n * lines and totals, the customer's addresses, and Pay while it is unpaid. No\n * proofs, no approval, no notes or terms (an order carries none). Allow-listed\n * as the quote's view is: the order's email, phone, Stripe ids and timeline\n * never leave the server.\n */\nexport function buildInvoicePageView(input: {\n order: Pick<\n HostOrder,\n | 'number'\n | 'status'\n | 'channel'\n | 'lineItems'\n | 'totals'\n | 'quote'\n | 'timeline'\n | 'taxMode'\n | 'customerName'\n | 'billingAddress'\n | 'shippingAddress'\n > &\n Partial<Pick<HostOrder, 'draftShipping'>> & { createdAtMs?: number }\n orderId: string\n storeName: string\n currency: string\n /** The order's status page, once paid. */\n receiptUrl?: string | null\n /** The store's sales tax choice; with it, a store that has not chosen refuses Pay (AGL-1999). */\n store?: PayLinkStore | null\n /** Whether the business can take a card payment now; absent, it is not judged here. */\n paymentsReady?: boolean\n}): QuotePageView {\n const { order } = input\n const status = quotePageStatus(order.status)\n const unpaid = status.status === 'unpaid'\n const charge = invoiceCheckoutCharge(order, input.orderId, input.store)\n const refused = unpaid\n ? payLinkRefusalWithPayments(invoicePayRefusal(order, input.orderId, input.store), input.paymentsReady)\n : null\n const stored = order.totals\n const totals =\n unpaid || !stored\n ? {\n itemsCents: charge.itemsCents,\n discountCents: charge.discountCents,\n shippingCents: charge.shippingCents,\n taxCents: charge.taxCents,\n totalCents: charge.totalCents,\n }\n : {\n itemsCents: cents(stored.itemsCents),\n discountCents: cents(stored.discountCents),\n shippingCents: cents(stored.shippingCents),\n taxCents: cents(stored.taxCents),\n totalCents: cents(stored.totalCents),\n }\n const taxAtPayment = unpaid && charge.taxAtPayment\n const created = orderCreatedAtMs(order as never)\n return {\n state: 'quote',\n kind: 'invoice',\n storeName: input.storeName,\n number: formatInvoiceNumber(order, input.orderId),\n dateMs: created > 0 ? created : null,\n // An invoice is not edited; the page has no version to send back.\n version: 0,\n currency: input.currency || 'USD',\n customerName: text(order.customerName),\n company: null,\n billTo: quotePageAddress(order.billingAddress),\n shipTo: quotePageAddress(order.shippingAddress),\n lines: quotePageLines(order.lineItems ?? []),\n totals,\n discountLabel: null,\n taxLabel: taxAtPayment ? 'Tax is added at payment' : 'Tax',\n taxAtPayment,\n shippingAtPayment: unpaid && charge.shippingOptions.length > 0,\n notes: null,\n terms: null,\n status: status.status,\n statusLabel: status.label,\n paidAtMs: orderPaidAtMs(order),\n receiptUrl: unpaid ? null : (input.receiptUrl ?? null),\n approvalRequired: false,\n payable: unpaid && refused === null,\n notPayableMessage: refused === 'payments-unavailable' ? payLinkPaymentsUnavailableMessage(input.storeName, 'invoice') : null,\n taxKey: null,\n revision: 1,\n proofs: [],\n response: null,\n respondable: false,\n }\n}\n\n/*==========================================\n * EMAILING AN INVOICE\n *=========================================*/\n\n/** The order's invoice sends on record, oldest first. */\nexport function invoiceSends(order: Pick<HostOrder, 'invoiceSends'> | null | undefined): OrderInvoiceSendRecord[] {\n return Array.isArray(order?.invoiceSends)\n ? order.invoiceSends.filter((send) => send && typeof send === 'object')\n : []\n}\n\n/** The last time the order's invoice was emailed, or null. */\nexport function lastInvoiceSend(order: Pick<HostOrder, 'invoiceSends'> | null | undefined): OrderInvoiceSendRecord | null {\n const sends = invoiceSends(order)\n return sends.length ? sends[sends.length - 1] : null\n}\n\n/** Where the invoice goes: what was typed, else the order's customer, else a quote's. */\nexport function invoiceSendRecipient(\n order: Pick<HostOrder, 'customerEmail' | 'quote'> | null | undefined,\n typed: string | null | undefined,\n): string {\n return (\n String(typed ?? '').trim() ||\n String(order?.customerEmail ?? '').trim() ||\n String(order?.quote?.customer?.email ?? '').trim()\n )\n}\n\n/**\n * Who the console's Send invoice form starts addressed to: the customer's\n * email, else where the last invoice went, else (for a quote) where the quote\n * was last emailed, so an order or quote that names no email still opens\n * addressed to the customer it was already sent to.\n */\nexport function invoiceSendPrefill(order: Pick<HostOrder, 'customerEmail' | 'quote' | 'invoiceSends'> | null | undefined): string {\n return (\n invoiceSendRecipient(order, null) ||\n String(lastInvoiceSend(order)?.to ?? '').trim() ||\n String(lastQuoteSend(order?.quote)?.to ?? '').trim()\n )\n}\n\n/**\n * The conversation an invoice replies into: a quote's own (its emails, and a\n * request's confirmation before them), else the order's, which the first\n * invoice starts.\n */\nexport function invoiceEmailThread(\n order: Pick<HostOrder, 'quote' | 'emailThread'> | null | undefined,\n): QuoteEmailThread | null {\n if (order?.quote) return order.quote.emailThread ?? null\n return order?.emailThread ?? null\n}\n\n/**\n * The subject an invoice defaults to: the conversation's, so it stays one\n * conversation in the customer's mailbox, else `Invoice #1042 from Acme Signs`.\n */\nexport function invoiceEmailDefaultSubject(\n order: Pick<HostOrder, 'number' | 'quote' | 'emailThread'>,\n businessName: string,\n orderId?: string,\n): string {\n const thread = String(invoiceEmailThread(order)?.subject ?? '').trim()\n if (thread) return thread\n const name = String(businessName ?? '').trim()\n const number = formatInvoiceNumber(order, orderId)\n return name ? `${number} from ${name}` : number\n}\n\n/** Why an invoice cannot be emailed now, and what the console says. */\nexport type InvoiceSendRefusal =\n | 'unknown'\n | 'closed'\n | 'empty'\n | 'not-payable'\n | 'approval-required'\n | 'tax-undecided'\n | 'tax-save'\n | 'nothing-to-pay'\n | 'shipping-unknown'\n | 'no-address'\n | 'bad-address'\n\n/**\n * Why the order's invoice cannot be emailed to `to` now, if it cannot:\n * a canceled or refunded order, one with nothing on it, an unpaid order its\n * pay link cannot take payment for (and why), and the address.\n */\nexport function invoiceSendRefusal(\n order:\n | (Pick<HostOrder, 'number' | 'status' | 'channel' | 'lineItems' | 'totals' | 'quote' | 'taxMode'> &\n Partial<Pick<HostOrder, 'draftShipping'>>)\n | null\n | undefined,\n orderId: string,\n to: string,\n /** The store's sales tax choice, as the pay link reads it (`invoicePayRefusal`). */\n store?: PayLinkStore | null,\n): InvoiceSendRefusal | null {\n if (!order) return 'unknown'\n if (order.status === 'cancelled' || order.status === 'refunded') return 'closed'\n const lines = (order.lineItems ?? []).filter(Boolean)\n if (!lines.length && cents(order.totals?.totalCents) <= 0) return 'empty'\n if (!invoiceIsPaid(order)) {\n const refused = invoicePayRefusal(order, orderId, store)\n if (refused === 'closed') return 'closed'\n // A quote saved before the store chose: the store has chosen, and a save prices it.\n if (refused === 'tax-undecided' && order.quote && quotePayTax(order.quote, store).source === 'save') {\n return 'tax-save'\n }\n if (refused && refused !== 'paid') return refused\n }\n if (!to) return 'no-address'\n if (to.length > 320 || !EMAIL.test(to)) return 'bad-address'\n return null\n}\n\n/** What the console says for a refused invoice send. */\nexport function invoiceSendRefusalMessage(reason: InvoiceSendRefusal): string {\n switch (reason) {\n case 'unknown':\n return 'Unknown order'\n case 'closed':\n return 'This order was canceled or refunded, so it has no invoice to send.'\n case 'empty':\n return 'This order has no items and no total, so there is nothing to put on an invoice.'\n case 'not-payable':\n return 'This order isn’t paid yet, and it can’t be paid online from an invoice. Take its payment where the sale was made, then send the invoice.'\n case 'approval-required':\n return 'This quote asks your customer to approve the proof before they pay, and they haven’t yet. Send the quote so they can approve it, then send the invoice.'\n case 'tax-undecided':\n return 'Sales tax isn’t set up for this store yet, so the invoice can’t be paid online. Finish the tax settings, then send it.'\n case 'tax-save':\n return 'This quote was saved before your store chose how it handles sales tax. Save the quote again, then send the invoice.'\n case 'nothing-to-pay':\n return 'This invoice totals less than $0.50, so it can’t be paid by card.'\n case 'shipping-unknown':\n return 'This draft order was made before invoices could charge its shipping, so its invoice can’t be paid online. Make a new draft order and send its invoice.'\n case 'no-address':\n return 'This order has no email for the customer. Type where to send the invoice.'\n case 'bad-address':\n return 'Enter a valid email address to send the invoice to.'\n }\n}\n\n/** The HTTP status a refused send answers with. */\nexport function invoiceSendRefusalStatus(reason: InvoiceSendRefusal): number {\n if (reason === 'unknown') return 404\n if (reason === 'no-address' || reason === 'bad-address') return 400\n return 409\n}\n\n/**\n * What an invoice email changes on the order, as a merge: the send on\n * record, a line on the timeline, and the conversation moved on, on the\n * quote for a quote and on the order otherwise.\n */\nexport function invoiceSendPatch(\n order: Pick<HostOrder, 'timeline' | 'invoiceSends' | 'quote'>,\n send: OrderInvoiceSendRecord,\n thread: QuoteEmailThread,\n): {\n timeline: OrderTimelineEvent[]\n invoiceSends: OrderInvoiceSendRecord[]\n emailThread?: QuoteEmailThread\n quote?: { emailThread: QuoteEmailThread }\n} {\n return {\n timeline: appendOrderEvent(\n order,\n 'invoice-sent',\n // The address is on the send record, which erasure clears; the timeline keeps none.\n `${send.paid ? 'Paid invoice' : 'Invoice'} emailed to the customer by ${send.by}`,\n send.atMs,\n ),\n invoiceSends: [...invoiceSends(order), send].slice(-INVOICE_MAX_SENDS),\n ...(order.quote ? { quote: { emailThread: thread } } : { emailThread: thread }),\n }\n}\n"],"names":["appendOrderEvent","formatOrderNumber","orderCreatedAtMs","QUOTE_MIN_CHARGE_CENTS","payLinkCheckoutCharge","payLinkPaymentsUnavailableMessage","payLinkRefusalWithPayments","quoteCheckoutCharge","quotePageAddress","quotePageLines","quotePageStatus","quotePayRefusal","quotePayRefusalMessage","quotePayTax","lastQuoteSend","isQuote","storefrontTaxDecision","lineRequiresShipping","INVOICE_MAX_SENDS","EMAIL","cents","value","number","Math","round","Number","isFinite","text","trimmed","trim","orderPayLinkKind","order","quote","channel","formatInvoiceNumber","orderId","PAID_STATUSES","Set","invoiceIsPaid","has","String","status","orderPaidAtMs","stamped","paidAtMs","event","timeline","find","entry","atMs","created","invoiceTaxBasis","taxMode","kind","taxCents","max","totals","reason","draftRate","option","source","name","amountCents","rateId","invoiceCheckoutCharge","store","shippingOptions","shippingCountries","discountCents","charge","lineItems","tax","discount","shippingCents","label","options","draftShipping","map","filter","rate","slice","countries","country","toUpperCase","test","length","invoicePayRefusal","settings","ships","some","line","included","totalCents","invoicePayRefusalMessage","storeName","business","payLinkGaps","input","paymentsReady","undefined","gaps","push","buildInvoicePageView","unpaid","refused","stored","itemsCents","taxAtPayment","state","dateMs","version","currency","customerName","company","billTo","billingAddress","shipTo","shippingAddress","lines","discountLabel","taxLabel","shippingAtPayment","notes","terms","statusLabel","receiptUrl","approvalRequired","payable","notPayableMessage","taxKey","revision","proofs","response","respondable","invoiceSends","Array","isArray","send","lastInvoiceSend","sends","invoiceSendRecipient","typed","customerEmail","customer","email","invoiceSendPrefill","to","invoiceEmailThread","emailThread","invoiceEmailDefaultSubject","businessName","thread","subject","invoiceSendRefusal","Boolean","invoiceSendRefusalMessage","invoiceSendRefusalStatus","invoiceSendPatch","paid","by"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAChBC,iBAAiB,EACjBC,gBAAgB,QAIX,uBAAmB;AAC1B,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,iCAAiC,EACjCC,0BAA0B,EAC1BC,mBAAmB,EACnBC,gBAAgB,EAChBC,cAAc,EACdC,eAAe,EACfC,eAAe,EACfC,sBAAsB,EACtBC,WAAW,QAKN,0BAAsB;AAC7B,SAASC,aAAa,QAAQ,4BAAwB;AACtD,SACEC,OAAO,QAIF,uBAAmB;A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AAW,WAAW,OAAO;IACjC,IAAIA,WAAW,gBAAgBA,WAAW,eAAe,OAAO;IAChE,OAAO;AACT;AAEA;;;;CAIC,GACD,OAAO,SAASoG,iBACd9H,KAA6D,EAC7D0G,IAA4B,EAC5Bc,MAAwB;IAOxB,OAAO;QACLzG,UAAU9C,iBACR+B,OACA,gBACA,oFAAoF;QACpF,GAAG0G,KAAKqB,IAAI,GAAG,iBAAiB,UAAU,4BAA4B,EAAErB,KAAKsB,EAAE,EAAE,EACjFtB,KAAKxF,IAAI;QAEXqF,cAAc;eAAIA,aAAavG;YAAQ0G;SAAK,CAACzD,KAAK,CAAC,CAAC9D;OAChDa,MAAMC,KAAK,GAAG;QAAEA,OAAO;YAAEoH,aAAaG;QAAO;IAAE,IAAI;QAAEH,aAAaG;IAAO;AAEjF"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* Whether a product's name answers the words typed, the way the catalog's
|
|
19
|
+
* search does: every word is the start of a word in the name, whatever the
|
|
20
|
+
* case. The query can hold only the first word, so the rest are asked here.
|
|
21
|
+
*/
|
|
22
|
+
export declare function posKioskNameMatches(name: string, typed: string): boolean;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ import { nameSearchKey, nameSearchToken, nameSearchTokens } from "@aglyn/aglyn/app-utils/name-search";
|
|
17
|
+
/*
|
|
18
|
+
* Its own module, not `commerce-pos-kiosk.ts`, which the plugin's eager chunk
|
|
19
|
+
* reaches: only the kiosk route and the kiosk's server read this, and every
|
|
20
|
+
* console screen would otherwise pay for it.
|
|
21
|
+
*/ /**
|
|
22
|
+
* Whether a product's name answers the words typed, the way the catalog's
|
|
23
|
+
* search does: every word is the start of a word in the name, whatever the
|
|
24
|
+
* case. The query can hold only the first word, so the rest are asked here.
|
|
25
|
+
*/ export function posKioskNameMatches(name, typed) {
|
|
26
|
+
const key = nameSearchKey(typed);
|
|
27
|
+
if (!key) return true;
|
|
28
|
+
const tokens = new Set(nameSearchTokens(name));
|
|
29
|
+
return key.split(' ').every((word)=>tokens.has(nameSearchToken(word)));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
//# sourceMappingURL=commerce-kiosk-search.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-kiosk-search.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameSearchKey, nameSearchToken, nameSearchTokens } from '@aglyn/aglyn/app-utils/name-search'\n\n/*\n * Its own module, not `commerce-pos-kiosk.ts`, which the plugin's eager chunk\n * reaches: only the kiosk route and the kiosk's server read this, and every\n * console screen would otherwise pay for it.\n */\n\n/**\n * Whether a product's name answers the words typed, the way the catalog's\n * search does: every word is the start of a word in the name, whatever the\n * case. The query can hold only the first word, so the rest are asked here.\n */\nexport function posKioskNameMatches(name: string, typed: string): boolean {\n const key = nameSearchKey(typed)\n if (!key) return true\n const tokens = new Set(nameSearchTokens(name))\n return key.split(' ').every((word) => tokens.has(nameSearchToken(word)))\n}\n"],"names":["nameSearchKey","nameSearchToken","nameSearchTokens","posKioskNameMatches","name","typed","key","tokens","Set","split","every","word","has"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,EAAEC,eAAe,EAAEC,gBAAgB,QAAQ,qCAAoC;AAErG;;;;CAIC,GAED;;;;CAIC,GACD,OAAO,SAASC,oBAAoBC,IAAY,EAAEC,KAAa;IAC7D,MAAMC,MAAMN,cAAcK;IAC1B,IAAI,CAACC,KAAK,OAAO;IACjB,MAAMC,SAAS,IAAIC,IAAIN,iBAAiBE;IACxC,OAAOE,IAAIG,KAAK,CAAC,KAAKC,KAAK,CAAC,CAACC,OAASJ,OAAOK,GAAG,CAACX,gBAAgBU;AACnE"}
|
|
@@ -50,6 +50,12 @@ export interface PosKioskCatalog {
|
|
|
50
50
|
categories: PosKioskCategory[];
|
|
51
51
|
/** The store's currency, lower case (`usd`). */
|
|
52
52
|
currency: string;
|
|
53
|
+
/**
|
|
54
|
+
* Set when the store has more to offer than this answer lists, so the menu
|
|
55
|
+
* offers a search that reaches the rest. Absent on an answer that lists
|
|
56
|
+
* everything, which is every catalog the menu can show whole.
|
|
57
|
+
*/
|
|
58
|
+
truncated?: boolean;
|
|
53
59
|
}
|
|
54
60
|
/** What the kiosk offers, resolved on the server for one paired register. */
|
|
55
61
|
export interface PosKioskContext {
|
|
@@ -131,7 +137,7 @@ export declare const POS_KIOSK_DONE_SECONDS = 15;
|
|
|
131
137
|
export declare const POS_KIOSK_MAX_LINES = 40;
|
|
132
138
|
/** Most of one line a customer may order at a kiosk. */
|
|
133
139
|
export declare const POS_KIOSK_MAX_QUANTITY = 20;
|
|
134
|
-
/** Most products the kiosk grid lists
|
|
140
|
+
/** Most products the kiosk grid lists at once, for the whole menu, a category or a search. */
|
|
135
141
|
export declare const POS_KIOSK_CATALOG_LIMIT = 200;
|
|
136
142
|
/** Wrong staff PINs a kiosk takes before it locks its unlock screen. */
|
|
137
143
|
export declare const POS_KIOSK_UNLOCK_MAX_ATTEMPTS = 5;
|
|
@@ -23,7 +23,7 @@ export const POS_KIOSK_IDLE_SECONDS_MAX = 600;
|
|
|
23
23
|
/** The order-number screen returns to the start after this long. */ export const POS_KIOSK_DONE_SECONDS = 15;
|
|
24
24
|
/** Most lines one kiosk order carries. */ export const POS_KIOSK_MAX_LINES = 40;
|
|
25
25
|
/** Most of one line a customer may order at a kiosk. */ export const POS_KIOSK_MAX_QUANTITY = 20;
|
|
26
|
-
/** Most products the kiosk grid lists
|
|
26
|
+
/** Most products the kiosk grid lists at once, for the whole menu, a category or a search. */ export const POS_KIOSK_CATALOG_LIMIT = 200;
|
|
27
27
|
/** Wrong staff PINs a kiosk takes before it locks its unlock screen. */ export const POS_KIOSK_UNLOCK_MAX_ATTEMPTS = 5;
|
|
28
28
|
/** How long a kiosk's unlock screen stays locked after too many wrong PINs. */ export const POS_KIOSK_UNLOCK_LOCKOUT_MS = 15 * 60 * 1000;
|
|
29
29
|
/** How long a staff unlock keeps the kiosk's settings open. */ export const POS_KIOSK_UNLOCK_TTL_MS = 5 * 60 * 1000;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-pos-kiosk.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { posTipFromPercent, posTipProblem, type PosReceiptChannel } from './commerce-pos'\nimport { modifierOptionPriceCents, type ModifierSelection, type ProductModifierGroup } from './product-modifiers'\n\n/*==========================================\n * THE SELF-SERVICE KIOSK (AGL-3623).\n *\n * A register's second kind of paired screen: where the customer display\n * (AGL-3608) mirrors the cashier's basket, a kiosk lets the customer build\n * their own order — a product grid with categories and modifiers, a cart, a\n * tip, payment on the register's card reader or Tap to Pay, or \"pay at\n * counter\", which sends the order to the register's queue for a cashier.\n *\n * It pairs exactly like a display (the same six-digit code and the same\n * hashed device token, with `mode: 'kiosk'` on both), and it never holds a\n * staff session: every request carries the device token and the server\n * prices everything. These are the shapes the kiosk route and every client\n * of it — the web kiosk and the native POS app — agree on.\n *=========================================*/\n\n/** Which kind of paired screen a device token opens. */\nexport type PosDeviceMode = 'display' | 'kiosk'\n\n/** A product as the kiosk grid shows it: no cost, no stock count, no supplier. */\nexport interface PosKioskProduct {\n id: string\n name: string\n description?: string\n imageUrl?: string\n categoryIds: string[]\n /** The product's option axes (\"Size\": S, M, L), for the variant picker. */\n options: Array<{ name: string; values: string[] }>\n variants: PosKioskVariant[]\n modifierGroups: ProductModifierGroup[]\n}\n\nexport interface PosKioskVariant {\n id: string\n /** Option selections keyed by option name; empty for the default variant. */\n options: Record<string, string>\n priceCents: number\n /** A tracked variant at or below zero whose product refuses to oversell. */\n soldOut: boolean\n}\n\nexport interface PosKioskCategory {\n id: string\n name: string\n}\n\nexport interface PosKioskCatalog {\n products: PosKioskProduct[]\n categories: PosKioskCategory[]\n /** The store's currency, lower case (`usd`). */\n currency: string\n}\n\n/** What the kiosk offers, resolved on the server for one paired register. */\nexport interface PosKioskContext {\n branding: {\n name: string\n logoUrl: string | null\n logoDarkUrl: string | null\n message: string\n }\n currency: string\n tipping: { enabled: boolean; percentages: number[] }\n payments: {\n /** A Stripe Terminal smart reader is assigned to this register. */\n reader: boolean\n /** Card-present payments are switched on for the platform (Tap to Pay needs the native app too). */\n cardPresent: boolean\n /** \"Pay at counter\" sends the order to the register's queue. */\n payAtCounter: boolean\n }\n receipts: PosReceiptChannel[]\n offerMarketing: boolean\n /** Seconds without a touch before the kiosk asks \"Still there?\". */\n idleSeconds: number\n /** Stripe test mode: a test card can be tapped from the payment screen. */\n testMode: boolean\n}\n\n/** One cart line as the kiosk sends it: ids and a count, never a price. */\nexport interface PosKioskLine {\n productId: string\n variantId?: string\n quantity: number\n modifiers?: ModifierSelection[]\n}\n\n/** A line of a priced kiosk order, as the customer's screen shows it. */\nexport interface PosKioskSaleLine {\n name: string\n variantLabel?: string\n quantity: number\n amountCents: number\n}\n\nexport type PosKioskSaleStatus =\n /** Priced and waiting for a card at the kiosk. */\n | 'open'\n /** Sent to the register's queue; a cashier takes payment. */\n | 'queued'\n | 'paid'\n | 'voided'\n\n/** A kiosk order as its own screen reads it back. */\nexport interface PosKioskSale {\n orderId: string\n /** The order number the customer is called by. */\n number: number\n status: PosKioskSaleStatus\n lines: PosKioskSaleLine[]\n itemsCents: number\n discountCents: number\n taxCents: number\n totalCents: number\n tipCents: number\n paidCents: number\n dueCents: number\n /** The card payment in flight, if any. */\n payment: { id: string; status: string; failureMessage?: string } | null\n}\n\n/** Seconds without a touch before the kiosk asks \"Still there?\", by default. */\nexport const POS_KIOSK_IDLE_SECONDS_DEFAULT = 90\nexport const POS_KIOSK_IDLE_SECONDS_MIN = 30\nexport const POS_KIOSK_IDLE_SECONDS_MAX = 600\n\n/** How long \"Still there?\" waits before the kiosk clears itself. */\nexport const POS_KIOSK_IDLE_WARNING_SECONDS = 20\n\n/** The order-number screen returns to the start after this long. */\nexport const POS_KIOSK_DONE_SECONDS = 15\n\n/** Most lines one kiosk order carries. */\nexport const POS_KIOSK_MAX_LINES = 40\n\n/** Most of one line a customer may order at a kiosk. */\nexport const POS_KIOSK_MAX_QUANTITY = 20\n\n/** Most products the kiosk grid lists in one category. */\nexport const POS_KIOSK_CATALOG_LIMIT = 200\n\n/** Wrong staff PINs a kiosk takes before it locks its unlock screen. */\nexport const POS_KIOSK_UNLOCK_MAX_ATTEMPTS = 5\n\n/** How long a kiosk's unlock screen stays locked after too many wrong PINs. */\nexport const POS_KIOSK_UNLOCK_LOCKOUT_MS = 15 * 60 * 1000\n\n/** How long a staff unlock keeps the kiosk's settings open. */\nexport const POS_KIOSK_UNLOCK_TTL_MS = 5 * 60 * 1000\n\nconst ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/\n\n/**\n * The cart as the kiosk may send it, or why not. Ids are shape-checked and\n * quantities bounded here; everything else — whether the product exists, is\n * for sale, what it costs and whether its modifiers are valid — is the sale\n * route's to decide from the product documents.\n */\nexport function sanitizePosKioskLines(\n raw: unknown,\n): { ok: true; lines: PosKioskLine[] } | { ok: false; error: string } {\n if (!Array.isArray(raw) || raw.length === 0) return { ok: false, error: 'Your cart is empty.' }\n if (raw.length > POS_KIOSK_MAX_LINES) {\n return { ok: false, error: `An order can have at most ${POS_KIOSK_MAX_LINES} items.` }\n }\n const lines: PosKioskLine[] = []\n for (const entry of raw as Array<Record<string, unknown>>) {\n const productId = String(entry?.['productId'] ?? '')\n const variantId = entry?.['variantId'] == null ? '' : String(entry['variantId'])\n const quantity = Number(entry?.['quantity'])\n if (!ID_PATTERN.test(productId) || (variantId && !ID_PATTERN.test(variantId))) {\n return { ok: false, error: 'An item in your cart is no longer available.' }\n }\n if (!Number.isInteger(quantity) || quantity < 1 || quantity > POS_KIOSK_MAX_QUANTITY) {\n return { ok: false, error: `Order 1 to ${POS_KIOSK_MAX_QUANTITY} of each item.` }\n }\n const rawModifiers = Array.isArray(entry?.['modifiers']) ? (entry['modifiers'] as unknown[]) : []\n if (rawModifiers.length > 200) return { ok: false, error: 'Too many choices on one item.' }\n const modifiers: ModifierSelection[] = []\n for (const pick of rawModifiers as Array<Record<string, unknown>>) {\n const groupId = String(pick?.['groupId'] ?? '')\n const optionId = String(pick?.['optionId'] ?? '')\n if (!ID_PATTERN.test(groupId) || !ID_PATTERN.test(optionId)) {\n return { ok: false, error: 'A choice on an item is no longer offered.' }\n }\n modifiers.push({ groupId, optionId })\n }\n lines.push({\n productId,\n ...(variantId ? { variantId } : {}),\n quantity,\n ...(modifiers.length ? { modifiers } : {}),\n })\n }\n return { ok: true, lines }\n}\n\n/**\n * The tip a kiosk customer chose, recomputed from the server's own figure\n * for what is being paid: a percentage only from the store's presets, a\n * custom amount bounded like every register tip. Null when the choice is\n * not one the store offers.\n */\nexport function posKioskTipCents(\n choice: unknown,\n input: { baseCents: number; enabled: boolean; percentages: readonly number[]; percent?: unknown; cents?: unknown },\n): number | null {\n if (choice === undefined || choice === null || choice === 'none') return 0\n if (!input.enabled) return null\n if (choice === 'percent') {\n const percent = Math.round(Number(input.percent))\n if (!input.percentages.includes(percent)) return null\n return posTipFromPercent(input.baseCents, percent)\n }\n if (choice === 'custom') {\n const cents = Math.round(Number(input.cents))\n return posTipProblem(cents, input.baseCents) ? null : cents\n }\n return null\n}\n\n/** The idle timeout a merchant set, bounded. */\nexport function posKioskIdleSeconds(raw: unknown): number {\n const value = Math.round(Number(raw))\n if (!Number.isFinite(value) || value <= 0) return POS_KIOSK_IDLE_SECONDS_DEFAULT\n return Math.min(POS_KIOSK_IDLE_SECONDS_MAX, Math.max(POS_KIOSK_IDLE_SECONDS_MIN, value))\n}\n\n/**\n * The kiosk's estimate of its cart, from the catalog prices it was given —\n * shown while the customer shops and never sent. The order is priced again,\n * with tax, by the server when they check out.\n */\nexport function posKioskEstimateCents(\n lines: readonly PosKioskLine[],\n products: readonly PosKioskProduct[],\n): number {\n let total = 0\n for (const line of lines) {\n const product = products.find((candidate) => candidate.id === line.productId)\n if (!product) continue\n const variant =\n product.variants.find((candidate) => candidate.id === line.variantId) ?? product.variants[0]\n if (!variant) continue\n const extra = (line.modifiers ?? []).reduce((sum, pick) => {\n const group = product.modifierGroups.find((candidate) => candidate.id === pick.groupId)\n const option = group?.options.find((candidate) => candidate.id === pick.optionId)\n // A choice priced by variant adds its price on this one (AGL-4100).\n return sum + (option ? modifierOptionPriceCents(option, variant.id) : 0)\n }, 0)\n total += (variant.priceCents + extra) * line.quantity\n }\n return total\n}\n"],"names":["posTipFromPercent","posTipProblem","modifierOptionPriceCents","POS_KIOSK_IDLE_SECONDS_DEFAULT","POS_KIOSK_IDLE_SECONDS_MIN","POS_KIOSK_IDLE_SECONDS_MAX","POS_KIOSK_IDLE_WARNING_SECONDS","POS_KIOSK_DONE_SECONDS","POS_KIOSK_MAX_LINES","POS_KIOSK_MAX_QUANTITY","POS_KIOSK_CATALOG_LIMIT","POS_KIOSK_UNLOCK_MAX_ATTEMPTS","POS_KIOSK_UNLOCK_LOCKOUT_MS","POS_KIOSK_UNLOCK_TTL_MS","ID_PATTERN","sanitizePosKioskLines","raw","Array","isArray","length","ok","error","lines","entry","productId","String","variantId","quantity","Number","test","isInteger","rawModifiers","modifiers","pick","groupId","optionId","push","posKioskTipCents","choice","input","undefined","enabled","percent","Math","round","percentages","includes","baseCents","cents","posKioskIdleSeconds","value","isFinite","min","max","posKioskEstimateCents","products","total","line","product","find","candidate","id","variant","variants","extra","reduce","sum","group","modifierGroups","option","options","priceCents"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,EAAEC,aAAa,QAAgC,oBAAgB;AACzF,SAASC,wBAAwB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AAUC,EAAE,KAAK5B,KAAKE,QAAQ;YAChF,oEAAoE;YACpE,OAAO+B,MAAOG,CAAAA,SAASnE,yBAAyBmE,QAAQP,QAAQD,EAAE,IAAI,CAAA;QACxE,GAAG;QACHL,SAAS,AAACM,CAAAA,QAAQS,UAAU,GAAGP,KAAI,IAAKP,KAAK9B,QAAQ;IACvD;IACA,OAAO6B;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-pos-kiosk.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { posTipFromPercent, posTipProblem, type PosReceiptChannel } from './commerce-pos'\nimport { modifierOptionPriceCents, type ModifierSelection, type ProductModifierGroup } from './product-modifiers'\n\n/*==========================================\n * THE SELF-SERVICE KIOSK (AGL-3623).\n *\n * A register's second kind of paired screen: where the customer display\n * (AGL-3608) mirrors the cashier's basket, a kiosk lets the customer build\n * their own order — a product grid with categories and modifiers, a cart, a\n * tip, payment on the register's card reader or Tap to Pay, or \"pay at\n * counter\", which sends the order to the register's queue for a cashier.\n *\n * It pairs exactly like a display (the same six-digit code and the same\n * hashed device token, with `mode: 'kiosk'` on both), and it never holds a\n * staff session: every request carries the device token and the server\n * prices everything. These are the shapes the kiosk route and every client\n * of it — the web kiosk and the native POS app — agree on.\n *=========================================*/\n\n/** Which kind of paired screen a device token opens. */\nexport type PosDeviceMode = 'display' | 'kiosk'\n\n/** A product as the kiosk grid shows it: no cost, no stock count, no supplier. */\nexport interface PosKioskProduct {\n id: string\n name: string\n description?: string\n imageUrl?: string\n categoryIds: string[]\n /** The product's option axes (\"Size\": S, M, L), for the variant picker. */\n options: Array<{ name: string; values: string[] }>\n variants: PosKioskVariant[]\n modifierGroups: ProductModifierGroup[]\n}\n\nexport interface PosKioskVariant {\n id: string\n /** Option selections keyed by option name; empty for the default variant. */\n options: Record<string, string>\n priceCents: number\n /** A tracked variant at or below zero whose product refuses to oversell. */\n soldOut: boolean\n}\n\nexport interface PosKioskCategory {\n id: string\n name: string\n}\n\nexport interface PosKioskCatalog {\n products: PosKioskProduct[]\n categories: PosKioskCategory[]\n /** The store's currency, lower case (`usd`). */\n currency: string\n /**\n * Set when the store has more to offer than this answer lists, so the menu\n * offers a search that reaches the rest. Absent on an answer that lists\n * everything, which is every catalog the menu can show whole.\n */\n truncated?: boolean\n}\n\n/** What the kiosk offers, resolved on the server for one paired register. */\nexport interface PosKioskContext {\n branding: {\n name: string\n logoUrl: string | null\n logoDarkUrl: string | null\n message: string\n }\n currency: string\n tipping: { enabled: boolean; percentages: number[] }\n payments: {\n /** A Stripe Terminal smart reader is assigned to this register. */\n reader: boolean\n /** Card-present payments are switched on for the platform (Tap to Pay needs the native app too). */\n cardPresent: boolean\n /** \"Pay at counter\" sends the order to the register's queue. */\n payAtCounter: boolean\n }\n receipts: PosReceiptChannel[]\n offerMarketing: boolean\n /** Seconds without a touch before the kiosk asks \"Still there?\". */\n idleSeconds: number\n /** Stripe test mode: a test card can be tapped from the payment screen. */\n testMode: boolean\n}\n\n/** One cart line as the kiosk sends it: ids and a count, never a price. */\nexport interface PosKioskLine {\n productId: string\n variantId?: string\n quantity: number\n modifiers?: ModifierSelection[]\n}\n\n/** A line of a priced kiosk order, as the customer's screen shows it. */\nexport interface PosKioskSaleLine {\n name: string\n variantLabel?: string\n quantity: number\n amountCents: number\n}\n\nexport type PosKioskSaleStatus =\n /** Priced and waiting for a card at the kiosk. */\n | 'open'\n /** Sent to the register's queue; a cashier takes payment. */\n | 'queued'\n | 'paid'\n | 'voided'\n\n/** A kiosk order as its own screen reads it back. */\nexport interface PosKioskSale {\n orderId: string\n /** The order number the customer is called by. */\n number: number\n status: PosKioskSaleStatus\n lines: PosKioskSaleLine[]\n itemsCents: number\n discountCents: number\n taxCents: number\n totalCents: number\n tipCents: number\n paidCents: number\n dueCents: number\n /** The card payment in flight, if any. */\n payment: { id: string; status: string; failureMessage?: string } | null\n}\n\n/** Seconds without a touch before the kiosk asks \"Still there?\", by default. */\nexport const POS_KIOSK_IDLE_SECONDS_DEFAULT = 90\nexport const POS_KIOSK_IDLE_SECONDS_MIN = 30\nexport const POS_KIOSK_IDLE_SECONDS_MAX = 600\n\n/** How long \"Still there?\" waits before the kiosk clears itself. */\nexport const POS_KIOSK_IDLE_WARNING_SECONDS = 20\n\n/** The order-number screen returns to the start after this long. */\nexport const POS_KIOSK_DONE_SECONDS = 15\n\n/** Most lines one kiosk order carries. */\nexport const POS_KIOSK_MAX_LINES = 40\n\n/** Most of one line a customer may order at a kiosk. */\nexport const POS_KIOSK_MAX_QUANTITY = 20\n\n/** Most products the kiosk grid lists at once, for the whole menu, a category or a search. */\nexport const POS_KIOSK_CATALOG_LIMIT = 200\n\n/** Wrong staff PINs a kiosk takes before it locks its unlock screen. */\nexport const POS_KIOSK_UNLOCK_MAX_ATTEMPTS = 5\n\n/** How long a kiosk's unlock screen stays locked after too many wrong PINs. */\nexport const POS_KIOSK_UNLOCK_LOCKOUT_MS = 15 * 60 * 1000\n\n/** How long a staff unlock keeps the kiosk's settings open. */\nexport const POS_KIOSK_UNLOCK_TTL_MS = 5 * 60 * 1000\n\nconst ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/\n\n/**\n * The cart as the kiosk may send it, or why not. Ids are shape-checked and\n * quantities bounded here; everything else — whether the product exists, is\n * for sale, what it costs and whether its modifiers are valid — is the sale\n * route's to decide from the product documents.\n */\nexport function sanitizePosKioskLines(\n raw: unknown,\n): { ok: true; lines: PosKioskLine[] } | { ok: false; error: string } {\n if (!Array.isArray(raw) || raw.length === 0) return { ok: false, error: 'Your cart is empty.' }\n if (raw.length > POS_KIOSK_MAX_LINES) {\n return { ok: false, error: `An order can have at most ${POS_KIOSK_MAX_LINES} items.` }\n }\n const lines: PosKioskLine[] = []\n for (const entry of raw as Array<Record<string, unknown>>) {\n const productId = String(entry?.['productId'] ?? '')\n const variantId = entry?.['variantId'] == null ? '' : String(entry['variantId'])\n const quantity = Number(entry?.['quantity'])\n if (!ID_PATTERN.test(productId) || (variantId && !ID_PATTERN.test(variantId))) {\n return { ok: false, error: 'An item in your cart is no longer available.' }\n }\n if (!Number.isInteger(quantity) || quantity < 1 || quantity > POS_KIOSK_MAX_QUANTITY) {\n return { ok: false, error: `Order 1 to ${POS_KIOSK_MAX_QUANTITY} of each item.` }\n }\n const rawModifiers = Array.isArray(entry?.['modifiers']) ? (entry['modifiers'] as unknown[]) : []\n if (rawModifiers.length > 200) return { ok: false, error: 'Too many choices on one item.' }\n const modifiers: ModifierSelection[] = []\n for (const pick of rawModifiers as Array<Record<string, unknown>>) {\n const groupId = String(pick?.['groupId'] ?? '')\n const optionId = String(pick?.['optionId'] ?? '')\n if (!ID_PATTERN.test(groupId) || !ID_PATTERN.test(optionId)) {\n return { ok: false, error: 'A choice on an item is no longer offered.' }\n }\n modifiers.push({ groupId, optionId })\n }\n lines.push({\n productId,\n ...(variantId ? { variantId } : {}),\n quantity,\n ...(modifiers.length ? { modifiers } : {}),\n })\n }\n return { ok: true, lines }\n}\n\n/**\n * The tip a kiosk customer chose, recomputed from the server's own figure\n * for what is being paid: a percentage only from the store's presets, a\n * custom amount bounded like every register tip. Null when the choice is\n * not one the store offers.\n */\nexport function posKioskTipCents(\n choice: unknown,\n input: { baseCents: number; enabled: boolean; percentages: readonly number[]; percent?: unknown; cents?: unknown },\n): number | null {\n if (choice === undefined || choice === null || choice === 'none') return 0\n if (!input.enabled) return null\n if (choice === 'percent') {\n const percent = Math.round(Number(input.percent))\n if (!input.percentages.includes(percent)) return null\n return posTipFromPercent(input.baseCents, percent)\n }\n if (choice === 'custom') {\n const cents = Math.round(Number(input.cents))\n return posTipProblem(cents, input.baseCents) ? null : cents\n }\n return null\n}\n\n/** The idle timeout a merchant set, bounded. */\nexport function posKioskIdleSeconds(raw: unknown): number {\n const value = Math.round(Number(raw))\n if (!Number.isFinite(value) || value <= 0) return POS_KIOSK_IDLE_SECONDS_DEFAULT\n return Math.min(POS_KIOSK_IDLE_SECONDS_MAX, Math.max(POS_KIOSK_IDLE_SECONDS_MIN, value))\n}\n\n/**\n * The kiosk's estimate of its cart, from the catalog prices it was given —\n * shown while the customer shops and never sent. The order is priced again,\n * with tax, by the server when they check out.\n */\nexport function posKioskEstimateCents(\n lines: readonly PosKioskLine[],\n products: readonly PosKioskProduct[],\n): number {\n let total = 0\n for (const line of lines) {\n const product = products.find((candidate) => candidate.id === line.productId)\n if (!product) continue\n const variant =\n product.variants.find((candidate) => candidate.id === line.variantId) ?? product.variants[0]\n if (!variant) continue\n const extra = (line.modifiers ?? []).reduce((sum, pick) => {\n const group = product.modifierGroups.find((candidate) => candidate.id === pick.groupId)\n const option = group?.options.find((candidate) => candidate.id === pick.optionId)\n // A choice priced by variant adds its price on this one (AGL-4100).\n return sum + (option ? modifierOptionPriceCents(option, variant.id) : 0)\n }, 0)\n total += (variant.priceCents + extra) * line.quantity\n }\n return total\n}\n"],"names":["posTipFromPercent","posTipProblem","modifierOptionPriceCents","POS_KIOSK_IDLE_SECONDS_DEFAULT","POS_KIOSK_IDLE_SECONDS_MIN","POS_KIOSK_IDLE_SECONDS_MAX","POS_KIOSK_IDLE_WARNING_SECONDS","POS_KIOSK_DONE_SECONDS","POS_KIOSK_MAX_LINES","POS_KIOSK_MAX_QUANTITY","POS_KIOSK_CATALOG_LIMIT","POS_KIOSK_UNLOCK_MAX_ATTEMPTS","POS_KIOSK_UNLOCK_LOCKOUT_MS","POS_KIOSK_UNLOCK_TTL_MS","ID_PATTERN","sanitizePosKioskLines","raw","Array","isArray","length","ok","error","lines","entry","productId","String","variantId","quantity","Number","test","isInteger","rawModifiers","modifiers","pick","groupId","optionId","push","posKioskTipCents","choice","input","undefined","enabled","percent","Math","round","percentages","includes","baseCents","cents","posKioskIdleSeconds","value","isFinite","min","max","posKioskEstimateCents","products","total","line","product","find","candidate","id","variant","variants","extra","reduce","sum","group","modifierGroups","option","options","priceCents"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,EAAEC,aAAa,QAAgC,oBAAgB;AACzF,SAASC,wBAAwB,QAA2D,yBAAqB;AAiIjH,8EAA8E,GAC9E,OAAO,MAAMC,iCAAiC,GAAE;AAChD,OAAO,MAAMC,6BAA6B,GAAE;AAC5C,OAAO,MAAMC,6BAA6B,IAAG;AAE7C,kEAAkE,GAClE,OAAO,MAAMC,iCAAiC,GAAE;AAEhD,kEAAkE,GAClE,OAAO,MAAMC,yBAAyB,GAAE;AAExC,wCAAwC,GACxC,OAAO,MAAMC,sBAAsB,GAAE;AAErC,sDAAsD,GACtD,OAAO,MAAMC,yBAAyB,GAAE;AAExC,4FAA4F,GAC5F,OAAO,MAAMC,0BAA0B,IAAG;AAE1C,sEAAsE,GACtE,OAAO,MAAMC,gCAAgC,EAAC;AAE9C,6EAA6E,GAC7E,OAAO,MAAMC,8BAA8B,KAAK,KAAK,KAAI;AAEzD,6DAA6D,GAC7D,OAAO,MAAMC,0BAA0B,IAAI,KAAK,KAAI;AAEpD,MAAMC,aAAa;AAEnB;;;;;CAKC,GACD,OAAO,SAASC,sBACdC,GAAY;IAEZ,IAAI,CAACC,MAAMC,OAAO,CAACF,QAAQA,IAAIG,MAAM,KAAK,GAAG,OAAO;QAAEC,IAAI;QAAOC,OAAO;IAAsB;IAC9F,IAAIL,IAAIG,MAAM,GAAGX,qBAAqB;QACpC,OAAO;YAAEY,IAAI;YAAOC,OAAO,CAAC,0BAA0B,EAAEb,oBAAoB,OAAO,CAAC;QAAC;IACvF;IACA,MAAMc,QAAwB,EAAE;IAChC,KAAK,MAAMC,SAASP,IAAuC;;QAC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