@aglyn/plugins-commerce 1.20.3 → 1.22.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 +16 -16
- package/src/lib/components/cart-fulfillment.js +19 -8
- package/src/lib/components/cart-fulfillment.js.map +1 -1
- package/src/lib/components/cart.js +106 -9
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/console/catalog-organization-card.component.js +102 -32
- package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
- package/src/lib/components/console/discounts-card.component.js +39 -5
- package/src/lib/components/console/discounts-card.component.js.map +1 -1
- package/src/lib/components/console/local-delivery-settings-card.component.js +34 -9
- package/src/lib/components/console/local-delivery-settings-card.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +72 -46
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/products-hub-card.component.js +43 -6
- package/src/lib/components/console/products-hub-card.component.js.map +1 -1
- package/src/lib/components/console/quote-settings-card.component.js +31 -8
- package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
- package/src/lib/components/console/reservations-card.component.js +39 -4
- package/src/lib/components/console/reservations-card.component.js.map +1 -1
- package/src/lib/components/console/return-settings-card.component.js +39 -17
- package/src/lib/components/console/return-settings-card.component.js.map +1 -1
- package/src/lib/components/console/shipping-settings-card.component.js +34 -10
- package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
- package/src/lib/components/console/store-settings-card.component.js +38 -13
- package/src/lib/components/console/store-settings-card.component.js.map +1 -1
- package/src/lib/components/console/suppliers-card.component.js +49 -15
- package/src/lib/components/console/suppliers-card.component.js.map +1 -1
- package/src/lib/components/console/tax-settings-card.component.js +36 -12
- package/src/lib/components/console/tax-settings-card.component.js.map +1 -1
- package/src/lib/model/commerce-pos-offline.d.ts +21 -3
- package/src/lib/model/commerce-pos-offline.js +17 -5
- package/src/lib/model/commerce-pos-offline.js.map +1 -1
- package/src/lib/server/cart.js +57 -0
- package/src/lib/server/cart.js.map +1 -1
- package/src/lib/server/pos-offline-card-order.d.ts +2 -0
- package/src/lib/server/pos-offline-card-order.js +6 -2
- package/src/lib/server/pos-offline-card-order.js.map +1 -1
- package/src/lib/server/pos-offline-card-reconcile.d.ts +5 -1
- package/src/lib/server/pos-offline-card-reconcile.js +42 -10
- package/src/lib/server/pos-offline-card-reconcile.js.map +1 -1
- package/src/lib/server/pos-offline-sync.d.ts +48 -6
- package/src/lib/server/pos-offline-sync.js +142 -31
- package/src/lib/server/pos-offline-sync.js.map +1 -1
- package/src/lib/server/pos-stripe.d.ts +11 -0
- package/src/lib/server/pos-stripe.js +14 -0
- package/src/lib/server/pos-stripe.js.map +1 -1
- package/src/lib/server/pos-terminal.d.ts +21 -1
- package/src/lib/server/pos-terminal.js +41 -7
- package/src/lib/server/pos-terminal.js.map +1 -1
- package/src/lib/transfer/product-transfer.js +15 -1
- package/src/lib/transfer/product-transfer.js.map +1 -1
|
@@ -53,6 +53,13 @@ export interface PosOfflineSaleCard {
|
|
|
53
53
|
last4?: string;
|
|
54
54
|
/** The bank's or Stripe's words for a decline or failure. */
|
|
55
55
|
declineMessage?: string;
|
|
56
|
+
/**
|
|
57
|
+
* The store's own Stripe account the device made the intent on, from the
|
|
58
|
+
* kit it sold with (a direct charge, AGL-4219). Absent: a destination
|
|
59
|
+
* charge made on the platform. The server reads the intent there, and
|
|
60
|
+
* captures it only when it is still the store's account.
|
|
61
|
+
*/
|
|
62
|
+
account?: string;
|
|
56
63
|
}
|
|
57
64
|
/** Every tender the register turns off while offline, and why, in its words. */
|
|
58
65
|
export declare const POS_OFFLINE_DISABLED_TENDERS: Readonly<Record<string, string>>;
|
|
@@ -183,8 +190,15 @@ export interface PosOfflineKitCard {
|
|
|
183
190
|
available: boolean;
|
|
184
191
|
/** Why not, in the cashier's words, when it is not. */
|
|
185
192
|
unavailableReason?: string;
|
|
186
|
-
/** The connected account the charge transfers to (a destination charge, as online). */
|
|
193
|
+
/** The connected account the charge transfers to (a destination charge, as online); '' for a direct charge. */
|
|
187
194
|
destination: string;
|
|
195
|
+
/**
|
|
196
|
+
* Set for a store on its own Stripe account (direct charges, AGL-4219):
|
|
197
|
+
* the device makes the intent with no transfer and no destination, on the
|
|
198
|
+
* account its connection token belongs to, which is this one. Offered only
|
|
199
|
+
* to an app that says it can (`cardChargeModels=direct` on the kit's GET).
|
|
200
|
+
*/
|
|
201
|
+
account?: string;
|
|
188
202
|
currency: string;
|
|
189
203
|
/** The limit of one card sale rung offline, in cents: the store's, or Stripe's own ceiling when it set none. */
|
|
190
204
|
maxSaleCents: number;
|
|
@@ -291,6 +305,10 @@ export declare function posOfflineCardRefusal(input: {
|
|
|
291
305
|
* What the app writes on the PaymentIntent it creates for a card rung
|
|
292
306
|
* offline: the sale key (the order's id once it syncs) and where it was rung,
|
|
293
307
|
* so the server can match the charge to the sale even if the sale's own sync
|
|
294
|
-
* never arrives.
|
|
308
|
+
* never arrives. An intent made on the store's own account (`direct`,
|
|
309
|
+
* AGL-4219) also says `chargeModel: direct`, as every direct sale's objects
|
|
310
|
+
* do, so its Connect-delivered events are read as the store's own.
|
|
295
311
|
*/
|
|
296
|
-
export declare function posOfflineCardIntentMetadata(sale: Pick<PosOfflineSale, 'saleKey' | 'hostId' | 'orgId' | 'registerId'>
|
|
312
|
+
export declare function posOfflineCardIntentMetadata(sale: Pick<PosOfflineSale, 'saleKey' | 'hostId' | 'orgId' | 'registerId'> & {
|
|
313
|
+
direct?: boolean;
|
|
314
|
+
}): Record<string, string>;
|
|
@@ -28,8 +28,11 @@ import { POS_OFFLINE_CARD_MAX_SALE_CENTS_LIMIT } from "./pos-offline-card-limits
|
|
|
28
28
|
* - A card, only on the native Aglyn POS app's own Stripe Terminal reader
|
|
29
29
|
* (AGL-4039): Stripe's SDK stores the card on the device ("store and
|
|
30
30
|
* forward") and forwards it once a connection returns. The app creates
|
|
31
|
-
* the PaymentIntent itself
|
|
32
|
-
*
|
|
31
|
+
* the PaymentIntent itself with MANUAL capture and NO application fee:
|
|
32
|
+
* a destination charge for a store on Aglyn's account, or, for a store on
|
|
33
|
+
* its own Stripe account (direct charges), an intent made ON that account
|
|
34
|
+
* (the connection token's) with no transfer at all (AGL-4219). The
|
|
35
|
+
* server captures it when the sale syncs and
|
|
33
36
|
* sizes the platform fee then, exactly as for an online card sale. A bank
|
|
34
37
|
* can still decline it at that point, after the customer left: the order
|
|
35
38
|
* is then recorded unpaid and flagged, and the register says so.
|
|
@@ -330,6 +333,7 @@ function wholeCents(value) {
|
|
|
330
333
|
return (_POS_OFFLINE_FLAG_LABELS_flag = POS_OFFLINE_FLAG_LABELS[flag]) != null ? _POS_OFFLINE_FLAG_LABELS_flag : flag;
|
|
331
334
|
});
|
|
332
335
|
}
|
|
336
|
+
/** A Stripe account id as Stripe mints them. */ const POS_OFFLINE_CARD_ACCOUNT = /^acct_[A-Za-z0-9]{8,64}$/;
|
|
333
337
|
const CARD_FORWARDS = [
|
|
334
338
|
'stored',
|
|
335
339
|
'forwarded',
|
|
@@ -347,6 +351,8 @@ const CARD_FORWARDS = [
|
|
|
347
351
|
const brand = bounded(input['brand'], 24);
|
|
348
352
|
const last4 = typeof input['last4'] === 'string' && /^\d{4}$/.test(input['last4']) ? input['last4'] : '';
|
|
349
353
|
const declineMessage = bounded(input['declineMessage'], 300);
|
|
354
|
+
const account = typeof input['account'] === 'string' ? input['account'].trim() : '';
|
|
355
|
+
if (account && !POS_OFFLINE_CARD_ACCOUNT.test(account)) return null;
|
|
350
356
|
return _extends({
|
|
351
357
|
forward
|
|
352
358
|
}, intent ? {
|
|
@@ -357,6 +363,8 @@ const CARD_FORWARDS = [
|
|
|
357
363
|
last4
|
|
358
364
|
} : {}, declineMessage ? {
|
|
359
365
|
declineMessage
|
|
366
|
+
} : {}, account ? {
|
|
367
|
+
account
|
|
360
368
|
} : {});
|
|
361
369
|
}
|
|
362
370
|
/**
|
|
@@ -384,15 +392,19 @@ const CARD_FORWARDS = [
|
|
|
384
392
|
* What the app writes on the PaymentIntent it creates for a card rung
|
|
385
393
|
* offline: the sale key (the order's id once it syncs) and where it was rung,
|
|
386
394
|
* so the server can match the charge to the sale even if the sale's own sync
|
|
387
|
-
* never arrives.
|
|
395
|
+
* never arrives. An intent made on the store's own account (`direct`,
|
|
396
|
+
* AGL-4219) also says `chargeModel: direct`, as every direct sale's objects
|
|
397
|
+
* do, so its Connect-delivered events are read as the store's own.
|
|
388
398
|
*/ export function posOfflineCardIntentMetadata(sale) {
|
|
389
|
-
return {
|
|
399
|
+
return _extends({
|
|
390
400
|
kind: POS_OFFLINE_CARD_INTENT_KIND,
|
|
391
401
|
saleKey: sale.saleKey,
|
|
392
402
|
hostId: sale.hostId,
|
|
393
403
|
orgId: sale.orgId,
|
|
394
404
|
registerId: sale.registerId
|
|
395
|
-
}
|
|
405
|
+
}, sale.direct ? {
|
|
406
|
+
chargeModel: 'direct'
|
|
407
|
+
} : {});
|
|
396
408
|
}
|
|
397
409
|
function dollars(cents) {
|
|
398
410
|
const whole = Math.floor(cents / 100);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-pos-offline.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 { computeOrderTotals, type OrderLineItem, type OrderTotals } from './commerce-orders'\nimport { computeTaxCents } from './commerce-tax'\nimport type { ModifierSelection } from './product-modifiers'\nimport { POS_OFFLINE_CARD_MAX_SALE_CENTS_LIMIT } from './pos-offline-card-limits'\n\n/*==========================================\n * THE OFFLINE REGISTER (AGL-3625): the contract every register client — the\n * web register and the native Aglyn POS app — shares with\n * `POST /api/commerce/pos-offline-sync`.\n *\n * WHAT SELLS OFFLINE IS CASH, AND A CARD ON THE NATIVE APP'S OWN READER.\n *\n * - Cash, on every register client.\n * - A card, only on the native Aglyn POS app's own Stripe Terminal reader\n * (AGL-4039): Stripe's SDK stores the card on the device (\"store and\n * forward\") and forwards it once a connection returns. The app creates\n * the PaymentIntent itself, a destination charge with MANUAL capture and\n * NO application fee; the server captures it when the sale syncs and\n * sizes the platform fee then, exactly as for an online card sale. A bank\n * can still decline it at that point, after the customer left: the order\n * is then recorded unpaid and flagged, and the register says so.\n * Off until the store turns it on, then within the store's two limits:\n * per sale, and per device per day (as Shopify POS words it).\n * - Every other card tender cannot: Tap to Pay on Android, the server's\n * smart readers, the typed card and the QR link are server-driven, and\n * Stripe does not take a server-driven card payment without the server.\n * - Gift cards DO NOT, deliberately. A balance cannot be checked without the\n * server, and a capped \"allow it anyway\" (Square's offer for cards) turns a\n * short balance into a sale whose money nobody collected — discovered at\n * sync, after the customer left. Square itself does not redeem gift cards\n * offline. A gift card is never over-redeemed silently because it is never\n * redeemed offline at all.\n * - Room charges do not: the stay is validated on the server.\n * - Store credit and rewards do not, for the gift card's reason: a balance\n * is the server's to check.\n * - Codes and store promotions do not: a redemption cap is counted on the\n * server. The cashier's own discount, bounded by the site's ceiling, does.\n *\n * WHAT THE SALE IS: the register prices the basket from its cached catalog and\n * the store's own tax rate, takes the cash and queues the sale with a key it\n * minted. That key is the order's id on the server, so the receipt printed\n * offline carries the barcode the real order answers to, and a sale sent twice\n * — a flapping connection, a retry after a lost answer — lands once.\n *\n * WHAT THE SERVER DOES WITH IT: records it as it happened, never re-prices the\n * money the customer handed over, and FLAGS what does not match — a price\n * that changed, stock that went short, a shift that closed first — on the\n * order and back to the register. A sale is never dropped for a flag.\n *=========================================*/\n\n/** The route both register clients sync through. */\nexport const POS_OFFLINE_SYNC_ROUTE = '/api/commerce/pos-offline-sync'\n\n/** The most sales one sync request carries; a longer queue sends in batches. */\nexport const POS_OFFLINE_SYNC_BATCH_MAX = 25\n\n/** Lines one offline sale may carry, the same bound the register's basket has. */\nexport const POS_OFFLINE_SALE_MAX_LINES = 100\n\n/** A sale synced later than this after it was rung is flagged `late-sync`. */\nexport const POS_OFFLINE_LATE_SYNC_MS = 24 * 60 * 60 * 1000\n\n/**\n * How far back a sale's own clock is believed. Older, and the server stamps\n * the sale at this bound and flags it, rather than letting a device clock\n * place a sale anywhere in history.\n */\nexport const POS_OFFLINE_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000\n\n/** How far ahead of the server a device clock may run before it is clamped. */\nexport const POS_OFFLINE_CLOCK_SKEW_MS = 10 * 60 * 1000\n\n/** What an offline sale was paid with. A sale with no tender is cash (the shape before AGL-4039). */\nexport type PosOfflineTender = 'cash' | 'card'\n\nexport {\n POS_OFFLINE_CARD_MAX_SALE_CENTS_LIMIT,\n POS_OFFLINE_CARD_RECONNECT_WITHIN_MS,\n} from './pos-offline-card-limits'\n\n/** The `metadata[kind]` of a PaymentIntent the app created for a card rung offline. */\nexport const POS_OFFLINE_CARD_INTENT_KIND = 'pos-offline'\n\n/**\n * Where a card rung offline stands. `stored`: on the device, not yet sent to\n * Stripe. `forwarded`: Stripe has it and it is authorized, waiting for the\n * sync to capture it. `declined`: the bank refused it when it was forwarded.\n * `failed`: Stripe could not take it at all (no PaymentIntent was made).\n */\nexport type PosOfflineCardForward = 'stored' | 'forwarded' | 'declined' | 'failed'\n\n/** The card side of a sale rung offline on the app's own reader. */\nexport interface PosOfflineSaleCard {\n forward: PosOfflineCardForward\n /** Stripe's PaymentIntent id, once the SDK forwarded it. */\n paymentIntentId?: string | null\n brand?: string\n last4?: string\n /** The bank's or Stripe's words for a decline or failure. */\n declineMessage?: string\n}\n\n/** Every tender the register turns off while offline, and why, in its words. */\nexport const POS_OFFLINE_DISABLED_TENDERS: Readonly<Record<string, string>> = {\n card_present: 'Card readers need the connection.',\n card_keyed: 'Typed cards need the connection.',\n card_link: 'The QR card link needs the connection.',\n gift_card: 'A gift card balance can only be checked online.',\n folio: 'Room charges are checked against the stay online.',\n credit: 'Store credit and rewards balances can only be checked online.',\n}\n\n/** One basket line as the register rang it. */\nexport interface PosOfflineSaleLine {\n productId: string\n variantId?: string\n name: string\n /** Variant options and modifier choices, as the receipt printed them. */\n variantLabel?: string\n sku?: string\n productType?: 'physical' | 'digital' | 'service'\n quantity: number\n /** Per unit, modifiers included, from the cached catalog. */\n unitAmountCents: number\n modifiers?: ModifierSelection[]\n}\n\n/** The customer the register attached: only what the sale and its receipt need. */\nexport interface PosOfflineSaleCustomer {\n email?: string\n name?: string\n kind?: string\n id?: string\n}\n\n/** One sale rung while offline, exactly as the register queued it. */\nexport interface PosOfflineSale {\n v: 1\n /** The register's key for this sale, minted once; the order's id on the server. */\n saleKey: string\n hostId: string\n /** The workspace the register was signed in to. */\n orgId: string\n /** Who was signed in on the device: the only member who may sync it. */\n signedInUid: string\n registerId: string\n /** The shift open on the register when the sale was rung. */\n shiftId?: string | null\n locationId?: string\n /** A PIN-switched cashier's assertion, valid when the sale was rung. */\n cashierAssertion?: string\n /** The device's clock when the cash was taken. */\n soldAtMs: number\n lines: PosOfflineSaleLine[]\n /** The cashier's discount, a percentage of the goods. */\n discountPct: number\n /** The totals the receipt printed and the customer paid. */\n totals: OrderTotals\n /** Cash handed over; 0 for a card sale. */\n cashTenderedCents: number\n changeCents: number\n customer?: PosOfflineSaleCustomer\n /** `card` only on the native app's own reader (AGL-4039); absent means cash. */\n tender?: PosOfflineTender\n /** The card, when `tender` is `card`. */\n card?: PosOfflineSaleCard\n}\n\n/** What does not match, said on the order and back to the register. */\nexport type PosOfflineFlag =\n | 'price-changed'\n | 'unknown-product'\n | 'tax-differs'\n | 'totals-restated'\n | 'discount-over-limit'\n | 'discount-not-permitted'\n | 'cash-short'\n | 'stock-short'\n | 'shift-closed'\n | 'no-shift'\n | 'unknown-register'\n | 'register-over-cap'\n | 'late-sync'\n | 'clock-adjusted'\n | 'cashier-unverified'\n | 'card-declined'\n | 'card-not-charged'\n | 'card-amount-differs'\n | 'card-fee-short'\n\n/** Each flag in the words the order and the register show. */\nexport const POS_OFFLINE_FLAG_LABELS: Record<PosOfflineFlag, string> = {\n 'price-changed': 'A price changed after the register cached it; the sale kept the price it was rung at',\n 'unknown-product': 'A product was deleted before the sale synced; the line kept what the receipt printed',\n 'tax-differs': 'The tax rung differs from the store’s rate now; the sale kept the tax it collected',\n 'totals-restated': 'The register’s totals did not add up; the server restated them from the lines',\n 'discount-over-limit': 'The discount is above this register’s limit',\n // Names the permission by its label in `plugin-permissions.ts` (AGL-4047);\n // `pos-offline-sync.spec.ts` holds the two to the same words.\n 'discount-not-permitted': 'The discount was given by a member whose role does not include “Give discounts at the register”',\n 'cash-short': 'The cash recorded is less than the total',\n 'stock-short': 'Stock went short: more was sold than the shelf held',\n 'shift-closed': 'Rung in a shift that closed before the sale synced; its Z report does not include it',\n 'no-shift': 'Rung with no shift open, on a site that requires one',\n 'unknown-register': 'The register it was rung on no longer exists',\n 'register-over-cap': 'The register it was rung on is over the plan’s register limit',\n 'late-sync': 'Synced more than a day after it was rung',\n 'clock-adjusted': 'The device clock was off; the sale is dated when it synced',\n 'cashier-unverified': 'The PIN-switched cashier could not be confirmed; the sale is under the signed-in member',\n 'card-declined': 'The card taken offline was declined when it was charged; the order is unpaid',\n 'card-not-charged': 'The card taken offline could not be charged; the order is unpaid',\n 'card-amount-differs': 'The card was charged a different amount than the sale’s total; the payment records what Stripe took',\n 'card-fee-short': 'Stripe took less than the platform fee from this card’s payout; the rest goes on the workspace’s monthly invoice',\n}\n\n/** A line whose stock went short when the sale synced. */\nexport interface PosOfflineStockConflict {\n productId: string\n variantId?: string\n name: string\n /** Units sold. */\n requested: number\n /** Units the shelf actually gave up. */\n applied: number\n /** Units sold that the shelf did not hold. */\n shortUnits: number\n}\n\n/** What the order records about having been rung offline. */\nexport interface PosOfflineOrderStamp {\n saleKey: string\n /** The device's clock when the cash was taken. */\n soldAtMs: number\n syncedAtMs: number\n /** Who synced it: always the member who was signed in when it was rung. */\n syncedBy: string\n flags: PosOfflineFlag[]\n stockConflicts?: PosOfflineStockConflict[]\n /** The server's own price per line where it differed, for the merchant to compare. */\n priceDrift?: Array<{ index: number; rungCents: number; currentCents: number }>\n}\n\n/** Why a sale was refused, and whether the register should keep trying. */\nexport type PosOfflineRefusal =\n | 'wrong-staff'\n | 'wrong-site'\n | 'wrong-workspace'\n | 'invalid'\n | 'conflict'\n | 'failed'\n\n/** What became of one sale the register sent. */\nexport type PosOfflineOutcomeStatus = 'recorded' | 'replayed' | 'refused'\n\n/**\n * One sale's answer, in the order the request sent them. `recorded` and\n * `replayed` carry the order; `refused` carries the reason, the sentence and\n * whether to keep trying. One flat shape, so every register client — the web\n * register and the native apps — decodes it the same way.\n */\nexport interface PosOfflineSaleOutcome {\n saleKey: string\n status: PosOfflineOutcomeStatus\n orderId?: string\n number?: number | null\n flags?: PosOfflineFlag[]\n stockConflicts?: PosOfflineStockConflict[]\n reason?: PosOfflineRefusal\n error?: string\n /** Keep it queued and try again later (a transient failure). */\n retry?: boolean\n}\n\nexport interface PosOfflineSyncRequest {\n hostId: string\n sales: PosOfflineSale[]\n}\n\nexport interface PosOfflineSyncResponse {\n results: PosOfflineSaleOutcome[]\n}\n\n/** One register as the offline kit lists it. */\nexport interface PosOfflineKitRegister {\n id: string\n name: string\n locationId?: string\n openShiftId: string | null\n}\n\n/** What the native app needs to take a card offline on its own reader (AGL-4039). */\nexport interface PosOfflineKitCard {\n available: boolean\n /** Why not, in the cashier's words, when it is not. */\n unavailableReason?: string\n /** The connected account the charge transfers to (a destination charge, as online). */\n destination: string\n currency: string\n /** The limit of one card sale rung offline, in cents: the store's, or Stripe's own ceiling when it set none. */\n maxSaleCents: number\n /** The limit of every card one device takes offline in a day, in cents; 0 is no daily limit. */\n maxDeviceDailyCents: number\n}\n\n/**\n * Everything a register needs to sell offline besides the catalog, from\n * `GET /api/commerce/pos-offline-sync?hostId=`: the server's own answers, so\n * the register and the sync agree about the rate and the rules.\n */\nexport interface PosOfflineKit {\n v: 1\n hostId: string\n orgId: string\n issuedAtMs: number\n /** Offline selling is possible for this site right now. */\n available: boolean\n /** Why not, in the cashier's words, when it is not. */\n unavailableReason?: string\n /** The store's own in-person rate; `null` pct is no tax. */\n tax: { pct: number | null; pricesIncludeTax: boolean }\n maxDiscountPct: number\n requireOpenShift: boolean\n registers: PosOfflineKitRegister[]\n /** Card sales on the app's own reader while offline; absent from a server that does not take them. */\n card?: PosOfflineKitCard\n /** What the receipt prints at its head and foot. `logo` is the stored value. */\n receipt: {\n name: string\n logo?: string\n address?: string\n footer?: string\n returnPolicy?: string\n }\n}\n\n/**\n * The totals of an offline sale: the cashier's discount on the goods, then\n * the store's in-person tax on what is left — exactly the arithmetic the\n * online register's sale route uses for the same basket with no promotion.\n * `pricesIncludeTax` adds nothing, as at the online till.\n */\nexport function posOfflineSaleTotals(input: {\n lines: ReadonlyArray<Pick<PosOfflineSaleLine, 'unitAmountCents' | 'quantity'>>\n discountPct: number\n tax: { pct: number | null; pricesIncludeTax: boolean }\n}): OrderTotals {\n const lines = input.lines.map((line) => ({\n unitAmountCents: wholeCents(line.unitAmountCents),\n quantity: Math.max(1, Math.round(Number(line.quantity) || 1)),\n }))\n const itemsCents = lines.reduce((sum, line) => sum + line.unitAmountCents * line.quantity, 0)\n const pct = Number.isFinite(input.discountPct) ? Math.min(100, Math.max(0, input.discountPct)) : 0\n const discountCents = Math.min(itemsCents, Math.round((itemsCents * pct) / 100))\n const taxPct = Number(input.tax.pct)\n const taxCents =\n taxPct > 0 && !input.tax.pricesIncludeTax ? computeTaxCents(itemsCents - discountCents, taxPct) : 0\n return computeOrderTotals(lines as unknown as OrderLineItem[], { discountCents, taxCents, feeCents: 0 })\n}\n\n/** Change for cash handed over, never negative. */\nexport function posOfflineChangeCents(totalCents: number, tenderedCents: number): number {\n return Math.max(0, wholeCents(tenderedCents) - wholeCents(totalCents))\n}\n\n/** A key the register minted: an id the order can take, and nothing else. */\nexport function posOfflineSaleKeyIsValid(key: unknown): key is string {\n return typeof key === 'string' && /^[A-Za-z0-9_-]{16,64}$/.test(key) && !/^__.*__$/.test(key)\n}\n\n/**\n * The sale's time as the server records it: the device's clock when it is\n * believable, clamped to now when it runs ahead, and to the oldest believable\n * moment when it claims to be older.\n */\nexport function posOfflineSoldAt(\n soldAtMs: number,\n nowMs: number,\n): { atMs: number; adjusted: boolean } {\n const at = Number(soldAtMs)\n if (!Number.isFinite(at) || at <= 0) return { atMs: nowMs, adjusted: true }\n if (at > nowMs + POS_OFFLINE_CLOCK_SKEW_MS) return { atMs: nowMs, adjusted: true }\n if (at < nowMs - POS_OFFLINE_MAX_AGE_MS) return { atMs: nowMs, adjusted: true }\n return { atMs: Math.min(at, nowMs), adjusted: false }\n}\n\nconst bounded = (value: unknown, max: number): string =>\n typeof value === 'string' ? value.trim().slice(0, max) : ''\n\nconst cleanId = (value: unknown): string => {\n const id = String(value ?? '').trim()\n return /^[A-Za-z0-9_-]{1,128}$/.test(id) && !/^__.*__$/.test(id) ? id : ''\n}\n\nfunction wholeCents(value: unknown): number {\n const number = Math.round(Number(value))\n return Number.isFinite(number) && number > 0 ? number : 0\n}\n\n/**\n * A queued sale read off the wire, every field typed and bounded — or the\n * sentence that says why it cannot be read at all. Pure, so the server and\n * any client that wants to check its own queue answer the same.\n */\nexport function sanitizePosOfflineSale(\n raw: unknown,\n): { ok: true; sale: PosOfflineSale } | { ok: false; error: string } {\n if (!raw || typeof raw !== 'object') return { ok: false, error: 'Not a sale' }\n const input = raw as Record<string, any>\n const saleKey = input['saleKey']\n if (!posOfflineSaleKeyIsValid(saleKey)) return { ok: false, error: 'The sale has no valid key' }\n const hostId = cleanId(input['hostId'])\n const registerId = cleanId(input['registerId'])\n const signedInUid = bounded(input['signedInUid'], 128)\n if (!hostId || !registerId || !signedInUid) {\n return { ok: false, error: 'The sale is missing its site, register or member' }\n }\n const rawLines = Array.isArray(input['lines']) ? input['lines'] : []\n if (rawLines.length === 0 || rawLines.length > POS_OFFLINE_SALE_MAX_LINES) {\n return { ok: false, error: 'The sale has no lines' }\n }\n const lines: PosOfflineSaleLine[] = []\n for (const line of rawLines) {\n const productId = cleanId(line?.productId)\n const name = bounded(line?.name, 200)\n const unit = Math.round(Number(line?.unitAmountCents))\n const quantity = Math.round(Number(line?.quantity))\n if (!productId || !name || !Number.isFinite(unit) || unit < 0 || !(quantity >= 1 && quantity <= 99)) {\n return { ok: false, error: 'A line of the sale cannot be read' }\n }\n const variantId = cleanId(line?.variantId)\n const variantLabel = bounded(line?.variantLabel, 200)\n const sku = bounded(line?.sku, 100)\n const productType = ['physical', 'digital', 'service'].includes(line?.productType)\n ? (line.productType as PosOfflineSaleLine['productType'])\n : undefined\n const modifiers = Array.isArray(line?.modifiers)\n ? (line.modifiers as unknown[])\n .slice(0, 50)\n .map((pick: any) => ({ groupId: cleanId(pick?.groupId), optionId: cleanId(pick?.optionId) }))\n .filter((pick) => pick.groupId && pick.optionId)\n : []\n lines.push({\n productId,\n ...(variantId ? { variantId } : {}),\n name,\n ...(variantLabel ? { variantLabel } : {}),\n ...(sku ? { sku } : {}),\n ...(productType ? { productType } : {}),\n quantity,\n unitAmountCents: unit,\n ...(modifiers.length ? { modifiers } : {}),\n })\n }\n const discountPct = Number(input['discountPct'] ?? 0)\n if (!Number.isFinite(discountPct) || discountPct < 0 || discountPct > 100) {\n return { ok: false, error: 'The sale’s discount cannot be read' }\n }\n const totals = (input['totals'] ?? {}) as Record<string, unknown>\n const customerRaw = input['customer']\n const customer: PosOfflineSaleCustomer = {}\n if (customerRaw && typeof customerRaw === 'object') {\n const email = bounded((customerRaw as any).email, 254).toLowerCase()\n if (email && /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email)) customer.email = email\n const name = bounded((customerRaw as any).name, 200)\n if (name) customer.name = name\n const kind = bounded((customerRaw as any).kind, 40)\n const id = cleanId((customerRaw as any).id)\n if (kind && kind !== 'none' && id) {\n customer.kind = kind\n customer.id = id\n }\n }\n const shiftId = cleanId(input['shiftId'])\n const locationId = cleanId(input['locationId'])\n const assertion = bounded(input['cashierAssertion'], 2000)\n const orgId = bounded(input['orgId'], 128)\n let card: PosOfflineSaleCard | undefined\n if (input['tender'] === 'card') {\n const read = sanitizePosOfflineSaleCard(input['card'])\n if (!read) return { ok: false, error: 'The card of the sale cannot be read' }\n card = read\n }\n return {\n ok: true,\n sale: {\n v: 1,\n saleKey,\n hostId,\n orgId,\n signedInUid,\n registerId,\n shiftId: shiftId || null,\n ...(locationId ? { locationId } : {}),\n ...(assertion ? { cashierAssertion: assertion } : {}),\n soldAtMs: Number(input['soldAtMs']) || 0,\n lines,\n discountPct,\n totals: {\n itemsCents: wholeCents(totals['itemsCents']),\n shippingCents: 0,\n taxCents: wholeCents(totals['taxCents']),\n discountCents: wholeCents(totals['discountCents']),\n totalCents: wholeCents(totals['totalCents']),\n feeCents: 0,\n },\n cashTenderedCents: card ? 0 : wholeCents(input['cashTenderedCents']),\n changeCents: card ? 0 : wholeCents(input['changeCents']),\n ...(Object.keys(customer).length ? { customer } : {}),\n ...(card ? { tender: 'card' as const, card } : {}),\n },\n }\n}\n\n/**\n * Whether the register's totals are the arithmetic of its own lines: the\n * goods are the lines' sum, the discount is the percentage of them, and the\n * total is goods less discount plus the tax it rang. The tax itself is the\n * register's, and checked against the store's rate separately.\n */\nexport function posOfflineTotalsAddUp(sale: Pick<PosOfflineSale, 'lines' | 'discountPct' | 'totals'>): boolean {\n const expected = posOfflineSaleTotals({\n lines: sale.lines,\n discountPct: sale.discountPct,\n tax: { pct: null, pricesIncludeTax: false },\n })\n return (\n expected.itemsCents === sale.totals.itemsCents &&\n expected.discountCents === sale.totals.discountCents &&\n sale.totals.taxCents <= sale.totals.itemsCents &&\n sale.totals.totalCents === expected.itemsCents - expected.discountCents + sale.totals.taxCents\n )\n}\n\n/** The flags in the order and words the register lists them. */\nexport function posOfflineFlagLabels(flags: readonly PosOfflineFlag[]): string[] {\n return flags.map((flag) => POS_OFFLINE_FLAG_LABELS[flag] ?? flag)\n}\n\nconst CARD_FORWARDS: readonly PosOfflineCardForward[] = ['stored', 'forwarded', 'declined', 'failed']\n\n/** The card side of a queued sale, typed and bounded, or `null` when it cannot be read. */\nexport function sanitizePosOfflineSaleCard(raw: unknown): PosOfflineSaleCard | null {\n if (!raw || typeof raw !== 'object') return null\n const input = raw as Record<string, unknown>\n const forward = input['forward'] as PosOfflineCardForward\n if (!CARD_FORWARDS.includes(forward)) return null\n const intent = typeof input['paymentIntentId'] === 'string' ? input['paymentIntentId'].trim() : ''\n if (intent && !/^pi_[A-Za-z0-9]{8,64}$/.test(intent)) return null\n if (forward === 'forwarded' && !intent) return null\n const brand = bounded(input['brand'], 24)\n const last4 = typeof input['last4'] === 'string' && /^\\d{4}$/.test(input['last4']) ? input['last4'] : ''\n const declineMessage = bounded(input['declineMessage'], 300)\n return {\n forward,\n ...(intent ? { paymentIntentId: intent } : {}),\n ...(brand ? { brand } : {}),\n ...(last4 ? { last4 } : {}),\n ...(declineMessage ? { declineMessage } : {}),\n }\n}\n\n/**\n * Why a card cannot be taken offline for `totalCents`, in the cashier's\n * words, or `null` when it can: the store has not turned it on, the sale is\n * over the store's (or Stripe's) limit per sale, or the cards this device\n * has taken offline today would pass the store's daily limit per device (a\n * daily limit of 0 is none: the store did not set one).\n */\nexport function posOfflineCardRefusal(input: {\n card: Pick<PosOfflineKitCard, 'available' | 'unavailableReason' | 'maxSaleCents' | 'maxDeviceDailyCents'> | null | undefined\n totalCents: number\n /** Every card this device took offline today, in cents. */\n takenTodayCents: number\n}): string | null {\n const card = input.card\n if (!card) return 'Card sales offline need the register to connect once first.'\n if (!card.available) return card.unavailableReason || 'Card sales offline are not turned on for this store.'\n const total = wholeCents(input.totalCents)\n if (total <= 0) return 'There is nothing to charge.'\n const perSale = Math.min(wholeCents(card.maxSaleCents), POS_OFFLINE_CARD_MAX_SALE_CENTS_LIMIT)\n if (total > perSale) return `Offline, a card sale can be up to ${dollars(perSale)}. Take cash, or charge it when you are back online.`\n const today = wholeCents(input.takenTodayCents)\n const daily = wholeCents(card.maxDeviceDailyCents)\n if (daily > 0 && today + total > daily) {\n return `This device has taken ${dollars(today)} in cards offline today, and its daily limit is ${dollars(daily)}. Take cash, or wait for the connection.`\n }\n return null\n}\n\n/**\n * What the app writes on the PaymentIntent it creates for a card rung\n * offline: the sale key (the order's id once it syncs) and where it was rung,\n * so the server can match the charge to the sale even if the sale's own sync\n * never arrives.\n */\nexport function posOfflineCardIntentMetadata(\n sale: Pick<PosOfflineSale, 'saleKey' | 'hostId' | 'orgId' | 'registerId'>,\n): Record<string, string> {\n return {\n kind: POS_OFFLINE_CARD_INTENT_KIND,\n saleKey: sale.saleKey,\n hostId: sale.hostId,\n orgId: sale.orgId,\n registerId: sale.registerId,\n }\n}\n\nfunction dollars(cents: number): string {\n const whole = Math.floor(cents / 100)\n const rest = cents % 100\n return `$${whole.toLocaleString('en-US')}.${String(rest).padStart(2, '0')}`\n}\n"],"names":["computeOrderTotals","computeTaxCents","POS_OFFLINE_CARD_MAX_SALE_CENTS_LIMIT","POS_OFFLINE_SYNC_ROUTE","POS_OFFLINE_SYNC_BATCH_MAX","POS_OFFLINE_SALE_MAX_LINES","POS_OFFLINE_LATE_SYNC_MS","POS_OFFLINE_MAX_AGE_MS","POS_OFFLINE_CLOCK_SKEW_MS","POS_OFFLINE_CARD_RECONNECT_WITHIN_MS","POS_OFFLINE_CARD_INTENT_KIND","POS_OFFLINE_DISABLED_TENDERS","card_present","card_keyed","card_link","gift_card","folio","credit","POS_OFFLINE_FLAG_LABELS","posOfflineSaleTotals","input","lines","map","line","unitAmountCents","wholeCents","quantity","Math","max","round","Number","itemsCents","reduce","sum","pct","isFinite","discountPct","min","discountCents","taxPct","tax","taxCents","pricesIncludeTax","feeCents","posOfflineChangeCents","totalCents","tenderedCents","posOfflineSaleKeyIsValid","key","test","posOfflineSoldAt","soldAtMs","nowMs","at","atMs","adjusted","bounded","value","trim","slice","cleanId","id","String","number","sanitizePosOfflineSale","raw","ok","error","saleKey","hostId","registerId","signedInUid","rawLines","Array","isArray","length","productId","name","unit","variantId","variantLabel","sku","productType","includes","undefined","modifiers","pick","groupId","optionId","filter","push","totals","customerRaw","customer","email","toLowerCase","kind","shiftId","locationId","assertion","orgId","card","read","sanitizePosOfflineSaleCard","sale","v","cashierAssertion","shippingCents","cashTenderedCents","changeCents","Object","keys","tender","posOfflineTotalsAddUp","expected","posOfflineFlagLabels","flags","flag","CARD_FORWARDS","forward","intent","brand","last4","declineMessage","paymentIntentId","posOfflineCardRefusal","available","unavailableReason","total","perSale","maxSaleCents","dollars","today","takenTodayCents","daily","maxDeviceDailyCents","posOfflineCardIntentMetadata","cents","whole","floor","rest","toLocaleString","padStart"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAA8C,uBAAmB;AAC5F,SAASC,eAAe,QAAQ,oBAAgB;AAEhD,SAASC,qCAAqC,QAAQ,+BAA2B;AAEjF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA2C2C,GAE3C,kDAAkD,GAClD,OAAO,MAAMC,yBAAyB,iCAAgC;AAEtE,8EAA8E,GAC9E,OAAO,MAAMC,6BAA6B,GAAE;AAE5C,gFAAgF,GAChF,OAAO,MAAMC,6BAA6B,IAAG;AAE7C,4EAA4E,GAC5E,OAAO,MAAMC,2BAA2B,KAAK,KAAK,KAAK,KAAI;AAE3D;;;;CAIC,GACD,OAAO,MAAMC,yBAAyB,KAAK,KAAK,KAAK,KAAK,KAAI;AAE9D,6EAA6E,GAC7E,OAAO,MAAMC,4BAA4B,KAAK,KAAK,KAAI;AAKvD,SACEN,qCAAqC,EACrCO,oCAAoC,QAC/B,+BAA2B;AAElC,qFAAqF,GACrF,OAAO,MAAMC,+BAA+B,cAAa;AAqBzD,8EAA8E,GAC9E,OAAO,MAAMC,+BAAiE;IAC5EC,cAAc;IACdC,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C,QAAQ7G,WAAW4E,KAAKkC,mBAAmB;IACjD,IAAID,QAAQ,KAAKF,QAAQJ,QAAQM,OAAO;QACtC,OAAO,CAAC,sBAAsB,EAAEH,QAAQC,OAAO,gDAAgD,EAAED,QAAQG,OAAO,wCAAwC,CAAC;IAC3J;IACA,OAAO;AACT;AAEA;;;;;CAKC,GACD,OAAO,SAASE,6BACdhC,IAAyE;IAEzE,OAAO;QACLR,MAAMtF;QACN0D,SAASoC,KAAKpC,OAAO;QACrBC,QAAQmC,KAAKnC,MAAM;QACnB+B,OAAOI,KAAKJ,KAAK;QACjB9B,YAAYkC,KAAKlC,UAAU;IAC7B;AACF;AAEA,SAAS6D,QAAQM,KAAa;IAC5B,MAAMC,QAAQ/G,KAAKgH,KAAK,CAACF,QAAQ;IACjC,MAAMG,OAAOH,QAAQ;IACrB,OAAO,CAAC,CAAC,EAAEC,MAAMG,cAAc,CAAC,SAAS,CAAC,EAAE/E,OAAO8E,MAAME,QAAQ,CAAC,GAAG,MAAM;AAC7E"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-pos-offline.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 { computeOrderTotals, type OrderLineItem, type OrderTotals } from './commerce-orders'\nimport { computeTaxCents } from './commerce-tax'\nimport type { ModifierSelection } from './product-modifiers'\nimport { POS_OFFLINE_CARD_MAX_SALE_CENTS_LIMIT } from './pos-offline-card-limits'\n\n/*==========================================\n * THE OFFLINE REGISTER (AGL-3625): the contract every register client — the\n * web register and the native Aglyn POS app — shares with\n * `POST /api/commerce/pos-offline-sync`.\n *\n * WHAT SELLS OFFLINE IS CASH, AND A CARD ON THE NATIVE APP'S OWN READER.\n *\n * - Cash, on every register client.\n * - A card, only on the native Aglyn POS app's own Stripe Terminal reader\n * (AGL-4039): Stripe's SDK stores the card on the device (\"store and\n * forward\") and forwards it once a connection returns. The app creates\n * the PaymentIntent itself with MANUAL capture and NO application fee:\n * a destination charge for a store on Aglyn's account, or, for a store on\n * its own Stripe account (direct charges), an intent made ON that account\n * (the connection token's) with no transfer at all (AGL-4219). The\n * server captures it when the sale syncs and\n * sizes the platform fee then, exactly as for an online card sale. A bank\n * can still decline it at that point, after the customer left: the order\n * is then recorded unpaid and flagged, and the register says so.\n * Off until the store turns it on, then within the store's two limits:\n * per sale, and per device per day (as Shopify POS words it).\n * - Every other card tender cannot: Tap to Pay on Android, the server's\n * smart readers, the typed card and the QR link are server-driven, and\n * Stripe does not take a server-driven card payment without the server.\n * - Gift cards DO NOT, deliberately. A balance cannot be checked without the\n * server, and a capped \"allow it anyway\" (Square's offer for cards) turns a\n * short balance into a sale whose money nobody collected — discovered at\n * sync, after the customer left. Square itself does not redeem gift cards\n * offline. A gift card is never over-redeemed silently because it is never\n * redeemed offline at all.\n * - Room charges do not: the stay is validated on the server.\n * - Store credit and rewards do not, for the gift card's reason: a balance\n * is the server's to check.\n * - Codes and store promotions do not: a redemption cap is counted on the\n * server. The cashier's own discount, bounded by the site's ceiling, does.\n *\n * WHAT THE SALE IS: the register prices the basket from its cached catalog and\n * the store's own tax rate, takes the cash and queues the sale with a key it\n * minted. That key is the order's id on the server, so the receipt printed\n * offline carries the barcode the real order answers to, and a sale sent twice\n * — a flapping connection, a retry after a lost answer — lands once.\n *\n * WHAT THE SERVER DOES WITH IT: records it as it happened, never re-prices the\n * money the customer handed over, and FLAGS what does not match — a price\n * that changed, stock that went short, a shift that closed first — on the\n * order and back to the register. A sale is never dropped for a flag.\n *=========================================*/\n\n/** The route both register clients sync through. */\nexport const POS_OFFLINE_SYNC_ROUTE = '/api/commerce/pos-offline-sync'\n\n/** The most sales one sync request carries; a longer queue sends in batches. */\nexport const POS_OFFLINE_SYNC_BATCH_MAX = 25\n\n/** Lines one offline sale may carry, the same bound the register's basket has. */\nexport const POS_OFFLINE_SALE_MAX_LINES = 100\n\n/** A sale synced later than this after it was rung is flagged `late-sync`. */\nexport const POS_OFFLINE_LATE_SYNC_MS = 24 * 60 * 60 * 1000\n\n/**\n * How far back a sale's own clock is believed. Older, and the server stamps\n * the sale at this bound and flags it, rather than letting a device clock\n * place a sale anywhere in history.\n */\nexport const POS_OFFLINE_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000\n\n/** How far ahead of the server a device clock may run before it is clamped. */\nexport const POS_OFFLINE_CLOCK_SKEW_MS = 10 * 60 * 1000\n\n/** What an offline sale was paid with. A sale with no tender is cash (the shape before AGL-4039). */\nexport type PosOfflineTender = 'cash' | 'card'\n\nexport {\n POS_OFFLINE_CARD_MAX_SALE_CENTS_LIMIT,\n POS_OFFLINE_CARD_RECONNECT_WITHIN_MS,\n} from './pos-offline-card-limits'\n\n/** The `metadata[kind]` of a PaymentIntent the app created for a card rung offline. */\nexport const POS_OFFLINE_CARD_INTENT_KIND = 'pos-offline'\n\n/**\n * Where a card rung offline stands. `stored`: on the device, not yet sent to\n * Stripe. `forwarded`: Stripe has it and it is authorized, waiting for the\n * sync to capture it. `declined`: the bank refused it when it was forwarded.\n * `failed`: Stripe could not take it at all (no PaymentIntent was made).\n */\nexport type PosOfflineCardForward = 'stored' | 'forwarded' | 'declined' | 'failed'\n\n/** The card side of a sale rung offline on the app's own reader. */\nexport interface PosOfflineSaleCard {\n forward: PosOfflineCardForward\n /** Stripe's PaymentIntent id, once the SDK forwarded it. */\n paymentIntentId?: string | null\n brand?: string\n last4?: string\n /** The bank's or Stripe's words for a decline or failure. */\n declineMessage?: string\n /**\n * The store's own Stripe account the device made the intent on, from the\n * kit it sold with (a direct charge, AGL-4219). Absent: a destination\n * charge made on the platform. The server reads the intent there, and\n * captures it only when it is still the store's account.\n */\n account?: string\n}\n\n/** Every tender the register turns off while offline, and why, in its words. */\nexport const POS_OFFLINE_DISABLED_TENDERS: Readonly<Record<string, string>> = {\n card_present: 'Card readers need the connection.',\n card_keyed: 'Typed cards need the connection.',\n card_link: 'The QR card link needs the connection.',\n gift_card: 'A gift card balance can only be checked online.',\n folio: 'Room charges are checked against the stay online.',\n credit: 'Store credit and rewards balances can only be checked online.',\n}\n\n/** One basket line as the register rang it. */\nexport interface PosOfflineSaleLine {\n productId: string\n variantId?: string\n name: string\n /** Variant options and modifier choices, as the receipt printed them. */\n variantLabel?: string\n sku?: string\n productType?: 'physical' | 'digital' | 'service'\n quantity: number\n /** Per unit, modifiers included, from the cached catalog. */\n unitAmountCents: number\n modifiers?: ModifierSelection[]\n}\n\n/** The customer the register attached: only what the sale and its receipt need. */\nexport interface PosOfflineSaleCustomer {\n email?: string\n name?: string\n kind?: string\n id?: string\n}\n\n/** One sale rung while offline, exactly as the register queued it. */\nexport interface PosOfflineSale {\n v: 1\n /** The register's key for this sale, minted once; the order's id on the server. */\n saleKey: string\n hostId: string\n /** The workspace the register was signed in to. */\n orgId: string\n /** Who was signed in on the device: the only member who may sync it. */\n signedInUid: string\n registerId: string\n /** The shift open on the register when the sale was rung. */\n shiftId?: string | null\n locationId?: string\n /** A PIN-switched cashier's assertion, valid when the sale was rung. */\n cashierAssertion?: string\n /** The device's clock when the cash was taken. */\n soldAtMs: number\n lines: PosOfflineSaleLine[]\n /** The cashier's discount, a percentage of the goods. */\n discountPct: number\n /** The totals the receipt printed and the customer paid. */\n totals: OrderTotals\n /** Cash handed over; 0 for a card sale. */\n cashTenderedCents: number\n changeCents: number\n customer?: PosOfflineSaleCustomer\n /** `card` only on the native app's own reader (AGL-4039); absent means cash. */\n tender?: PosOfflineTender\n /** The card, when `tender` is `card`. */\n card?: PosOfflineSaleCard\n}\n\n/** What does not match, said on the order and back to the register. */\nexport type PosOfflineFlag =\n | 'price-changed'\n | 'unknown-product'\n | 'tax-differs'\n | 'totals-restated'\n | 'discount-over-limit'\n | 'discount-not-permitted'\n | 'cash-short'\n | 'stock-short'\n | 'shift-closed'\n | 'no-shift'\n | 'unknown-register'\n | 'register-over-cap'\n | 'late-sync'\n | 'clock-adjusted'\n | 'cashier-unverified'\n | 'card-declined'\n | 'card-not-charged'\n | 'card-amount-differs'\n | 'card-fee-short'\n\n/** Each flag in the words the order and the register show. */\nexport const POS_OFFLINE_FLAG_LABELS: Record<PosOfflineFlag, string> = {\n 'price-changed': 'A price changed after the register cached it; the sale kept the price it was rung at',\n 'unknown-product': 'A product was deleted before the sale synced; the line kept what the receipt printed',\n 'tax-differs': 'The tax rung differs from the store’s rate now; the sale kept the tax it collected',\n 'totals-restated': 'The register’s totals did not add up; the server restated them from the lines',\n 'discount-over-limit': 'The discount is above this register’s limit',\n // Names the permission by its label in `plugin-permissions.ts` (AGL-4047);\n // `pos-offline-sync.spec.ts` holds the two to the same words.\n 'discount-not-permitted': 'The discount was given by a member whose role does not include “Give discounts at the register”',\n 'cash-short': 'The cash recorded is less than the total',\n 'stock-short': 'Stock went short: more was sold than the shelf held',\n 'shift-closed': 'Rung in a shift that closed before the sale synced; its Z report does not include it',\n 'no-shift': 'Rung with no shift open, on a site that requires one',\n 'unknown-register': 'The register it was rung on no longer exists',\n 'register-over-cap': 'The register it was rung on is over the plan’s register limit',\n 'late-sync': 'Synced more than a day after it was rung',\n 'clock-adjusted': 'The device clock was off; the sale is dated when it synced',\n 'cashier-unverified': 'The PIN-switched cashier could not be confirmed; the sale is under the signed-in member',\n 'card-declined': 'The card taken offline was declined when it was charged; the order is unpaid',\n 'card-not-charged': 'The card taken offline could not be charged; the order is unpaid',\n 'card-amount-differs': 'The card was charged a different amount than the sale’s total; the payment records what Stripe took',\n 'card-fee-short': 'Stripe took less than the platform fee from this card’s payout; the rest goes on the workspace’s monthly invoice',\n}\n\n/** A line whose stock went short when the sale synced. */\nexport interface PosOfflineStockConflict {\n productId: string\n variantId?: string\n name: string\n /** Units sold. */\n requested: number\n /** Units the shelf actually gave up. */\n applied: number\n /** Units sold that the shelf did not hold. */\n shortUnits: number\n}\n\n/** What the order records about having been rung offline. */\nexport interface PosOfflineOrderStamp {\n saleKey: string\n /** The device's clock when the cash was taken. */\n soldAtMs: number\n syncedAtMs: number\n /** Who synced it: always the member who was signed in when it was rung. */\n syncedBy: string\n flags: PosOfflineFlag[]\n stockConflicts?: PosOfflineStockConflict[]\n /** The server's own price per line where it differed, for the merchant to compare. */\n priceDrift?: Array<{ index: number; rungCents: number; currentCents: number }>\n}\n\n/** Why a sale was refused, and whether the register should keep trying. */\nexport type PosOfflineRefusal =\n | 'wrong-staff'\n | 'wrong-site'\n | 'wrong-workspace'\n | 'invalid'\n | 'conflict'\n | 'failed'\n\n/** What became of one sale the register sent. */\nexport type PosOfflineOutcomeStatus = 'recorded' | 'replayed' | 'refused'\n\n/**\n * One sale's answer, in the order the request sent them. `recorded` and\n * `replayed` carry the order; `refused` carries the reason, the sentence and\n * whether to keep trying. One flat shape, so every register client — the web\n * register and the native apps — decodes it the same way.\n */\nexport interface PosOfflineSaleOutcome {\n saleKey: string\n status: PosOfflineOutcomeStatus\n orderId?: string\n number?: number | null\n flags?: PosOfflineFlag[]\n stockConflicts?: PosOfflineStockConflict[]\n reason?: PosOfflineRefusal\n error?: string\n /** Keep it queued and try again later (a transient failure). */\n retry?: boolean\n}\n\nexport interface PosOfflineSyncRequest {\n hostId: string\n sales: PosOfflineSale[]\n}\n\nexport interface PosOfflineSyncResponse {\n results: PosOfflineSaleOutcome[]\n}\n\n/** One register as the offline kit lists it. */\nexport interface PosOfflineKitRegister {\n id: string\n name: string\n locationId?: string\n openShiftId: string | null\n}\n\n/** What the native app needs to take a card offline on its own reader (AGL-4039). */\nexport interface PosOfflineKitCard {\n available: boolean\n /** Why not, in the cashier's words, when it is not. */\n unavailableReason?: string\n /** The connected account the charge transfers to (a destination charge, as online); '' for a direct charge. */\n destination: string\n /**\n * Set for a store on its own Stripe account (direct charges, AGL-4219):\n * the device makes the intent with no transfer and no destination, on the\n * account its connection token belongs to, which is this one. Offered only\n * to an app that says it can (`cardChargeModels=direct` on the kit's GET).\n */\n account?: string\n currency: string\n /** The limit of one card sale rung offline, in cents: the store's, or Stripe's own ceiling when it set none. */\n maxSaleCents: number\n /** The limit of every card one device takes offline in a day, in cents; 0 is no daily limit. */\n maxDeviceDailyCents: number\n}\n\n/**\n * Everything a register needs to sell offline besides the catalog, from\n * `GET /api/commerce/pos-offline-sync?hostId=`: the server's own answers, so\n * the register and the sync agree about the rate and the rules.\n */\nexport interface PosOfflineKit {\n v: 1\n hostId: string\n orgId: string\n issuedAtMs: number\n /** Offline selling is possible for this site right now. */\n available: boolean\n /** Why not, in the cashier's words, when it is not. */\n unavailableReason?: string\n /** The store's own in-person rate; `null` pct is no tax. */\n tax: { pct: number | null; pricesIncludeTax: boolean }\n maxDiscountPct: number\n requireOpenShift: boolean\n registers: PosOfflineKitRegister[]\n /** Card sales on the app's own reader while offline; absent from a server that does not take them. */\n card?: PosOfflineKitCard\n /** What the receipt prints at its head and foot. `logo` is the stored value. */\n receipt: {\n name: string\n logo?: string\n address?: string\n footer?: string\n returnPolicy?: string\n }\n}\n\n/**\n * The totals of an offline sale: the cashier's discount on the goods, then\n * the store's in-person tax on what is left — exactly the arithmetic the\n * online register's sale route uses for the same basket with no promotion.\n * `pricesIncludeTax` adds nothing, as at the online till.\n */\nexport function posOfflineSaleTotals(input: {\n lines: ReadonlyArray<Pick<PosOfflineSaleLine, 'unitAmountCents' | 'quantity'>>\n discountPct: number\n tax: { pct: number | null; pricesIncludeTax: boolean }\n}): OrderTotals {\n const lines = input.lines.map((line) => ({\n unitAmountCents: wholeCents(line.unitAmountCents),\n quantity: Math.max(1, Math.round(Number(line.quantity) || 1)),\n }))\n const itemsCents = lines.reduce((sum, line) => sum + line.unitAmountCents * line.quantity, 0)\n const pct = Number.isFinite(input.discountPct) ? Math.min(100, Math.max(0, input.discountPct)) : 0\n const discountCents = Math.min(itemsCents, Math.round((itemsCents * pct) / 100))\n const taxPct = Number(input.tax.pct)\n const taxCents =\n taxPct > 0 && !input.tax.pricesIncludeTax ? computeTaxCents(itemsCents - discountCents, taxPct) : 0\n return computeOrderTotals(lines as unknown as OrderLineItem[], { discountCents, taxCents, feeCents: 0 })\n}\n\n/** Change for cash handed over, never negative. */\nexport function posOfflineChangeCents(totalCents: number, tenderedCents: number): number {\n return Math.max(0, wholeCents(tenderedCents) - wholeCents(totalCents))\n}\n\n/** A key the register minted: an id the order can take, and nothing else. */\nexport function posOfflineSaleKeyIsValid(key: unknown): key is string {\n return typeof key === 'string' && /^[A-Za-z0-9_-]{16,64}$/.test(key) && !/^__.*__$/.test(key)\n}\n\n/**\n * The sale's time as the server records it: the device's clock when it is\n * believable, clamped to now when it runs ahead, and to the oldest believable\n * moment when it claims to be older.\n */\nexport function posOfflineSoldAt(\n soldAtMs: number,\n nowMs: number,\n): { atMs: number; adjusted: boolean } {\n const at = Number(soldAtMs)\n if (!Number.isFinite(at) || at <= 0) return { atMs: nowMs, adjusted: true }\n if (at > nowMs + POS_OFFLINE_CLOCK_SKEW_MS) return { atMs: nowMs, adjusted: true }\n if (at < nowMs - POS_OFFLINE_MAX_AGE_MS) return { atMs: nowMs, adjusted: true }\n return { atMs: Math.min(at, nowMs), adjusted: false }\n}\n\nconst bounded = (value: unknown, max: number): string =>\n typeof value === 'string' ? value.trim().slice(0, max) : ''\n\nconst cleanId = (value: unknown): string => {\n const id = String(value ?? '').trim()\n return /^[A-Za-z0-9_-]{1,128}$/.test(id) && !/^__.*__$/.test(id) ? id : ''\n}\n\nfunction wholeCents(value: unknown): number {\n const number = Math.round(Number(value))\n return Number.isFinite(number) && number > 0 ? number : 0\n}\n\n/**\n * A queued sale read off the wire, every field typed and bounded — or the\n * sentence that says why it cannot be read at all. Pure, so the server and\n * any client that wants to check its own queue answer the same.\n */\nexport function sanitizePosOfflineSale(\n raw: unknown,\n): { ok: true; sale: PosOfflineSale } | { ok: false; error: string } {\n if (!raw || typeof raw !== 'object') return { ok: false, error: 'Not a sale' }\n const input = raw as Record<string, any>\n const saleKey = input['saleKey']\n if (!posOfflineSaleKeyIsValid(saleKey)) return { ok: false, error: 'The sale has no valid key' }\n const hostId = cleanId(input['hostId'])\n const registerId = cleanId(input['registerId'])\n const signedInUid = bounded(input['signedInUid'], 128)\n if (!hostId || !registerId || !signedInUid) {\n return { ok: false, error: 'The sale is missing its site, register or member' }\n }\n const rawLines = Array.isArray(input['lines']) ? input['lines'] : []\n if (rawLines.length === 0 || rawLines.length > POS_OFFLINE_SALE_MAX_LINES) {\n return { ok: false, error: 'The sale has no lines' }\n }\n const lines: PosOfflineSaleLine[] = []\n for (const line of rawLines) {\n const productId = cleanId(line?.productId)\n const name = bounded(line?.name, 200)\n const unit = Math.round(Number(line?.unitAmountCents))\n const quantity = Math.round(Number(line?.quantity))\n if (!productId || !name || !Number.isFinite(unit) || unit < 0 || !(quantity >= 1 && quantity <= 99)) {\n return { ok: false, error: 'A line of the sale cannot be read' }\n }\n const variantId = cleanId(line?.variantId)\n const variantLabel = bounded(line?.variantLabel, 200)\n const sku = bounded(line?.sku, 100)\n const productType = ['physical', 'digital', 'service'].includes(line?.productType)\n ? (line.productType as PosOfflineSaleLine['productType'])\n : undefined\n const modifiers = Array.isArray(line?.modifiers)\n ? (line.modifiers as unknown[])\n .slice(0, 50)\n .map((pick: any) => ({ groupId: cleanId(pick?.groupId), optionId: cleanId(pick?.optionId) }))\n .filter((pick) => pick.groupId && pick.optionId)\n : []\n lines.push({\n productId,\n ...(variantId ? { variantId } : {}),\n name,\n ...(variantLabel ? { variantLabel } : {}),\n ...(sku ? { sku } : {}),\n ...(productType ? { productType } : {}),\n quantity,\n unitAmountCents: unit,\n ...(modifiers.length ? { modifiers } : {}),\n })\n }\n const discountPct = Number(input['discountPct'] ?? 0)\n if (!Number.isFinite(discountPct) || discountPct < 0 || discountPct > 100) {\n return { ok: false, error: 'The sale’s discount cannot be read' }\n }\n const totals = (input['totals'] ?? {}) as Record<string, unknown>\n const customerRaw = input['customer']\n const customer: PosOfflineSaleCustomer = {}\n if (customerRaw && typeof customerRaw === 'object') {\n const email = bounded((customerRaw as any).email, 254).toLowerCase()\n if (email && /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email)) customer.email = email\n const name = bounded((customerRaw as any).name, 200)\n if (name) customer.name = name\n const kind = bounded((customerRaw as any).kind, 40)\n const id = cleanId((customerRaw as any).id)\n if (kind && kind !== 'none' && id) {\n customer.kind = kind\n customer.id = id\n }\n }\n const shiftId = cleanId(input['shiftId'])\n const locationId = cleanId(input['locationId'])\n const assertion = bounded(input['cashierAssertion'], 2000)\n const orgId = bounded(input['orgId'], 128)\n let card: PosOfflineSaleCard | undefined\n if (input['tender'] === 'card') {\n const read = sanitizePosOfflineSaleCard(input['card'])\n if (!read) return { ok: false, error: 'The card of the sale cannot be read' }\n card = read\n }\n return {\n ok: true,\n sale: {\n v: 1,\n saleKey,\n hostId,\n orgId,\n signedInUid,\n registerId,\n shiftId: shiftId || null,\n ...(locationId ? { locationId } : {}),\n ...(assertion ? { cashierAssertion: assertion } : {}),\n soldAtMs: Number(input['soldAtMs']) || 0,\n lines,\n discountPct,\n totals: {\n itemsCents: wholeCents(totals['itemsCents']),\n shippingCents: 0,\n taxCents: wholeCents(totals['taxCents']),\n discountCents: wholeCents(totals['discountCents']),\n totalCents: wholeCents(totals['totalCents']),\n feeCents: 0,\n },\n cashTenderedCents: card ? 0 : wholeCents(input['cashTenderedCents']),\n changeCents: card ? 0 : wholeCents(input['changeCents']),\n ...(Object.keys(customer).length ? { customer } : {}),\n ...(card ? { tender: 'card' as const, card } : {}),\n },\n }\n}\n\n/**\n * Whether the register's totals are the arithmetic of its own lines: the\n * goods are the lines' sum, the discount is the percentage of them, and the\n * total is goods less discount plus the tax it rang. The tax itself is the\n * register's, and checked against the store's rate separately.\n */\nexport function posOfflineTotalsAddUp(sale: Pick<PosOfflineSale, 'lines' | 'discountPct' | 'totals'>): boolean {\n const expected = posOfflineSaleTotals({\n lines: sale.lines,\n discountPct: sale.discountPct,\n tax: { pct: null, pricesIncludeTax: false },\n })\n return (\n expected.itemsCents === sale.totals.itemsCents &&\n expected.discountCents === sale.totals.discountCents &&\n sale.totals.taxCents <= sale.totals.itemsCents &&\n sale.totals.totalCents === expected.itemsCents - expected.discountCents + sale.totals.taxCents\n )\n}\n\n/** The flags in the order and words the register lists them. */\nexport function posOfflineFlagLabels(flags: readonly PosOfflineFlag[]): string[] {\n return flags.map((flag) => POS_OFFLINE_FLAG_LABELS[flag] ?? flag)\n}\n\n/** A Stripe account id as Stripe mints them. */\nconst POS_OFFLINE_CARD_ACCOUNT = /^acct_[A-Za-z0-9]{8,64}$/\n\nconst CARD_FORWARDS: readonly PosOfflineCardForward[] = ['stored', 'forwarded', 'declined', 'failed']\n\n/** The card side of a queued sale, typed and bounded, or `null` when it cannot be read. */\nexport function sanitizePosOfflineSaleCard(raw: unknown): PosOfflineSaleCard | null {\n if (!raw || typeof raw !== 'object') return null\n const input = raw as Record<string, unknown>\n const forward = input['forward'] as PosOfflineCardForward\n if (!CARD_FORWARDS.includes(forward)) return null\n const intent = typeof input['paymentIntentId'] === 'string' ? input['paymentIntentId'].trim() : ''\n if (intent && !/^pi_[A-Za-z0-9]{8,64}$/.test(intent)) return null\n if (forward === 'forwarded' && !intent) return null\n const brand = bounded(input['brand'], 24)\n const last4 = typeof input['last4'] === 'string' && /^\\d{4}$/.test(input['last4']) ? input['last4'] : ''\n const declineMessage = bounded(input['declineMessage'], 300)\n const account = typeof input['account'] === 'string' ? input['account'].trim() : ''\n if (account && !POS_OFFLINE_CARD_ACCOUNT.test(account)) return null\n return {\n forward,\n ...(intent ? { paymentIntentId: intent } : {}),\n ...(brand ? { brand } : {}),\n ...(last4 ? { last4 } : {}),\n ...(declineMessage ? { declineMessage } : {}),\n ...(account ? { account } : {}),\n }\n}\n\n/**\n * Why a card cannot be taken offline for `totalCents`, in the cashier's\n * words, or `null` when it can: the store has not turned it on, the sale is\n * over the store's (or Stripe's) limit per sale, or the cards this device\n * has taken offline today would pass the store's daily limit per device (a\n * daily limit of 0 is none: the store did not set one).\n */\nexport function posOfflineCardRefusal(input: {\n card: Pick<PosOfflineKitCard, 'available' | 'unavailableReason' | 'maxSaleCents' | 'maxDeviceDailyCents'> | null | undefined\n totalCents: number\n /** Every card this device took offline today, in cents. */\n takenTodayCents: number\n}): string | null {\n const card = input.card\n if (!card) return 'Card sales offline need the register to connect once first.'\n if (!card.available) return card.unavailableReason || 'Card sales offline are not turned on for this store.'\n const total = wholeCents(input.totalCents)\n if (total <= 0) return 'There is nothing to charge.'\n const perSale = Math.min(wholeCents(card.maxSaleCents), POS_OFFLINE_CARD_MAX_SALE_CENTS_LIMIT)\n if (total > perSale) return `Offline, a card sale can be up to ${dollars(perSale)}. Take cash, or charge it when you are back online.`\n const today = wholeCents(input.takenTodayCents)\n const daily = wholeCents(card.maxDeviceDailyCents)\n if (daily > 0 && today + total > daily) {\n return `This device has taken ${dollars(today)} in cards offline today, and its daily limit is ${dollars(daily)}. Take cash, or wait for the connection.`\n }\n return null\n}\n\n/**\n * What the app writes on the PaymentIntent it creates for a card rung\n * offline: the sale key (the order's id once it syncs) and where it was rung,\n * so the server can match the charge to the sale even if the sale's own sync\n * never arrives. An intent made on the store's own account (`direct`,\n * AGL-4219) also says `chargeModel: direct`, as every direct sale's objects\n * do, so its Connect-delivered events are read as the store's own.\n */\nexport function posOfflineCardIntentMetadata(\n sale: Pick<PosOfflineSale, 'saleKey' | 'hostId' | 'orgId' | 'registerId'> & { direct?: boolean },\n): Record<string, string> {\n return {\n kind: POS_OFFLINE_CARD_INTENT_KIND,\n saleKey: sale.saleKey,\n hostId: sale.hostId,\n orgId: sale.orgId,\n registerId: sale.registerId,\n ...(sale.direct ? { chargeModel: 'direct' } : {}),\n }\n}\n\nfunction dollars(cents: number): string {\n const whole = Math.floor(cents / 100)\n const rest = cents % 100\n return `$${whole.toLocaleString('en-US')}.${String(rest).padStart(2, '0')}`\n}\n"],"names":["computeOrderTotals","computeTaxCents","POS_OFFLINE_CARD_MAX_SALE_CENTS_LIMIT","POS_OFFLINE_SYNC_ROUTE","POS_OFFLINE_SYNC_BATCH_MAX","POS_OFFLINE_SALE_MAX_LINES","POS_OFFLINE_LATE_SYNC_MS","POS_OFFLINE_MAX_AGE_MS","POS_OFFLINE_CLOCK_SKEW_MS","POS_OFFLINE_CARD_RECONNECT_WITHIN_MS","POS_OFFLINE_CARD_INTENT_KIND","POS_OFFLINE_DISABLED_TENDERS","card_present","card_keyed","card_link","gift_card","folio","credit","POS_OFFLINE_FLAG_LABELS","posOfflineSaleTotals","input","lines","map","line","unitAmountCents","wholeCents","quantity","Math","max","round","Number","itemsCents","reduce","sum","pct","isFinite","discountPct","min","discountCents","taxPct","tax","taxCents","pricesIncludeTax","feeCents","posOfflineChangeCents","totalCents","tenderedCents","posOfflineSaleKeyIsValid","key","test","posOfflineSoldAt","soldAtMs","nowMs","at","atMs","adjusted","bounded","value","trim","slice","cleanId","id","String","number","sanitizePosOfflineSale","raw","ok","error","saleKey","hostId","registerId","signedInUid","rawLines","Array","isArray","length","productId","name","unit","variantId","variantLabel","sku","productType","includes","undefined","modifiers","pick","groupId","optionId","filter","push","totals","customerRaw","customer","email","toLowerCase","kind","shiftId","locationId","assertion","orgId","card","read","sanitizePosOfflineSaleCard","sale","v","cashierAssertion","shippingCents","cashTenderedCents","changeCents","Object","keys","tender","posOfflineTotalsAddUp","expected","posOfflineFlagLabels","flags","flag","POS_OFFLINE_CARD_ACCOUNT","CARD_FORWARDS","forward","intent","brand","last4","declineMessage","account","paymentIntentId","posOfflineCardRefusal","available","unavailableReason","total","perSale","maxSaleCents","dollars","today","takenTodayCents","daily","maxDeviceDailyCents","posOfflineCardIntentMetadata","direct","chargeModel","cents","whole","floor","rest","toLocaleString","padStart"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,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O;QACrBC,QAAQmC,KAAKnC,MAAM;QACnB+B,OAAOI,KAAKJ,KAAK;QACjB9B,YAAYkC,KAAKlC,UAAU;OACvBkC,KAAKmC,MAAM,GAAG;QAAEC,aAAa;IAAS,IAAI,CAAC;AAEnD;AAEA,SAASP,QAAQQ,KAAa;IAC5B,MAAMC,QAAQnH,KAAKoH,KAAK,CAACF,QAAQ;IACjC,MAAMG,OAAOH,QAAQ;IACrB,OAAO,CAAC,CAAC,EAAEC,MAAMG,cAAc,CAAC,SAAS,CAAC,EAAEnF,OAAOkF,MAAME,QAAQ,CAAC,GAAG,MAAM;AAC7E"}
|
package/src/lib/server/cart.js
CHANGED
|
@@ -20,6 +20,7 @@ import { firebaseAdmin } from "@aglyn/tenant-data-admin";
|
|
|
20
20
|
import { isDocumentId } from "@aglyn/tenant-data-admin/server/document-id";
|
|
21
21
|
import { cartCookieName, mintCartId, readCartId } from "./cart-cookie.js";
|
|
22
22
|
import { readStoreDay } from "./store-day.js";
|
|
23
|
+
import { planCheckoutShippingWithCarriers } from "./carrier-shipping.js";
|
|
23
24
|
/**
|
|
24
25
|
* Server-backed cart (AGL-293): cookie-keyed doc under
|
|
25
26
|
* `hosts/{hostId}/carts`. GET returns the resolved cart; POST mutates
|
|
@@ -252,12 +253,25 @@ import { readStoreDay } from "./store-day.js";
|
|
|
252
253
|
var _productsById_get;
|
|
253
254
|
return isPosHardwareSkuId((_productsById_get = productsById.get(line.productId)) == null ? void 0 : _productsById_get.hardwareSku);
|
|
254
255
|
});
|
|
256
|
+
// Where it is going, asked WITH the cart rather than after the first
|
|
257
|
+
// Checkout press: the same plan checkout makes, with no destination yet.
|
|
258
|
+
const askShippingCountry = await shippingCountryNeeded({
|
|
259
|
+
hostRef,
|
|
260
|
+
lines,
|
|
261
|
+
productsById,
|
|
262
|
+
subtotalCents
|
|
263
|
+
});
|
|
255
264
|
return res.status(200).json(_extends({
|
|
256
265
|
lines,
|
|
257
266
|
count: CommerceModel.cartCount(cart),
|
|
258
267
|
subtotalCents
|
|
259
268
|
}, hardwareTerms ? {
|
|
260
269
|
hardwareTerms: true
|
|
270
|
+
} : {}, askShippingCountry ? {
|
|
271
|
+
needsShippingCountry: true,
|
|
272
|
+
shippingCountries: [
|
|
273
|
+
...CommerceModel.CHECKOUT_SHIPPING_COUNTRIES
|
|
274
|
+
]
|
|
261
275
|
} : {}));
|
|
262
276
|
} catch (error) {
|
|
263
277
|
console.error(error);
|
|
@@ -266,5 +280,48 @@ import { readStoreDay } from "./store-day.js";
|
|
|
266
280
|
});
|
|
267
281
|
}
|
|
268
282
|
};
|
|
283
|
+
/**
|
|
284
|
+
* Whether checkout will ask this cart where it is shipping to, answered while
|
|
285
|
+
* the cart is shown so the cart can ask up front. A shopper who pressed
|
|
286
|
+
* Checkout used to be refused with "Choose where you’re shipping to." and only
|
|
287
|
+
* then shown the field.
|
|
288
|
+
*
|
|
289
|
+
* The same plan `cart-checkout.ts` makes, with no destination, so the two
|
|
290
|
+
* cannot disagree: rates that differ by zone, or carrier rates, need one. A
|
|
291
|
+
* cart with nothing posted reads nothing more, and a store with one zone, a
|
|
292
|
+
* rest-of-world zone or no shipping at all is never asked. Checkout still asks
|
|
293
|
+
* and enforces the answer on its own; this only moves the question earlier.
|
|
294
|
+
*/ async function shippingCountryNeeded(input) {
|
|
295
|
+
let physical = false;
|
|
296
|
+
let totalGrams = 0;
|
|
297
|
+
for (const line of input.lines){
|
|
298
|
+
var _product_type, _ref;
|
|
299
|
+
if (line.unavailable) continue;
|
|
300
|
+
const product = input.productsById.get(line.productId);
|
|
301
|
+
if (!product) continue;
|
|
302
|
+
// A missing `type` reads as physical, as checkout reads it.
|
|
303
|
+
if (((_product_type = product.type) != null ? _product_type : 'physical') !== 'physical') continue;
|
|
304
|
+
physical = true;
|
|
305
|
+
const variant = line.variantId ? product.variants.find((item)=>item.id === line.variantId) : product.variants[0];
|
|
306
|
+
totalGrams += Math.max(0, Number((_ref = variant == null ? void 0 : variant.weightGrams) != null ? _ref : 0)) * line.quantity;
|
|
307
|
+
}
|
|
308
|
+
if (!physical) return false;
|
|
309
|
+
try {
|
|
310
|
+
const storeSettings = await input.hostRef.collection('settings').doc('store').get();
|
|
311
|
+
const plan = await planCheckoutShippingWithCarriers({
|
|
312
|
+
hostId: input.hostRef.id,
|
|
313
|
+
settings: storeSettings.get('shipping'),
|
|
314
|
+
cart: {
|
|
315
|
+
subtotalCents: input.subtotalCents,
|
|
316
|
+
totalGrams
|
|
317
|
+
},
|
|
318
|
+
destination: {}
|
|
319
|
+
});
|
|
320
|
+
return plan.refusal === 'destination-required';
|
|
321
|
+
} catch (unused) {
|
|
322
|
+
// The cart still shows; checkout asks, as it always has.
|
|
323
|
+
return false;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
269
326
|
|
|
270
327
|
//# sourceMappingURL=cart.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/cart.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 { isPosHardwareSkuId, parsePosHardwareInPersonConfig } from '../model/pos-hardware'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport { cartCookieName, mintCartId, readCartId } from './cart-cookie'\nimport { readStoreDay } from './store-day'\n\nexport interface ResolvedCartLine extends CommerceModel.CartLine {\n name: string\n variantLabel?: string\n unitAmountCents: number\n imageUrl?: string\n /** Line no longer purchasable (deleted/draft/sold out). */\n unavailable?: boolean\n /**\n * What the shopper must do about an unavailable line, when the cart can say\n * (AGL-4100): its add-ons no longer answer the product's choices.\n */\n problem?: string\n}\n\n/**\n * Server-backed cart (AGL-293): cookie-keyed doc under\n * `hosts/{hostId}/carts`. GET returns the resolved cart; POST mutates\n * with {action: add|set|remove|clear}. Lines resolve against product\n * docs on every read so prices/names never go stale, and unavailable\n * lines surface instead of silently charging.\n */\nexport const cartHandler: PluginApiHandler = async (req, res) => {\n const isPost = req.method === 'POST'\n if (!isPost && req.method !== 'GET') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const body = isPost\n ? typeof req.body === 'string'\n ? JSON.parse(req.body || '{}')\n : (req.body ?? {})\n : {}\n // AGL-1769: BOTH components of the path this handler writes come from the\n // caller — `hostId` off the body, `cartId` off a cookie whose name embeds\n // `hostId` — and `.doc()` appends a slash-separated PATH rather than taking\n // one opaque id. So an unvalidated pair named the nesting as well as the\n // document: a `hostId` of `a/b/c` wrote under `hosts/a/b/c`, invisible to\n // every console list because they resolve the host doc first.\n //\n // This handler is the one visitor-facing write in the AGL-1763 sweep that\n // needs NO credentials — no session, no member gate, no signature — so it is\n // the one place the id rule has to hold on its own.\n const hostId = String((isPost ? body.hostId : req.query.hostId) ?? '')\n // The message names BOTH causes it now covers (`762621581`): the guard reads\n // as \"absent\" but also refuses a hostId that is a path rather than an id, and\n // a caller told only \"missing\" would go looking for the wrong mistake.\n // AGL-1771: `isDocumentId`, not the cart module's old `isCartId` alias — this\n // value is a HOST id, and the rule it has to satisfy was never about carts.\n if (!isDocumentId(hostId))\n return res.status(400).json({ error: 'Missing or invalid hostId' })\n\n const cookieName = cartCookieName(hostId)\n // A cookie that is not a single document id reads as NO cart: a GET returns\n // an empty one and a POST mints a fresh id below, exactly as for a first-time\n // visitor. Nothing is stranded — a path that was never a cart id was never a\n // basket anyone filled.\n let cartId = readCartId(req.cookies, hostId)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n\n try {\n if (!cartId) {\n if (!isPost) return res.status(200).json({ lines: [], count: 0 })\n cartId = mintCartId()\n res.setHeader(\n 'Set-Cookie',\n `${cookieName}=${cartId}; Path=/; Max-Age=${60 * 60 * 24 * 90}; ` +\n 'HttpOnly; SameSite=Lax; Secure',\n )\n }\n const cartRef = hostRef.collection('carts').doc(cartId)\n const cartSnapshot = await cartRef.get()\n const cart: CommerceModel.HostCart = (cartSnapshot.data() as any) ?? { lines: [] }\n\n if (isPost) {\n const action = String(body.action ?? 'add')\n // The day the shopper chose to use a check-in item (AGL-4043): part of\n // the line's identity, so two days of one pass are two lines.\n const useDayKey = typeof body.useDayKey === 'string' ? body.useDayKey.trim() : ''\n // The add-ons chosen on the product's page (AGL-4100), ids only: part\n // of the line's identity, priced from the product, never from here.\n const requestedModifiers = CommerceModel.modifierSelectionFrom(body.modifiers)\n const line: CommerceModel.CartLine = {\n productId: String(body.productId ?? ''),\n ...(body.variantId ? { variantId: String(body.variantId) } : {}),\n ...(useDayKey ? { useDayKey } : {}),\n ...(requestedModifiers.length ? { modifiers: requestedModifiers } : {}),\n // Clamped at the door as well as in the model (AGL-2285): the route\n // used `Math.round(Number(...))` alone, which yields `NaN` for\n // `{\"quantity\":\"x\"}` and slipped past `upsertCartLine`'s `<= 0` guard.\n quantity: Math.min(\n CommerceModel.CART_MAX_QUANTITY,\n Math.max(\n -CommerceModel.CART_MAX_QUANTITY,\n Number.isFinite(Number(body.quantity ?? 1))\n ? Math.round(Number(body.quantity ?? 1))\n : 0,\n ),\n ),\n }\n if (useDayKey && !CommerceModel.isCheckInDayKey(useDayKey)) {\n return res.status(400).json({ error: 'Choose the day as a date.' })\n }\n if (action === 'clear') {\n cart.lines = []\n } else if (!line.productId) {\n return res.status(400).json({ error: 'Missing productId' })\n } else if (action === 'remove') {\n cart.lines = CommerceModel.removeCartLine(cart, line)\n } else {\n // A product sold in person only (AGL-4060) never enters a basket: it\n // answers as no product at all, as its page does. A line already in\n // the cart stays removable and resolves as unavailable below.\n if (line.quantity > 0 && isDocumentId(line.productId)) {\n const productSnapshot = await hostRef.collection('products').doc(line.productId).get()\n if (productSnapshot.exists && !CommerceModel.productSellsOnline(productSnapshot.data())) {\n return res.status(404).json({ error: 'Unknown product' })\n }\n // A use day is asked only by an item that asks for one, and is a\n // day that has not passed on the store's calendar (AGL-4043).\n const isNewLine = !cart.lines.some(\n (held) => CommerceModel.cartLineKey(held) === CommerceModel.cartLineKey(line),\n )\n const product = productSnapshot.exists ? CommerceModel.liftLegacyProduct(productSnapshot.data() as any) : null\n if (useDayKey && (action === 'add' || isNewLine)) {\n const variantId = line.variantId ?? product?.variants[0]?.id\n if (!product || !CommerceModel.productAsksUseDate(product, variantId)) {\n return res.status(400).json({ error: 'This item has no day to choose.' })\n }\n const problem = CommerceModel.checkInUseDayProblem(useDayKey, (await readStoreDay(hostRef)).todayKey)\n if (problem) return res.status(400).json({ error: problem })\n }\n // Add-ons (AGL-4100): asked of the groups the website shows, every\n // required one answered, and kept as ids in the product's order. A\n // required group left unanswered is refused here, so no line goes\n // in a basket that checkout would have to turn away.\n if (product && (action === 'add' || isNewLine)) {\n const chosen = CommerceModel.resolveWebsiteLineModifiers(\n product,\n line.modifiers,\n line.variantId ?? product.variants[0]?.id,\n )\n if (!chosen.ok) return res.status(400).json({ error: chosen.error })\n const selection = CommerceModel.modifierSelectionOf(chosen.modifiers)\n if (selection.length) line.modifiers = selection\n else delete line.modifiers\n }\n }\n cart.lines = CommerceModel.upsertCartLine(\n cart,\n line,\n action === 'set' ? 'set' : 'add',\n )\n }\n // AGL-1769: never mint an EMPTY cart. `clear` returns above before the\n // `!line.productId` check, so `{ hostId, action: 'clear' }` — no\n // product, valid or otherwise, and no credentials — used to create a\n // document per request holding `lines: []` and two timestamps. A `remove`\n // or a `set 0` that empties an absent basket is the same request wearing\n // a productId. A cart that would store no lines is not a cart.\n //\n // AGL-1760's test — does refusing discard money or work that already\n // occurred — is passed trivially here: there is no basket to strand. The\n // caller still gets its cookie and its empty-cart response, so the next\n // add lands on this id and creates the document properly.\n if (cartSnapshot.exists || cart.lines.length > 0) {\n await cartRef.set(\n {\n lines: cart.lines,\n updatedAtMs: Date.now(),\n ...(cartSnapshot.exists ? {} : { createdAtMs: Date.now() }),\n },\n { merge: true },\n )\n }\n }\n\n // Resolve display lines from product docs — never trust stored data.\n const uniqueProductIds = [...new Set(cart.lines.map((l) => l.productId))]\n const productSnapshots = await Promise.all(\n uniqueProductIds.map((id) =>\n hostRef.collection('products').doc(id).get(),\n ),\n )\n const productsById = new Map(\n productSnapshots.map((snapshot) => [\n snapshot.id,\n snapshot.exists ? CommerceModel.liftLegacyProduct(snapshot.data() as any) : null,\n ]),\n )\n const lines: ResolvedCartLine[] = cart.lines.map((line) => {\n const product = productsById.get(line.productId)\n if (!product || !CommerceModel.productListedOnline(product)) {\n return {\n ...line,\n name: product?.name ?? 'Unavailable product',\n unitAmountCents: 0,\n unavailable: true,\n }\n }\n const variant = line.variantId\n ? product.variants.find((item) => item.id === line.variantId)\n : product.variants[0]\n // A variant with no price yet (AGL-2916) is not for sale, and never a\n // line worth nothing.\n if (!variant || !CommerceModel.variantHasPrice(variant)) {\n return {\n ...line,\n name: product.name,\n unitAmountCents: 0,\n unavailable: true,\n }\n }\n const variantLabel = Object.keys(variant.options ?? {}).length\n ? Object.values(variant.options ?? {}).join(' / ')\n : undefined\n // Add-ons priced from the product on every read (AGL-4100), on this\n // variant. Choices the product no longer offers, or a required one\n // now unanswered, make the line unavailable with what to do.\n const chosen = CommerceModel.resolveWebsiteLineModifiers(product, line.modifiers, variant.id)\n if (!chosen.ok) {\n return {\n ...line,\n name: product.name,\n ...(variantLabel ? { variantLabel } : {}),\n unitAmountCents: 0,\n unavailable: true,\n problem: CommerceModel.cartLineModifierProblem(chosen.error),\n }\n }\n const label = CommerceModel.lineLabelWithModifiers(variantLabel, chosen.modifiers)\n return {\n ...line,\n name: product.name,\n ...(label ? { variantLabel: label } : {}),\n unitAmountCents: Math.round(Number(variant.priceUsd) * 100) + chosen.extraCents,\n ...(variant.imageUrl || product.mediaUrls?.[0] || product.imageUrl\n ? {\n imageUrl:\n variant.imageUrl ??\n product.mediaUrls?.[0] ??\n product.imageUrl,\n }\n : {}),\n ...(CommerceModel.canPurchase(product, variant.id, line.quantity)\n ? {}\n : { unavailable: true }),\n }\n })\n const subtotalCents = lines\n .filter((line) => !line.unavailable)\n .reduce((sum, line) => sum + line.unitAmountCents * line.quantity, 0)\n // Card reader hardware the platform's own store sells (AGL-4038): the\n // cart asks for the terms of sale before checkout. Read from the\n // environment first, so no other store reads anything more.\n const sellerHostId = parsePosHardwareInPersonConfig(process.env)?.sellerHostId\n const hardwareTerms =\n sellerHostId === hostId &&\n cart.lines.some((line) => isPosHardwareSkuId(productsById.get(line.productId)?.hardwareSku))\n return res.status(200).json({\n lines,\n count: CommerceModel.cartCount(cart),\n subtotalCents,\n ...(hardwareTerms ? { hardwareTerms: true } : {}),\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Cart unavailable' })\n }\n}\n"],"names":["isPosHardwareSkuId","parsePosHardwareInPersonConfig","CommerceModel","firebaseAdmin","isDocumentId","cartCookieName","mintCartId","readCartId","readStoreDay","cartHandler","req","res","isPost","method","status","json","error","body","JSON","parse","hostId","String","query","cookieName","cartId","cookies","firestore","app","hostRef","collection","doc","cartSnapshot","lines","count","setHeader","cartRef","get","cart","data","action","useDayKey","trim","requestedModifiers","modifierSelectionFrom","modifiers","line","productId","variantId","length","quantity","Math","min","CART_MAX_QUANTITY","max","Number","isFinite","round","isCheckInDayKey","removeCartLine","productSnapshot","exists","productSellsOnline","isNewLine","some","held","cartLineKey","product","liftLegacyProduct","variants","id","productAsksUseDate","problem","checkInUseDayProblem","todayKey","chosen","resolveWebsiteLineModifiers","ok","selection","modifierSelectionOf","upsertCartLine","set","updatedAtMs","Date","now","createdAtMs","merge","uniqueProductIds","Set","map","l","productSnapshots","Promise","all","productsById","Map","snapshot","variant","productListedOnline","name","unitAmountCents","unavailable","find","item","variantHasPrice","variantLabel","Object","keys","options","values","join","undefined","cartLineModifierProblem","label","lineLabelWithModifiers","priceUsd","extraCents","imageUrl","mediaUrls","canPurchase","subtotalCents","filter","reduce","sum","sellerHostId","process","env","hardwareTerms","hardwareSku","cartCount","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,EAAEC,8BAA8B,QAAQ,2BAAuB;AAG1F,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,SAASC,cAAc,EAAEC,UAAU,EAAEC,UAAU,QAAQ,mBAAe;AACtE,SAASC,YAAY,QAAQ,iBAAa;AAgB1C;;;;;;CAMC,GACD,OAAO,MAAMC,cAAgC,OAAOC,KAAKC;QAQhDD,WAYgBE;IAnBvB,MAAMA,SAASF,IAAIG,MAAM,KAAK;IAC9B,IAAI,CAACD,UAAUF,IAAIG,MAAM,KAAK,OAAO;QACnC,OAAOF,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,OAAOL,SACT,OAAOF,IAAIO,IAAI,KAAK,WAClBC,KAAKC,KAAK,CAACT,IAAIO,IAAI,IAAI,SACtBP,YAAAA,IAAIO,IAAI,YAARP,YAAY,CAAC,IAChB,CAAC;IACL,0EAA0E;IAC1E,0EAA0E;IAC1E,4EAA4E;IAC5E,yEAAyE;IACzE,0EAA0E;IAC1E,8DAA8D;IAC9D,EAAE;IACF,0EAA0E;IAC1E,6EAA6E;IAC7E,oDAAoD;IACpD,MAAMU,SAASC,QAAQT,OAAAA,SAASK,KAAKG,MAAM,GAAGV,IAAIY,KAAK,CAACF,MAAM,YAAvCR,OAA4C;IACnE,6EAA6E;IAC7E,8EAA8E;IAC9E,uEAAuE;IACvE,8EAA8E;IAC9E,4E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;QAC5F,OAAOpH,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAC1BiB;YACAC,OAAO/B,cAAc8H,SAAS,CAAC3F;YAC/BkF;WACIO,gBAAgB;YAAEA,eAAe;QAAK,IAAI,CAAC;IAEnD,EAAE,OAAO9G,OAAO;QACdiH,QAAQjH,KAAK,CAACA;QACd,OAAOL,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAmB;IAC1D;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/cart.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 { isPosHardwareSkuId, parsePosHardwareInPersonConfig } from '../model/pos-hardware'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport { cartCookieName, mintCartId, readCartId } from './cart-cookie'\nimport { readStoreDay } from './store-day'\nimport { planCheckoutShippingWithCarriers } from './carrier-shipping'\n\nexport interface ResolvedCartLine extends CommerceModel.CartLine {\n name: string\n variantLabel?: string\n unitAmountCents: number\n imageUrl?: string\n /** Line no longer purchasable (deleted/draft/sold out). */\n unavailable?: boolean\n /**\n * What the shopper must do about an unavailable line, when the cart can say\n * (AGL-4100): its add-ons no longer answer the product's choices.\n */\n problem?: string\n}\n\n/**\n * Server-backed cart (AGL-293): cookie-keyed doc under\n * `hosts/{hostId}/carts`. GET returns the resolved cart; POST mutates\n * with {action: add|set|remove|clear}. Lines resolve against product\n * docs on every read so prices/names never go stale, and unavailable\n * lines surface instead of silently charging.\n */\nexport const cartHandler: PluginApiHandler = async (req, res) => {\n const isPost = req.method === 'POST'\n if (!isPost && req.method !== 'GET') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const body = isPost\n ? typeof req.body === 'string'\n ? JSON.parse(req.body || '{}')\n : (req.body ?? {})\n : {}\n // AGL-1769: BOTH components of the path this handler writes come from the\n // caller — `hostId` off the body, `cartId` off a cookie whose name embeds\n // `hostId` — and `.doc()` appends a slash-separated PATH rather than taking\n // one opaque id. So an unvalidated pair named the nesting as well as the\n // document: a `hostId` of `a/b/c` wrote under `hosts/a/b/c`, invisible to\n // every console list because they resolve the host doc first.\n //\n // This handler is the one visitor-facing write in the AGL-1763 sweep that\n // needs NO credentials — no session, no member gate, no signature — so it is\n // the one place the id rule has to hold on its own.\n const hostId = String((isPost ? body.hostId : req.query.hostId) ?? '')\n // The message names BOTH causes it now covers (`762621581`): the guard reads\n // as \"absent\" but also refuses a hostId that is a path rather than an id, and\n // a caller told only \"missing\" would go looking for the wrong mistake.\n // AGL-1771: `isDocumentId`, not the cart module's old `isCartId` alias — this\n // value is a HOST id, and the rule it has to satisfy was never about carts.\n if (!isDocumentId(hostId))\n return res.status(400).json({ error: 'Missing or invalid hostId' })\n\n const cookieName = cartCookieName(hostId)\n // A cookie that is not a single document id reads as NO cart: a GET returns\n // an empty one and a POST mints a fresh id below, exactly as for a first-time\n // visitor. Nothing is stranded — a path that was never a cart id was never a\n // basket anyone filled.\n let cartId = readCartId(req.cookies, hostId)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n\n try {\n if (!cartId) {\n if (!isPost) return res.status(200).json({ lines: [], count: 0 })\n cartId = mintCartId()\n res.setHeader(\n 'Set-Cookie',\n `${cookieName}=${cartId}; Path=/; Max-Age=${60 * 60 * 24 * 90}; ` +\n 'HttpOnly; SameSite=Lax; Secure',\n )\n }\n const cartRef = hostRef.collection('carts').doc(cartId)\n const cartSnapshot = await cartRef.get()\n const cart: CommerceModel.HostCart = (cartSnapshot.data() as any) ?? { lines: [] }\n\n if (isPost) {\n const action = String(body.action ?? 'add')\n // The day the shopper chose to use a check-in item (AGL-4043): part of\n // the line's identity, so two days of one pass are two lines.\n const useDayKey = typeof body.useDayKey === 'string' ? body.useDayKey.trim() : ''\n // The add-ons chosen on the product's page (AGL-4100), ids only: part\n // of the line's identity, priced from the product, never from here.\n const requestedModifiers = CommerceModel.modifierSelectionFrom(body.modifiers)\n const line: CommerceModel.CartLine = {\n productId: String(body.productId ?? ''),\n ...(body.variantId ? { variantId: String(body.variantId) } : {}),\n ...(useDayKey ? { useDayKey } : {}),\n ...(requestedModifiers.length ? { modifiers: requestedModifiers } : {}),\n // Clamped at the door as well as in the model (AGL-2285): the route\n // used `Math.round(Number(...))` alone, which yields `NaN` for\n // `{\"quantity\":\"x\"}` and slipped past `upsertCartLine`'s `<= 0` guard.\n quantity: Math.min(\n CommerceModel.CART_MAX_QUANTITY,\n Math.max(\n -CommerceModel.CART_MAX_QUANTITY,\n Number.isFinite(Number(body.quantity ?? 1))\n ? Math.round(Number(body.quantity ?? 1))\n : 0,\n ),\n ),\n }\n if (useDayKey && !CommerceModel.isCheckInDayKey(useDayKey)) {\n return res.status(400).json({ error: 'Choose the day as a date.' })\n }\n if (action === 'clear') {\n cart.lines = []\n } else if (!line.productId) {\n return res.status(400).json({ error: 'Missing productId' })\n } else if (action === 'remove') {\n cart.lines = CommerceModel.removeCartLine(cart, line)\n } else {\n // A product sold in person only (AGL-4060) never enters a basket: it\n // answers as no product at all, as its page does. A line already in\n // the cart stays removable and resolves as unavailable below.\n if (line.quantity > 0 && isDocumentId(line.productId)) {\n const productSnapshot = await hostRef.collection('products').doc(line.productId).get()\n if (productSnapshot.exists && !CommerceModel.productSellsOnline(productSnapshot.data())) {\n return res.status(404).json({ error: 'Unknown product' })\n }\n // A use day is asked only by an item that asks for one, and is a\n // day that has not passed on the store's calendar (AGL-4043).\n const isNewLine = !cart.lines.some(\n (held) => CommerceModel.cartLineKey(held) === CommerceModel.cartLineKey(line),\n )\n const product = productSnapshot.exists ? CommerceModel.liftLegacyProduct(productSnapshot.data() as any) : null\n if (useDayKey && (action === 'add' || isNewLine)) {\n const variantId = line.variantId ?? product?.variants[0]?.id\n if (!product || !CommerceModel.productAsksUseDate(product, variantId)) {\n return res.status(400).json({ error: 'This item has no day to choose.' })\n }\n const problem = CommerceModel.checkInUseDayProblem(useDayKey, (await readStoreDay(hostRef)).todayKey)\n if (problem) return res.status(400).json({ error: problem })\n }\n // Add-ons (AGL-4100): asked of the groups the website shows, every\n // required one answered, and kept as ids in the product's order. A\n // required group left unanswered is refused here, so no line goes\n // in a basket that checkout would have to turn away.\n if (product && (action === 'add' || isNewLine)) {\n const chosen = CommerceModel.resolveWebsiteLineModifiers(\n product,\n line.modifiers,\n line.variantId ?? product.variants[0]?.id,\n )\n if (!chosen.ok) return res.status(400).json({ error: chosen.error })\n const selection = CommerceModel.modifierSelectionOf(chosen.modifiers)\n if (selection.length) line.modifiers = selection\n else delete line.modifiers\n }\n }\n cart.lines = CommerceModel.upsertCartLine(\n cart,\n line,\n action === 'set' ? 'set' : 'add',\n )\n }\n // AGL-1769: never mint an EMPTY cart. `clear` returns above before the\n // `!line.productId` check, so `{ hostId, action: 'clear' }` — no\n // product, valid or otherwise, and no credentials — used to create a\n // document per request holding `lines: []` and two timestamps. A `remove`\n // or a `set 0` that empties an absent basket is the same request wearing\n // a productId. A cart that would store no lines is not a cart.\n //\n // AGL-1760's test — does refusing discard money or work that already\n // occurred — is passed trivially here: there is no basket to strand. The\n // caller still gets its cookie and its empty-cart response, so the next\n // add lands on this id and creates the document properly.\n if (cartSnapshot.exists || cart.lines.length > 0) {\n await cartRef.set(\n {\n lines: cart.lines,\n updatedAtMs: Date.now(),\n ...(cartSnapshot.exists ? {} : { createdAtMs: Date.now() }),\n },\n { merge: true },\n )\n }\n }\n\n // Resolve display lines from product docs — never trust stored data.\n const uniqueProductIds = [...new Set(cart.lines.map((l) => l.productId))]\n const productSnapshots = await Promise.all(\n uniqueProductIds.map((id) =>\n hostRef.collection('products').doc(id).get(),\n ),\n )\n const productsById = new Map(\n productSnapshots.map((snapshot) => [\n snapshot.id,\n snapshot.exists ? CommerceModel.liftLegacyProduct(snapshot.data() as any) : null,\n ]),\n )\n const lines: ResolvedCartLine[] = cart.lines.map((line) => {\n const product = productsById.get(line.productId)\n if (!product || !CommerceModel.productListedOnline(product)) {\n return {\n ...line,\n name: product?.name ?? 'Unavailable product',\n unitAmountCents: 0,\n unavailable: true,\n }\n }\n const variant = line.variantId\n ? product.variants.find((item) => item.id === line.variantId)\n : product.variants[0]\n // A variant with no price yet (AGL-2916) is not for sale, and never a\n // line worth nothing.\n if (!variant || !CommerceModel.variantHasPrice(variant)) {\n return {\n ...line,\n name: product.name,\n unitAmountCents: 0,\n unavailable: true,\n }\n }\n const variantLabel = Object.keys(variant.options ?? {}).length\n ? Object.values(variant.options ?? {}).join(' / ')\n : undefined\n // Add-ons priced from the product on every read (AGL-4100), on this\n // variant. Choices the product no longer offers, or a required one\n // now unanswered, make the line unavailable with what to do.\n const chosen = CommerceModel.resolveWebsiteLineModifiers(product, line.modifiers, variant.id)\n if (!chosen.ok) {\n return {\n ...line,\n name: product.name,\n ...(variantLabel ? { variantLabel } : {}),\n unitAmountCents: 0,\n unavailable: true,\n problem: CommerceModel.cartLineModifierProblem(chosen.error),\n }\n }\n const label = CommerceModel.lineLabelWithModifiers(variantLabel, chosen.modifiers)\n return {\n ...line,\n name: product.name,\n ...(label ? { variantLabel: label } : {}),\n unitAmountCents: Math.round(Number(variant.priceUsd) * 100) + chosen.extraCents,\n ...(variant.imageUrl || product.mediaUrls?.[0] || product.imageUrl\n ? {\n imageUrl:\n variant.imageUrl ??\n product.mediaUrls?.[0] ??\n product.imageUrl,\n }\n : {}),\n ...(CommerceModel.canPurchase(product, variant.id, line.quantity)\n ? {}\n : { unavailable: true }),\n }\n })\n const subtotalCents = lines\n .filter((line) => !line.unavailable)\n .reduce((sum, line) => sum + line.unitAmountCents * line.quantity, 0)\n // Card reader hardware the platform's own store sells (AGL-4038): the\n // cart asks for the terms of sale before checkout. Read from the\n // environment first, so no other store reads anything more.\n const sellerHostId = parsePosHardwareInPersonConfig(process.env)?.sellerHostId\n const hardwareTerms =\n sellerHostId === hostId &&\n cart.lines.some((line) => isPosHardwareSkuId(productsById.get(line.productId)?.hardwareSku))\n // Where it is going, asked WITH the cart rather than after the first\n // Checkout press: the same plan checkout makes, with no destination yet.\n const askShippingCountry = await shippingCountryNeeded({\n hostRef,\n lines,\n productsById,\n subtotalCents,\n })\n return res.status(200).json({\n lines,\n count: CommerceModel.cartCount(cart),\n subtotalCents,\n ...(hardwareTerms ? { hardwareTerms: true } : {}),\n ...(askShippingCountry\n ? {\n needsShippingCountry: true,\n shippingCountries: [...CommerceModel.CHECKOUT_SHIPPING_COUNTRIES],\n }\n : {}),\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Cart unavailable' })\n }\n}\n\n/**\n * Whether checkout will ask this cart where it is shipping to, answered while\n * the cart is shown so the cart can ask up front. A shopper who pressed\n * Checkout used to be refused with \"Choose where you’re shipping to.\" and only\n * then shown the field.\n *\n * The same plan `cart-checkout.ts` makes, with no destination, so the two\n * cannot disagree: rates that differ by zone, or carrier rates, need one. A\n * cart with nothing posted reads nothing more, and a store with one zone, a\n * rest-of-world zone or no shipping at all is never asked. Checkout still asks\n * and enforces the answer on its own; this only moves the question earlier.\n */\nasync function shippingCountryNeeded(input: {\n hostRef: FirebaseFirestore.DocumentReference\n lines: ResolvedCartLine[]\n productsById: Map<string, CommerceModel.HostProduct | null>\n subtotalCents: number\n}): Promise<boolean> {\n let physical = false\n let totalGrams = 0\n for (const line of input.lines) {\n if (line.unavailable) continue\n const product = input.productsById.get(line.productId)\n if (!product) continue\n // A missing `type` reads as physical, as checkout reads it.\n if ((product.type ?? 'physical') !== 'physical') continue\n physical = true\n const variant = line.variantId\n ? product.variants.find((item) => item.id === line.variantId)\n : product.variants[0]\n totalGrams += Math.max(0, Number(variant?.weightGrams ?? 0)) * line.quantity\n }\n if (!physical) return false\n try {\n const storeSettings = await input.hostRef.collection('settings').doc('store').get()\n const plan = await planCheckoutShippingWithCarriers({\n hostId: input.hostRef.id,\n settings: storeSettings.get('shipping') as CommerceModel.ShippingSettings | undefined,\n cart: { subtotalCents: input.subtotalCents, totalGrams },\n destination: {},\n })\n return plan.refusal === 'destination-required'\n } catch {\n // The cart still shows; checkout asks, as it always has.\n return false\n }\n}\n"],"names":["isPosHardwareSkuId","parsePosHardwareInPersonConfig","CommerceModel","firebaseAdmin","isDocumentId","cartCookieName","mintCartId","readCartId","readStoreDay","planCheckoutShippingWithCarriers","cartHandler","req","res","isPost","method","status","json","error","body","JSON","parse","hostId","String","query","cookieName","cartId","cookies","firestore","app","hostRef","collection","doc","cartSnapshot","lines","count","setHeader","cartRef","get","cart","data","action","useDayKey","trim","requestedModifiers","modifierSelectionFrom","modifiers","line","productId","variantId","length","quantity","Math","min","CART_MAX_QUANTITY","max","Number","isFinite","round","isCheckInDayKey","removeCartLine","productSnapshot","exists","productSellsOnline","isNewLine","some","held","cartLineKey","product","liftLegacyProduct","variants","id","productAsksUseDate","problem","checkInUseDayProblem","todayKey","chosen","resolveWebsiteLineModifiers","ok","selection","modifierSelectionOf","upsertCartLine","set","updatedAtMs","Date","now","createdAtMs","merge","uniqueProductIds","Set","map","l","productSnapshots","Promise","all","productsById","Map","snapshot","variant","productListedOnline","name","unitAmountCents","unavailable","find","item","variantHasPrice","variantLabel","Object","keys","options","values","join","undefined","cartLineModifierProblem","label","lineLabelWithModifiers","priceUsd","extraCents","imageUrl","mediaUrls","canPurchase","subtotalCents","filter","reduce","sum","sellerHostId","process","env","hardwareTerms","hardwareSku","askShippingCountry","shippingCountryNeeded","cartCount","needsShippingCountry","shippingCountries","CHECKOUT_SHIPPING_COUNTRIES","console","input","physical","totalGrams","type","weightGrams","storeSettings","plan","settings","destination","refusal"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,EAAEC,8BAA8B,QAAQ,2BAAuB;AAG1F,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,SAASC,cAAc,EAAEC,UAAU,EAAEC,UAAU,QAAQ,mBAAe;AACtE,SAASC,YAAY,QAAQ,iBAAa;AAC1C,SAASC,gCAAgC,QAAQ,wBAAoB;AAgBrE;;;;;;CAMC,GACD,OAAO,MAAMC,cAAgC,OAAOC,KAAKC;QAQhDD,WAYgBE;IAnBvB,MAAMA,SAASF,IAAIG,MAAM,KAAK;IAC9B,IAAI,CAACD,UAAUF,IAAIG,MAAM,KAAK,OAAO;QACnC,OAAOF,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,OAAOL,SACT,OAAOF,IAAIO,IAAI,KAAK,WAClBC,KAAKC,KAAK,CAACT,IAAIO,IAAI,IAAI,SACtBP,YAAAA,IAAIO,IAAI,YAARP,YAAY,CAAC,IAChB,CAAC;IACL,0EAA0E;IAC1E,0EAA0E;IAC1E,4EAA4E;IAC5E,yEAAyE;IACzE,0EAA0E;IAC1E,8DAA8D;IAC9D,EAAE;IACF,0EAA0E;IAC1E,6EAA6E;IAC7E,oDAAoD;IACpD,MAAMU,SAASC,QAAQT,OAAAA,SAASK,KAAKG,MAAM,GAAGV,IAAIY,KAAK,CAACF,MAAM,YAAvCR,OAA4C;IACnE,6EAA6E;IAC7E,8EAA8E;IAC9E,uEAAuE;IACvE,8EAA8E;IAC9E,4EAA4E;IAC5E,IAAI,CAACT,aAAaiB,SAChB,OAAOT,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;QAAEC,OAAO;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QmH,MAAM3G,OAAO,CAACyC,EAAE;YACxByE,UAAUF,cAAcxG,GAAG,CAAC;YAC5BC,MAAM;gBAAEkF,eAAegB,MAAMhB,aAAa;gBAAEkB;YAAW;YACvDM,aAAa,CAAC;QAChB;QACA,OAAOF,KAAKG,OAAO,KAAK;IAC1B,EAAE,eAAM;QACN,yDAAyD;QACzD,OAAO;IACT;AACF"}
|
|
@@ -28,6 +28,8 @@ export type PosOfflineCardSettled = {
|
|
|
28
28
|
/** The card tender's share of the plan's take. */
|
|
29
29
|
takeShareCents: number;
|
|
30
30
|
livemode: boolean;
|
|
31
|
+
/** The store's own account the intent was made and captured on (a direct charge); absent for a destination one. */
|
|
32
|
+
account?: string;
|
|
31
33
|
brand?: string;
|
|
32
34
|
last4?: string;
|
|
33
35
|
} | {
|
|
@@ -65,6 +65,10 @@ export function posOfflineCardOrderMoney(input) {
|
|
|
65
65
|
if (shortfallCents > 0) flags.push('card-fee-short');
|
|
66
66
|
const invoiceCents = feeOrgId ? shortfallCents : 0;
|
|
67
67
|
const feeCents = nettedCents + invoiceCents;
|
|
68
|
+
const direct = settled.account ? {
|
|
69
|
+
chargeModel: 'direct',
|
|
70
|
+
stripeAccountId: settled.account
|
|
71
|
+
} : {};
|
|
68
72
|
return {
|
|
69
73
|
status: 'paid',
|
|
70
74
|
totals: _extends({}, input.totals, {
|
|
@@ -80,10 +84,10 @@ export function posOfflineCardOrderMoney(input) {
|
|
|
80
84
|
takeFeeCents: whole(settled.takeShareCents),
|
|
81
85
|
feeCents: nettedCents,
|
|
82
86
|
livemode: settled.livemode
|
|
83
|
-
}, card, {
|
|
87
|
+
}, card, direct, {
|
|
84
88
|
cashierId
|
|
85
89
|
}),
|
|
86
|
-
fields: _extends({}, feeCents > 0 ? {
|
|
90
|
+
fields: _extends({}, direct, feeCents > 0 ? {
|
|
87
91
|
feeCollection: invoiceCents > 0 ? nettedCents > 0 ? 'split' : 'invoice' : 'payout'
|
|
88
92
|
} : {}, {
|
|
89
93
|
paymentIntentId: settled.intentId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-offline-card-order.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 type { OrderPayment, OrderTotals } from '../model'\nimport type { PosOfflineFlag } from '../model/commerce-pos-offline'\n\n/*==========================================\n * THE MONEY ON AN ORDER FOR A CARD TAKEN OFFLINE (AGL-4039).\n *\n * Pure: the offline sync settles the card with Stripe first, then hands the\n * result here and writes what comes back in the transaction that creates the\n * order. Kept out of `pos-offline-sync.ts` so the refund, dispute and\n * register-collection specs can build an order exactly as the sync writes it\n * without loading the sync's Firestore and Stripe dependencies.\n *\n * What a CAPTURED card writes, and why each field:\n *\n * - `paymentIntentId`, `paymentIntentIds` and `paidAtMs` at the ORDER level,\n * as the online register's completion writes them (`posCompletionPatch`).\n * The refund route and the dispute lookup read the order-level fields; an\n * intent kept only inside `payments[0]` leaves the order unrefundable and\n * its chargeback matched to no order.\n * - The payment's `amountCents` is what Stripe took (`intent.amount`), not\n * the server's restated total. Where they differ the order is flagged\n * `card-amount-differs` for the merchant to check against the receipt.\n * - `totals.feeCents` is the whole fee the sale settled: the card's\n * `application_fee_amount` (the take share plus Stripe's processing cost)\n * as the online completion counts it, plus any shortfall invoiced below.\n * - A FEE SHORTFALL: an intent the server first meets already `succeeded`\n * (captured on the device, with no application fee) netted less than the\n * tender rule's fee from the payout. The difference accrues to the org's\n * month ledger (`orgs/{id}/offlineFees`), the same ledger a room charge's\n * take accrues to, and the order is flagged `card-fee-short`.\n *\n * What an UNPAID card writes: `status: 'pending'` with the failed payment,\n * and the sale's plan take on `posTakeFeeCents` with the org it accrues to.\n * Collecting it later at the register reads that take, exactly as an open\n * sale does, so a later card, room charge or cash collection is charged by\n * the same tender rule as any other sale.\n *=========================================*/\n\nexport type PosOfflineCardSettled =\n | {\n kind: 'captured'\n intentId: string\n /** What Stripe charged, `intent.amount`. */\n amountCents: number\n /** What Stripe kept for the platform, `intent.application_fee_amount`. */\n feeCents: number\n /** What the tender rule says the platform's fee is on this charge. */\n expectedFeeCents: number\n /** The card tender's share of the plan's take. */\n takeShareCents: number\n livemode: boolean\n brand?: string\n last4?: string\n }\n | {\n kind: 'unpaid'\n flag: 'card-declined' | 'card-not-charged'\n intentId?: string\n message: string\n brand?: string\n last4?: string\n }\n\nexport interface PosOfflineCardOrderMoney {\n status: 'paid' | 'pending'\n /** The server's totals with the fee the sale settled. */\n totals: OrderTotals\n payment: OrderPayment\n /** Written at the order's top level beside the payment. */\n fields: Record<string, unknown>\n /** Cents to accrue to the org's month ledger with the order, 0 for none. */\n invoiceCents: number\n /** What the money adds to the sale's flags. */\n flags: PosOfflineFlag[]\n}\n\nconst whole = (value: unknown): number => {\n const number = Math.round(Number(value))\n return Number.isFinite(number) && number > 0 ? number : 0\n}\n\nexport function posOfflineCardOrderMoney(input: {\n settled: PosOfflineCardSettled\n /** The server's totals for the sale, restated where the register's did not add up. */\n totals: OrderTotals\n /** The plan's take on the goods, before the tender rule. */\n planTakeCents: number\n soldAtMs: number\n nowMs: number\n cashierId: string\n /** The org the fees accrue to; '' when the site has none, and nothing accrues. */\n feeOrgId: string\n}): PosOfflineCardOrderMoney {\n const { settled, soldAtMs, nowMs, cashierId, feeOrgId } = input\n const card = {\n ...(settled.intentId ? { paymentIntentId: settled.intentId } : {}),\n ...(settled.brand ? { cardBrand: settled.brand } : {}),\n ...(settled.last4 ? { last4: settled.last4 } : {}),\n }\n if (settled.kind === 'unpaid') {\n const planTakeCents = whole(input.planTakeCents)\n return {\n status: 'pending',\n totals: { ...input.totals, feeCents: 0 },\n payment: {\n id: 'pay_card_offline',\n method: 'card_present',\n amountCents: whole(input.totals.totalCents),\n status: 'failed',\n atMs: soldAtMs,\n takeFeeCents: 0,\n feeCents: 0,\n failureMessage: settled.message.slice(0, 300),\n ...card,\n cashierId,\n },\n fields: {\n posTakeFeeCents: planTakeCents,\n ...(feeOrgId ? { posFeeOrgId: feeOrgId } : {}),\n },\n invoiceCents: 0,\n flags: [settled.flag],\n }\n }\n const flags: PosOfflineFlag[] = []\n const amountCents = whole(settled.amountCents)\n if (amountCents !== whole(input.totals.totalCents)) flags.push('card-amount-differs')\n const nettedCents = whole(settled.feeCents)\n const shortfallCents = Math.max(0, whole(settled.expectedFeeCents) - nettedCents)\n if (shortfallCents > 0) flags.push('card-fee-short')\n const invoiceCents = feeOrgId ? shortfallCents : 0\n const feeCents = nettedCents + invoiceCents\n return {\n status: 'paid',\n totals: { ...input.totals, feeCents },\n payment: {\n id: 'pay_card_offline',\n method: 'card_present',\n amountCents,\n status: 'succeeded',\n atMs: soldAtMs,\n settledAtMs: nowMs,\n takeFeeCents: whole(settled.takeShareCents),\n feeCents: nettedCents,\n livemode: settled.livemode,\n ...card,\n cashierId,\n },\n fields: {\n ...(feeCents > 0\n ? { feeCollection: invoiceCents > 0 ? (nettedCents > 0 ? 'split' : 'invoice') : 'payout' }\n : {}),\n paymentIntentId: settled.intentId,\n paymentIntentIds: [settled.intentId],\n paidAtMs: soldAtMs,\n ...(settled.livemode === false ? { livemode: false } : {}),\n },\n invoiceCents,\n flags,\n }\n}\n"],"names":["whole","value","number","Math","round","Number","isFinite","posOfflineCardOrderMoney","input","settled","soldAtMs","nowMs","cashierId","feeOrgId","card","intentId","paymentIntentId","brand","cardBrand","last4","kind","planTakeCents","status","totals","feeCents","payment","id","method","amountCents","totalCents","atMs","takeFeeCents","failureMessage","message","slice","fields","posTakeFeeCents","posFeeOrgId","invoiceCents","flags","flag","push","nettedCents","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C,IAAIA,gBAAgB5B,MAAMQ,MAAMe,MAAM,CAACM,UAAU,GAAGU,MAAME,IAAI,CAAC;IAC/D,MAAMC,cAAc1C,MAAMS,QAAQe,QAAQ;IAC1C,MAAMmB,iBAAiBxC,KAAKyC,GAAG,CAAC,GAAG5C,MAAMS,QAAQoC,gBAAgB,IAAIH;IACrE,IAAIC,iBAAiB,GAAGJ,MAAME,IAAI,CAAC;IACnC,MAAMH,eAAezB,WAAW8B,iBAAiB;IACjD,MAAMnB,WAAWkB,cAAcJ;IAC/B,OAAO;QACLhB,QAAQ;QACRC,QAAQ,aAAKf,MAAMe,MAAM;YAAEC;;QAC3BC,SAAS;YACPC,IAAI;YACJC,QAAQ;YACRC;YACAN,QAAQ;YACRQ,MAAMpB;YACNoC,aAAanC;YACboB,cAAc/B,MAAMS,QAAQsC,cAAc;YAC1CvB,UAAUkB;YACVM,UAAUvC,QAAQuC,QAAQ;WACvBlC;YACHF;;QAEFuB,QAAQ,aACFX,WAAW,IACX;YAAEyB,eAAeX,eAAe,IAAKI,cAAc,IAAI,UAAU,YAAa;QAAS,IACvF,CAAC;YACL1B,iBAAiBP,QAAQM,QAAQ;YACjCmC,kBAAkB;gBAACzC,QAAQM,QAAQ;aAAC;YACpCoC,UAAUzC;WACND,QAAQuC,QAAQ,KAAK,QAAQ;YAAEA,UAAU;QAAM,IAAI,CAAC;QAE1DV;QACAC;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-offline-card-order.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 type { OrderPayment, OrderTotals } from '../model'\nimport type { PosOfflineFlag } from '../model/commerce-pos-offline'\n\n/*==========================================\n * THE MONEY ON AN ORDER FOR A CARD TAKEN OFFLINE (AGL-4039).\n *\n * Pure: the offline sync settles the card with Stripe first, then hands the\n * result here and writes what comes back in the transaction that creates the\n * order. Kept out of `pos-offline-sync.ts` so the refund, dispute and\n * register-collection specs can build an order exactly as the sync writes it\n * without loading the sync's Firestore and Stripe dependencies.\n *\n * What a CAPTURED card writes, and why each field:\n *\n * - `paymentIntentId`, `paymentIntentIds` and `paidAtMs` at the ORDER level,\n * as the online register's completion writes them (`posCompletionPatch`).\n * The refund route and the dispute lookup read the order-level fields; an\n * intent kept only inside `payments[0]` leaves the order unrefundable and\n * its chargeback matched to no order.\n * - The payment's `amountCents` is what Stripe took (`intent.amount`), not\n * the server's restated total. Where they differ the order is flagged\n * `card-amount-differs` for the merchant to check against the receipt.\n * - `totals.feeCents` is the whole fee the sale settled: the card's\n * `application_fee_amount` (the take share plus Stripe's processing cost)\n * as the online completion counts it, plus any shortfall invoiced below.\n * - A FEE SHORTFALL: an intent the server first meets already `succeeded`\n * (captured on the device, with no application fee) netted less than the\n * tender rule's fee from the payout. The difference accrues to the org's\n * month ledger (`orgs/{id}/offlineFees`), the same ledger a room charge's\n * take accrues to, and the order is flagged `card-fee-short`.\n * - A card made on the store's OWN Stripe account (a direct charge,\n * AGL-4219) says so on the payment and the order (`chargeModel: direct`,\n * `stripeAccountId`), as an online direct sale does, so its refund, its\n * return at the register and its chargeback are made on that account.\n *\n * What an UNPAID card writes: `status: 'pending'` with the failed payment,\n * and the sale's plan take on `posTakeFeeCents` with the org it accrues to.\n * Collecting it later at the register reads that take, exactly as an open\n * sale does, so a later card, room charge or cash collection is charged by\n * the same tender rule as any other sale.\n *=========================================*/\n\nexport type PosOfflineCardSettled =\n | {\n kind: 'captured'\n intentId: string\n /** What Stripe charged, `intent.amount`. */\n amountCents: number\n /** What Stripe kept for the platform, `intent.application_fee_amount`. */\n feeCents: number\n /** What the tender rule says the platform's fee is on this charge. */\n expectedFeeCents: number\n /** The card tender's share of the plan's take. */\n takeShareCents: number\n livemode: boolean\n /** The store's own account the intent was made and captured on (a direct charge); absent for a destination one. */\n account?: string\n brand?: string\n last4?: string\n }\n | {\n kind: 'unpaid'\n flag: 'card-declined' | 'card-not-charged'\n intentId?: string\n message: string\n brand?: string\n last4?: string\n }\n\nexport interface PosOfflineCardOrderMoney {\n status: 'paid' | 'pending'\n /** The server's totals with the fee the sale settled. */\n totals: OrderTotals\n payment: OrderPayment\n /** Written at the order's top level beside the payment. */\n fields: Record<string, unknown>\n /** Cents to accrue to the org's month ledger with the order, 0 for none. */\n invoiceCents: number\n /** What the money adds to the sale's flags. */\n flags: PosOfflineFlag[]\n}\n\nconst whole = (value: unknown): number => {\n const number = Math.round(Number(value))\n return Number.isFinite(number) && number > 0 ? number : 0\n}\n\nexport function posOfflineCardOrderMoney(input: {\n settled: PosOfflineCardSettled\n /** The server's totals for the sale, restated where the register's did not add up. */\n totals: OrderTotals\n /** The plan's take on the goods, before the tender rule. */\n planTakeCents: number\n soldAtMs: number\n nowMs: number\n cashierId: string\n /** The org the fees accrue to; '' when the site has none, and nothing accrues. */\n feeOrgId: string\n}): PosOfflineCardOrderMoney {\n const { settled, soldAtMs, nowMs, cashierId, feeOrgId } = input\n const card = {\n ...(settled.intentId ? { paymentIntentId: settled.intentId } : {}),\n ...(settled.brand ? { cardBrand: settled.brand } : {}),\n ...(settled.last4 ? { last4: settled.last4 } : {}),\n }\n if (settled.kind === 'unpaid') {\n const planTakeCents = whole(input.planTakeCents)\n return {\n status: 'pending',\n totals: { ...input.totals, feeCents: 0 },\n payment: {\n id: 'pay_card_offline',\n method: 'card_present',\n amountCents: whole(input.totals.totalCents),\n status: 'failed',\n atMs: soldAtMs,\n takeFeeCents: 0,\n feeCents: 0,\n failureMessage: settled.message.slice(0, 300),\n ...card,\n cashierId,\n },\n fields: {\n posTakeFeeCents: planTakeCents,\n ...(feeOrgId ? { posFeeOrgId: feeOrgId } : {}),\n },\n invoiceCents: 0,\n flags: [settled.flag],\n }\n }\n const flags: PosOfflineFlag[] = []\n const amountCents = whole(settled.amountCents)\n if (amountCents !== whole(input.totals.totalCents)) flags.push('card-amount-differs')\n const nettedCents = whole(settled.feeCents)\n const shortfallCents = Math.max(0, whole(settled.expectedFeeCents) - nettedCents)\n if (shortfallCents > 0) flags.push('card-fee-short')\n const invoiceCents = feeOrgId ? shortfallCents : 0\n const feeCents = nettedCents + invoiceCents\n const direct = settled.account ? { chargeModel: 'direct' as const, stripeAccountId: settled.account } : {}\n return {\n status: 'paid',\n totals: { ...input.totals, feeCents },\n payment: {\n id: 'pay_card_offline',\n method: 'card_present',\n amountCents,\n status: 'succeeded',\n atMs: soldAtMs,\n settledAtMs: nowMs,\n takeFeeCents: whole(settled.takeShareCents),\n feeCents: nettedCents,\n livemode: settled.livemode,\n ...card,\n ...direct,\n cashierId,\n },\n fields: {\n ...direct,\n ...(feeCents > 0\n ? { feeCollection: invoiceCents > 0 ? (nettedCents > 0 ? 'split' : 'invoice') : 'payout' }\n : {}),\n paymentIntentId: settled.intentId,\n paymentIntentIds: [settled.intentId],\n paidAtMs: soldAtMs,\n ...(settled.livemode === false ? { livemode: false } : {}),\n },\n invoiceCents,\n flags,\n }\n}\n"],"names":["whole","value","number","Math","round","Number","isFinite","posOfflineCardOrderMoney","input","settled","soldAtMs","nowMs","cashierId","feeOrgId","card","intentId","paymentIntentId","brand","cardBrand","last4","kind","planTakeCents","status","totals","feeCents","payment","id","method","amountCents","totalCents","atMs","takeFeeCents","failureMessage","message","slice","fields","posTakeFeeCents","posFeeOrgId","invoiceCents","flags","flag","push","nettedCents","shortfallCents","max","expectedFeeCents","direct","account","chargeModel","stripeAccountId","settledAtMs","takeShareCents","livemode","feeCollection","paymentIntentIds","paidAtMs"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAoFD,MAAMA,QAAQ,CAACC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