@aglyn/plugins-commerce 1.21.0 → 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/console/catalog-organization-card.component.js +28 -9
- package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
- package/src/lib/components/console/discounts-card.component.js +13 -4
- package/src/lib/components/console/discounts-card.component.js.map +1 -1
- package/src/lib/components/console/local-delivery-settings-card.component.js +13 -4
- package/src/lib/components/console/local-delivery-settings-card.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +13 -4
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/products-hub-card.component.js +13 -4
- package/src/lib/components/console/products-hub-card.component.js.map +1 -1
- package/src/lib/components/console/quote-settings-card.component.js +13 -4
- package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
- package/src/lib/components/console/reservations-card.component.js +13 -4
- package/src/lib/components/console/reservations-card.component.js.map +1 -1
- package/src/lib/components/console/return-settings-card.component.js +13 -4
- package/src/lib/components/console/return-settings-card.component.js.map +1 -1
- package/src/lib/components/console/shipping-settings-card.component.js +13 -4
- package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
- package/src/lib/components/console/store-settings-card.component.js +13 -4
- package/src/lib/components/console/store-settings-card.component.js.map +1 -1
- package/src/lib/components/console/suppliers-card.component.js +13 -4
- package/src/lib/components/console/suppliers-card.component.js.map +1 -1
- package/src/lib/components/console/tax-settings-card.component.js +13 -4
- 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/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 +39 -5
- package/src/lib/server/pos-terminal.js.map +1 -1
|
@@ -16,6 +16,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
16
16
|
* limitations under the License.
|
|
17
17
|
*/ import { formatOperatorAlertAmount } from "@aglyn/aglyn/app-utils/operator-alerts";
|
|
18
18
|
import { firebaseAdmin, hostDisplayName, notifyHostManagers, raiseOperatorAlert } from "@aglyn/tenant-data-admin";
|
|
19
|
+
import { sellerPaymentAccount } from "@aglyn/tenant-data-admin/server/seller-payment-account";
|
|
19
20
|
import { FieldValue } from "firebase-admin/firestore";
|
|
20
21
|
import { COMMERCE_POS_OFFLINE_CARD_UNSYNCED, COMMERCE_POS_OFFLINE_CARD_WRONG_ACCOUNT } from "../constants/operator-alerts.js";
|
|
21
22
|
import { POS_OFFLINE_CARD_INTENT_KIND, posOfflineSaleKeyIsValid } from "../model/commerce-pos-offline.js";
|
|
@@ -51,6 +52,14 @@ import { POS_OFFLINE_CARD_INTENT_KIND, posOfflineSaleKeyIsValid } from "../model
|
|
|
51
52
|
* commerce handlers, rather than as a branch of the storefront sections. The
|
|
52
53
|
* four `payment_intent.*` events it reads are in the platform destination's
|
|
53
54
|
* `WEBHOOK_EVENTS` (`tools/scripts/lib/stripe-webhook-health.mjs`).
|
|
55
|
+
*
|
|
56
|
+
* A STORE ON ITS OWN STRIPE ACCOUNT (AGL-4219). Its app makes the intent on
|
|
57
|
+
* that account, so the events come through the Connect destination, naming
|
|
58
|
+
* the account. Metadata is only a claim, and the account's owner can write
|
|
59
|
+
* any: a Connect-delivered event is kept only when it says it is a direct
|
|
60
|
+
* sale's and the account is the one the site sells on now. Those four events
|
|
61
|
+
* reach the Connect destination only once it subscribes to them; the sync
|
|
62
|
+
* never depends on this record, because it reads Stripe.
|
|
54
63
|
*=========================================*/ /** The subcollection, under `hosts/{hostId}/terminal/config`, and its collection-group name. */ export const POS_OFFLINE_CARD_CHARGES = 'offlineCardCharges';
|
|
55
64
|
/**
|
|
56
65
|
* How long an intent that holds money may wait for its sale before the sweep
|
|
@@ -115,16 +124,39 @@ export async function reconcilePosOfflineCardEvent(input, firestore, now = Date.
|
|
|
115
124
|
hostId
|
|
116
125
|
};
|
|
117
126
|
}
|
|
118
|
-
/** The
|
|
119
|
-
const
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
127
|
+
/** The connected account a Connect-delivered event names; null for the platform's own. */ function eventAccount(event) {
|
|
128
|
+
const account = event == null ? void 0 : event.account;
|
|
129
|
+
return typeof account === 'string' && account ? account : null;
|
|
130
|
+
}
|
|
131
|
+
/** The account a site's direct sales are made on now; null for a store selling through the platform. */ async function directAccountOf(hostId) {
|
|
132
|
+
const seller = await sellerPaymentAccount(hostId);
|
|
133
|
+
return (seller == null ? void 0 : seller.chargeModel) === 'direct' ? seller.accountId : null;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* The platform webhook's handler for offline card intents: claims only its
|
|
137
|
+
* own. A Connect-delivered event counts only for the site's own account.
|
|
138
|
+
*/ export function createPosOfflineCardBillingWebhookHandler(directAccount = directAccountOf) {
|
|
139
|
+
return async ({ type, object, event })=>{
|
|
140
|
+
const account = eventAccount(event);
|
|
141
|
+
if (account) {
|
|
142
|
+
var _ref, _metadata_hostId;
|
|
143
|
+
if (!type.startsWith('payment_intent.')) return undefined;
|
|
144
|
+
const metadata = (_ref = object == null ? void 0 : object.metadata) != null ? _ref : {};
|
|
145
|
+
if (metadata['kind'] !== POS_OFFLINE_CARD_INTENT_KIND || metadata['chargeModel'] !== 'direct') return undefined;
|
|
146
|
+
const hostId = String((_metadata_hostId = metadata['hostId']) != null ? _metadata_hostId : '');
|
|
147
|
+
if (!validHostId(hostId) || await directAccount(hostId) !== account) return undefined;
|
|
148
|
+
}
|
|
149
|
+
const reconciled = await reconcilePosOfflineCardEvent({
|
|
150
|
+
type,
|
|
151
|
+
object
|
|
152
|
+
});
|
|
153
|
+
return reconciled ? {
|
|
154
|
+
claimed: true,
|
|
155
|
+
hostId: reconciled.hostId
|
|
156
|
+
} : undefined;
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
export const posOfflineCardBillingWebhookHandler = createPosOfflineCardBillingWebhookHandler();
|
|
128
160
|
const describeWait = (ms)=>{
|
|
129
161
|
const hours = Math.max(1, Math.round(ms / (60 * 60 * 1000)));
|
|
130
162
|
return hours >= 48 ? `${Math.round(hours / 24)} days` : `${hours} hour${hours === 1 ? '' : 's'}`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-offline-card-reconcile.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 { formatOperatorAlertAmount } from '@aglyn/aglyn/app-utils/operator-alerts'\nimport type { BillingWebhookHandler, PluginJobHostGate } from '@aglyn/aglyn/server'\nimport {\n firebaseAdmin,\n hostDisplayName,\n notifyHostManagers,\n raiseOperatorAlert,\n} from '@aglyn/tenant-data-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n COMMERCE_POS_OFFLINE_CARD_UNSYNCED,\n COMMERCE_POS_OFFLINE_CARD_WRONG_ACCOUNT,\n} from '../constants/operator-alerts'\nimport {\n POS_OFFLINE_CARD_INTENT_KIND,\n posOfflineSaleKeyIsValid,\n} from '../model/commerce-pos-offline'\n\n/*==========================================\n * A CARD TAKEN OFFLINE, AS STRIPE REPORTS IT (AGL-4039).\n *\n * The Aglyn POS app creates the PaymentIntent of a card it takes offline, so\n * Stripe can know of a charge before the sale itself reaches the server: the\n * SDK forwards the card the moment a connection returns, and the sale syncs\n * right after, from the same device. Usually seconds apart. If the sale never\n * arrives (the device was lost or wiped between the two, or it waits for a\n * member who never signs in again), the charge must not be invisible: each\n * event on such an intent is kept on the site, by the sale's key, under the\n * site's server-only Terminal document\n * (`terminal/config/offlineCardCharges/{saleKey}`), beside whether the sale\n * has synced. The sync itself never depends on this: it reads Stripe.\n *\n * WHO SAYS \"SYNCED\". Both writers, in transactions, so neither can undo the\n * other: the sync marks the record when it creates the order, and an event\n * reads the record and the sync record together. An event that arrives after\n * the sync therefore keeps `synced`, and one that raced it retries and sees\n * it.\n *\n * NOBODY LOOKING. An intent that holds or has taken money while its sale has\n * not synced gets `alertDueAtMs`, {@link POS_OFFLINE_CARD_UNSYNCED_ALERT_MS}\n * after it was first seen. The hourly sweep ({@link scanUnsyncedOfflineCards})\n * tells the operator and the site's managers once, with time left to sync the\n * sale before Stripe's authorization lapses (about two days). It never\n * captures: without the sale there is no fee to capture with.\n *\n * Self-selecting: every other event returns `null` untouched. Registered on\n * the platform webhook from the commerce server module, beside the other\n * commerce handlers, rather than as a branch of the storefront sections. The\n * four `payment_intent.*` events it reads are in the platform destination's\n * `WEBHOOK_EVENTS` (`tools/scripts/lib/stripe-webhook-health.mjs`).\n *=========================================*/\n\n/** The subcollection, under `hosts/{hostId}/terminal/config`, and its collection-group name. */\nexport const POS_OFFLINE_CARD_CHARGES = 'offlineCardCharges'\n\n/**\n * How long an intent that holds money may wait for its sale before the sweep\n * says so: six hours, which leaves well over a day of Stripe's two-day\n * authorization to sync it, and is far past the seconds a healthy sync takes.\n */\nexport const POS_OFFLINE_CARD_UNSYNCED_ALERT_MS = 6 * 60 * 60 * 1000\n\n/** Statuses in which an intent holds money or has taken it. */\nconst HOLDS_MONEY: ReadonlySet<string> = new Set(['requires_capture', 'processing', 'succeeded'])\n\n/** Statuses an intent never leaves; an older event must not turn one back. */\nconst FINAL: ReadonlySet<string> = new Set(['succeeded', 'canceled'])\n\n/** What the site keeps about one offline card's PaymentIntent. */\nexport interface PosOfflineCardChargeRecord {\n hostId: string\n saleKey: string\n paymentIntentId: string\n status: string\n amountCents: number\n registerId: string\n livemode: boolean\n /** Whether the sale has synced (its order exists). */\n synced: boolean\n orderId?: string\n syncedAtMs?: number\n lastEvent: string\n updatedAtMs: number\n /** When the sweep says the sale never synced; absent once synced or told. */\n alertDueAtMs?: number\n alertedAtMs?: number\n /** The capture's idempotency attempt, raised only after a definite failure. */\n captureAttempt?: number\n}\n\n/** `hosts/{hostId}/terminal/config/offlineCardCharges/{saleKey}`. */\nexport function posOfflineCardChargeRef(\n hostRef: FirebaseFirestore.DocumentReference,\n saleKey: string,\n): FirebaseFirestore.DocumentReference {\n return hostRef.collection('terminal').doc('config').collection(POS_OFFLINE_CARD_CHARGES).doc(saleKey)\n}\n\nconst validHostId = (hostId: string) => /^[A-Za-z0-9_-]{1,128}$/.test(hostId)\n\nexport async function reconcilePosOfflineCardEvent(\n input: { type: string; object: any },\n firestore?: FirebaseFirestore.Firestore,\n now: () => number = Date.now,\n): Promise<{ hostId: string } | null> {\n if (!input.type.startsWith('payment_intent.')) return null\n const intent = input.object ?? {}\n const metadata = (intent.metadata ?? {}) as Record<string, string>\n if (metadata['kind'] !== POS_OFFLINE_CARD_INTENT_KIND) return null\n const hostId = String(metadata['hostId'] ?? '')\n const saleKey = String(metadata['saleKey'] ?? '')\n if (!validHostId(hostId) || !posOfflineSaleKeyIsValid(saleKey)) return null\n const db = firestore ?? firebaseAdmin.app().firestore()\n const hostRef = db.collection('hosts').doc(hostId)\n const chargeRef = posOfflineCardChargeRef(hostRef, saleKey)\n const saleRef = hostRef.collection('posOfflineSales').doc(saleKey)\n await db.runTransaction(async (transaction) => {\n const charge = await transaction.get(chargeRef)\n const sale = await transaction.get(saleRef)\n const previous = (charge.exists ? charge.data() : {}) as Partial<PosOfflineCardChargeRecord>\n const synced = previous.synced === true || sale.exists\n const incoming = String(intent.status ?? '')\n // Stripe does not promise event order: a late `amount_capturable_updated`\n // must not turn a captured or canceled intent back into an authorized one.\n const status =\n previous.status && FINAL.has(previous.status) && !FINAL.has(incoming) ? previous.status : incoming\n const at = now()\n const alertDueAtMs =\n !synced && HOLDS_MONEY.has(status) && !previous.alertedAtMs\n ? typeof previous.alertDueAtMs === 'number'\n ? previous.alertDueAtMs\n : at + POS_OFFLINE_CARD_UNSYNCED_ALERT_MS\n : null\n transaction.set(\n chargeRef,\n {\n hostId,\n saleKey,\n paymentIntentId: String(intent.id ?? ''),\n status,\n amountCents: Math.max(0, Math.round(Number(intent.amount ?? 0))),\n registerId: String(metadata['registerId'] ?? '').slice(0, 128),\n livemode: Boolean(intent.livemode),\n synced,\n lastEvent: input.type,\n updatedAtMs: at,\n alertDueAtMs: alertDueAtMs ?? FieldValue.delete(),\n },\n { merge: true },\n )\n })\n return { hostId }\n}\n\n/** The platform webhook's handler for offline card intents: claims only its own. */\nexport const posOfflineCardBillingWebhookHandler: BillingWebhookHandler =\n async ({ type, object }) => {\n const reconciled = await reconcilePosOfflineCardEvent({ type, object })\n return reconciled ? { claimed: true, hostId: reconciled.hostId } : undefined\n }\n\n/*==========================================\n * THE SWEEP: AN OFFLINE CARD WHOSE SALE NEVER SYNCED.\n *=========================================*/\n\nexport interface UnsyncedOfflineCardReport {\n hostId: string\n saleKey: string\n paymentIntentId: string\n status: string\n amountCents: number\n registerId: string\n /** How long ago the intent was first seen waiting, in ms. */\n waitedMs: number\n}\n\nexport interface UnsyncedOfflineCardScan {\n due: number\n alerted: number\n /** Synced, or no longer holding money, since the alert was set. */\n cleared: number\n skippedLocked: number\n}\n\nconst describeWait = (ms: number) => {\n const hours = Math.max(1, Math.round(ms / (60 * 60 * 1000)))\n return hours >= 48 ? `${Math.round(hours / 24)} days` : `${hours} hour${hours === 1 ? '' : 's'}`\n}\n\n/** Tells the operator and the site's managers about one card. Never throws. */\nexport async function reportUnsyncedOfflineCard(report: UnsyncedOfflineCardReport): Promise<void> {\n try {\n const host = await firebaseAdmin.app().firestore().collection('hosts').doc(report.hostId).get().catch(() => null)\n const site = host?.exists ? hostDisplayName(host.data() as Record<string, unknown>, report.hostId) : report.hostId\n const amount = formatOperatorAlertAmount(report.amountCents)\n await raiseOperatorAlert(COMMERCE_POS_OFFLINE_CARD_UNSYNCED, {\n dedupeKey: `${report.hostId}:${report.saleKey}`,\n hostId: report.hostId,\n context: {\n amount,\n paymentIntentId: report.paymentIntentId,\n status: report.status,\n site: `${site} (${report.hostId})`,\n registerId: report.registerId || 'unknown',\n age: describeWait(report.waitedMs),\n },\n })\n await notifyHostManagers(report.hostId, {\n type: 'content.order',\n title: `A ${amount} card taken offline on {site} has no sale`,\n body:\n report.status === 'succeeded'\n ? `A ${amount} card taken offline was charged, but the register never sent its sale, so there is no order for it. ` +\n 'Open the register that took it, signed in as the member who rang it, so the sale syncs.'\n : `A ${amount} card taken offline is approved but not yet charged, because the register never sent its sale. ` +\n 'Open the register that took it, signed in as the member who rang it, so the sale syncs. ' +\n 'If it does not sync within about two days of the sale, the card is never charged.',\n link: `/${report.hostId}/products`,\n })\n } catch (error) {\n console.error('[pos-offline-card] unsynced report failed', report.hostId, report.saleKey, error)\n }\n}\n\n/** Tells the operator a card was made out to an account that is not the store's. Never throws. */\nexport async function reportPosOfflineCardWrongAccount(input: {\n hostId: string\n orderId: string\n paymentIntentId: string\n status: string\n amountCents: number\n destination: string\n expected: string\n}): Promise<void> {\n try {\n const host = await firebaseAdmin.app().firestore().collection('hosts').doc(input.hostId).get().catch(() => null)\n const site = host?.exists ? hostDisplayName(host.data() as Record<string, unknown>, input.hostId) : input.hostId\n await raiseOperatorAlert(COMMERCE_POS_OFFLINE_CARD_WRONG_ACCOUNT, {\n dedupeKey: `${input.hostId}:${input.orderId}`,\n hostId: input.hostId,\n context: {\n amount: formatOperatorAlertAmount(input.amountCents),\n paymentIntentId: input.paymentIntentId,\n status: input.status,\n orderId: input.orderId,\n site: `${site} (${input.hostId})`,\n destination: input.destination || 'none',\n expected: input.expected,\n },\n })\n } catch (error) {\n console.error('[pos-offline-card] wrong-account alert failed', input.hostId, input.orderId, error)\n }\n}\n\n/**\n * The hourly sweep (registered in `server.ts`): every offline card record\n * whose alert is due. Re-checks the sale first, so a sale that synced while\n * the event was in flight clears the record and tells nobody.\n *\n * One collection-group range query on `alertDueAtMs`, which is set only on a\n * record that holds money and has not synced, so the ordinary beat reads an\n * empty result. Its COLLECTION_GROUP index is declared in\n * `cloud/firebase-firestore.indexes.json` and pinned by\n * `cron-scan-indexes.spec.ts`.\n */\nexport async function scanUnsyncedOfflineCards(\n /** The lockdown gate, injected by the runner (AGL-2495). */\n gate: PluginJobHostGate,\n options: {\n firestore?: FirebaseFirestore.Firestore\n nowMs?: number\n limit?: number\n report?: (report: UnsyncedOfflineCardReport) => Promise<void>\n } = {},\n): Promise<UnsyncedOfflineCardScan> {\n const db = options.firestore ?? firebaseAdmin.app().firestore()\n const nowMs = options.nowMs ?? Date.now()\n const report = options.report ?? reportUnsyncedOfflineCard\n const scan: UnsyncedOfflineCardScan = { due: 0, alerted: 0, cleared: 0, skippedLocked: 0 }\n const due = await db\n .collectionGroup(POS_OFFLINE_CARD_CHARGES)\n .where('alertDueAtMs', '<=', nowMs)\n .orderBy('alertDueAtMs', 'asc')\n .limit(options.limit ?? 100)\n .get()\n .catch((error: unknown) => {\n console.error('[pos-offline-card] unsynced scan failed', error)\n return null\n })\n if (!due) return scan\n for (const doc of due.docs) {\n const record = (doc.data() ?? {}) as Partial<PosOfflineCardChargeRecord>\n if (typeof record.alertDueAtMs !== 'number') continue\n // `hosts/{hostId}/terminal/config/offlineCardCharges/{saleKey}`.\n const hostId = String(record.hostId || doc.ref.parent.parent?.parent?.parent?.id || '')\n const saleKey = String(record.saleKey || doc.id)\n if (!validHostId(hostId) || !posOfflineSaleKeyIsValid(saleKey)) continue\n scan.due += 1\n // A locked site is skipped, not dropped: its record stays due and is\n // told on the first beat after the lift.\n if (await gate.isLocked(hostId)) {\n scan.skippedLocked += 1\n continue\n }\n const hostRef = db.collection('hosts').doc(hostId)\n const synced = (await hostRef.collection('posOfflineSales').doc(saleKey).get()).exists\n if (synced || !HOLDS_MONEY.has(String(record.status ?? ''))) {\n await doc.ref.set(\n { ...(synced ? { synced: true } : {}), alertDueAtMs: FieldValue.delete() },\n { merge: true },\n )\n scan.cleared += 1\n continue\n }\n await report({\n hostId,\n saleKey,\n paymentIntentId: String(record.paymentIntentId ?? ''),\n status: String(record.status ?? ''),\n amountCents: Math.max(0, Math.round(Number(record.amountCents ?? 0))),\n registerId: String(record.registerId ?? ''),\n waitedMs: Math.max(0, nowMs - (record.alertDueAtMs - POS_OFFLINE_CARD_UNSYNCED_ALERT_MS)),\n })\n await doc.ref.set({ alertedAtMs: nowMs, alertDueAtMs: FieldValue.delete() }, { merge: true })\n scan.alerted += 1\n }\n return scan\n}\n"],"names":["formatOperatorAlertAmount","firebaseAdmin","hostDisplayName","notifyHostManagers","raiseOperatorAlert","FieldValue","COMMERCE_POS_OFFLINE_CARD_UNSYNCED","COMMERCE_POS_OFFLINE_CARD_WRONG_ACCOUNT","POS_OFFLINE_CARD_INTENT_KIND","posOfflineSaleKeyIsValid","POS_OFFLINE_CARD_CHARGES","POS_OFFLINE_CARD_UNSYNCED_ALERT_MS","HOLDS_MONEY","Set","FINAL","posOfflineCardChargeRef","hostRef","saleKey","collection","doc","validHostId","hostId","test","reconcilePosOfflineCardEvent","input","firestore","now","Date","intent","metadata","type","startsWith","object","String","db","app","chargeRef","saleRef","runTransaction","transaction","charge","get","sale","previous","exists","data","synced","incoming","status","has","at","alertDueAtMs","alertedAtMs","set","paymentIntentId","id","amountCents","Math","max","round","Number","amount","registerId","slice","livemode","Boolean","lastEvent","updatedAtMs","delete","merge","posOfflineCardBillingWebhookHandler","reconciled","claimed","undefined","describeWait","ms","hours","reportUnsyncedOfflineCard","report","host","catch","site","dedupeKey","context","age","waitedMs","title","body","link","error","console","reportPosOfflineCardWrongAccount","orderId","destination","expected","scanUnsyncedOfflineCards","gate","options","nowMs","scan","due","alerted","cleared","skippedLocked","collectionGroup","where","orderBy","limit","docs","record","ref","parent","isLocked"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,yBAAyB,QAAQ,yCAAwC;AAElF,SACEC,aAAa,EACbC,eAAe,EACfC,kBAAkB,EAClBC,kBAAkB,QACb,2BAA0B;AACjC,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SACEC,kCAAkC,EAClCC,uCAAuC,QAClC,kCAA8B;AACrC,SACEC,4BAA4B,EAC5BC,wBAAwB,QACnB,mCAA+B;AAEtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAgC2C,GAE3C,8FAA8F,GAC9F,OAAO,MAAMC,2BAA2B,qBAAoB;AAE5D;;;;CAIC,GACD,OAAO,MAAMC,qCAAqC,IAAI,KAAK,KAAK,KAAI;AAEpE,6DAA6D,GAC7D,MAAMC,cAAmC,IAAIC,IAAI;IAAC;IAAoB;IAAc;CAAY;AAEhG,4EAA4E,GAC5E,MAAMC,QAA6B,IAAID,IAAI;IAAC;IAAa;CAAW;AAwBpE,mEAAmE,GACnE,OAAO,SAASE,wBACdC,OAA4C,EAC5CC,OAAe;IAEf,OAAOD,QAAQE,UAAU,CAAC,YAAYC,GAAG,CAAC,UAAUD,UAAU,CAACR,0BAA0BS,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AC/B8E,KAAKI,aAAa,IAAI;YACtB;QACF;QACA,MAAMvF,UAAUkB,GAAGhB,UAAU,CAAC,SAASC,GAAG,CAACE;QAC3C,MAAMyB,SAAS,AAAC,CAAA,MAAM9B,QAAQE,UAAU,CAAC,mBAAmBC,GAAG,CAACF,SAASwB,GAAG,EAAC,EAAGG,MAAM;QACtF,IAAIE,UAAU,CAAClC,YAAYqC,GAAG,CAAChB,QAAO4E,iBAAAA,OAAO7D,MAAM,YAAb6D,iBAAiB,MAAM;YAC3D,MAAM1F,IAAI2F,GAAG,CAACzD,GAAG,CACf,aAAMP,SAAS;gBAAEA,QAAQ;YAAK,IAAI,CAAC;gBAAIK,cAAc9C,WAAW+D,MAAM;gBACtE;gBAAEC,OAAO;YAAK;YAEhB8B,KAAKG,OAAO,IAAI;YAChB;QACF;QACA,MAAMxB,OAAO;YACXzD;YACAJ;YACAqC,iBAAiBrB,QAAO4E,0BAAAA,OAAOvD,eAAe,YAAtBuD,0BAA0B;YAClD7D,QAAQf,QAAO4E,kBAAAA,OAAO7D,MAAM,YAAb6D,kBAAiB;YAChCrD,aAAaC,KAAKC,GAAG,CAAC,GAAGD,KAAKE,KAAK,CAACC,QAAOiD,sBAAAA,OAAOrD,WAAW,YAAlBqD,sBAAsB;YACjE/C,YAAY7B,QAAO4E,qBAAAA,OAAO/C,UAAU,YAAjB+C,qBAAqB;YACxCxB,UAAU5B,KAAKC,GAAG,CAAC,GAAGwC,QAASW,CAAAA,OAAO1D,YAAY,GAAGxC,kCAAiC;QACxF;QACA,MAAMQ,IAAI2F,GAAG,CAACzD,GAAG,CAAC;YAAED,aAAa8C;YAAO/C,cAAc9C,WAAW+D,MAAM;QAAG,GAAG;YAAEC,OAAO;QAAK;QAC3F8B,KAAKE,OAAO,IAAI;IAClB;IACA,OAAOF;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-offline-card-reconcile.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 { formatOperatorAlertAmount } from '@aglyn/aglyn/app-utils/operator-alerts'\nimport type { BillingWebhookHandler, PluginJobHostGate } from '@aglyn/aglyn/server'\nimport {\n firebaseAdmin,\n hostDisplayName,\n notifyHostManagers,\n raiseOperatorAlert,\n} from '@aglyn/tenant-data-admin'\nimport { sellerPaymentAccount } from '@aglyn/tenant-data-admin/server/seller-payment-account'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n COMMERCE_POS_OFFLINE_CARD_UNSYNCED,\n COMMERCE_POS_OFFLINE_CARD_WRONG_ACCOUNT,\n} from '../constants/operator-alerts'\nimport {\n POS_OFFLINE_CARD_INTENT_KIND,\n posOfflineSaleKeyIsValid,\n} from '../model/commerce-pos-offline'\n\n/*==========================================\n * A CARD TAKEN OFFLINE, AS STRIPE REPORTS IT (AGL-4039).\n *\n * The Aglyn POS app creates the PaymentIntent of a card it takes offline, so\n * Stripe can know of a charge before the sale itself reaches the server: the\n * SDK forwards the card the moment a connection returns, and the sale syncs\n * right after, from the same device. Usually seconds apart. If the sale never\n * arrives (the device was lost or wiped between the two, or it waits for a\n * member who never signs in again), the charge must not be invisible: each\n * event on such an intent is kept on the site, by the sale's key, under the\n * site's server-only Terminal document\n * (`terminal/config/offlineCardCharges/{saleKey}`), beside whether the sale\n * has synced. The sync itself never depends on this: it reads Stripe.\n *\n * WHO SAYS \"SYNCED\". Both writers, in transactions, so neither can undo the\n * other: the sync marks the record when it creates the order, and an event\n * reads the record and the sync record together. An event that arrives after\n * the sync therefore keeps `synced`, and one that raced it retries and sees\n * it.\n *\n * NOBODY LOOKING. An intent that holds or has taken money while its sale has\n * not synced gets `alertDueAtMs`, {@link POS_OFFLINE_CARD_UNSYNCED_ALERT_MS}\n * after it was first seen. The hourly sweep ({@link scanUnsyncedOfflineCards})\n * tells the operator and the site's managers once, with time left to sync the\n * sale before Stripe's authorization lapses (about two days). It never\n * captures: without the sale there is no fee to capture with.\n *\n * Self-selecting: every other event returns `null` untouched. Registered on\n * the platform webhook from the commerce server module, beside the other\n * commerce handlers, rather than as a branch of the storefront sections. The\n * four `payment_intent.*` events it reads are in the platform destination's\n * `WEBHOOK_EVENTS` (`tools/scripts/lib/stripe-webhook-health.mjs`).\n *\n * A STORE ON ITS OWN STRIPE ACCOUNT (AGL-4219). Its app makes the intent on\n * that account, so the events come through the Connect destination, naming\n * the account. Metadata is only a claim, and the account's owner can write\n * any: a Connect-delivered event is kept only when it says it is a direct\n * sale's and the account is the one the site sells on now. Those four events\n * reach the Connect destination only once it subscribes to them; the sync\n * never depends on this record, because it reads Stripe.\n *=========================================*/\n\n/** The subcollection, under `hosts/{hostId}/terminal/config`, and its collection-group name. */\nexport const POS_OFFLINE_CARD_CHARGES = 'offlineCardCharges'\n\n/**\n * How long an intent that holds money may wait for its sale before the sweep\n * says so: six hours, which leaves well over a day of Stripe's two-day\n * authorization to sync it, and is far past the seconds a healthy sync takes.\n */\nexport const POS_OFFLINE_CARD_UNSYNCED_ALERT_MS = 6 * 60 * 60 * 1000\n\n/** Statuses in which an intent holds money or has taken it. */\nconst HOLDS_MONEY: ReadonlySet<string> = new Set(['requires_capture', 'processing', 'succeeded'])\n\n/** Statuses an intent never leaves; an older event must not turn one back. */\nconst FINAL: ReadonlySet<string> = new Set(['succeeded', 'canceled'])\n\n/** What the site keeps about one offline card's PaymentIntent. */\nexport interface PosOfflineCardChargeRecord {\n hostId: string\n saleKey: string\n paymentIntentId: string\n status: string\n amountCents: number\n registerId: string\n livemode: boolean\n /** Whether the sale has synced (its order exists). */\n synced: boolean\n orderId?: string\n syncedAtMs?: number\n lastEvent: string\n updatedAtMs: number\n /** When the sweep says the sale never synced; absent once synced or told. */\n alertDueAtMs?: number\n alertedAtMs?: number\n /** The capture's idempotency attempt, raised only after a definite failure. */\n captureAttempt?: number\n}\n\n/** `hosts/{hostId}/terminal/config/offlineCardCharges/{saleKey}`. */\nexport function posOfflineCardChargeRef(\n hostRef: FirebaseFirestore.DocumentReference,\n saleKey: string,\n): FirebaseFirestore.DocumentReference {\n return hostRef.collection('terminal').doc('config').collection(POS_OFFLINE_CARD_CHARGES).doc(saleKey)\n}\n\nconst validHostId = (hostId: string) => /^[A-Za-z0-9_-]{1,128}$/.test(hostId)\n\nexport async function reconcilePosOfflineCardEvent(\n input: { type: string; object: any },\n firestore?: FirebaseFirestore.Firestore,\n now: () => number = Date.now,\n): Promise<{ hostId: string } | null> {\n if (!input.type.startsWith('payment_intent.')) return null\n const intent = input.object ?? {}\n const metadata = (intent.metadata ?? {}) as Record<string, string>\n if (metadata['kind'] !== POS_OFFLINE_CARD_INTENT_KIND) return null\n const hostId = String(metadata['hostId'] ?? '')\n const saleKey = String(metadata['saleKey'] ?? '')\n if (!validHostId(hostId) || !posOfflineSaleKeyIsValid(saleKey)) return null\n const db = firestore ?? firebaseAdmin.app().firestore()\n const hostRef = db.collection('hosts').doc(hostId)\n const chargeRef = posOfflineCardChargeRef(hostRef, saleKey)\n const saleRef = hostRef.collection('posOfflineSales').doc(saleKey)\n await db.runTransaction(async (transaction) => {\n const charge = await transaction.get(chargeRef)\n const sale = await transaction.get(saleRef)\n const previous = (charge.exists ? charge.data() : {}) as Partial<PosOfflineCardChargeRecord>\n const synced = previous.synced === true || sale.exists\n const incoming = String(intent.status ?? '')\n // Stripe does not promise event order: a late `amount_capturable_updated`\n // must not turn a captured or canceled intent back into an authorized one.\n const status =\n previous.status && FINAL.has(previous.status) && !FINAL.has(incoming) ? previous.status : incoming\n const at = now()\n const alertDueAtMs =\n !synced && HOLDS_MONEY.has(status) && !previous.alertedAtMs\n ? typeof previous.alertDueAtMs === 'number'\n ? previous.alertDueAtMs\n : at + POS_OFFLINE_CARD_UNSYNCED_ALERT_MS\n : null\n transaction.set(\n chargeRef,\n {\n hostId,\n saleKey,\n paymentIntentId: String(intent.id ?? ''),\n status,\n amountCents: Math.max(0, Math.round(Number(intent.amount ?? 0))),\n registerId: String(metadata['registerId'] ?? '').slice(0, 128),\n livemode: Boolean(intent.livemode),\n synced,\n lastEvent: input.type,\n updatedAtMs: at,\n alertDueAtMs: alertDueAtMs ?? FieldValue.delete(),\n },\n { merge: true },\n )\n })\n return { hostId }\n}\n\n/** The connected account a Connect-delivered event names; null for the platform's own. */\nfunction eventAccount(event: unknown): string | null {\n const account = (event as { account?: unknown } | null)?.account\n return typeof account === 'string' && account ? account : null\n}\n\n/** The account a site's direct sales are made on now; null for a store selling through the platform. */\nasync function directAccountOf(hostId: string): Promise<string | null> {\n const seller = await sellerPaymentAccount(hostId)\n return seller?.chargeModel === 'direct' ? seller.accountId : null\n}\n\n/**\n * The platform webhook's handler for offline card intents: claims only its\n * own. A Connect-delivered event counts only for the site's own account.\n */\nexport function createPosOfflineCardBillingWebhookHandler(\n directAccount: (hostId: string) => Promise<string | null> = directAccountOf,\n): BillingWebhookHandler {\n return async ({ type, object, event }) => {\n const account = eventAccount(event)\n if (account) {\n if (!type.startsWith('payment_intent.')) return undefined\n const metadata = (object?.metadata ?? {}) as Record<string, string>\n if (metadata['kind'] !== POS_OFFLINE_CARD_INTENT_KIND || metadata['chargeModel'] !== 'direct') return undefined\n const hostId = String(metadata['hostId'] ?? '')\n if (!validHostId(hostId) || (await directAccount(hostId)) !== account) return undefined\n }\n const reconciled = await reconcilePosOfflineCardEvent({ type, object })\n return reconciled ? { claimed: true, hostId: reconciled.hostId } : undefined\n }\n}\n\nexport const posOfflineCardBillingWebhookHandler: BillingWebhookHandler = createPosOfflineCardBillingWebhookHandler()\n\n/*==========================================\n * THE SWEEP: AN OFFLINE CARD WHOSE SALE NEVER SYNCED.\n *=========================================*/\n\nexport interface UnsyncedOfflineCardReport {\n hostId: string\n saleKey: string\n paymentIntentId: string\n status: string\n amountCents: number\n registerId: string\n /** How long ago the intent was first seen waiting, in ms. */\n waitedMs: number\n}\n\nexport interface UnsyncedOfflineCardScan {\n due: number\n alerted: number\n /** Synced, or no longer holding money, since the alert was set. */\n cleared: number\n skippedLocked: number\n}\n\nconst describeWait = (ms: number) => {\n const hours = Math.max(1, Math.round(ms / (60 * 60 * 1000)))\n return hours >= 48 ? `${Math.round(hours / 24)} days` : `${hours} hour${hours === 1 ? '' : 's'}`\n}\n\n/** Tells the operator and the site's managers about one card. Never throws. */\nexport async function reportUnsyncedOfflineCard(report: UnsyncedOfflineCardReport): Promise<void> {\n try {\n const host = await firebaseAdmin.app().firestore().collection('hosts').doc(report.hostId).get().catch(() => null)\n const site = host?.exists ? hostDisplayName(host.data() as Record<string, unknown>, report.hostId) : report.hostId\n const amount = formatOperatorAlertAmount(report.amountCents)\n await raiseOperatorAlert(COMMERCE_POS_OFFLINE_CARD_UNSYNCED, {\n dedupeKey: `${report.hostId}:${report.saleKey}`,\n hostId: report.hostId,\n context: {\n amount,\n paymentIntentId: report.paymentIntentId,\n status: report.status,\n site: `${site} (${report.hostId})`,\n registerId: report.registerId || 'unknown',\n age: describeWait(report.waitedMs),\n },\n })\n await notifyHostManagers(report.hostId, {\n type: 'content.order',\n title: `A ${amount} card taken offline on {site} has no sale`,\n body:\n report.status === 'succeeded'\n ? `A ${amount} card taken offline was charged, but the register never sent its sale, so there is no order for it. ` +\n 'Open the register that took it, signed in as the member who rang it, so the sale syncs.'\n : `A ${amount} card taken offline is approved but not yet charged, because the register never sent its sale. ` +\n 'Open the register that took it, signed in as the member who rang it, so the sale syncs. ' +\n 'If it does not sync within about two days of the sale, the card is never charged.',\n link: `/${report.hostId}/products`,\n })\n } catch (error) {\n console.error('[pos-offline-card] unsynced report failed', report.hostId, report.saleKey, error)\n }\n}\n\n/** Tells the operator a card was made out to an account that is not the store's. Never throws. */\nexport async function reportPosOfflineCardWrongAccount(input: {\n hostId: string\n orderId: string\n paymentIntentId: string\n status: string\n amountCents: number\n destination: string\n expected: string\n}): Promise<void> {\n try {\n const host = await firebaseAdmin.app().firestore().collection('hosts').doc(input.hostId).get().catch(() => null)\n const site = host?.exists ? hostDisplayName(host.data() as Record<string, unknown>, input.hostId) : input.hostId\n await raiseOperatorAlert(COMMERCE_POS_OFFLINE_CARD_WRONG_ACCOUNT, {\n dedupeKey: `${input.hostId}:${input.orderId}`,\n hostId: input.hostId,\n context: {\n amount: formatOperatorAlertAmount(input.amountCents),\n paymentIntentId: input.paymentIntentId,\n status: input.status,\n orderId: input.orderId,\n site: `${site} (${input.hostId})`,\n destination: input.destination || 'none',\n expected: input.expected,\n },\n })\n } catch (error) {\n console.error('[pos-offline-card] wrong-account alert failed', input.hostId, input.orderId, error)\n }\n}\n\n/**\n * The hourly sweep (registered in `server.ts`): every offline card record\n * whose alert is due. Re-checks the sale first, so a sale that synced while\n * the event was in flight clears the record and tells nobody.\n *\n * One collection-group range query on `alertDueAtMs`, which is set only on a\n * record that holds money and has not synced, so the ordinary beat reads an\n * empty result. Its COLLECTION_GROUP index is declared in\n * `cloud/firebase-firestore.indexes.json` and pinned by\n * `cron-scan-indexes.spec.ts`.\n */\nexport async function scanUnsyncedOfflineCards(\n /** The lockdown gate, injected by the runner (AGL-2495). */\n gate: PluginJobHostGate,\n options: {\n firestore?: FirebaseFirestore.Firestore\n nowMs?: number\n limit?: number\n report?: (report: UnsyncedOfflineCardReport) => Promise<void>\n } = {},\n): Promise<UnsyncedOfflineCardScan> {\n const db = options.firestore ?? firebaseAdmin.app().firestore()\n const nowMs = options.nowMs ?? Date.now()\n const report = options.report ?? reportUnsyncedOfflineCard\n const scan: UnsyncedOfflineCardScan = { due: 0, alerted: 0, cleared: 0, skippedLocked: 0 }\n const due = await db\n .collectionGroup(POS_OFFLINE_CARD_CHARGES)\n .where('alertDueAtMs', '<=', nowMs)\n .orderBy('alertDueAtMs', 'asc')\n .limit(options.limit ?? 100)\n .get()\n .catch((error: unknown) => {\n console.error('[pos-offline-card] unsynced scan failed', error)\n return null\n })\n if (!due) return scan\n for (const doc of due.docs) {\n const record = (doc.data() ?? {}) as Partial<PosOfflineCardChargeRecord>\n if (typeof record.alertDueAtMs !== 'number') continue\n // `hosts/{hostId}/terminal/config/offlineCardCharges/{saleKey}`.\n const hostId = String(record.hostId || doc.ref.parent.parent?.parent?.parent?.id || '')\n const saleKey = String(record.saleKey || doc.id)\n if (!validHostId(hostId) || !posOfflineSaleKeyIsValid(saleKey)) continue\n scan.due += 1\n // A locked site is skipped, not dropped: its record stays due and is\n // told on the first beat after the lift.\n if (await gate.isLocked(hostId)) {\n scan.skippedLocked += 1\n continue\n }\n const hostRef = db.collection('hosts').doc(hostId)\n const synced = (await hostRef.collection('posOfflineSales').doc(saleKey).get()).exists\n if (synced || !HOLDS_MONEY.has(String(record.status ?? ''))) {\n await doc.ref.set(\n { ...(synced ? { synced: true } : {}), alertDueAtMs: FieldValue.delete() },\n { merge: true },\n )\n scan.cleared += 1\n continue\n }\n await report({\n hostId,\n saleKey,\n paymentIntentId: String(record.paymentIntentId ?? ''),\n status: String(record.status ?? ''),\n amountCents: Math.max(0, Math.round(Number(record.amountCents ?? 0))),\n registerId: String(record.registerId ?? ''),\n waitedMs: Math.max(0, nowMs - (record.alertDueAtMs - POS_OFFLINE_CARD_UNSYNCED_ALERT_MS)),\n })\n await doc.ref.set({ alertedAtMs: nowMs, alertDueAtMs: FieldValue.delete() }, { merge: true })\n scan.alerted += 1\n }\n return scan\n}\n"],"names":["formatOperatorAlertAmount","firebaseAdmin","hostDisplayName","notifyHostManagers","raiseOperatorAlert","sellerPaymentAccount","FieldValue","COMMERCE_POS_OFFLINE_CARD_UNSYNCED","COMMERCE_POS_OFFLINE_CARD_WRONG_ACCOUNT","POS_OFFLINE_CARD_INTENT_KIND","posOfflineSaleKeyIsValid","POS_OFFLINE_CARD_CHARGES","POS_OFFLINE_CARD_UNSYNCED_ALERT_MS","HOLDS_MONEY","Set","FINAL","posOfflineCardChargeRef","hostRef","saleKey","collection","doc","validHostId","hostId","test","reconcilePosOfflineCardEvent","input","firestore","now","Date","intent","metadata","type","startsWith","object","String","db","app","chargeRef","saleRef","runTransaction","transaction","charge","get","sale","previous","exists","data","synced","incoming","status","has","at","alertDueAtMs","alertedAtMs","set","paymentIntentId","id","amountCents","Math","max","round","Number","amount","registerId","slice","livemode","Boolean","lastEvent","updatedAtMs","delete","merge","eventAccount","event","account","directAccountOf","seller","chargeModel","accountId","createPosOfflineCardBillingWebhookHandler","directAccount","undefined","reconciled","claimed","posOfflineCardBillingWebhookHandler","describeWait","ms","hours","reportUnsyncedOfflineCard","report","host","catch","site","dedupeKey","context","age","waitedMs","title","body","link","error","console","reportPosOfflineCardWrongAccount","orderId","destination","expected","scanUnsyncedOfflineCards","gate","options","nowMs","scan","due","alerted","cleared","skippedLocked","collectionGroup","where","orderBy","limit","docs","record","ref","parent","isLocked"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,yBAAyB,QAAQ,yCAAwC;AAElF,SACEC,aAAa,EACbC,eAAe,EACfC,kBAAkB,EAClBC,kBAAkB,QACb,2BAA0B;AACjC,SAASC,oBAAoB,QAAQ,yDAAwD;AAC7F,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SACEC,kCAAkC,EAClCC,uCAAuC,QAClC,kCAA8B;AACrC,SACEC,4BAA4B,EAC5BC,wBAAwB,QACnB,mCAA+B;AAEtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAwC2C,GAE3C,8FAA8F,GAC9F,OAAO,MAAMC,2BAA2B,qBAAoB;AAE5D;;;;CAIC,GACD,OAAO,MAAMC,qCAAqC,IAAI,KAAK,KAAK,KAAI;AAEpE,6DAA6D,GAC7D,MAAMC,cAAmC,IAAIC,IAAI;IAAC;IAAoB;IAAc;CAAY;AAEhG,4EAA4E,GAC5E,MAAMC,QAA6B,IA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AG,CAAChB,QAAOqF,iBAAAA,OAAOtE,MAAM,YAAbsE,iBAAiB,MAAM;YAC3D,MAAMnG,IAAIoG,GAAG,CAAClE,GAAG,CACf,aAAMP,SAAS;gBAAEA,QAAQ;YAAK,IAAI,CAAC;gBAAIK,cAAc9C,WAAW+D,MAAM;gBACtE;gBAAEC,OAAO;YAAK;YAEhBuC,KAAKG,OAAO,IAAI;YAChB;QACF;QACA,MAAMxB,OAAO;YACXlE;YACAJ;YACAqC,iBAAiBrB,QAAOqF,0BAAAA,OAAOhE,eAAe,YAAtBgE,0BAA0B;YAClDtE,QAAQf,QAAOqF,kBAAAA,OAAOtE,MAAM,YAAbsE,kBAAiB;YAChC9D,aAAaC,KAAKC,GAAG,CAAC,GAAGD,KAAKE,KAAK,CAACC,QAAO0D,sBAAAA,OAAO9D,WAAW,YAAlB8D,sBAAsB;YACjExD,YAAY7B,QAAOqF,qBAAAA,OAAOxD,UAAU,YAAjBwD,qBAAqB;YACxCxB,UAAUrC,KAAKC,GAAG,CAAC,GAAGiD,QAASW,CAAAA,OAAOnE,YAAY,GAAGxC,kCAAiC;QACxF;QACA,MAAMQ,IAAIoG,GAAG,CAAClE,GAAG,CAAC;YAAED,aAAauD;YAAOxD,cAAc9C,WAAW+D,MAAM;QAAG,GAAG;YAAEC,OAAO;QAAK;QAC3FuC,KAAKE,OAAO,IAAI;IAClB;IACA,OAAOF;AACT"}
|
|
@@ -39,6 +39,18 @@ export interface PosOfflineSyncRecord {
|
|
|
39
39
|
notified: boolean;
|
|
40
40
|
/** A card taken offline that was declined or never charged: no receipt and no "paid" for it. */
|
|
41
41
|
unpaid?: boolean;
|
|
42
|
+
/**
|
|
43
|
+
* A card refused as made out to another account whose authorization still
|
|
44
|
+
* holds the customer's money (AGL-4219): the intent to cancel, and where.
|
|
45
|
+
* `account` null is the platform.
|
|
46
|
+
*/
|
|
47
|
+
releaseHold?: {
|
|
48
|
+
paymentIntentId: string;
|
|
49
|
+
account: string | null;
|
|
50
|
+
};
|
|
51
|
+
/** Whether that cancel went through; absent until it was tried. */
|
|
52
|
+
holdReleased?: boolean;
|
|
53
|
+
holdReleaseError?: string;
|
|
42
54
|
}
|
|
43
55
|
export interface PosOfflineAfterSale {
|
|
44
56
|
hostId: string;
|
|
@@ -78,18 +90,25 @@ export interface PosOfflineCardDeps {
|
|
|
78
90
|
merchantAccount(hostId: string, org: Record<string, any> | null): Promise<PosMerchant | null>;
|
|
79
91
|
/** Turns Stripe's offline mode on for the site's readers; false when Stripe refused. */
|
|
80
92
|
enableOffline(hostId: string): Promise<boolean>;
|
|
81
|
-
|
|
93
|
+
/**
|
|
94
|
+
* Reads an intent on `account` (a store's own Stripe account, for a direct
|
|
95
|
+
* charge, AGL-4219) or, with null, the platform. A failure carries Stripe's
|
|
96
|
+
* HTTP status when Stripe answered.
|
|
97
|
+
*/
|
|
98
|
+
retrieve(paymentIntentId: string, account: string | null): Promise<{
|
|
82
99
|
ok: true;
|
|
83
100
|
intent: PosOfflineCardIntent;
|
|
84
101
|
} | {
|
|
85
102
|
ok: false;
|
|
86
103
|
error: string;
|
|
104
|
+
status?: number;
|
|
87
105
|
}>;
|
|
88
106
|
/**
|
|
89
|
-
* Captures with the platform fee
|
|
90
|
-
* when Stripe answered; a request that never
|
|
107
|
+
* Captures with the platform fee, on `account` or the platform. A failure
|
|
108
|
+
* carries Stripe's HTTP status when Stripe answered; a request that never
|
|
109
|
+
* got an answer throws.
|
|
91
110
|
*/
|
|
92
|
-
capture(paymentIntentId: string, applicationFeeCents: number, idempotencyKey: string): Promise<{
|
|
111
|
+
capture(paymentIntentId: string, applicationFeeCents: number, idempotencyKey: string, account: string | null): Promise<{
|
|
93
112
|
ok: true;
|
|
94
113
|
intent: PosOfflineCardIntent;
|
|
95
114
|
} | {
|
|
@@ -97,7 +116,23 @@ export interface PosOfflineCardDeps {
|
|
|
97
116
|
error: string;
|
|
98
117
|
status?: number;
|
|
99
118
|
}>;
|
|
100
|
-
/**
|
|
119
|
+
/**
|
|
120
|
+
* Cancels an authorized intent on `account` (or the platform, null), so the
|
|
121
|
+
* customer's hold is released (AGL-4219). Only ever asked for an intent the
|
|
122
|
+
* sync read as `requires_capture`; Stripe refuses to cancel a captured one.
|
|
123
|
+
*/
|
|
124
|
+
cancel(paymentIntentId: string, account: string | null, idempotencyKey: string): Promise<{
|
|
125
|
+
ok: true;
|
|
126
|
+
} | {
|
|
127
|
+
ok: false;
|
|
128
|
+
error: string;
|
|
129
|
+
status?: number;
|
|
130
|
+
}>;
|
|
131
|
+
/**
|
|
132
|
+
* Tells the operator a card was made out to another account. Never throws.
|
|
133
|
+
* `destination` is where the money went: the transfer's account for a
|
|
134
|
+
* destination charge, the account the intent was made on for a direct one.
|
|
135
|
+
*/
|
|
101
136
|
wrongAccount(input: {
|
|
102
137
|
hostId: string;
|
|
103
138
|
orderId: string;
|
|
@@ -124,8 +159,13 @@ export declare function posInPersonTax(settings: CommerceModel.TaxSettings | und
|
|
|
124
159
|
ok: false;
|
|
125
160
|
reason: string;
|
|
126
161
|
};
|
|
162
|
+
/** What the app asking for the kit can do, from the GET's query. */
|
|
163
|
+
export interface PosOfflineKitClient {
|
|
164
|
+
/** The app makes a card's intent on a store's own Stripe account (AGL-4219). */
|
|
165
|
+
directCards?: boolean;
|
|
166
|
+
}
|
|
127
167
|
/** The kit a register caches to sell offline. */
|
|
128
|
-
export declare function buildPosOfflineKit(deps: PosOfflineSyncDeps, staff: PosOpsStaff): Promise<PosOfflineKit>;
|
|
168
|
+
export declare function buildPosOfflineKit(deps: PosOfflineSyncDeps, staff: PosOpsStaff, client?: PosOfflineKitClient): Promise<PosOfflineKit>;
|
|
129
169
|
/**
|
|
130
170
|
* How long after a capture that Stripe answered with a 5xx the sync waits
|
|
131
171
|
* before reading "still waiting for capture" as the definite answer.
|
|
@@ -150,6 +190,8 @@ export declare const POS_OFFLINE_CAPTURE_SETTLE_MS = 60000;
|
|
|
150
190
|
export declare function posOfflineCaptureKey(hostId: string, saleKey: string, attempt: number): string;
|
|
151
191
|
/** A capture Stripe refused for good: retrying the same key would replay the refusal. */
|
|
152
192
|
export declare function posOfflineCaptureRefused(status: number | undefined): boolean;
|
|
193
|
+
/** The cancel's idempotency key: one cancel per sale. */
|
|
194
|
+
export declare function posOfflineReleaseKey(hostId: string, saleKey: string): string;
|
|
153
195
|
export declare function handlePosOfflineSync(deps: PosOfflineSyncDeps, req: PluginApiRequest): Promise<Outcome>;
|
|
154
196
|
export declare function createPosOfflineSyncHandler(deps?: () => PosOfflineSyncDeps): PluginApiHandler;
|
|
155
197
|
export declare const posOfflineSyncHandler: Aglyn.PluginApiHandler;
|
|
@@ -31,8 +31,8 @@ import { posOfflineCardChargeRef, reportPosOfflineCardWrongAccount } from "./pos
|
|
|
31
31
|
import { posHardwareSaleFields } from "./pos-hardware-sale-fields.js";
|
|
32
32
|
import { posOfflineCardOrderMoney } from "./pos-offline-card-order.js";
|
|
33
33
|
import { notifyPosSaleCompleted } from "./pos-sale.js";
|
|
34
|
-
import { POS_CURRENCY,
|
|
35
|
-
import { capturePosOfflineCardIntent, ensurePosOfflineCardConfiguration, posMerchantAccount, posTerminalLocationId, retrievePosOfflineCardIntent } from "./pos-terminal.js";
|
|
34
|
+
import { POS_CURRENCY, posOfflineCardFeeCents, posTerminalAvailable } from "./pos-stripe.js";
|
|
35
|
+
import { cancelPosOfflineCardIntent, capturePosOfflineCardIntent, ensurePosOfflineCardConfiguration, posMerchantAccount, posTerminalLocationId, retrievePosOfflineCardIntent } from "./pos-terminal.js";
|
|
36
36
|
import { decrementVariantStock } from "./reserve-stock.js";
|
|
37
37
|
export function defaultPosOfflineCardDeps() {
|
|
38
38
|
return {
|
|
@@ -44,6 +44,7 @@ export function defaultPosOfflineCardDeps() {
|
|
|
44
44
|
enableOffline: ensurePosOfflineCardConfiguration,
|
|
45
45
|
retrieve: retrievePosOfflineCardIntent,
|
|
46
46
|
capture: capturePosOfflineCardIntent,
|
|
47
|
+
cancel: cancelPosOfflineCardIntent,
|
|
47
48
|
wrongAccount: reportPosOfflineCardWrongAccount
|
|
48
49
|
};
|
|
49
50
|
}
|
|
@@ -178,7 +179,7 @@ async function readStoreTax(staff) {
|
|
|
178
179
|
const store = await staff.hostRef.collection('settings').doc('store').get();
|
|
179
180
|
return (_store_get = store.get('tax')) != null ? _store_get : undefined;
|
|
180
181
|
}
|
|
181
|
-
/** The kit a register caches to sell offline. */ export async function buildPosOfflineKit(deps, staff) {
|
|
182
|
+
/** The kit a register caches to sell offline. */ export async function buildPosOfflineKit(deps, staff, client = {}) {
|
|
182
183
|
var _host_get;
|
|
183
184
|
const [registers, taxSettings, config, host, store] = await Promise.all([
|
|
184
185
|
readRegisters(staff),
|
|
@@ -188,7 +189,7 @@ async function readStoreTax(staff) {
|
|
|
188
189
|
staff.hostRef.collection('settings').doc('store').get()
|
|
189
190
|
]);
|
|
190
191
|
const tax = posInPersonTax(taxSettings);
|
|
191
|
-
const card = await buildPosOfflineKitCard(deps, staff, config);
|
|
192
|
+
const card = await buildPosOfflineKitCard(deps, staff, config, client);
|
|
192
193
|
return _extends({
|
|
193
194
|
v: 1,
|
|
194
195
|
hostId: staff.hostId,
|
|
@@ -239,7 +240,7 @@ async function readStoreTax(staff) {
|
|
|
239
240
|
/**
|
|
240
241
|
* What the app needs to take a card offline on its own reader (AGL-4039), or
|
|
241
242
|
* why it cannot. Absent where this server takes no offline cards.
|
|
242
|
-
*/ async function buildPosOfflineKitCard(deps, staff, config) {
|
|
243
|
+
*/ async function buildPosOfflineKitCard(deps, staff, config, client) {
|
|
243
244
|
if (!deps.card) return undefined;
|
|
244
245
|
const settings = posOfflineCardSettings(config);
|
|
245
246
|
const base = {
|
|
@@ -258,19 +259,27 @@ async function readStoreTax(staff) {
|
|
|
258
259
|
if (!terminal.locationId) return off('Connect a card reader once while online, then cards keep working offline.');
|
|
259
260
|
const merchant = await deps.card.merchantAccount(staff.hostId, staff.org);
|
|
260
261
|
if (!merchant) return off('Finish connecting Stripe to take cards.');
|
|
261
|
-
// The app makes an offline card's intent itself
|
|
262
|
-
// to `destination`.
|
|
263
|
-
//
|
|
264
|
-
//
|
|
265
|
-
|
|
262
|
+
// The app makes an offline card's intent itself. For a store on Aglyn's
|
|
263
|
+
// account it is a DESTINATION charge to `destination`. For a store on its
|
|
264
|
+
// own Stripe account (AGL-4219) it is made ON that account, which is the
|
|
265
|
+
// one the SDK's connection token and the site's Location belong to
|
|
266
|
+
// (`createPosTerminalConnectionToken`), with no transfer at all: Stripe's
|
|
267
|
+
// Terminal-with-direct-charges guide asks a client-side intent for no
|
|
268
|
+
// Connect parameters. An app from before that cannot make one, so it is
|
|
269
|
+
// offered no kit for such a store rather than a card that fails at the
|
|
270
|
+
// counter or lands on the wrong account.
|
|
271
|
+
const direct = merchant.chargeModel === 'direct';
|
|
272
|
+
if (direct && !client.directCards) {
|
|
266
273
|
return off('Card sales offline are not available for this store’s payment account yet. Take cards while online.');
|
|
267
274
|
}
|
|
268
|
-
const destination = merchant.accountId;
|
|
269
275
|
if (!await deps.card.enableOffline(staff.hostId)) {
|
|
270
276
|
return off('Card sales offline could not be turned on for this store’s readers yet. Try again later.');
|
|
271
277
|
}
|
|
272
|
-
return _extends({}, base, {
|
|
273
|
-
|
|
278
|
+
return direct ? _extends({}, base, {
|
|
279
|
+
account: merchant.accountId,
|
|
280
|
+
available: true
|
|
281
|
+
}) : _extends({}, base, {
|
|
282
|
+
destination: merchant.accountId,
|
|
274
283
|
available: true
|
|
275
284
|
});
|
|
276
285
|
}
|
|
@@ -313,6 +322,7 @@ async function readStoreTax(staff) {
|
|
|
313
322
|
* to a Stripe account that is not the store's. Anything Stripe has not
|
|
314
323
|
* finished yet waits on the register for the next sync.
|
|
315
324
|
*/ async function settleOfflineCard(context, sale, takeFee) {
|
|
325
|
+
var _card_account;
|
|
316
326
|
const { deps, staff } = context;
|
|
317
327
|
const { saleKey } = sale;
|
|
318
328
|
const card = sale.card;
|
|
@@ -334,8 +344,37 @@ async function readStoreTax(staff) {
|
|
|
334
344
|
message: card.declineMessage || 'Stripe did not take the card.'
|
|
335
345
|
}, details);
|
|
336
346
|
}
|
|
337
|
-
|
|
338
|
-
|
|
347
|
+
// WHERE THE INTENT LIVES. A direct-charge kit has the device make it on
|
|
348
|
+
// the store's own account, and the sale says which (`card.account`); every
|
|
349
|
+
// other card was made on the platform. It is read where the device made
|
|
350
|
+
// it, and judged below against where the store sells NOW.
|
|
351
|
+
const madeOn = (_card_account = card.account) != null ? _card_account : null;
|
|
352
|
+
const read = await deps.card.retrieve(card.paymentIntentId, madeOn);
|
|
353
|
+
if ('error' in read) {
|
|
354
|
+
// Stripe answering that the account has no such intent (or that it may
|
|
355
|
+
// not be read there) is definite. When that account is not the store's
|
|
356
|
+
// now, the card cannot be this store's money, so the sale is recorded
|
|
357
|
+
// unpaid rather than kept on the register for good.
|
|
358
|
+
if (madeOn && posOfflineCaptureRefused(read.status)) {
|
|
359
|
+
const merchant = await deps.card.merchantAccount(staff.hostId, staff.org);
|
|
360
|
+
if (merchant && !(merchant.chargeModel === 'direct' && merchant.accountId === madeOn)) {
|
|
361
|
+
return _extends({
|
|
362
|
+
kind: 'unpaid',
|
|
363
|
+
flag: 'card-not-charged',
|
|
364
|
+
intentId: card.paymentIntentId,
|
|
365
|
+
message: 'The card was made out to a Stripe account that is not this store’s, so it was not charged here.'
|
|
366
|
+
}, details, {
|
|
367
|
+
wrongAccount: {
|
|
368
|
+
destination: madeOn,
|
|
369
|
+
expected: merchant.accountId,
|
|
370
|
+
status: 'unreadable',
|
|
371
|
+
amountCents: 0
|
|
372
|
+
}
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
return wait(`The card payment could not be checked yet: ${read.error}`);
|
|
377
|
+
}
|
|
339
378
|
let intent = read.intent;
|
|
340
379
|
// The amount is NOT checked here: what Stripe took is what the customer
|
|
341
380
|
// paid, and a difference from the server's total is flagged on the order
|
|
@@ -351,21 +390,24 @@ async function readStoreTax(staff) {
|
|
|
351
390
|
} : {}, intent.last4 ? {
|
|
352
391
|
last4: intent.last4
|
|
353
392
|
} : {});
|
|
354
|
-
// THE
|
|
355
|
-
//
|
|
356
|
-
//
|
|
357
|
-
//
|
|
393
|
+
// THE ACCOUNT. The device made this intent where its offline kit said:
|
|
394
|
+
// out to `destination` on the platform, or on the store's own account for
|
|
395
|
+
// a direct charge. A kit can be stale (the store reconnected Stripe, or
|
|
396
|
+
// moved to its own account) or a register tampered with. Money that holds
|
|
397
|
+
// or has moved is only ever captured into, or recorded as paid to, the
|
|
398
|
+
// store's account as it is now:
|
|
399
|
+
// - DESTINATION store: made on the platform, transferred to its account.
|
|
400
|
+
// - DIRECT store: made ON its current account, transferring nowhere.
|
|
401
|
+
// Anything else reads as made out elsewhere, like a kit gone stale.
|
|
358
402
|
if (INTENT_HOLDS_MONEY.has(intent.status)) {
|
|
359
403
|
var _ref;
|
|
360
404
|
const merchant = await deps.card.merchantAccount(staff.hostId, staff.org);
|
|
361
|
-
// A direct-charge store is offered no offline kit, so an intent the app
|
|
362
|
-
// made out to a destination is never its account's money: it reads as
|
|
363
|
-
// made out elsewhere, like a kit gone stale.
|
|
364
405
|
const expected = (_ref = merchant == null ? void 0 : merchant.accountId) != null ? _ref : null;
|
|
365
|
-
if (!expected) {
|
|
406
|
+
if (!merchant || !expected) {
|
|
366
407
|
return wait('This store’s Stripe account cannot take card payments right now. The card syncs once it can.');
|
|
367
408
|
}
|
|
368
|
-
|
|
409
|
+
const onStoreAccount = merchant.chargeModel === 'direct' ? madeOn === expected && !intent.destination : madeOn === null && intent.destination === expected;
|
|
410
|
+
if (!onStoreAccount) {
|
|
369
411
|
return _extends({
|
|
370
412
|
kind: 'unpaid',
|
|
371
413
|
flag: 'card-not-charged',
|
|
@@ -373,19 +415,30 @@ async function readStoreTax(staff) {
|
|
|
373
415
|
message: 'The card was made out to a Stripe account that is not this store’s, so it was not charged here.'
|
|
374
416
|
}, found, {
|
|
375
417
|
wrongAccount: {
|
|
376
|
-
destination: intent.destination,
|
|
418
|
+
destination: madeOn != null ? madeOn : intent.destination,
|
|
377
419
|
expected,
|
|
378
420
|
status: intent.status,
|
|
379
421
|
amountCents: intent.amount
|
|
380
422
|
}
|
|
381
|
-
}
|
|
423
|
+
}, intent.status === 'requires_capture' ? {
|
|
424
|
+
releaseHold: {
|
|
425
|
+
paymentIntentId: intent.id,
|
|
426
|
+
account: madeOn
|
|
427
|
+
}
|
|
428
|
+
} : {});
|
|
382
429
|
}
|
|
383
430
|
}
|
|
431
|
+
// The fee, by the one tender rule, exactly as an online reader payment is
|
|
432
|
+
// captured (`posCaptureFeeCents`): the card's share of the take plus
|
|
433
|
+
// Stripe's processing on a destination charge, the take alone on the
|
|
434
|
+
// store's own account, where Stripe bills the store its card fee.
|
|
384
435
|
const takeShareCents = CommerceModel.posTenderTakeCents('card_present', takeFee);
|
|
385
|
-
const expectedFeeCents =
|
|
436
|
+
const expectedFeeCents = posOfflineCardFeeCents(_extends({
|
|
386
437
|
takeShareCents,
|
|
387
438
|
chargeCents: intent.amount
|
|
388
|
-
}
|
|
439
|
+
}, madeOn ? {
|
|
440
|
+
direct: true
|
|
441
|
+
} : {}));
|
|
389
442
|
if (intent.status === 'requires_capture') {
|
|
390
443
|
var _data, _charge_captureAttempt, _charge_captureUncertainAtMs;
|
|
391
444
|
const chargeRef = posOfflineCardChargeRef(staff.hostRef, saleKey);
|
|
@@ -403,7 +456,7 @@ async function readStoreTax(staff) {
|
|
|
403
456
|
merge: true
|
|
404
457
|
});
|
|
405
458
|
}
|
|
406
|
-
const captured = await deps.card.capture(intent.id, expectedFeeCents, posOfflineCaptureKey(staff.hostId, saleKey, attempt));
|
|
459
|
+
const captured = await deps.card.capture(intent.id, expectedFeeCents, posOfflineCaptureKey(staff.hostId, saleKey, attempt), madeOn);
|
|
407
460
|
if ('error' in captured) {
|
|
408
461
|
const stamp = {
|
|
409
462
|
hostId: staff.hostId,
|
|
@@ -439,7 +492,9 @@ async function readStoreTax(staff) {
|
|
|
439
492
|
expectedFeeCents,
|
|
440
493
|
takeShareCents,
|
|
441
494
|
livemode: intent.livemode
|
|
442
|
-
},
|
|
495
|
+
}, madeOn ? {
|
|
496
|
+
account: madeOn
|
|
497
|
+
} : {}, found);
|
|
443
498
|
}
|
|
444
499
|
if (intent.status === 'requires_payment_method' || intent.status === 'canceled') {
|
|
445
500
|
return _extends({
|
|
@@ -569,6 +624,9 @@ const replayOf = (record)=>({
|
|
|
569
624
|
}
|
|
570
625
|
if (!stockDone) return current;
|
|
571
626
|
}
|
|
627
|
+
if (current.releaseHold && current.holdReleased === undefined) {
|
|
628
|
+
current = await releaseOfflineCardHold(context, recordRef, orderRef, current);
|
|
629
|
+
}
|
|
572
630
|
if (!current.notified && current.unpaid) {
|
|
573
631
|
// A card that was never paid gets no receipt and no "paid": the order
|
|
574
632
|
// waits, flagged, for the merchant to collect it another way.
|
|
@@ -602,6 +660,53 @@ const replayOf = (record)=>({
|
|
|
602
660
|
}
|
|
603
661
|
return current;
|
|
604
662
|
}
|
|
663
|
+
/** The cancel's idempotency key: one cancel per sale. */ export function posOfflineReleaseKey(hostId, saleKey) {
|
|
664
|
+
return `pos-offline-release:${hostId}:${saleKey}`;
|
|
665
|
+
}
|
|
666
|
+
/**
|
|
667
|
+
* Cancels the authorization of a card refused as made out to another
|
|
668
|
+
* account (AGL-4219), so the customer's card no longer holds the money, and
|
|
669
|
+
* records what happened on the sale and its order. Tried once, after the
|
|
670
|
+
* order exists: a failure (Stripe refused, or no answer) is recorded and
|
|
671
|
+
* never stops the sync. The order stays unpaid and flagged either way.
|
|
672
|
+
*/ async function releaseOfflineCardHold(context, recordRef, orderRef, record) {
|
|
673
|
+
const { deps, staff } = context;
|
|
674
|
+
const hold = record.releaseHold;
|
|
675
|
+
let error = '';
|
|
676
|
+
try {
|
|
677
|
+
const cancelled = deps.card ? await deps.card.cancel(hold.paymentIntentId, hold.account, posOfflineReleaseKey(staff.hostId, record.saleKey)) : {
|
|
678
|
+
ok: false,
|
|
679
|
+
error: 'Card sales taken offline cannot sync to this store.'
|
|
680
|
+
};
|
|
681
|
+
if ('error' in cancelled) error = cancelled.error || 'Stripe refused the cancel.';
|
|
682
|
+
} catch (failure) {
|
|
683
|
+
console.error('[pos-offline-sync] hold release failed', staff.hostId, record.saleKey, failure);
|
|
684
|
+
error = 'Stripe did not answer.';
|
|
685
|
+
}
|
|
686
|
+
const released = !error;
|
|
687
|
+
const fields = released ? {
|
|
688
|
+
holdReleased: true
|
|
689
|
+
} : {
|
|
690
|
+
holdReleased: false,
|
|
691
|
+
holdReleaseError: error.slice(0, 300)
|
|
692
|
+
};
|
|
693
|
+
await recordRef.update(fields);
|
|
694
|
+
try {
|
|
695
|
+
var _data;
|
|
696
|
+
const fresh = (_data = (await orderRef.get()).data()) != null ? _data : {};
|
|
697
|
+
await orderRef.update({
|
|
698
|
+
timeline: CommerceModel.appendOrderEvent(fresh, released ? 'offline-card-released' : 'offline-card-release-failed', released ? 'The card’s authorization was cancelled on Stripe, so the customer’s card no longer holds the money.' : `The card’s authorization could not be cancelled on Stripe (${error}). The hold on the customer’s card lapses on its own.`.slice(0, 500), deps.now())
|
|
699
|
+
});
|
|
700
|
+
await posOfflineCardChargeRef(staff.hostRef, record.saleKey).set(_extends({}, fields, {
|
|
701
|
+
updatedAtMs: deps.now()
|
|
702
|
+
}), {
|
|
703
|
+
merge: true
|
|
704
|
+
});
|
|
705
|
+
} catch (failure) {
|
|
706
|
+
console.error('[pos-offline-sync] hold release note failed', staff.hostId, record.saleKey, failure);
|
|
707
|
+
}
|
|
708
|
+
return _extends({}, record, fields);
|
|
709
|
+
}
|
|
605
710
|
async function syncOne(context, raw) {
|
|
606
711
|
var _ref, _staff_orgId, _ref1, _sale_customer;
|
|
607
712
|
const { deps, staff } = context;
|
|
@@ -926,6 +1031,8 @@ async function syncOne(context, raw) {
|
|
|
926
1031
|
notified: false
|
|
927
1032
|
}, (settled == null ? void 0 : settled.kind) === 'unpaid' ? {
|
|
928
1033
|
unpaid: true
|
|
1034
|
+
} : {}, (settled == null ? void 0 : settled.kind) === 'unpaid' && settled.releaseHold ? {
|
|
1035
|
+
releaseHold: settled.releaseHold
|
|
929
1036
|
} : {});
|
|
930
1037
|
transaction.create(recordRef, record);
|
|
931
1038
|
// The intent's record says its sale synced, in the same commit, so the
|
|
@@ -1011,10 +1118,14 @@ export async function handlePosOfflineSync(deps, req) {
|
|
|
1011
1118
|
};
|
|
1012
1119
|
const staff = gate.staff;
|
|
1013
1120
|
if (req.method === 'GET') {
|
|
1121
|
+
var _body_cardChargeModels;
|
|
1122
|
+
const models = String((_body_cardChargeModels = body['cardChargeModels']) != null ? _body_cardChargeModels : '').split(',').map((model)=>model.trim());
|
|
1014
1123
|
return {
|
|
1015
1124
|
status: 200,
|
|
1016
1125
|
body: {
|
|
1017
|
-
kit: await buildPosOfflineKit(deps, staff
|
|
1126
|
+
kit: await buildPosOfflineKit(deps, staff, {
|
|
1127
|
+
directCards: models.includes('direct')
|
|
1128
|
+
})
|
|
1018
1129
|
}
|
|
1019
1130
|
};
|
|
1020
1131
|
}
|