@aglyn/plugins-commerce 1.14.0 → 1.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +13 -13
- package/src/lib/components/account-subscriptions.d.ts +51 -0
- package/src/lib/components/account-subscriptions.js +168 -0
- package/src/lib/components/account-subscriptions.js.map +1 -0
- package/src/lib/components/account.js +12 -48
- package/src/lib/components/account.js.map +1 -1
- package/src/lib/components/cart.js +38 -9
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/commerce-console-page.js +6 -0
- package/src/lib/components/commerce-console-page.js.map +1 -1
- package/src/lib/components/commerce-console-sections.d.ts +1 -1
- package/src/lib/components/commerce-console-sections.js +5 -0
- package/src/lib/components/commerce-console-sections.js.map +1 -1
- package/src/lib/components/console/paid-media.d.ts +1 -0
- package/src/lib/components/console/paid-media.js +15 -4
- package/src/lib/components/console/paid-media.js.map +1 -1
- package/src/lib/components/console/payments-settings-card.component.js +1 -1
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-api.d.ts +10 -1
- package/src/lib/components/console/pos/pos-hardware-api.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-buyer.component.js +2 -2
- package/src/lib/components/console/pos/pos-hardware-buyer.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-sale-api.d.ts +2 -0
- package/src/lib/components/console/pos/pos-hardware-sale-api.js.map +1 -1
- package/src/lib/components/console/pos-cellular-control.component.d.ts +1 -1
- package/src/lib/components/console/pos-cellular-control.component.js +5 -5
- package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
- package/src/lib/components/console/pos-devices-card.component.js +2 -2
- package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
- package/src/lib/components/console/pos-hardware-card.component.d.ts +5 -0
- package/src/lib/components/console/pos-hardware-card.component.js +77 -8
- package/src/lib/components/console/pos-hardware-card.component.js.map +1 -1
- package/src/lib/components/console/pos-hardware-orders-staff-page.component.js +137 -19
- package/src/lib/components/console/pos-hardware-orders-staff-page.component.js.map +1 -1
- package/src/lib/components/console/pos-page.component.js +19 -2
- package/src/lib/components/console/pos-page.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +21 -2
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/subscription-detail-dialog.component.d.ts +58 -0
- package/src/lib/components/console/subscription-detail-dialog.component.js +201 -0
- package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -0
- package/src/lib/components/console/subscriptions-card.component.d.ts +60 -0
- package/src/lib/components/console/subscriptions-card.component.js +282 -0
- package/src/lib/components/console/subscriptions-card.component.js.map +1 -0
- package/src/lib/components/hardware-terms-consent.d.ts +22 -0
- package/src/lib/components/hardware-terms-consent.js +85 -0
- package/src/lib/components/hardware-terms-consent.js.map +1 -0
- package/src/lib/components/product-detail.js +32 -8
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/quote-page-body.js +7 -3
- package/src/lib/components/quote-page-body.js.map +1 -1
- package/src/lib/components/related-products.js +6 -3
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/components/storefront-payment-element.d.ts +7 -1
- package/src/lib/components/storefront-payment-element.js +11 -7
- package/src/lib/components/storefront-payment-element.js.map +1 -1
- package/src/lib/constants/operator-alerts.d.ts +1 -1
- package/src/lib/constants/operator-alerts.js +4 -4
- package/src/lib/constants/operator-alerts.js.map +1 -1
- package/src/lib/model/commerce-orders.d.ts +6 -2
- package/src/lib/model/commerce-orders.js.map +1 -1
- package/src/lib/model/commerce-payment-methods.d.ts +27 -16
- package/src/lib/model/commerce-payment-methods.js +11 -83
- package/src/lib/model/commerce-payment-methods.js.map +1 -1
- package/src/lib/model/commerce.d.ts +6 -0
- package/src/lib/model/commerce.js.map +1 -1
- package/src/lib/model/index.d.ts +1 -0
- package/src/lib/model/index.js +1 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/model/paid-media.d.ts +8 -0
- package/src/lib/model/paid-media.js +13 -0
- package/src/lib/model/paid-media.js.map +1 -1
- package/src/lib/model/pos-hardware-in-person.d.ts +23 -2
- package/src/lib/model/pos-hardware-in-person.js +52 -20
- package/src/lib/model/pos-hardware-in-person.js.map +1 -1
- package/src/lib/model/pos-hardware-tax-summary.d.ts +5 -1
- package/src/lib/model/pos-hardware-tax-summary.js +2 -1
- package/src/lib/model/pos-hardware-tax-summary.js.map +1 -1
- package/src/lib/model/pos-hardware-terms.d.ts +37 -2
- package/src/lib/model/pos-hardware-terms.js +68 -3
- package/src/lib/model/pos-hardware-terms.js.map +1 -1
- package/src/lib/model/pos-hardware.d.ts +101 -15
- package/src/lib/model/pos-hardware.js +128 -18
- package/src/lib/model/pos-hardware.js.map +1 -1
- package/src/lib/model/pos-reader-splash.js +2 -2
- package/src/lib/model/pos-reader-splash.js.map +1 -1
- package/src/lib/model/product-write.d.ts +3 -0
- package/src/lib/model/subscription-view.d.ts +90 -0
- package/src/lib/model/subscription-view.js +176 -0
- package/src/lib/model/subscription-view.js.map +1 -0
- package/src/lib/server/billing-webhook.d.ts +27 -6
- package/src/lib/server/billing-webhook.js +271 -81
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/cancel-order.js +4 -3
- package/src/lib/server/cancel-order.js.map +1 -1
- package/src/lib/server/cart-checkout.js +105 -23
- package/src/lib/server/cart-checkout.js.map +1 -1
- package/src/lib/server/cart.js +15 -3
- package/src/lib/server/cart.js.map +1 -1
- package/src/lib/server/catalog.js +58 -22
- package/src/lib/server/catalog.js.map +1 -1
- package/src/lib/server/checkout-session-expiry.d.ts +1 -1
- package/src/lib/server/checkout-session-expiry.js +19 -5
- package/src/lib/server/checkout-session-expiry.js.map +1 -1
- package/src/lib/server/checkout-status.js +4 -3
- package/src/lib/server/checkout-status.js.map +1 -1
- package/src/lib/server/checkout.js +98 -26
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/connect.js +42 -11
- package/src/lib/server/connect.js.map +1 -1
- package/src/lib/server/draft-order.js +36 -7
- package/src/lib/server/draft-order.js.map +1 -1
- package/src/lib/server/manual-tax-rate.d.ts +11 -3
- package/src/lib/server/manual-tax-rate.js +10 -6
- package/src/lib/server/manual-tax-rate.js.map +1 -1
- package/src/lib/server/membership-account.d.ts +22 -0
- package/src/lib/server/membership-account.js +52 -8
- package/src/lib/server/membership-account.js.map +1 -1
- package/src/lib/server/native-checkout.d.ts +10 -3
- package/src/lib/server/native-checkout.js +8 -3
- package/src/lib/server/native-checkout.js.map +1 -1
- package/src/lib/server/payment-method-domains.d.ts +50 -9
- package/src/lib/server/payment-method-domains.js +150 -51
- package/src/lib/server/payment-method-domains.js.map +1 -1
- package/src/lib/server/payment-methods.js +3 -2
- package/src/lib/server/payment-methods.js.map +1 -1
- package/src/lib/server/pos-auth.d.ts +3 -3
- package/src/lib/server/pos-auth.js +3 -3
- package/src/lib/server/pos-auth.js.map +1 -1
- package/src/lib/server/pos-cellular-billing.js +1 -1
- package/src/lib/server/pos-cellular-billing.js.map +1 -1
- package/src/lib/server/pos-cellular-notify.js +1 -1
- package/src/lib/server/pos-cellular-notify.js.map +1 -1
- package/src/lib/server/pos-cellular.js +1 -1
- package/src/lib/server/pos-cellular.js.map +1 -1
- package/src/lib/server/pos-hardware-admin.js +86 -13
- package/src/lib/server/pos-hardware-admin.js.map +1 -1
- package/src/lib/server/pos-hardware-attach.js +5 -5
- package/src/lib/server/pos-hardware-attach.js.map +1 -1
- package/src/lib/server/pos-hardware-cancel.js +65 -0
- package/src/lib/server/pos-hardware-cancel.js.map +1 -1
- package/src/lib/server/pos-hardware-closure-notices.js +2 -5
- package/src/lib/server/pos-hardware-closure-notices.js.map +1 -1
- package/src/lib/server/pos-hardware-closure.js +5 -8
- package/src/lib/server/pos-hardware-closure.js.map +1 -1
- package/src/lib/server/pos-hardware-in-person.d.ts +2 -1
- package/src/lib/server/pos-hardware-in-person.js +72 -17
- package/src/lib/server/pos-hardware-in-person.js.map +1 -1
- package/src/lib/server/pos-hardware-notify.d.ts +2 -0
- package/src/lib/server/pos-hardware-notify.js +30 -5
- package/src/lib/server/pos-hardware-notify.js.map +1 -1
- package/src/lib/server/pos-hardware-readers.d.ts +25 -0
- package/src/lib/server/pos-hardware-readers.js +206 -85
- package/src/lib/server/pos-hardware-readers.js.map +1 -1
- package/src/lib/server/pos-hardware-returns.d.ts +8 -3
- package/src/lib/server/pos-hardware-returns.js +39 -7
- package/src/lib/server/pos-hardware-returns.js.map +1 -1
- package/src/lib/server/pos-hardware-sale-fields.d.ts +76 -0
- package/src/lib/server/pos-hardware-sale-fields.js +114 -1
- package/src/lib/server/pos-hardware-sale-fields.js.map +1 -1
- package/src/lib/server/pos-hardware-sale.d.ts +2 -0
- package/src/lib/server/pos-hardware-sale.js +1 -0
- package/src/lib/server/pos-hardware-sale.js.map +1 -1
- package/src/lib/server/pos-hardware-tax-return-source.js +7 -4
- package/src/lib/server/pos-hardware-tax-return-source.js.map +1 -1
- package/src/lib/server/pos-hardware-webhook.js +16 -3
- package/src/lib/server/pos-hardware-webhook.js.map +1 -1
- package/src/lib/server/pos-hardware.d.ts +14 -3
- package/src/lib/server/pos-hardware.js +83 -18
- package/src/lib/server/pos-hardware.js.map +1 -1
- package/src/lib/server/pos-ops-routes.js +2 -10
- package/src/lib/server/pos-ops-routes.js.map +1 -1
- package/src/lib/server/pos-order.js +5 -1
- package/src/lib/server/pos-order.js.map +1 -1
- package/src/lib/server/pos-stripe.d.ts +7 -7
- package/src/lib/server/pos-stripe.js +15 -13
- package/src/lib/server/pos-stripe.js.map +1 -1
- package/src/lib/server/pos-terminal.js +11 -3
- package/src/lib/server/pos-terminal.js.map +1 -1
- package/src/lib/server/quote-pay.d.ts +23 -1
- package/src/lib/server/quote-pay.js +111 -27
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/quote.d.ts +2 -1
- package/src/lib/server/quote.js +12 -11
- package/src/lib/server/quote.js.map +1 -1
- package/src/lib/server/refund.js +13 -6
- package/src/lib/server/refund.js.map +1 -1
- package/src/lib/server/related.js +10 -3
- package/src/lib/server/related.js.map +1 -1
- package/src/lib/server/reserve.js +19 -6
- package/src/lib/server/reserve.js.map +1 -1
- package/src/lib/server/revenue-source.d.ts +6 -0
- package/src/lib/server/revenue-source.js +25 -9
- package/src/lib/server/revenue-source.js.map +1 -1
- package/src/lib/server/seller-stripe-account.d.ts +45 -0
- package/src/lib/server/seller-stripe-account.js +99 -0
- package/src/lib/server/seller-stripe-account.js.map +1 -0
- package/src/lib/server/storefront-tax-record.js +6 -1
- package/src/lib/server/storefront-tax-record.js.map +1 -1
- package/src/lib/server/storefront-tax.d.ts +33 -2
- package/src/lib/server/storefront-tax.js +39 -3
- package/src/lib/server/storefront-tax.js.map +1 -1
- package/src/lib/server/stream.d.ts +2 -0
- package/src/lib/server/stream.js +22 -2
- package/src/lib/server/stream.js.map +1 -1
- package/src/lib/server/stripe-refund.d.ts +15 -0
- package/src/lib/server/stripe-refund.js +54 -26
- package/src/lib/server/stripe-refund.js.map +1 -1
- package/src/lib/server/subscription-portal.js +8 -3
- package/src/lib/server/subscription-portal.js.map +1 -1
- package/src/lib/server/tax-return-source.js +5 -1
- package/src/lib/server/tax-return-source.js.map +1 -1
- package/src/lib/server.js +2 -2
- package/src/lib/server.js.map +1 -1
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/ import { firebaseAdmin } from "@aglyn/tenant-data-admin";
|
|
17
|
-
import { formatPosHardwareCents, POS_HARDWARE_ORDERS_COLLECTION, posHardwareRefundable } from "../model/pos-hardware.js";
|
|
17
|
+
import { POS_HARDWARE_UNSHIPPED_STATUSES, formatPosHardwareCents, POS_HARDWARE_ORDERS_COLLECTION, posHardwareRefundable } from "../model/pos-hardware.js";
|
|
18
18
|
/*==========================================
|
|
19
19
|
* BEFORE A CLOSURE: WHICH HARDWARE ORDERS IT WILL CANCEL AND REFUND (AGL-4038).
|
|
20
20
|
*
|
|
@@ -61,10 +61,7 @@ import { formatPosHardwareCents, POS_HARDWARE_ORDERS_COLLECTION, posHardwareRefu
|
|
|
61
61
|
if (subject.kind === 'workspace') {
|
|
62
62
|
const orders = firestore.collection('orgs').doc(subject.orgId).collection(POS_HARDWARE_ORDERS_COLLECTION);
|
|
63
63
|
// One equality query per status, as the closure reads them.
|
|
64
|
-
const found = await Promise.all(
|
|
65
|
-
'paid',
|
|
66
|
-
'ordered'
|
|
67
|
-
].map((status)=>orders.where('status', '==', status).get()));
|
|
64
|
+
const found = await Promise.all(POS_HARDWARE_UNSHIPPED_STATUSES.map((status)=>orders.where('status', '==', status).get()));
|
|
68
65
|
return found.flatMap((snapshot)=>snapshot.docs.map((doc)=>({
|
|
69
66
|
orderId: doc.id,
|
|
70
67
|
order: doc.data()
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-closure-notices.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 {\n ClosureNotice,\n ClosureNoticeSource,\n ClosureSubject,\n} from '@aglyn/aglyn/plugin-manager/plugin-closure-notices'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport {\n formatPosHardwareCents,\n POS_HARDWARE_ORDERS_COLLECTION,\n posHardwareRefundable,\n type PosHardwareOrder,\n} from '../model/pos-hardware'\n\n/*==========================================\n * BEFORE A CLOSURE: WHICH HARDWARE ORDERS IT WILL CANCEL AND REFUND (AGL-4038).\n *\n * Deleting a workspace, or closing the account that placed an order, cancels\n * every card reader order that has not shipped — paid, or already placed\n * with Stripe — and refunds it in full (`pos-hardware-closure.ts`). The\n * delete-workspace and close-account screens ask core's closure notices\n * before the confirm, and this answers for the hardware shop: one warning\n * listing each such order, its number, its items and what is refunded.\n *\n * The same orders the closure reads: a workspace's own (`paid` or `ordered`),\n * or every one the person placed in any workspace (by `createdBy`, the\n * collection-group override the account eraser uses). Nothing is held back:\n * the closure goes ahead, and this only says what it will do.\n *=========================================*/\n\n/** The notice's id. */\nexport const POS_HARDWARE_CLOSURE_NOTICE_ID = 'pos-hardware-unshipped-orders'\n\n/** The number a person reads: `HW-` and six characters of the id. */\nfunction orderNumber(orderId: string): string {\n return `HW-${orderId.replace(/^hw_/, '').slice(0, 6).toUpperCase()}`\n}\n\n/** The warning for these unshipped orders, or none when there are none. Pure. */\nexport function posHardwareClosureNotice(\n subject: ClosureSubject['kind'],\n orders: ReadonlyArray<{ orderId: string; order: Pick<PosHardwareOrder, 'status' | 'lines' | 'totalCents'> }>,\n): ClosureNotice[] {\n const unshipped = orders.filter(({ order }) => posHardwareRefundable(order?.status))\n if (!unshipped.length) return []\n const count = unshipped.length\n const one = count === 1\n return [\n {\n id: POS_HARDWARE_CLOSURE_NOTICE_ID,\n severity: 'warning',\n title: one\n ? 'A card reader order will be canceled and refunded'\n : `${count} card reader orders will be canceled and refunded`,\n body:\n subject === 'workspace'\n ? `${one ? 'This order has' : 'These orders have'} not shipped yet. When the workspace is deleted, ` +\n `${one ? 'it is' : 'each is'} canceled and refunded in full, shipping and tax included, to the card ` +\n `it was paid with, and the person who placed ${one ? 'it gets an email' : 'each gets an email'}. ` +\n `Nothing will ship. Keep the workspace if you still want ${one ? 'it' : 'them'}.`\n : `${one ? 'This order you placed has' : 'These orders you placed have'} not shipped yet. When your ` +\n `account is closed, ${one ? 'it is' : 'each is'} canceled and refunded in full, shipping and tax ` +\n `included, to the card it was paid with, and you get an email about ${one ? 'it' : 'each'}. Nothing ` +\n `will ship. Keep your account if you still want ${one ? 'it' : 'them'}.`,\n items: unshipped.map(({ orderId, order }) => ({\n id: orderId,\n primary: `Order ${orderNumber(orderId)}`,\n secondary: (order.lines ?? []).map((line) => `${line.name} × ${line.quantity}`).join(', ') || undefined,\n amount: formatPosHardwareCents(Number(order.totalCents ?? 0)),\n })),\n },\n ]\n}\n\n/** Reads the unshipped orders a closure of `subject` would cancel. */\nasync function unshippedOrders(\n subject: ClosureSubject,\n): Promise<Array<{ orderId: string; order: PosHardwareOrder }>> {\n const firestore = firebaseAdmin.app().firestore()\n if (subject.kind === 'workspace') {\n const orders = firestore.collection('orgs').doc(subject.orgId).collection(POS_HARDWARE_ORDERS_COLLECTION)\n // One equality query per status, as the closure reads them.\n const found = await Promise.all(
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-closure-notices.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 {\n ClosureNotice,\n ClosureNoticeSource,\n ClosureSubject,\n} from '@aglyn/aglyn/plugin-manager/plugin-closure-notices'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport {\n POS_HARDWARE_UNSHIPPED_STATUSES,\n formatPosHardwareCents,\n POS_HARDWARE_ORDERS_COLLECTION,\n posHardwareRefundable,\n type PosHardwareOrder,\n} from '../model/pos-hardware'\n\n/*==========================================\n * BEFORE A CLOSURE: WHICH HARDWARE ORDERS IT WILL CANCEL AND REFUND (AGL-4038).\n *\n * Deleting a workspace, or closing the account that placed an order, cancels\n * every card reader order that has not shipped — paid, or already placed\n * with Stripe — and refunds it in full (`pos-hardware-closure.ts`). The\n * delete-workspace and close-account screens ask core's closure notices\n * before the confirm, and this answers for the hardware shop: one warning\n * listing each such order, its number, its items and what is refunded.\n *\n * The same orders the closure reads: a workspace's own (`paid` or `ordered`),\n * or every one the person placed in any workspace (by `createdBy`, the\n * collection-group override the account eraser uses). Nothing is held back:\n * the closure goes ahead, and this only says what it will do.\n *=========================================*/\n\n/** The notice's id. */\nexport const POS_HARDWARE_CLOSURE_NOTICE_ID = 'pos-hardware-unshipped-orders'\n\n/** The number a person reads: `HW-` and six characters of the id. */\nfunction orderNumber(orderId: string): string {\n return `HW-${orderId.replace(/^hw_/, '').slice(0, 6).toUpperCase()}`\n}\n\n/** The warning for these unshipped orders, or none when there are none. Pure. */\nexport function posHardwareClosureNotice(\n subject: ClosureSubject['kind'],\n orders: ReadonlyArray<{ orderId: string; order: Pick<PosHardwareOrder, 'status' | 'lines' | 'totalCents'> }>,\n): ClosureNotice[] {\n const unshipped = orders.filter(({ order }) => posHardwareRefundable(order?.status))\n if (!unshipped.length) return []\n const count = unshipped.length\n const one = count === 1\n return [\n {\n id: POS_HARDWARE_CLOSURE_NOTICE_ID,\n severity: 'warning',\n title: one\n ? 'A card reader order will be canceled and refunded'\n : `${count} card reader orders will be canceled and refunded`,\n body:\n subject === 'workspace'\n ? `${one ? 'This order has' : 'These orders have'} not shipped yet. When the workspace is deleted, ` +\n `${one ? 'it is' : 'each is'} canceled and refunded in full, shipping and tax included, to the card ` +\n `it was paid with, and the person who placed ${one ? 'it gets an email' : 'each gets an email'}. ` +\n `Nothing will ship. Keep the workspace if you still want ${one ? 'it' : 'them'}.`\n : `${one ? 'This order you placed has' : 'These orders you placed have'} not shipped yet. When your ` +\n `account is closed, ${one ? 'it is' : 'each is'} canceled and refunded in full, shipping and tax ` +\n `included, to the card it was paid with, and you get an email about ${one ? 'it' : 'each'}. Nothing ` +\n `will ship. Keep your account if you still want ${one ? 'it' : 'them'}.`,\n items: unshipped.map(({ orderId, order }) => ({\n id: orderId,\n primary: `Order ${orderNumber(orderId)}`,\n secondary: (order.lines ?? []).map((line) => `${line.name} × ${line.quantity}`).join(', ') || undefined,\n amount: formatPosHardwareCents(Number(order.totalCents ?? 0)),\n })),\n },\n ]\n}\n\n/** Reads the unshipped orders a closure of `subject` would cancel. */\nasync function unshippedOrders(\n subject: ClosureSubject,\n): Promise<Array<{ orderId: string; order: PosHardwareOrder }>> {\n const firestore = firebaseAdmin.app().firestore()\n if (subject.kind === 'workspace') {\n const orders = firestore.collection('orgs').doc(subject.orgId).collection(POS_HARDWARE_ORDERS_COLLECTION)\n // One equality query per status, as the closure reads them.\n const found = await Promise.all(POS_HARDWARE_UNSHIPPED_STATUSES.map((status) => orders.where('status', '==', status).get()))\n return found.flatMap((snapshot) =>\n snapshot.docs.map((doc: { id: string; data: () => unknown }) => ({ orderId: doc.id, order: doc.data() as PosHardwareOrder })),\n )\n }\n const placed = await firestore.collectionGroup(POS_HARDWARE_ORDERS_COLLECTION).where('createdBy', '==', subject.uid).get()\n return placed.docs.map((doc: { id: string; data: () => unknown }) => ({ orderId: doc.id, order: doc.data() as PosHardwareOrder }))\n}\n\n/** The hardware shop's closure notices, as the declarations register them. */\nexport const posHardwareClosureNoticeSource: ClosureNoticeSource = {\n async notices(subject) {\n return posHardwareClosureNotice(subject.kind, await unshippedOrders(subject))\n },\n}\n"],"names":["firebaseAdmin","POS_HARDWARE_UNSHIPPED_STATUSES","formatPosHardwareCents","POS_HARDWARE_ORDERS_COLLECTION","posHardwareRefundable","POS_HARDWARE_CLOSURE_NOTICE_ID","orderNumber","orderId","replace","slice","toUpperCase","posHardwareClosureNotice","subject","orders","unshipped","filter","order","status","length","count","one","id","severity","title","body","items","map","primary","secondary","lines","line","name","quantity","join","undefined","amount","Number","totalCents","unshippedOrders","firestore","app","kind","collection","doc","orgId","found","Promise","all","where","get","flatMap","snapshot","docs","data","placed","collectionGroup","uid","posHardwareClosureNoticeSource","notices"],"mappings":"AAAA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AI;QAAuB,CAAA;AACjI;AAEA,4EAA4E,GAC5E,OAAO,MAAMI,iCAAsD;IACjE,MAAMC,SAAQ9C,OAAO;QACnB,OAAOD,yBAAyBC,QAAQ6B,IAAI,EAAE,MAAMH,gBAAgB1B;IACtE;AACF,EAAC"}
|
|
@@ -16,13 +16,10 @@
|
|
|
16
16
|
*/ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
17
17
|
import { firebaseAdmin } from "@aglyn/tenant-data-admin";
|
|
18
18
|
import { addAdminAudit } from "@aglyn/tenant-data-admin/server/admin-audit-write";
|
|
19
|
-
import { POS_HARDWARE_ORDERS_COLLECTION } from "../model/pos-hardware.js";
|
|
19
|
+
import { POS_HARDWARE_ORDERS_COLLECTION, POS_HARDWARE_UNSHIPPED_STATUSES } from "../model/pos-hardware.js";
|
|
20
20
|
import { cancelAndRefundPosHardwareOrder } from "./pos-hardware-cancel.js";
|
|
21
21
|
import { raisePosHardwareCanceledAfterOrderingAlert, raisePosHardwareRefundFailedAlert, sendPosHardwareEmailOnce } from "./pos-hardware-notify.js";
|
|
22
|
-
/** The unshipped statuses a closure cancels. */ const UNSHIPPED =
|
|
23
|
-
'paid',
|
|
24
|
-
'ordered'
|
|
25
|
-
];
|
|
22
|
+
/** The unshipped statuses a closure cancels: paid, ordered, or received and being set up. */ const UNSHIPPED = POS_HARDWARE_UNSHIPPED_STATUSES;
|
|
26
23
|
/** The audit row's actor: the closure, never a person. */ const CLOSURE_ACTOR = {
|
|
27
24
|
'workspace-closed': 'system:workspace-closed',
|
|
28
25
|
'account-closed': 'system:account-closed'
|
|
@@ -77,7 +74,7 @@ import { raisePosHardwareCanceledAfterOrderingAlert, raisePosHardwareRefundFaile
|
|
|
77
74
|
// Once between this and the staff page: a staff cancel that already
|
|
78
75
|
// told the buyer is not told again (AGL-4038).
|
|
79
76
|
await sendPosHardwareEmailOnce('canceled', orderId, result.order);
|
|
80
|
-
if (result.before.status === 'ordered') {
|
|
77
|
+
if (result.before.status === 'ordered' || result.before.status === 'received') {
|
|
81
78
|
await raisePosHardwareCanceledAfterOrderingAlert(orderId, result.order, reason);
|
|
82
79
|
}
|
|
83
80
|
return 'canceled';
|
|
@@ -108,7 +105,7 @@ import { raisePosHardwareCanceledAfterOrderingAlert, raisePosHardwareRefundFaile
|
|
|
108
105
|
const outcome = await closeUnshippedPosHardwareOrder(order.orgId, orderId, reason, order);
|
|
109
106
|
if (outcome === 'canceled') {
|
|
110
107
|
counts.hardwareOrdersCanceled += 1;
|
|
111
|
-
if (order.status === 'ordered') counts.hardwareOrdersPlacedWithStripe += 1;
|
|
108
|
+
if (order.status === 'ordered' || order.status === 'received') counts.hardwareOrdersPlacedWithStripe += 1;
|
|
112
109
|
}
|
|
113
110
|
if (outcome === 'failed') counts.hardwareRefundsFailed += 1;
|
|
114
111
|
}
|
|
@@ -139,7 +136,7 @@ import { raisePosHardwareCanceledAfterOrderingAlert, raisePosHardwareRefundFaile
|
|
|
139
136
|
if (dryRun) {
|
|
140
137
|
return {
|
|
141
138
|
hardwareOrdersCanceled: unshipped.length,
|
|
142
|
-
hardwareOrdersPlacedWithStripe: unshipped.filter(({ order })=>order.status === 'ordered').length,
|
|
139
|
+
hardwareOrdersPlacedWithStripe: unshipped.filter(({ order })=>order.status === 'ordered' || order.status === 'received').length,
|
|
143
140
|
hardwareRefundsFailed: 0
|
|
144
141
|
};
|
|
145
142
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-closure.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 {\n PluginOrgEraser,\n PluginOrgErasureReport,\n} from '@aglyn/aglyn/plugin-manager/plugin-org-erasure'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { addAdminAudit } from '@aglyn/tenant-data-admin/server/admin-audit-write'\nimport {\n POS_HARDWARE_ORDERS_COLLECTION,\n type PosHardwareCancelReason,\n type PosHardwareOrder,\n} from '../model/pos-hardware'\nimport { cancelAndRefundPosHardwareOrder } from './pos-hardware-cancel'\nimport {\n raisePosHardwareCanceledAfterOrderingAlert,\n raisePosHardwareRefundFailedAlert,\n sendPosHardwareEmailOnce,\n} from './pos-hardware-notify'\n\n/*==========================================\n * A CLOSURE CANCELS EVERY UNSHIPPED HARDWARE ORDER (AGL-4038).\n *\n * When the workspace that bought hardware is deleted, or the account that\n * placed an order is closed, every order of theirs that has not shipped —\n * `paid` or `ordered` — is canceled and refunded in full on the platform's\n * Stripe account, through the staff page's own path and its idempotency\n * (`pos-hardware-cancel.ts`). Then:\n *\n * - the buyer gets the \"canceled and refunded\" email, once: the same claim\n * the staff page sends it under (`sendPosHardwareEmailOnce`);\n * - staff get an alert when the order was already placed with Stripe\n * (`ordered`), because Stripe will still ship it unless someone cancels\n * it there, and another when Stripe refuses the refund;\n * - an `adminAudit` row records the cancel, with the closure as its actor.\n *\n * THE CLOSURE NEVER WAITS ON THIS. A refusal, or a throw, is counted and\n * alerted and the next order is tried; nothing here fails the erasure, so\n * the workspace or the account closes right away whatever Stripe says.\n * Shipped, delivered and registered orders are untouched, and the retained\n * sale record (`posHardwareSales`) records the refund and outlives both.\n *\n * Idempotent: a canceled order is no longer `paid` or `ordered`, so a second\n * closure run finds nothing to refund, sends no second email, raises no\n * second alert and makes no second Stripe call. A run that died after Stripe\n * refunded and before the order said so reads that refund back instead of\n * making another (`pos-hardware-cancel.ts`).\n *=========================================*/\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport type PosHardwareClosureOutcome = 'canceled' | 'already' | 'skipped' | 'failed'\n\n/** The unshipped statuses a closure cancels. */\nconst UNSHIPPED = ['paid', 'ordered'] as const\n\n/** The audit row's actor: the closure, never a person. */\nconst CLOSURE_ACTOR: Record<Exclude<PosHardwareCancelReason, 'staff'>, string> = {\n 'workspace-closed': 'system:workspace-closed',\n 'account-closed': 'system:account-closed',\n}\n\n/**\n * Cancels and refunds one unshipped order because of a closure, and tells\n * the buyer and staff. Never throws. `known` is the order as the closure read\n * it, for the alert should the cancel itself throw.\n */\nexport async function closeUnshippedPosHardwareOrder(\n orgId: string,\n orderId: string,\n reason: Exclude<PosHardwareCancelReason, 'staff'>,\n known?: PosHardwareOrder,\n): Promise<PosHardwareClosureOutcome> {\n try {\n const result = await cancelAndRefundPosHardwareOrder({ orgId, orderId, finalStatus: 'canceled', reason })\n switch (result.outcome) {\n case 'missing':\n case 'not-refundable':\n return 'skipped'\n case 'already':\n // Canceled between the closure's read and the lock: whoever canceled\n // it told the buyer and staff.\n return 'already'\n case 'no-payment':\n await raisePosHardwareRefundFailedAlert(orderId, result.order, reason, 'the order has no payment to refund')\n return 'failed'\n case 'refused':\n await raisePosHardwareRefundFailedAlert(orderId, result.order, reason, result.message)\n return 'failed'\n }\n const firestore = firebaseAdmin.app().firestore()\n await addAdminAudit(firestore, {\n action: 'pos-hardware-order-cancel',\n actorUid: CLOSURE_ACTOR[reason],\n actorEmail: null,\n scope: 'posHardwareOrder',\n target: `orgs/${orgId}/${POS_HARDWARE_ORDERS_COLLECTION}/${orderId}`,\n orgId,\n before: { status: result.before.status },\n after: {\n status: result.order.status,\n refundId: result.order.refundId ?? null,\n refundedCents: result.order.refundedCents ?? null,\n reason,\n },\n at: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n }).catch((error: unknown) => console.error('[pos-hardware] closure audit failed', orderId, error))\n // Once between this and the staff page: a staff cancel that already\n // told the buyer is not told again (AGL-4038).\n await sendPosHardwareEmailOnce('canceled', orderId, result.order)\n if (result.before.status === 'ordered') {\n await raisePosHardwareCanceledAfterOrderingAlert(orderId, result.order, reason)\n }\n return 'canceled'\n } catch (error) {\n console.error('[pos-hardware] closure cancel failed', orderId, error)\n await raisePosHardwareRefundFailedAlert(\n orderId,\n known ?? ({ orgId, hostId: '', status: 'paid', totalCents: 0, stripePaymentIntentId: null } as unknown as PosHardwareOrder),\n reason,\n error instanceof Error ? error.message : String(error),\n )\n return 'failed'\n }\n}\n\n/** What a closure did to one buyer's or workspace's hardware orders. */\nexport interface PosHardwareClosureCounts {\n hardwareOrdersCanceled: number\n /** Of those, the ones staff had already placed with Stripe. */\n hardwareOrdersPlacedWithStripe: number\n /** Unshipped orders whose refund Stripe refused; staff were alerted. */\n hardwareRefundsFailed: number\n}\n\n/**\n * Cancels every order given that is still unshipped. `orders` is read before\n * the call; each order is re-read under the lock by the cancel itself, so one\n * that shipped in between is left alone.\n */\nexport async function closeUnshippedPosHardwareOrders(\n orders: ReadonlyArray<{ orderId: string; order: PosHardwareOrder }>,\n reason: Exclude<PosHardwareCancelReason, 'staff'>,\n): Promise<PosHardwareClosureCounts> {\n const counts: PosHardwareClosureCounts = {\n hardwareOrdersCanceled: 0,\n hardwareOrdersPlacedWithStripe: 0,\n hardwareRefundsFailed: 0,\n }\n for (const { orderId, order } of orders) {\n if (!(UNSHIPPED as readonly string[]).includes(order?.status)) continue\n const outcome = await closeUnshippedPosHardwareOrder(order.orgId, orderId, reason, order)\n if (outcome === 'canceled') {\n counts.hardwareOrdersCanceled += 1\n if (order.status === 'ordered') counts.hardwareOrdersPlacedWithStripe += 1\n }\n if (outcome === 'failed') counts.hardwareRefundsFailed += 1\n }\n return counts\n}\n\nexport interface PosHardwareOrgEraserDeps {\n firestore(): Firestore\n}\n\n/**\n * COMMERCE'S SHARE OF A WORKSPACE ERASURE: the workspace's unshipped hardware\n * orders, canceled and refunded before the erasure deletes them with the\n * workspace. It runs first among the erasure's steps (plugin erasers run\n * while the workspace still stands), so the buyer's email can still name the\n * site and the workspace.\n *\n * A plan (`dryRun`) counts what it would cancel and touches neither Stripe\n * nor Firestore.\n */\nexport function createPosHardwareOrgEraser(deps: PosHardwareOrgEraserDeps): PluginOrgEraser {\n return async ({ orgId, dryRun }): Promise<PluginOrgErasureReport> => {\n const orders = deps.firestore().collection('orgs').doc(orgId).collection(POS_HARDWARE_ORDERS_COLLECTION)\n // One equality query per status, each served by the automatic\n // single-field index: a workspace's hardware orders are few.\n const found = await Promise.all(UNSHIPPED.map((status) => orders.where('status', '==', status).get()))\n const unshipped = found.flatMap((snapshot) =>\n snapshot.docs.map((doc) => ({\n orderId: doc.id,\n // The path names the workspace; the field is what the order says.\n order: { ...(doc.data() as PosHardwareOrder), orgId },\n })),\n )\n if (dryRun) {\n return {\n hardwareOrdersCanceled: unshipped.length,\n hardwareOrdersPlacedWithStripe: unshipped.filter(({ order }) => order.status === 'ordered').length,\n hardwareRefundsFailed: 0,\n }\n }\n return { ...(await closeUnshippedPosHardwareOrders(unshipped, 'workspace-closed')) }\n }\n}\n\n/** The eraser over the platform's own Firestore, as the declarations register it. */\nexport const posHardwareOrgEraser: PluginOrgEraser = (request) =>\n createPosHardwareOrgEraser({ firestore: () => firebaseAdmin.app().firestore() })(request)\n"],"names":["firebaseAdmin","addAdminAudit","POS_HARDWARE_ORDERS_COLLECTION","cancelAndRefundPosHardwareOrder","raisePosHardwareCanceledAfterOrderingAlert","raisePosHardwareRefundFailedAlert","sendPosHardwareEmailOnce","UNSHIPPED","CLOSURE_ACTOR","closeUnshippedPosHardwareOrder","orgId","orderId","reason","known","result","finalStatus","outcome","order","message","firestore","app","action","actorUid","actorEmail","scope","target","before","status","after","refundId","refundedCents","at","FieldValue","serverTimestamp","catch","error","console","hostId","totalCents","stripePaymentIntentId","Error","String","closeUnshippedPosHardwareOrders","orders","counts","hardwareOrdersCanceled","hardwareOrdersPlacedWithStripe","hardwareRefundsFailed","includes","createPosHardwareOrgEraser","deps","dryRun","collection","doc","found","Promise","all","map","where","get","unshipped","flatMap","snapshot","docs","id","data","length","filter","posHard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QAC3E;QACA,IAAI9B,YAAY,UAAU4B,OAAOG,qBAAqB,IAAI;IAC5D;IACA,OAAOH;AACT;AAMA;;;;;;;;;CASC,GACD,OAAO,SAASK,2BAA2BC,IAA8B;IACvE,OAAO,OAAO,EAAExC,KAAK,EAAEyC,MAAM,EAAE;QAC7B,MAAMR,SAASO,KAAK/B,SAAS,GAAGiC,UAAU,CAAC,QAAQC,GAAG,CAAC3C,OAAO0C,UAAU,CAAClD;QACzE,8DAA8D;QAC9D,6DAA6D;QAC7D,MAAMoD,QAAQ,MAAMC,QAAQC,GAAG,CAACjD,UAAUkD,GAAG,CAAC,CAAC9B,SAAWgB,OAAOe,KAAK,CAAC,UAAU,MAAM/B,QAAQgC,GAAG;QAClG,MAAMC,YAAYN,MAAMO,OAAO,CAAC,CAACC,WAC/BA,SAASC,IAAI,CAACN,GAAG,CAAC,CAACJ,MAAS,CAAA;oBAC1B1C,SAAS0C,IAAIW,EAAE;oBACf,kEAAkE;oBAClE/C,OAAO,aAAMoC,IAAIY,IAAI;wBAAyBvD;;gBAChD,CAAA;QAEF,IAAIyC,QAAQ;YACV,OAAO;gBACLN,wBAAwBe,UAAUM,MAAM;gBACxCpB,gCAAgCc,UAAUO,MAAM,CAAC,CAAC,EAAElD,KAAK,EAAE,GAAKA,MAAMU,MAAM,KAAK,WAAWuC,MAAM;gBAClGnB,uBAAuB;YACzB;QACF;QACA,OAAO,aAAM,MAAML,gCAAgCkB,WAAW;IAChE;AACF;AAEA,mFAAmF,GACnF,OAAO,MAAMQ,uBAAwC,CAACC,UACpDpB,2BAA2B;QAAE9B,WAAW,IAAMnB,cAAcoB,GAAG,GAAGD,SAAS;IAAG,GAAGkD,SAAQ"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-closure.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 {\n PluginOrgEraser,\n PluginOrgErasureReport,\n} from '@aglyn/aglyn/plugin-manager/plugin-org-erasure'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { addAdminAudit } from '@aglyn/tenant-data-admin/server/admin-audit-write'\nimport {\n POS_HARDWARE_ORDERS_COLLECTION,\n POS_HARDWARE_UNSHIPPED_STATUSES,\n type PosHardwareCancelReason,\n type PosHardwareOrder,\n} from '../model/pos-hardware'\nimport { cancelAndRefundPosHardwareOrder } from './pos-hardware-cancel'\nimport {\n raisePosHardwareCanceledAfterOrderingAlert,\n raisePosHardwareRefundFailedAlert,\n sendPosHardwareEmailOnce,\n} from './pos-hardware-notify'\n\n/*==========================================\n * A CLOSURE CANCELS EVERY UNSHIPPED HARDWARE ORDER (AGL-4038).\n *\n * When the workspace that bought hardware is deleted, or the account that\n * placed an order is closed, every order of theirs that has not shipped —\n * `paid` or `ordered` — is canceled and refunded in full on the platform's\n * Stripe account, through the staff page's own path and its idempotency\n * (`pos-hardware-cancel.ts`). Then:\n *\n * - the buyer gets the \"canceled and refunded\" email, once: the same claim\n * the staff page sends it under (`sendPosHardwareEmailOnce`);\n * - staff get an alert when the order was already placed with Stripe\n * (`ordered`), because Stripe will still ship it unless someone cancels\n * it there, and another when Stripe refuses the refund;\n * - an `adminAudit` row records the cancel, with the closure as its actor.\n *\n * THE CLOSURE NEVER WAITS ON THIS. A refusal, or a throw, is counted and\n * alerted and the next order is tried; nothing here fails the erasure, so\n * the workspace or the account closes right away whatever Stripe says.\n * Shipped, delivered and registered orders are untouched, and the retained\n * sale record (`posHardwareSales`) records the refund and outlives both.\n *\n * Idempotent: a canceled order is no longer `paid` or `ordered`, so a second\n * closure run finds nothing to refund, sends no second email, raises no\n * second alert and makes no second Stripe call. A run that died after Stripe\n * refunded and before the order said so reads that refund back instead of\n * making another (`pos-hardware-cancel.ts`).\n *=========================================*/\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport type PosHardwareClosureOutcome = 'canceled' | 'already' | 'skipped' | 'failed'\n\n/** The unshipped statuses a closure cancels: paid, ordered, or received and being set up. */\nconst UNSHIPPED = POS_HARDWARE_UNSHIPPED_STATUSES\n\n/** The audit row's actor: the closure, never a person. */\nconst CLOSURE_ACTOR: Record<Exclude<PosHardwareCancelReason, 'staff'>, string> = {\n 'workspace-closed': 'system:workspace-closed',\n 'account-closed': 'system:account-closed',\n}\n\n/**\n * Cancels and refunds one unshipped order because of a closure, and tells\n * the buyer and staff. Never throws. `known` is the order as the closure read\n * it, for the alert should the cancel itself throw.\n */\nexport async function closeUnshippedPosHardwareOrder(\n orgId: string,\n orderId: string,\n reason: Exclude<PosHardwareCancelReason, 'staff'>,\n known?: PosHardwareOrder,\n): Promise<PosHardwareClosureOutcome> {\n try {\n const result = await cancelAndRefundPosHardwareOrder({ orgId, orderId, finalStatus: 'canceled', reason })\n switch (result.outcome) {\n case 'missing':\n case 'not-refundable':\n return 'skipped'\n case 'already':\n // Canceled between the closure's read and the lock: whoever canceled\n // it told the buyer and staff.\n return 'already'\n case 'no-payment':\n await raisePosHardwareRefundFailedAlert(orderId, result.order, reason, 'the order has no payment to refund')\n return 'failed'\n case 'refused':\n await raisePosHardwareRefundFailedAlert(orderId, result.order, reason, result.message)\n return 'failed'\n }\n const firestore = firebaseAdmin.app().firestore()\n await addAdminAudit(firestore, {\n action: 'pos-hardware-order-cancel',\n actorUid: CLOSURE_ACTOR[reason],\n actorEmail: null,\n scope: 'posHardwareOrder',\n target: `orgs/${orgId}/${POS_HARDWARE_ORDERS_COLLECTION}/${orderId}`,\n orgId,\n before: { status: result.before.status },\n after: {\n status: result.order.status,\n refundId: result.order.refundId ?? null,\n refundedCents: result.order.refundedCents ?? null,\n reason,\n },\n at: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n }).catch((error: unknown) => console.error('[pos-hardware] closure audit failed', orderId, error))\n // Once between this and the staff page: a staff cancel that already\n // told the buyer is not told again (AGL-4038).\n await sendPosHardwareEmailOnce('canceled', orderId, result.order)\n if (result.before.status === 'ordered' || result.before.status === 'received') {\n await raisePosHardwareCanceledAfterOrderingAlert(orderId, result.order, reason)\n }\n return 'canceled'\n } catch (error) {\n console.error('[pos-hardware] closure cancel failed', orderId, error)\n await raisePosHardwareRefundFailedAlert(\n orderId,\n known ?? ({ orgId, hostId: '', status: 'paid', totalCents: 0, stripePaymentIntentId: null } as unknown as PosHardwareOrder),\n reason,\n error instanceof Error ? error.message : String(error),\n )\n return 'failed'\n }\n}\n\n/** What a closure did to one buyer's or workspace's hardware orders. */\nexport interface PosHardwareClosureCounts {\n hardwareOrdersCanceled: number\n /** Of those, the ones staff had already placed with Stripe. */\n hardwareOrdersPlacedWithStripe: number\n /** Unshipped orders whose refund Stripe refused; staff were alerted. */\n hardwareRefundsFailed: number\n}\n\n/**\n * Cancels every order given that is still unshipped. `orders` is read before\n * the call; each order is re-read under the lock by the cancel itself, so one\n * that shipped in between is left alone.\n */\nexport async function closeUnshippedPosHardwareOrders(\n orders: ReadonlyArray<{ orderId: string; order: PosHardwareOrder }>,\n reason: Exclude<PosHardwareCancelReason, 'staff'>,\n): Promise<PosHardwareClosureCounts> {\n const counts: PosHardwareClosureCounts = {\n hardwareOrdersCanceled: 0,\n hardwareOrdersPlacedWithStripe: 0,\n hardwareRefundsFailed: 0,\n }\n for (const { orderId, order } of orders) {\n if (!(UNSHIPPED as readonly string[]).includes(order?.status)) continue\n const outcome = await closeUnshippedPosHardwareOrder(order.orgId, orderId, reason, order)\n if (outcome === 'canceled') {\n counts.hardwareOrdersCanceled += 1\n if (order.status === 'ordered' || order.status === 'received') counts.hardwareOrdersPlacedWithStripe += 1\n }\n if (outcome === 'failed') counts.hardwareRefundsFailed += 1\n }\n return counts\n}\n\nexport interface PosHardwareOrgEraserDeps {\n firestore(): Firestore\n}\n\n/**\n * COMMERCE'S SHARE OF A WORKSPACE ERASURE: the workspace's unshipped hardware\n * orders, canceled and refunded before the erasure deletes them with the\n * workspace. It runs first among the erasure's steps (plugin erasers run\n * while the workspace still stands), so the buyer's email can still name the\n * site and the workspace.\n *\n * A plan (`dryRun`) counts what it would cancel and touches neither Stripe\n * nor Firestore.\n */\nexport function createPosHardwareOrgEraser(deps: PosHardwareOrgEraserDeps): PluginOrgEraser {\n return async ({ orgId, dryRun }): Promise<PluginOrgErasureReport> => {\n const orders = deps.firestore().collection('orgs').doc(orgId).collection(POS_HARDWARE_ORDERS_COLLECTION)\n // One equality query per status, each served by the automatic\n // single-field index: a workspace's hardware orders are few.\n const found = await Promise.all(UNSHIPPED.map((status) => orders.where('status', '==', status).get()))\n const unshipped = found.flatMap((snapshot) =>\n snapshot.docs.map((doc) => ({\n orderId: doc.id,\n // The path names the workspace; the field is what the order says.\n order: { ...(doc.data() as PosHardwareOrder), orgId },\n })),\n )\n if (dryRun) {\n return {\n hardwareOrdersCanceled: unshipped.length,\n hardwareOrdersPlacedWithStripe: unshipped.filter(({ order }) => order.status === 'ordered' || order.status === 'received').length,\n hardwareRefundsFailed: 0,\n }\n }\n return { ...(await closeUnshippedPosHardwareOrders(unshipped, 'workspace-closed')) }\n }\n}\n\n/** The eraser over the platform's own Firestore, as the declarations register it. */\nexport const posHardwareOrgEraser: PluginOrgEraser = (request) =>\n createPosHardwareOrgEraser({ firestore: () => firebaseAdmin.app().firestore() })(request)\n"],"names":["firebaseAdmin","addAdminAudit","POS_HARDWARE_ORDERS_COLLECTION","POS_HARDWARE_UNSHIPPED_STATUSES","cancelAndRefundPosHardwareOrder","raisePosHardwareCanceledAfterOrderingAlert","raisePosHardwareRefundFailedAlert","sendPosHardwareEmailOnce","UNSHIPPED","CLOSURE_ACTOR","closeUnshippedPosHardwareOrder","orgId","orderId","reason","known","result","finalStatus","outcome","order","message","firestore","app","action","actorUid","actorEmail","scope","target","before","status","after","refundId","refundedCents","at","FieldValue","serverTimestamp","catch","error","console","hostId","totalCents","stripePaymentIntentId","Error","String","closeUnshippedPosHardwareOrders","orders","counts","hardwareOrdersCanceled","hardwareOrdersPlacedWithStripe","hardwareRefundsFailed","includes","createPosHardwareOrgEraser","deps","dryRun","collection","doc","found","Promise","all","map","where","get","unshipped","flatMap","snapshot","docs","id","data","length","filter","posHardwareOrgEraser","request"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAMD,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SAASC,aAAa,QAAQ,oDAAmD;AACjF,SACEC,8BAA8B,EAC9BC,+BAA+B,QAG1B,2BAAuB;AAC9B,SAASC,+BAA+B,QAAQ,2BAAuB;AACvE,SACEC,0CAA0C,EAC1CC,iCAAiC,EACjCC,wBAAwB,QACnB,2BAAuB;AAmC9B,2FAA2F,GAC3F,MAAMC,YAAYL;AAElB,wDAAwD,GACxD,MAAMM,gBAA2E;IAC/E,oBAAoB;IACpB,kBAAkB;AACpB;AAEA;;;;CAIC,GACD,OAAO,eAAeC,+BACpBC,KAAa,EACbC,OAAe,EACfC,MAAiD,EACjDC,KAAwB;IAExB,IAAI;YA4BYC,wBACKA;QA5BnB,MAAMA,SAAS,MAAMX,gCAAgC;YAAEO;YAAOC;YAASI,aAAa;YAAYH;QAAO;QACvG,OAAQE,OAAOE,OAAO;YACpB,KAAK;YACL,KAAK;gBACH,OAAO;YACT,KAAK;gBACH,qEAAqE;gBACrE,+BAA+B;gBAC/B,OAAO;YACT,KAAK;gBACH,MAAMX,kCAAkCM,SAASG,OAAOG,KAAK,EAAEL,QAAQ;gBACvE,OAAO;YACT,KAAK;gBACH,MAAMP,kCAAkCM,SAASG,OAAOG,KAAK,EAAEL,QAAQE,OAAOI,OAAO;gBACrF,OAAO;QACX;QACA,MAAMC,YAAYpB,cAAcqB,GAAG,GAAGD,SAAS;QAC/C,MAAMn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AuB;YACzB;QACF;QACA,OAAO,aAAM,MAAML,gCAAgCkB,WAAW;IAChE;AACF;AAEA,mFAAmF,GACnF,OAAO,MAAMQ,uBAAwC,CAACC,UACpDpB,2BAA2B;QAAE9B,WAAW,IAAMpB,cAAcqB,GAAG,GAAGD,SAAS;IAAG,GAAGkD,SAAQ"}
|
|
@@ -26,7 +26,8 @@ export type InPersonRecordOutcome = {
|
|
|
26
26
|
/** How many marked sales one sweep records at most. */
|
|
27
27
|
export declare const IN_PERSON_SWEEP_LIMIT = 25;
|
|
28
28
|
/**
|
|
29
|
-
* Records the hardware order of one
|
|
29
|
+
* Records the hardware order of one sale on the seller store, at its
|
|
30
|
+
* register or online (AGL-4038), once.
|
|
30
31
|
* Never throws for a sale that is not one: it says why it did nothing.
|
|
31
32
|
*/
|
|
32
33
|
export declare function recordInPersonPosHardwareSale(hostId: string, registerOrderId: string, options?: {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
1
2
|
/**
|
|
2
3
|
* @license
|
|
3
4
|
* Copyright 2026 Aglyn LLC
|
|
@@ -14,6 +15,7 @@
|
|
|
14
15
|
* See the License for the specific language governing permissions and
|
|
15
16
|
* limitations under the License.
|
|
16
17
|
*/ import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
|
|
18
|
+
import { findUserByEmailAcrossPools } from "@aglyn/tenant-data-admin/server/auth-pools";
|
|
17
19
|
import * as CommerceModel from "../model/index.js";
|
|
18
20
|
import { isPosHardwareSkuId, normalizePosHardwareSerial } from "../model/pos-hardware.js";
|
|
19
21
|
import { inPersonPosHardwareOrder, posHardwareRegisterShare } from "../model/pos-hardware-in-person.js";
|
|
@@ -21,6 +23,10 @@ import { hardwareOrdersRef, posHardwareInPersonConfig, posHardwareInPersonOrderI
|
|
|
21
23
|
import { recordPosHardwareOrder } from "./pos-hardware-webhook.js";
|
|
22
24
|
import { posStripeTestMode } from "./pos-stripe.js";
|
|
23
25
|
/** How many marked sales one sweep records at most. */ export const IN_PERSON_SWEEP_LIMIT = 25;
|
|
26
|
+
/** A paid online order's statuses once the store marked it shipped, which still record. */ const SHIPPED_ONLINE = new Set([
|
|
27
|
+
'fulfilled',
|
|
28
|
+
'partially_fulfilled'
|
|
29
|
+
]);
|
|
24
30
|
/** Statuses after which a marked sale can never be paid, so the mark is dropped. */ const NEVER_PAID = new Set([
|
|
25
31
|
'cancelled',
|
|
26
32
|
'canceled',
|
|
@@ -60,12 +66,21 @@ function registerOrderRef(hostId, orderId) {
|
|
|
60
66
|
const profile = await firestore().collection('profiles').doc(ownerUid).get();
|
|
61
67
|
return text(profile.get('stripeAccountId'));
|
|
62
68
|
}
|
|
69
|
+
/** Whether an account already uses this address; an unanswerable lookup reads as yes, so no stray sign-up invitation goes out. */ async function buyerHasAccount(email) {
|
|
70
|
+
try {
|
|
71
|
+
return Boolean(await findUserByEmailAcrossPools(email));
|
|
72
|
+
} catch (error) {
|
|
73
|
+
console.error('[pos-hardware-in-person] account lookup failed', error);
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
63
77
|
/**
|
|
64
|
-
* Records the hardware order of one
|
|
78
|
+
* Records the hardware order of one sale on the seller store, at its
|
|
79
|
+
* register or online (AGL-4038), once.
|
|
65
80
|
* Never throws for a sale that is not one: it says why it did nothing.
|
|
66
81
|
*/ export async function recordInPersonPosHardwareSale(hostId, registerOrderId, options = {}) {
|
|
67
|
-
var _ref, _ref1, _ref2, _ref3, _order_paidAtMs, _text,
|
|
68
|
-
var _order_totals, _order_totals1,
|
|
82
|
+
var _ref, _ref1, _ref2, _ref3, _ref4, _order_paidAtMs, _ref5, _order_shippingAddress, _text, _order_hardwareBuyer, _text1, _order_currency;
|
|
83
|
+
var _order_totals, _order_totals1, _order_totals2, _text2, _payments_find, _hardwareOrder_attachment, _hardwareOrder_attachment1;
|
|
69
84
|
const config = options.config === undefined ? posHardwareInPersonConfig() : options.config;
|
|
70
85
|
if (!config) return {
|
|
71
86
|
outcome: 'off'
|
|
@@ -79,9 +94,15 @@ function registerOrderRef(hostId, orderId) {
|
|
|
79
94
|
outcome: 'missing'
|
|
80
95
|
};
|
|
81
96
|
const order = snapshot.data();
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
97
|
+
// An order from the store's own product pages and cart (AGL-4038), rather
|
|
98
|
+
// than its register: it ships, and its buyer is whoever paid online. Its
|
|
99
|
+
// store order may already be marked fulfilled; it was paid all the same.
|
|
100
|
+
const online = order.channel === 'online';
|
|
101
|
+
if (order.status !== 'paid' && !(online && SHIPPED_ONLINE.has(String(order.status)))) {
|
|
102
|
+
return {
|
|
103
|
+
outcome: 'not-paid'
|
|
104
|
+
};
|
|
105
|
+
}
|
|
85
106
|
const lineItems = Array.isArray(order.lineItems) ? order.lineItems : [];
|
|
86
107
|
const productIds = [
|
|
87
108
|
...new Set(lineItems.map((line)=>{
|
|
@@ -102,11 +123,13 @@ function registerOrderRef(hostId, orderId) {
|
|
|
102
123
|
unitAmountCents: Number(line.unitAmountCents)
|
|
103
124
|
};
|
|
104
125
|
});
|
|
105
|
-
const share = posHardwareRegisterShare({
|
|
126
|
+
const share = posHardwareRegisterShare(_extends({
|
|
106
127
|
lines,
|
|
107
128
|
discountCents: Number((_ref = (_order_totals = order.totals) == null ? void 0 : _order_totals.discountCents) != null ? _ref : 0),
|
|
108
129
|
taxCents: Number((_ref1 = (_order_totals1 = order.totals) == null ? void 0 : _order_totals1.taxCents) != null ? _ref1 : 0)
|
|
109
|
-
}
|
|
130
|
+
}, online ? {
|
|
131
|
+
shippingCents: Number((_ref2 = (_order_totals2 = order.totals) == null ? void 0 : _order_totals2.shippingCents) != null ? _ref2 : 0)
|
|
132
|
+
} : {}));
|
|
110
133
|
if (!share) {
|
|
111
134
|
// Marked when it was rung, but no line is hardware now: nothing to record.
|
|
112
135
|
if (order.hardwareSalePending) {
|
|
@@ -127,8 +150,25 @@ function registerOrderRef(hostId, orderId) {
|
|
|
127
150
|
storeTax(hostId),
|
|
128
151
|
storeStripeAccount(hostId)
|
|
129
152
|
]);
|
|
130
|
-
const paidAtMs = Number((
|
|
131
|
-
const
|
|
153
|
+
const paidAtMs = Number((_ref3 = (_ref4 = (_order_paidAtMs = order.paidAtMs) != null ? _order_paidAtMs : order.createdAtMs) != null ? _ref4 : options.now) != null ? _ref3 : Date.now());
|
|
154
|
+
const receiptEmail = (_ref5 = (_text2 = text(order.customerEmail)) == null ? void 0 : _text2.toLowerCase()) != null ? _ref5 : null;
|
|
155
|
+
const shippingAddress = (_order_shippingAddress = order.shippingAddress) != null ? _order_shippingAddress : null;
|
|
156
|
+
const shipName = (_text = text(shippingAddress == null ? void 0 : shippingAddress.name)) != null ? _text : text(order.customerName);
|
|
157
|
+
// Online, the buyer is whoever paid: their address and name, to attach
|
|
158
|
+
// when they sign up or pair a reader, or by staff from To attach.
|
|
159
|
+
const buyer = online ? (_order_hardwareBuyer = order.hardwareBuyer) != null ? _order_hardwareBuyer : _extends({
|
|
160
|
+
uid: null,
|
|
161
|
+
orgId: null,
|
|
162
|
+
hostId: null,
|
|
163
|
+
email: receiptEmail,
|
|
164
|
+
attachedBy: '',
|
|
165
|
+
attachedAtMs: paidAtMs
|
|
166
|
+
}, shipName ? {
|
|
167
|
+
name: shipName
|
|
168
|
+
} : {}, shippingAddress ? {
|
|
169
|
+
address: shippingAddress
|
|
170
|
+
} : {}) : order.hardwareBuyer;
|
|
171
|
+
const hardwareOrder = inPersonPosHardwareOrder(_extends({
|
|
132
172
|
sellerHostId: config.sellerHostId,
|
|
133
173
|
sellerOrgId: config.sellerOrgId,
|
|
134
174
|
registerOrderId,
|
|
@@ -139,9 +179,9 @@ function registerOrderRef(hostId, orderId) {
|
|
|
139
179
|
share,
|
|
140
180
|
paidAtMs,
|
|
141
181
|
tenders: payments.map((payment)=>payment.method),
|
|
142
|
-
paymentLinkSessionId: (
|
|
143
|
-
receiptEmail
|
|
144
|
-
buyer
|
|
182
|
+
paymentLinkSessionId: (_text1 = text((_payments_find = payments.find((payment)=>payment.checkoutSessionId)) == null ? void 0 : _payments_find.checkoutSessionId)) != null ? _text1 : text(order.checkoutSessionId),
|
|
183
|
+
receiptEmail,
|
|
184
|
+
buyer,
|
|
145
185
|
termsAcceptance: order.hardwareTermsAcceptance,
|
|
146
186
|
serials: (Array.isArray(order.hardwareSerials) ? order.hardwareSerials : []).map(normalizePosHardwareSerial).filter(Boolean),
|
|
147
187
|
taxRegion: tax.region,
|
|
@@ -151,7 +191,13 @@ function registerOrderRef(hostId, orderId) {
|
|
|
151
191
|
// deployment's, so a test deployment's booth is never a real sale.
|
|
152
192
|
livemode: livemodes.length ? livemodes.every(Boolean) : !posStripeTestMode(),
|
|
153
193
|
currency: String((_order_currency = order.currency) != null ? _order_currency : 'usd').toLowerCase()
|
|
154
|
-
}
|
|
194
|
+
}, online ? {
|
|
195
|
+
storefront: {
|
|
196
|
+
name: shipName,
|
|
197
|
+
phone: text(order.customerPhone),
|
|
198
|
+
address: shippingAddress
|
|
199
|
+
}
|
|
200
|
+
} : {}));
|
|
155
201
|
const { created } = await recordPosHardwareOrder(orderId, hardwareOrder);
|
|
156
202
|
// The mark comes off once the order exists, by this call or an earlier one.
|
|
157
203
|
await orderRef.set({
|
|
@@ -160,10 +206,19 @@ function registerOrderRef(hostId, orderId) {
|
|
|
160
206
|
}, {
|
|
161
207
|
merge: true
|
|
162
208
|
});
|
|
209
|
+
if (created && online) {
|
|
210
|
+
// Staff prepare and ship it: the same alert a Hardware card order raises.
|
|
211
|
+
await (await import("./pos-hardware-notify.js")).raisePosHardwareOrderAlert(orderId, hardwareOrder);
|
|
212
|
+
}
|
|
163
213
|
// A buyer with no account, named at the register while the sale was open,
|
|
164
|
-
// is invited to sign up now that there is an order to point them at.
|
|
214
|
+
// is invited to sign up now that there is an order to point them at. One
|
|
215
|
+
// who paid online is invited only when no account has their address: one
|
|
216
|
+
// that does is attached by staff from To attach, or by pairing a reader.
|
|
165
217
|
if (created && ((_hardwareOrder_attachment = hardwareOrder.attachment) == null ? void 0 : _hardwareOrder_attachment.state) === 'pending' && hardwareOrder.attachment.email) {
|
|
166
|
-
|
|
218
|
+
const hasAccount = online && await buyerHasAccount(hardwareOrder.attachment.email);
|
|
219
|
+
if (!hasAccount) {
|
|
220
|
+
await (await import("./pos-hardware-attach.js")).invitePendingBuyer(orderId, hardwareOrder.orgId, hardwareOrder);
|
|
221
|
+
}
|
|
167
222
|
}
|
|
168
223
|
return {
|
|
169
224
|
outcome: created ? 'recorded' : 'already',
|
|
@@ -197,7 +252,7 @@ function registerOrderRef(hostId, orderId) {
|
|
|
197
252
|
});
|
|
198
253
|
continue;
|
|
199
254
|
}
|
|
200
|
-
if (status !== 'paid') continue;
|
|
255
|
+
if (status !== 'paid' && !SHIPPED_ONLINE.has(status)) continue;
|
|
201
256
|
const outcome = await recordInPersonPosHardwareSale(config.sellerHostId, String(doc.id), {
|
|
202
257
|
config
|
|
203
258
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-in-person.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 { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport * as CommerceModel from '../model'\nimport {\n isPosHardwareSkuId,\n normalizePosHardwareSerial,\n type PosHardwareInPersonConfig,\n type PosHardwareOrder,\n type PosHardwareTaxRegion,\n} from '../model/pos-hardware'\nimport {\n inPersonPosHardwareOrder,\n posHardwareRegisterShare,\n type PosHardwareRegisterLine,\n} from '../model/pos-hardware-in-person'\nimport { hardwareOrdersRef, posHardwareInPersonConfig, posHardwareInPersonOrderId } from './pos-hardware'\nimport { recordPosHardwareOrder } from './pos-hardware-webhook'\nimport { posStripeTestMode } from './pos-stripe'\n\n/*==========================================\n * RECORDING A REGISTER SALE OF HARDWARE (AGL-4038).\n *\n * The platform's own store sells a card reader at its register; once the\n * sale is paid this writes the hardware order it becomes — attached to the\n * buyer's workspace when a register user attached one, PENDING on the\n * selling workspace's \"To attach\" list otherwise — and its retained sale\n * record, through the shop's own recorder.\n *\n * ONE SALE IS ONE ORDER. The order's id is derived from the register sale\n * (`posHardwareInPersonOrderId`) and the recorder writes it once by that id,\n * so the completion listener, a replayed webhook, an offline sync and the\n * sweep below can all reach the same sale and only the first writes.\n *\n * NOTHING IS LOST TO A FAILED LISTENER. Listeners on a completed sale are\n * logged and swallowed (the money is already taken), so the sale is marked\n * `hardwareSalePending` when it is written (`pos-hardware-sale-fields.ts`)\n * and the mark is cleared only once the order exists. The sweep records\n * every paid sale still marked, each time the To attach list is read.\n *=========================================*/\n\nexport type InPersonRecordOutcome =\n | { outcome: 'off' | 'not-seller' | 'missing' | 'not-paid' | 'no-hardware' }\n | { outcome: 'recorded' | 'already'; orderId: string; orgId: string; pending: boolean }\n\n/** How many marked sales one sweep records at most. */\nexport const IN_PERSON_SWEEP_LIMIT = 25\n\n/** Statuses after which a marked sale can never be paid, so the mark is dropped. */\nconst NEVER_PAID = new Set(['cancelled', 'canceled', 'voided', 'refunded', 'expired'])\n\nconst text = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() ? value.trim() : null\n\nfunction firestore() {\n return firebaseAdmin.app().firestore()\n}\n\nfunction registerOrderRef(hostId: string, orderId: string) {\n return firestore().collection('hosts').doc(hostId).collection('orders').doc(orderId)\n}\n\n/** Where the store taxes from, and its rate there, from its own tax settings. */\nasync function storeTax(hostId: string): Promise<{ region: PosHardwareTaxRegion | null; ratePct: number | null }> {\n const settings = await firestore().collection('hosts').doc(hostId).collection('settings').doc('store').get()\n const tax = (settings.get('tax') ?? {}) as CommerceModel.TaxSettings\n const origin = tax.origin ?? {}\n const country = text(origin.country)?.toUpperCase() ?? null\n const rate = country ? CommerceModel.resolveTaxRate(tax, origin) : null\n return {\n region: country ? { country, state: text(origin.state)?.toUpperCase() ?? null, postalCode: null } : null,\n ratePct: rate && Number.isFinite(rate.pct) ? rate.pct : null,\n }\n}\n\n/** The store owner's connected Stripe account, where the store's card money goes. */\nasync function storeStripeAccount(hostId: string): Promise<string | null> {\n const owner = await getOrgForHost(hostId).catch(() => null)\n const ownerUid = text((owner?.org as { ownerUid?: unknown } | undefined)?.ownerUid)\n if (!ownerUid) return null\n const profile = await firestore().collection('profiles').doc(ownerUid).get()\n return text(profile.get('stripeAccountId'))\n}\n\n/**\n * Records the hardware order of one register sale on the seller store, once.\n * Never throws for a sale that is not one: it says why it did nothing.\n */\nexport async function recordInPersonPosHardwareSale(\n hostId: string,\n registerOrderId: string,\n options: { offline?: boolean; config?: PosHardwareInPersonConfig | null; now?: number } = {},\n): Promise<InPersonRecordOutcome> {\n const config = options.config === undefined ? posHardwareInPersonConfig() : options.config\n if (!config) return { outcome: 'off' }\n if (hostId !== config.sellerHostId) return { outcome: 'not-seller' }\n const orderRef = registerOrderRef(hostId, registerOrderId)\n const snapshot = await orderRef.get()\n if (!snapshot.exists) return { outcome: 'missing' }\n const order = snapshot.data() as CommerceModel.HostOrder & {\n paidAtMs?: number\n checkoutSessionId?: string\n customerEmail?: string | null\n }\n if (order.status !== 'paid') return { outcome: 'not-paid' }\n\n const lineItems = Array.isArray(order.lineItems) ? order.lineItems : []\n const productIds = [...new Set(lineItems.map((line) => String(line.productId ?? '')).filter(Boolean))]\n const products = new Map(\n (\n await Promise.all(\n productIds.map((id) => firestore().collection('hosts').doc(hostId).collection('products').doc(id).get()),\n )\n ).map((doc: any) => [String(doc.id), doc.exists ? (doc.data() as CommerceModel.HostProduct) : null]),\n )\n const lines: PosHardwareRegisterLine[] = lineItems.map((line) => {\n const sku = products.get(String(line.productId))?.hardwareSku\n return {\n sku: isPosHardwareSkuId(sku) ? sku : null,\n quantity: Number(line.quantity),\n unitAmountCents: Number(line.unitAmountCents),\n }\n })\n const share = posHardwareRegisterShare({\n lines,\n discountCents: Number(order.totals?.discountCents ?? 0),\n taxCents: Number(order.totals?.taxCents ?? 0),\n })\n if (!share) {\n // Marked when it was rung, but no line is hardware now: nothing to record.\n if (order.hardwareSalePending) {\n await orderRef.set({ hardwareSalePending: firebaseAdmin.firestore.FieldValue.delete() }, { merge: true })\n }\n return { outcome: 'no-hardware' }\n }\n\n const orderId = posHardwareInPersonOrderId(hostId, registerOrderId)\n const payments = CommerceModel.orderPayments(order).filter((payment) => payment.status === 'succeeded')\n const livemodes = payments.map((payment) => payment.livemode).filter((mode): mode is boolean => typeof mode === 'boolean')\n const [tax, stripeAccountId] = await Promise.all([storeTax(hostId), storeStripeAccount(hostId)])\n const paidAtMs = Number(order.paidAtMs ?? order.createdAtMs ?? options.now ?? Date.now())\n const hardwareOrder: PosHardwareOrder = inPersonPosHardwareOrder({\n sellerHostId: config.sellerHostId,\n sellerOrgId: config.sellerOrgId,\n registerOrderId,\n number: Number.isFinite(Number(order.number)) ? Number(order.number) : null,\n registerId: text(order.registerId),\n kiosk: order.posSource === 'kiosk',\n offline: options.offline === true || Boolean((order as { offline?: unknown }).offline),\n share,\n paidAtMs,\n tenders: payments.map((payment) => payment.method),\n paymentLinkSessionId:\n text(payments.find((payment) => payment.checkoutSessionId)?.checkoutSessionId) ?? text(order.checkoutSessionId),\n receiptEmail: text(order.customerEmail)?.toLowerCase() ?? null,\n buyer: order.hardwareBuyer,\n termsAcceptance: order.hardwareTermsAcceptance,\n serials: (Array.isArray(order.hardwareSerials) ? order.hardwareSerials : [])\n .map(normalizePosHardwareSerial)\n .filter(Boolean),\n taxRegion: tax.region,\n ratePct: tax.ratePct,\n stripeAccountId,\n // A card payment says which mode it was in; a cash sale takes the\n // deployment's, so a test deployment's booth is never a real sale.\n livemode: livemodes.length ? livemodes.every(Boolean) : !posStripeTestMode(),\n currency: String((order as { currency?: unknown }).currency ?? 'usd').toLowerCase(),\n })\n\n const { created } = await recordPosHardwareOrder(orderId, hardwareOrder)\n // The mark comes off once the order exists, by this call or an earlier one.\n await orderRef.set(\n { hardwareOrderId: orderId, hardwareSalePending: firebaseAdmin.firestore.FieldValue.delete() },\n { merge: true },\n )\n // A buyer with no account, named at the register while the sale was open,\n // is invited to sign up now that there is an order to point them at.\n if (created && hardwareOrder.attachment?.state === 'pending' && hardwareOrder.attachment.email) {\n await (await import('./pos-hardware-attach')).invitePendingBuyer(orderId, hardwareOrder.orgId, hardwareOrder)\n }\n return {\n outcome: created ? 'recorded' : 'already',\n orderId,\n orgId: hardwareOrder.orgId,\n pending: hardwareOrder.attachment?.state === 'pending',\n }\n}\n\n/**\n * Records every paid sale on the seller store that is still marked, at most\n * {@link IN_PERSON_SWEEP_LIMIT} a time, and drops the mark from a sale that\n * can no longer be paid. Never throws: a sale it cannot record stays marked\n * for the next sweep.\n */\nexport async function sweepInPersonPosHardwareSales(\n config: PosHardwareInPersonConfig | null = posHardwareInPersonConfig(),\n): Promise<{ recorded: number; failed: number }> {\n if (!config) return { recorded: 0, failed: 0 }\n const marked = await firestore()\n .collection('hosts')\n .doc(config.sellerHostId)\n .collection('orders')\n .where('hardwareSalePending', '==', true)\n .limit(IN_PERSON_SWEEP_LIMIT)\n .get()\n let recorded = 0\n let failed = 0\n for (const doc of marked.docs as Array<{ id: string; ref: any; get: (field: string) => unknown }>) {\n const status = String(doc.get('status') ?? '')\n try {\n if (NEVER_PAID.has(status)) {\n await doc.ref.set({ hardwareSalePending: firebaseAdmin.firestore.FieldValue.delete() }, { merge: true })\n continue\n }\n if (status !== 'paid') continue\n const outcome = await recordInPersonPosHardwareSale(config.sellerHostId, String(doc.id), { config })\n if (outcome.outcome === 'recorded') recorded += 1\n } catch (error) {\n failed += 1\n console.error('[pos-hardware-in-person] a marked sale could not be recorded', doc.id, error)\n }\n }\n return { recorded, failed }\n}\n\n/** The \"To attach\" list: the selling workspace's pending in-person orders, newest first. */\nexport async function pendingInPersonPosHardwareOrders(\n config: PosHardwareInPersonConfig,\n limit = 50,\n): Promise<Array<{ id: string; order: PosHardwareOrder }>> {\n const snapshot = await hardwareOrdersRef(config.sellerOrgId)\n .where('attachment.state', '==', 'pending')\n .orderBy('createdAtMs', 'desc')\n .limit(limit)\n .get()\n return snapshot.docs.map((doc: any) => ({ id: String(doc.id), order: doc.data() as PosHardwareOrder }))\n}\n\n/**\n * What the completion listener runs for a sale on the seller store. Never\n * throws into a sale: a failure is logged and the sale stays marked for the\n * sweep.\n */\nexport async function recordCompletedSaleHardware(event: {\n hostId: string\n orderId: string\n offline?: boolean\n}): Promise<void> {\n try {\n await recordInPersonPosHardwareSale(event.hostId, event.orderId, { offline: event.offline === true })\n } catch (error) {\n console.error('[pos-hardware-in-person] sale not recorded; the sweep will', event.orderId, error)\n }\n}\n"],"names":["firebaseAdmin","getOrgForHost","CommerceModel","isPosHardwareSkuId","normalizePosHardwareSerial","inPersonPosHardwareOrder","posHardwareRegisterShare","hardwareOrdersRef","posHardwareInPersonConfig","posHardwareInPersonOrderId","recordPosHardwareOrder","posStripeTestMode","IN_PERSON_SWEEP_LIMIT","NEVER_PAID","Set","text","value","trim","firestore","app","registerOrderRef","hostId","orderId","collection","doc","storeTax","settings","tax","get","origin","country","toUpperCase","rate","resolveTaxRate","region","state","postalCode","ratePct","Number","isFinite","pct","storeStripeAccount","owner","catch","ownerUid","org","profile","recordInPersonPosHardwareSale","registerOrderId","options","order","payments","hardwareOrder","config","undefined","outcome","sellerHostId","orderRef","snapshot","exists","data","status","lineItems","Array","isArray","productIds","map","line","String","productId","filter","Boolean","products","Map","Promise","all","id","lines","sku","hardwareSku","quantity","unitAmountCents","share","discountCents","totals","taxCents","hardwareSalePending","set","FieldValue","delete","merge","orderPayments","payment","livemodes","livemode","mode","stripeAccountId","paidAtMs","createdAtMs","now","Date","sellerOrgId","number","registerId","kiosk","posSource","offline","tenders","method","paymentLinkSessionId","find","checkoutSessionId","receiptEmail","customerEmail","toLowerCase","buyer","hardwareBuyer","termsAcceptance","hardwareTermsAcceptance","serials","hardwareSerials","taxRegion","length","every","currency","created","hardwareOrderId","attachment","email","invitePendingBuyer","orgId","pending","sweepInPersonPosHardwareSales","recorded","failed","marked","where","limit","docs","has","ref","error","console","pendingInPersonPosHardwareOrders","orderBy","recordCompletedSaleHardware","event"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,YAAYC,mBAAmB,oBAAU;AACzC,SACEC,kBAAkB,EAClBC,0BAA0B,QAIrB,2BAAuB;AAC9B,SACEC,wBAAwB,EACxBC,wBAAwB,QAEnB,qCAAiC;AACxC,SAASC,iBAAiB,EAAEC,yBAAyB,EAAEC,0BAA0B,QAAQ,oBAAgB;AACzG,SAASC,sBAAsB,QAAQ,4BAAwB;AAC/D,SAASC,iBAAiB,QAAQ,kBAAc;AA2BhD,qDAAqD,GACrD,OAAO,MAAMC,wBAAwB,GAAE;AAEvC,kFAAkF,GAClF,MAAMC,aAAa,IAAIC,IAAI;IAAC;IAAa;IAAY;IAAU;IAAY;CAAU;AAErF,MAAMC,OAAO,CAACC,QACZ,OAAOA,UAAU,YAAYA,MAAMC,IAAI,KAAKD,MAAMC,IAAI,KAAK;AAE7D,SAASC;IACP,OAAOlB,cAAcmB,GAAG,GAAGD,SAAS;AACtC;AAEA,SAASE,iBAAiBC,MAAc,EAAEC,OAAe;IACvD,OAAOJ,YAAYK,UAAU,CAAC,SAASC,GAAG,CAACH,QAAQE,UAAU,CAAC,UAAUC,GAAG,CAACF;AAC9E;AAEA,+EAA+E,GAC/E,eAAeG,SAASJ,MAAc;QAEvBK,eACEC;QACCZ,OAGsBA;IANtC,MAAMW,WAAW,MAAMR,YAAYK,UAAU,CAAC,SAASC,GAAG,CAACH,QAAQE,UAAU,CAAC,Y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AUC;IAAO;AAC5B;AAEA,0FAA0F,GAC1F,OAAO,eAAeS,iCACpB1F,MAAiC,EACjCoF,QAAQ,EAAE;IAEV,MAAM/E,WAAW,MAAMnD,kBAAkB8C,OAAOgD,WAAW,EACxDmC,KAAK,CAAC,oBAAoB,MAAM,WAChCQ,OAAO,CAAC,eAAe,QACvBP,KAAK,CAACA,OACN7G,GAAG;IACN,OAAO8B,SAASgF,IAAI,CAACxE,GAAG,CAAC,CAAC1C,MAAc,CAAA;YAAEoD,IAAIR,OAAO5C,IAAIoD,EAAE;YAAG1B,OAAO1B,IAAIoC,IAAI;QAAuB,CAAA;AACtG;AAEA;;;;CAIC,GACD,OAAO,eAAeqF,4BAA4BC,KAIjD;IACC,IAAI;QACF,MAAMnG,8BAA8BmG,MAAM7H,MAAM,EAAE6H,MAAM5H,OAAO,EAAE;YAAEoF,SAASwC,MAAMxC,OAAO,KAAK;QAAK;IACrG,EAAE,OAAOmC,OAAO;QACdC,QAAQD,KAAK,CAAC,8DAA8DK,MAAM5H,OAAO,EAAEuH;IAC7F;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-in-person.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 { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { findUserByEmailAcrossPools } from '@aglyn/tenant-data-admin/server/auth-pools'\nimport * as CommerceModel from '../model'\nimport {\n isPosHardwareSkuId,\n normalizePosHardwareSerial,\n type PosHardwareInPersonConfig,\n type PosHardwareOrder,\n type PosHardwareTaxRegion,\n} from '../model/pos-hardware'\nimport {\n inPersonPosHardwareOrder,\n posHardwareRegisterShare,\n type PosHardwareRegisterLine,\n} from '../model/pos-hardware-in-person'\nimport { hardwareOrdersRef, posHardwareInPersonConfig, posHardwareInPersonOrderId } from './pos-hardware'\nimport { recordPosHardwareOrder } from './pos-hardware-webhook'\nimport { posStripeTestMode } from './pos-stripe'\n\n/*==========================================\n * RECORDING A REGISTER SALE OF HARDWARE (AGL-4038).\n *\n * The platform's own store sells a card reader at its register; once the\n * sale is paid this writes the hardware order it becomes — attached to the\n * buyer's workspace when a register user attached one, PENDING on the\n * selling workspace's \"To attach\" list otherwise — and its retained sale\n * record, through the shop's own recorder.\n *\n * ONE SALE IS ONE ORDER. The order's id is derived from the register sale\n * (`posHardwareInPersonOrderId`) and the recorder writes it once by that id,\n * so the completion listener, a replayed webhook, an offline sync and the\n * sweep below can all reach the same sale and only the first writes.\n *\n * NOTHING IS LOST TO A FAILED LISTENER. Listeners on a completed sale are\n * logged and swallowed (the money is already taken), so the sale is marked\n * `hardwareSalePending` when it is written (`pos-hardware-sale-fields.ts`)\n * and the mark is cleared only once the order exists. The sweep records\n * every paid sale still marked, each time the To attach list is read.\n *=========================================*/\n\nexport type InPersonRecordOutcome =\n | { outcome: 'off' | 'not-seller' | 'missing' | 'not-paid' | 'no-hardware' }\n | { outcome: 'recorded' | 'already'; orderId: string; orgId: string; pending: boolean }\n\n/** How many marked sales one sweep records at most. */\nexport const IN_PERSON_SWEEP_LIMIT = 25\n\n/** A paid online order's statuses once the store marked it shipped, which still record. */\nconst SHIPPED_ONLINE = new Set(['fulfilled', 'partially_fulfilled'])\n\n/** Statuses after which a marked sale can never be paid, so the mark is dropped. */\nconst NEVER_PAID = new Set(['cancelled', 'canceled', 'voided', 'refunded', 'expired'])\n\nconst text = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() ? value.trim() : null\n\nfunction firestore() {\n return firebaseAdmin.app().firestore()\n}\n\nfunction registerOrderRef(hostId: string, orderId: string) {\n return firestore().collection('hosts').doc(hostId).collection('orders').doc(orderId)\n}\n\n/** Where the store taxes from, and its rate there, from its own tax settings. */\nasync function storeTax(hostId: string): Promise<{ region: PosHardwareTaxRegion | null; ratePct: number | null }> {\n const settings = await firestore().collection('hosts').doc(hostId).collection('settings').doc('store').get()\n const tax = (settings.get('tax') ?? {}) as CommerceModel.TaxSettings\n const origin = tax.origin ?? {}\n const country = text(origin.country)?.toUpperCase() ?? null\n const rate = country ? CommerceModel.resolveTaxRate(tax, origin) : null\n return {\n region: country ? { country, state: text(origin.state)?.toUpperCase() ?? null, postalCode: null } : null,\n ratePct: rate && Number.isFinite(rate.pct) ? rate.pct : null,\n }\n}\n\n/** The store owner's connected Stripe account, where the store's card money goes. */\nasync function storeStripeAccount(hostId: string): Promise<string | null> {\n const owner = await getOrgForHost(hostId).catch(() => null)\n const ownerUid = text((owner?.org as { ownerUid?: unknown } | undefined)?.ownerUid)\n if (!ownerUid) return null\n const profile = await firestore().collection('profiles').doc(ownerUid).get()\n return text(profile.get('stripeAccountId'))\n}\n\n/** Whether an account already uses this address; an unanswerable lookup reads as yes, so no stray sign-up invitation goes out. */\nasync function buyerHasAccount(email: string): Promise<boolean> {\n try {\n return Boolean(await findUserByEmailAcrossPools(email))\n } catch (error) {\n console.error('[pos-hardware-in-person] account lookup failed', error)\n return true\n }\n}\n\n/**\n * Records the hardware order of one sale on the seller store, at its\n * register or online (AGL-4038), once.\n * Never throws for a sale that is not one: it says why it did nothing.\n */\nexport async function recordInPersonPosHardwareSale(\n hostId: string,\n registerOrderId: string,\n options: { offline?: boolean; config?: PosHardwareInPersonConfig | null; now?: number } = {},\n): Promise<InPersonRecordOutcome> {\n const config = options.config === undefined ? posHardwareInPersonConfig() : options.config\n if (!config) return { outcome: 'off' }\n if (hostId !== config.sellerHostId) return { outcome: 'not-seller' }\n const orderRef = registerOrderRef(hostId, registerOrderId)\n const snapshot = await orderRef.get()\n if (!snapshot.exists) return { outcome: 'missing' }\n const order = snapshot.data() as CommerceModel.HostOrder & {\n paidAtMs?: number\n checkoutSessionId?: string\n customerEmail?: string | null\n }\n // An order from the store's own product pages and cart (AGL-4038), rather\n // than its register: it ships, and its buyer is whoever paid online. Its\n // store order may already be marked fulfilled; it was paid all the same.\n const online = order.channel === 'online'\n if (order.status !== 'paid' && !(online && SHIPPED_ONLINE.has(String(order.status)))) {\n return { outcome: 'not-paid' }\n }\n\n const lineItems = Array.isArray(order.lineItems) ? order.lineItems : []\n const productIds = [...new Set(lineItems.map((line) => String(line.productId ?? '')).filter(Boolean))]\n const products = new Map(\n (\n await Promise.all(\n productIds.map((id) => firestore().collection('hosts').doc(hostId).collection('products').doc(id).get()),\n )\n ).map((doc: any) => [String(doc.id), doc.exists ? (doc.data() as CommerceModel.HostProduct) : null]),\n )\n const lines: PosHardwareRegisterLine[] = lineItems.map((line) => {\n const sku = products.get(String(line.productId))?.hardwareSku\n return {\n sku: isPosHardwareSkuId(sku) ? sku : null,\n quantity: Number(line.quantity),\n unitAmountCents: Number(line.unitAmountCents),\n }\n })\n const share = posHardwareRegisterShare({\n lines,\n discountCents: Number(order.totals?.discountCents ?? 0),\n taxCents: Number(order.totals?.taxCents ?? 0),\n ...(online ? { shippingCents: Number(order.totals?.shippingCents ?? 0) } : {}),\n })\n if (!share) {\n // Marked when it was rung, but no line is hardware now: nothing to record.\n if (order.hardwareSalePending) {\n await orderRef.set({ hardwareSalePending: firebaseAdmin.firestore.FieldValue.delete() }, { merge: true })\n }\n return { outcome: 'no-hardware' }\n }\n\n const orderId = posHardwareInPersonOrderId(hostId, registerOrderId)\n const payments = CommerceModel.orderPayments(order).filter((payment) => payment.status === 'succeeded')\n const livemodes = payments.map((payment) => payment.livemode).filter((mode): mode is boolean => typeof mode === 'boolean')\n const [tax, stripeAccountId] = await Promise.all([storeTax(hostId), storeStripeAccount(hostId)])\n const paidAtMs = Number(order.paidAtMs ?? order.createdAtMs ?? options.now ?? Date.now())\n const receiptEmail = text(order.customerEmail)?.toLowerCase() ?? null\n const shippingAddress = order.shippingAddress ?? null\n const shipName = text(shippingAddress?.name) ?? text(order.customerName)\n // Online, the buyer is whoever paid: their address and name, to attach\n // when they sign up or pair a reader, or by staff from To attach.\n const buyer = online\n ? (order.hardwareBuyer ?? {\n uid: null,\n orgId: null,\n hostId: null,\n email: receiptEmail,\n attachedBy: '',\n attachedAtMs: paidAtMs,\n ...(shipName ? { name: shipName } : {}),\n ...(shippingAddress ? { address: shippingAddress as never } : {}),\n })\n : order.hardwareBuyer\n const hardwareOrder: PosHardwareOrder = inPersonPosHardwareOrder({\n sellerHostId: config.sellerHostId,\n sellerOrgId: config.sellerOrgId,\n registerOrderId,\n number: Number.isFinite(Number(order.number)) ? Number(order.number) : null,\n registerId: text(order.registerId),\n kiosk: order.posSource === 'kiosk',\n offline: options.offline === true || Boolean((order as { offline?: unknown }).offline),\n share,\n paidAtMs,\n tenders: payments.map((payment) => payment.method),\n paymentLinkSessionId:\n text(payments.find((payment) => payment.checkoutSessionId)?.checkoutSessionId) ?? text(order.checkoutSessionId),\n receiptEmail,\n buyer,\n termsAcceptance: order.hardwareTermsAcceptance,\n serials: (Array.isArray(order.hardwareSerials) ? order.hardwareSerials : [])\n .map(normalizePosHardwareSerial)\n .filter(Boolean),\n taxRegion: tax.region,\n ratePct: tax.ratePct,\n stripeAccountId,\n // A card payment says which mode it was in; a cash sale takes the\n // deployment's, so a test deployment's booth is never a real sale.\n livemode: livemodes.length ? livemodes.every(Boolean) : !posStripeTestMode(),\n currency: String((order as { currency?: unknown }).currency ?? 'usd').toLowerCase(),\n ...(online\n ? { storefront: { name: shipName, phone: text(order.customerPhone), address: shippingAddress } }\n : {}),\n })\n\n const { created } = await recordPosHardwareOrder(orderId, hardwareOrder)\n // The mark comes off once the order exists, by this call or an earlier one.\n await orderRef.set(\n { hardwareOrderId: orderId, hardwareSalePending: firebaseAdmin.firestore.FieldValue.delete() },\n { merge: true },\n )\n if (created && online) {\n // Staff prepare and ship it: the same alert a Hardware card order raises.\n await (await import('./pos-hardware-notify')).raisePosHardwareOrderAlert(orderId, hardwareOrder)\n }\n // A buyer with no account, named at the register while the sale was open,\n // is invited to sign up now that there is an order to point them at. One\n // who paid online is invited only when no account has their address: one\n // that does is attached by staff from To attach, or by pairing a reader.\n if (created && hardwareOrder.attachment?.state === 'pending' && hardwareOrder.attachment.email) {\n const hasAccount = online && (await buyerHasAccount(hardwareOrder.attachment.email))\n if (!hasAccount) {\n await (await import('./pos-hardware-attach')).invitePendingBuyer(orderId, hardwareOrder.orgId, hardwareOrder)\n }\n }\n return {\n outcome: created ? 'recorded' : 'already',\n orderId,\n orgId: hardwareOrder.orgId,\n pending: hardwareOrder.attachment?.state === 'pending',\n }\n}\n\n/**\n * Records every paid sale on the seller store that is still marked, at most\n * {@link IN_PERSON_SWEEP_LIMIT} a time, and drops the mark from a sale that\n * can no longer be paid. Never throws: a sale it cannot record stays marked\n * for the next sweep.\n */\nexport async function sweepInPersonPosHardwareSales(\n config: PosHardwareInPersonConfig | null = posHardwareInPersonConfig(),\n): Promise<{ recorded: number; failed: number }> {\n if (!config) return { recorded: 0, failed: 0 }\n const marked = await firestore()\n .collection('hosts')\n .doc(config.sellerHostId)\n .collection('orders')\n .where('hardwareSalePending', '==', true)\n .limit(IN_PERSON_SWEEP_LIMIT)\n .get()\n let recorded = 0\n let failed = 0\n for (const doc of marked.docs as Array<{ id: string; ref: any; get: (field: string) => unknown }>) {\n const status = String(doc.get('status') ?? '')\n try {\n if (NEVER_PAID.has(status)) {\n await doc.ref.set({ hardwareSalePending: firebaseAdmin.firestore.FieldValue.delete() }, { merge: true })\n continue\n }\n if (status !== 'paid' && !SHIPPED_ONLINE.has(status)) continue\n const outcome = await recordInPersonPosHardwareSale(config.sellerHostId, String(doc.id), { config })\n if (outcome.outcome === 'recorded') recorded += 1\n } catch (error) {\n failed += 1\n console.error('[pos-hardware-in-person] a marked sale could not be recorded', doc.id, error)\n }\n }\n return { recorded, failed }\n}\n\n/** The \"To attach\" list: the selling workspace's pending in-person orders, newest first. */\nexport async function pendingInPersonPosHardwareOrders(\n config: PosHardwareInPersonConfig,\n limit = 50,\n): Promise<Array<{ id: string; order: PosHardwareOrder }>> {\n const snapshot = await hardwareOrdersRef(config.sellerOrgId)\n .where('attachment.state', '==', 'pending')\n .orderBy('createdAtMs', 'desc')\n .limit(limit)\n .get()\n return snapshot.docs.map((doc: any) => ({ id: String(doc.id), order: doc.data() as PosHardwareOrder }))\n}\n\n/**\n * What the completion listener runs for a sale on the seller store. Never\n * throws into a sale: a failure is logged and the sale stays marked for the\n * sweep.\n */\nexport async function recordCompletedSaleHardware(event: {\n hostId: string\n orderId: string\n offline?: boolean\n}): Promise<void> {\n try {\n await recordInPersonPosHardwareSale(event.hostId, event.orderId, { offline: event.offline === true })\n } catch (error) {\n console.error('[pos-hardware-in-person] sale not recorded; the sweep will', event.orderId, error)\n }\n}\n"],"names":["firebaseAdmin","getOrgForHost","findUserByEmailAcrossPools","CommerceModel","isPosHardwareSkuId","normalizePosHardwareSerial","inPersonPosHardwareOrder","posHardwareRegisterShare","hardwareOrdersRef","posHardwareInPersonConfig","posHardwareInPersonOrderId","recordPosHardwareOrder","posStripeTestMode","IN_PERSON_SWEEP_LIMIT","SHIPPED_ONLINE","Set","NEVER_PAID","text","value","trim","firestore","app","registerOrderRef","hostId","orderId","collection","doc","storeTax","settings","tax","get","origin","country","toUpperCase","rate","resolveTaxRate","region","state","postalCode","ratePct","Number","isFinite","pct","storeStripeAccount","owner","catch","ownerUid","org","profile","buyerHasAccount","email","Boolean","error","console","recordInPersonPosHardwareSale","registerOrderId","options","order","payments","hardwareOrder","config","undefined","outcome","sellerHostId","orderRef","snapshot","exists","data","online","channel","status","has","String","lineItems","Array","isArray","productIds","map","line","productId","filter","products","Map","Promise","all","id","lines","sku","hardwareSku","quantity","unitAmountCents","share","discountCents","totals","taxCents","shippingCents","hardwareSalePending","set","FieldValue","delete","merge","orderPayments","payment","livemodes","livemode","mode","stripeAccountId","paidAtMs","createdAtMs","now","Date","receiptEmail","customerEmail","toLowerCase","shippingAddress","shipName","name","customerName","buyer","hardwareBuyer","uid","orgId","attachedBy","attachedAtMs","address","sellerOrgId","number","registerId","kiosk","posSource","offline","tenders","method","paymentLinkSessionId","find","checkoutSessionId","termsAcceptance","hardwareTermsAcceptance","serials","hardwareSerials","taxRegion","length","every","currency","storefront","phone","customerPhone","created","hardwareOrderId","raisePosHardwareOrderAlert","attachment","hasAccount","invitePendingBuyer","pending","sweepInPersonPosHardwareSales","recorded","failed","marked","where","limit","docs","ref","pendingInPersonPosHardwareOrders","orderBy","recordCompletedSaleHardware","event"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,0BAA0B,QAAQ,6CAA4C;AACvF,YAAYC,mBAAmB,oBAAU;AACzC,SACEC,kBAAkB,EAClBC,0BAA0B,QAIrB,2BAAuB;AAC9B,SACEC,wBAAwB,EACxBC,wBAAwB,QAEnB,qCAAiC;AACxC,SAASC,iBAAiB,EAAEC,yBAAyB,EAAEC,0BAA0B,QAAQ,oBAAgB;AACzG,SAASC,sBAAsB,QAAQ,4BAAwB;AAC/D,SAASC,iBAAiB,QAAQ,kBAAc;AA2BhD,qDAAqD,GACrD,OAAO,MAAMC,wBAAwB,GAAE;AAEvC,yFAAyF,GACzF,MAAMC,iBAAiB,IAAIC,IAAI;IAAC;IAAa;CAAsB;AAEnE,kFAAkF,GAClF,MAAMC,aAAa,IAAID,IAAI;IAAC;IAAa;IAAY;IAAU;IAAY;CAAU;AAErF,MAAME,OAAO,CAACC,QACZ,OAAOA,UAAU,YAAYA,MAAMC,IAAI,KAAKD,MAAMC,IAAI,KAAK;AAE7D,SAASC;IACP,OAAOpB,cAAcqB,GAAG,GAAGD,SAAS;AACtC;AAEA,SAASE,iBAAiBC,MAAc,EAAEC,OAAe;IACvD,OAAOJ,YAAYK,UAAU,CAAC,SAASC,GAAG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AO;gBAAK;gBACtG;YACF;YACA,IAAI9B,WAAW,UAAU,CAACxD,eAAeyD,GAAG,CAACD,SAAS;YACtD,MAAMR,UAAU,MAAMR,8BAA8BM,OAAOG,YAAY,EAAES,OAAO9C,IAAI2D,EAAE,GAAG;gBAAEzB;YAAO;YAClG,IAAIE,QAAQA,OAAO,KAAK,YAAY6F,YAAY;QAClD,EAAE,OAAOvG,OAAO;YACdwG,UAAU;YACVvG,QAAQD,KAAK,CAAC,gEAAgE1B,IAAI2D,EAAE,EAAEjC;QACxF;IACF;IACA,OAAO;QAAEuG;QAAUC;IAAO;AAC5B;AAEA,0FAA0F,GAC1F,OAAO,eAAeM,iCACpBtG,MAAiC,EACjCmG,QAAQ,EAAE;IAEV,MAAM9F,WAAW,MAAMzD,kBAAkBoD,OAAOiE,WAAW,EACxDiC,KAAK,CAAC,oBAAoB,MAAM,WAChCK,OAAO,CAAC,eAAe,QACvBJ,KAAK,CAACA,OACNjI,GAAG;IACN,OAAOmC,SAAS+F,IAAI,CAACnF,GAAG,CAAC,CAACnD,MAAc,CAAA;YAAE2D,IAAIb,OAAO9C,IAAI2D,EAAE;YAAG5B,OAAO/B,IAAIyC,IAAI;QAAuB,CAAA;AACtG;AAEA;;;;CAIC,GACD,OAAO,eAAeiG,4BAA4BC,KAIjD;IACC,IAAI;QACF,MAAM/G,8BAA8B+G,MAAM9I,MAAM,EAAE8I,MAAM7I,OAAO,EAAE;YAAE0G,SAASmC,MAAMnC,OAAO,KAAK;QAAK;IACrG,EAAE,OAAO9E,OAAO;QACdC,QAAQD,KAAK,CAAC,8DAA8DiH,MAAM7I,OAAO,EAAE4B;IAC7F;AACF"}
|
|
@@ -17,6 +17,8 @@
|
|
|
17
17
|
import { POS_HARDWARE_EMAIL_KEYS } from '@aglyn/shared-util-email';
|
|
18
18
|
import { type PosHardwareCancelReason, type PosHardwareOrder } from '../model/pos-hardware';
|
|
19
19
|
export type PosHardwareEmailKind = keyof typeof POS_HARDWARE_EMAIL_KEYS;
|
|
20
|
+
/** The steps the delivered email gives: pair the reader, or it is already set up. */
|
|
21
|
+
export declare function posHardwareSetupSteps(order: Pick<PosHardwareOrder, 'units' | 'lines'>): string;
|
|
20
22
|
/** The merge values for one order's emails. Exported for the render spec. */
|
|
21
23
|
export declare function posHardwareEmailMerge(orderId: string, order: PosHardwareOrder, names: {
|
|
22
24
|
site: string;
|
|
@@ -23,7 +23,7 @@ import { filterSuppressedEmails } from "@aglyn/tenant-data-admin/server/email-su
|
|
|
23
23
|
import { orgSystemEmailBrand, renderSystemEmailContent } from "@aglyn/tenant-data-admin/server/render-system-email";
|
|
24
24
|
import { COMMERCE_POS_HARDWARE_CANCELED_AFTER_ORDERING, COMMERCE_POS_HARDWARE_ORDER, COMMERCE_POS_HARDWARE_REFUND_FAILED } from "../constants/operator-alerts.js";
|
|
25
25
|
import { carrierLabelFor } from "../model/tracking-url.js";
|
|
26
|
-
import { formatPosHardwareCents, POS_HARDWARE_ANCHOR } from "../model/pos-hardware.js";
|
|
26
|
+
import { formatPosHardwareCents, POS_HARDWARE_ANCHOR, posHardwareOrderUnits } from "../model/pos-hardware.js";
|
|
27
27
|
import { hardwareOrdersRef, posHardwareOrderNumber, posSettingsUrl } from "./pos-hardware.js";
|
|
28
28
|
/** The lines as the emails list them, one per item. */ function itemsText(order) {
|
|
29
29
|
var _order_lines;
|
|
@@ -48,7 +48,19 @@ function shipToText(order) {
|
|
|
48
48
|
}
|
|
49
49
|
async function siteAndOrgNames(order) {
|
|
50
50
|
var _ref;
|
|
51
|
+
var _order_attachment, _order_posSale;
|
|
51
52
|
const firestore = firebaseAdmin.app().firestore();
|
|
53
|
+
// Bought from the platform's own store and not yet in the buyer's
|
|
54
|
+
// workspace (AGL-4038): it is for their business, which has no workspace
|
|
55
|
+
// here yet, and the selling store's name says where it came from.
|
|
56
|
+
if (((_order_attachment = order.attachment) == null ? void 0 : _order_attachment.state) === 'pending' && ((_order_posSale = order.posSale) == null ? void 0 : _order_posSale.hostId)) {
|
|
57
|
+
const seller = await firestore.collection('hosts').doc(order.posSale.hostId).get().catch(()=>null);
|
|
58
|
+
return {
|
|
59
|
+
site: (seller == null ? void 0 : seller.exists) ? hostDisplayName(seller.data(), order.posSale.hostId) : 'our store',
|
|
60
|
+
org: PENDING_BUYER,
|
|
61
|
+
ban: false
|
|
62
|
+
};
|
|
63
|
+
}
|
|
52
64
|
const [host, org] = await Promise.all([
|
|
53
65
|
firestore.collection('hosts').doc(order.hostId).get().catch(()=>null),
|
|
54
66
|
firestore.collection('orgs').doc(order.orgId).get().catch(()=>null)
|
|
@@ -70,6 +82,7 @@ async function siteAndOrgNames(order) {
|
|
|
70
82
|
returnRefunded: (number)=>`We refunded your returned card reader order ${number}`
|
|
71
83
|
};
|
|
72
84
|
/** The fallback a workspace with no name gets in a sentence. */ const UNNAMED_WORKSPACE = 'your workspace';
|
|
85
|
+
/** Who a sale not yet in anyone's workspace is for, in a sentence. */ const PENDING_BUYER = 'your business';
|
|
73
86
|
/**
|
|
74
87
|
* Who canceled the order and why, as the email's first sentence; the
|
|
75
88
|
* template goes on "It had not shipped yet, so we refunded …".
|
|
@@ -85,12 +98,21 @@ async function siteAndOrgNames(order) {
|
|
|
85
98
|
if (reason === 'account-closed') return 'the account that placed it was closed';
|
|
86
99
|
return 'staff canceled it';
|
|
87
100
|
}
|
|
101
|
+
/** The steps the delivered email gives: pair the reader, or it is already set up. */ export function posHardwareSetupSteps(order) {
|
|
102
|
+
const units = posHardwareOrderUnits(order);
|
|
103
|
+
if (units.length && units.every((unit)=>unit.readerId)) {
|
|
104
|
+
return 'We set your reader up on your store before it shipped.\n' + '1. Charge it and switch it on.\n' + '2. Connect it to Wi-Fi from the reader’s Settings.\n' + '3. It shows on the POS devices card, ready for a register.';
|
|
105
|
+
}
|
|
106
|
+
return '1. Charge it and switch it on.\n' + '2. Connect it to Wi-Fi from the reader’s Settings.\n' + '3. On the reader, generate a pairing code.\n' + '4. On the POS devices card, choose Add card reader and enter the code.';
|
|
107
|
+
}
|
|
88
108
|
/** The merge values for one order's emails. Exported for the render spec. */ export async function posHardwareEmailMerge(orderId, order, names) {
|
|
89
109
|
var _order_totalCents, _ref, _ref1, _ref2, _ref3, _order_refundedCents, _ref4, _ref5, _ref6, _order_refunds, _order_totalCents1, _order_refundedCents1;
|
|
90
110
|
var _order_shipping, _order_tracking, _order_tracking1, _order_tracking2, _slice_;
|
|
91
|
-
|
|
111
|
+
// An order with no store yet (AGL-4038) has no settings page to link: the
|
|
112
|
+
// console's front door, where signing in or up leads to it.
|
|
113
|
+
const base = order.hostId ? await posSettingsUrl(order.hostId) : platformConsoleOrigin();
|
|
92
114
|
const [path] = base.split('#');
|
|
93
|
-
const ordersUrl = `${path}#${POS_HARDWARE_ANCHOR}
|
|
115
|
+
const ordersUrl = order.hostId ? `${path}#${POS_HARDWARE_ANCHOR}` : path;
|
|
94
116
|
return {
|
|
95
117
|
'org.name': names.org,
|
|
96
118
|
'site.name': names.site,
|
|
@@ -104,7 +126,10 @@ async function siteAndOrgNames(order) {
|
|
|
104
126
|
// An unknown carrier has no tracker to link; the card shows the number.
|
|
105
127
|
'order.trackingUrl': (_ref2 = (_order_tracking2 = order.tracking) == null ? void 0 : _order_tracking2.url) != null ? _ref2 : ordersUrl,
|
|
106
128
|
'order.ordersUrl': ordersUrl,
|
|
107
|
-
'order.setupUrl': `${path}#pos-devices
|
|
129
|
+
'order.setupUrl': order.hostId ? `${path}#pos-devices` : path,
|
|
130
|
+
// What arrived: readers registered to the store before they shipped
|
|
131
|
+
// (AGL-4038) only need power and Wi-Fi; any other is paired by its code.
|
|
132
|
+
'order.setupSteps': posHardwareSetupSteps(order),
|
|
108
133
|
// What Stripe reported refunding, or the whole charge where it has not.
|
|
109
134
|
'order.refunded': formatPosHardwareCents((_ref3 = (_order_refundedCents = order.refundedCents) != null ? _order_refundedCents : order.totalCents) != null ? _ref3 : 0),
|
|
110
135
|
// This refund alone, for an order refunded in parts; the whole of it otherwise.
|
|
@@ -291,7 +316,7 @@ export async function sendPosHardwareInvite(orderId, order) {
|
|
|
291
316
|
reason: staffReasonText(reason, order.orgId),
|
|
292
317
|
error: error || 'no reason given',
|
|
293
318
|
paymentIntentId: (_order_stripePaymentIntentId = order.stripePaymentIntentId) != null ? _order_stripePaymentIntentId : 'for this order (no payment id is recorded on it)',
|
|
294
|
-
orderedNote: order.status === 'ordered' ? `. It had already been placed with Stripe${stripeOrderId ? ` as ${stripeOrderId}` : ''}, so cancel it there too before it ships` : ''
|
|
319
|
+
orderedNote: order.status === 'ordered' || order.status === 'received' ? `. It had already been placed with Stripe${stripeOrderId ? ` as ${stripeOrderId}` : ''}, so cancel it there too before it ships` : ''
|
|
295
320
|
}
|
|
296
321
|
});
|
|
297
322
|
} catch (failure) {
|