@aglyn/plugins-commerce 1.30.0 → 1.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/package.json +13 -13
- package/src/lib/components/cart.js +46 -20
- 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/console/currencies-card.component.d.ts +21 -0
- package/src/lib/components/console/currencies-card.component.js +408 -0
- package/src/lib/components/console/currencies-card.component.js.map +1 -0
- package/src/lib/components/console/product-add-ons-fields.component.d.ts +13 -0
- package/src/lib/components/console/product-add-ons-fields.component.js +74 -2
- package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +47 -1
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/product-fixed-prices-fields.component.d.ts +25 -0
- package/src/lib/components/console/product-fixed-prices-fields.component.js +112 -0
- package/src/lib/components/console/product-fixed-prices-fields.component.js.map +1 -0
- package/src/lib/components/console/product-traffic-card.component.d.ts +24 -0
- package/src/lib/components/console/product-traffic-card.component.js +172 -0
- package/src/lib/components/console/product-traffic-card.component.js.map +1 -0
- package/src/lib/components/console/products-hub-card.component.js +181 -59
- package/src/lib/components/console/products-hub-card.component.js.map +1 -1
- package/src/lib/components/console/reservations-card.component.js +32 -15
- package/src/lib/components/console/reservations-card.component.js.map +1 -1
- package/src/lib/components/console/shipping-settings-card.component.js +131 -10
- package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
- package/src/lib/components/console/store-settings-card.component.js +1 -1
- package/src/lib/components/console/store-settings-card.component.js.map +1 -1
- package/src/lib/components/console/use-currency-setup.d.ts +20 -0
- package/src/lib/components/console/use-currency-setup.js +61 -0
- package/src/lib/components/console/use-currency-setup.js.map +1 -0
- package/src/lib/components/currency-selector.d.ts +36 -0
- package/src/lib/components/currency-selector.js +157 -0
- package/src/lib/components/currency-selector.js.map +1 -0
- package/src/lib/components/product-add-ons.d.ts +9 -1
- package/src/lib/components/product-add-ons.js +8 -4
- package/src/lib/components/product-add-ons.js.map +1 -1
- package/src/lib/components/product-choice-cards.d.ts +13 -1
- package/src/lib/components/product-choice-cards.js +5 -4
- package/src/lib/components/product-choice-cards.js.map +1 -1
- package/src/lib/components/product-detail.d.ts +8 -0
- package/src/lib/components/product-detail.js +38 -11
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/product-grid.d.ts +2 -0
- package/src/lib/components/product-grid.js +22 -9
- package/src/lib/components/product-grid.js.map +1 -1
- package/src/lib/components/related-products.js +6 -2
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/components/shopper-currency.d.ts +108 -0
- package/src/lib/components/shopper-currency.js +262 -0
- package/src/lib/components/shopper-currency.js.map +1 -0
- package/src/lib/components/wishlist.js +7 -1
- package/src/lib/components/wishlist.js.map +1 -1
- package/src/lib/declarations.server.js +39 -0
- package/src/lib/declarations.server.js.map +1 -1
- package/src/lib/model/commerce-currency-setup.d.ts +79 -0
- package/src/lib/model/commerce-currency-setup.js +124 -0
- package/src/lib/model/commerce-currency-setup.js.map +1 -0
- package/src/lib/model/commerce-currency.d.ts +215 -0
- package/src/lib/model/commerce-currency.js +511 -0
- package/src/lib/model/commerce-currency.js.map +1 -0
- package/src/lib/model/commerce-orders.d.ts +17 -0
- package/src/lib/model/commerce-orders.js +10 -5
- package/src/lib/model/commerce-orders.js.map +1 -1
- package/src/lib/model/commerce-record-routes.js +56 -0
- package/src/lib/model/commerce-record-routes.js.map +1 -1
- package/src/lib/model/commerce-reservations.d.ts +6 -0
- package/src/lib/model/commerce-reservations.js.map +1 -1
- package/src/lib/model/commerce-shipping.d.ts +61 -17
- package/src/lib/model/commerce-shipping.js +346 -32
- package/src/lib/model/commerce-shipping.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 +2 -0
- package/src/lib/model/index.js +2 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/model/order-figures.js +9 -2
- package/src/lib/model/order-figures.js.map +1 -1
- package/src/lib/model/product-modifiers.d.ts +5 -0
- package/src/lib/model/product-modifiers.js.map +1 -1
- package/src/lib/model/product-write.d.ts +10 -1
- package/src/lib/model/product-write.js +13 -2
- package/src/lib/model/product-write.js.map +1 -1
- package/src/lib/server/billing-webhook.js +37 -24
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/carrier-shipping.js +3 -2
- package/src/lib/server/carrier-shipping.js.map +1 -1
- package/src/lib/server/cart-checkout.js +77 -15
- package/src/lib/server/cart-checkout.js.map +1 -1
- package/src/lib/server/cart.d.ts +12 -0
- package/src/lib/server/cart.js +52 -6
- package/src/lib/server/cart.js.map +1 -1
- package/src/lib/server/catalog.d.ts +5 -0
- package/src/lib/server/catalog.js +7 -0
- package/src/lib/server/catalog.js.map +1 -1
- package/src/lib/server/checkout.js +54 -16
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/currency.d.ts +93 -0
- package/src/lib/server/currency.js +182 -0
- package/src/lib/server/currency.js.map +1 -0
- package/src/lib/server/draft-order.js +3 -3
- package/src/lib/server/draft-order.js.map +1 -1
- package/src/lib/server/order-notifications.js +4 -2
- package/src/lib/server/order-notifications.js.map +1 -1
- package/src/lib/server/product.d.ts +9 -0
- package/src/lib/server/product.js +12 -0
- package/src/lib/server/product.js.map +1 -1
- package/src/lib/server/products-write.js +10 -2
- package/src/lib/server/products-write.js.map +1 -1
- package/src/lib/server/refund.js +3 -3
- package/src/lib/server/refund.js.map +1 -1
- package/src/lib/server/site-chat-tools.d.ts +22 -0
- package/src/lib/server/site-chat-tools.js +369 -0
- package/src/lib/server/site-chat-tools.js.map +1 -0
- package/src/lib/server/site-chat-visitor.d.ts +24 -0
- package/src/lib/server/site-chat-visitor.js +39 -0
- package/src/lib/server/site-chat-visitor.js.map +1 -0
- package/src/lib/server/site-offers.d.ts +31 -0
- package/src/lib/server/site-offers.js +91 -0
- package/src/lib/server/site-offers.js.map +1 -0
- package/src/lib/server/stays-site-search.d.ts +20 -0
- package/src/lib/server/stays-site-search.js +78 -0
- package/src/lib/server/stays-site-search.js.map +1 -0
- package/src/lib/server.js +20 -0
- package/src/lib/server.js.map +1 -1
- package/src/lib/site-chat-tool-definitions.d.ts +26 -0
- package/src/lib/site-chat-tool-definitions.js +141 -0
- package/src/lib/site-chat-tool-definitions.js.map +1 -0
- package/src/lib/site.js +8 -0
- package/src/lib/site.js.map +1 -1
- package/src/lib/subprocessors.js +7 -0
- package/src/lib/subprocessors.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/order-notifications.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 * as Aglyn from '@aglyn/aglyn/server'\nimport { withPosHardwareReceiptNotice } from '../model/pos-hardware-terms'\nimport { pluginSmsMessaging } from '@aglyn/aglyn/plugin-manager/plugin-sms-messaging'\nimport { resolveSiteTimeZone } from '@aglyn/aglyn/app-utils/collection-entry-date'\nimport {\n resolveHostToken,\n type HostTokenSource,\n} from '@aglyn/aglyn/app-utils/host-tokens'\nimport {\n firebaseAdmin,\n getOrgForHost,\n hostSendingIdentity,\n meterHostEmail,\n renderHostEmailWithTokens,\n} from '@aglyn/tenant-data-admin'\nimport {\n isEmailConfigured,\n renderTextEmailHtml,\n sendEmail,\n} from '@aglyn/shared-util-email'\nimport {\n resolvePluginOrderEmailCopies,\n withOrderEmailDataBlocks,\n} from '@aglyn/aglyn/plugin-manager/plugin-order-email-copies'\nimport * as CommerceModel from '../model'\nimport { orderViewFromData } from './api-v1/order-view'\nimport { mintDownloadToken } from './download'\nimport { orderStatusUrl } from './order-status-token'\n\n/**\n * Every message a buyer gets about their order, through ONE door (AGL-3610).\n *\n * Before this, the buyer heard about their order once — the online receipt —\n * and never again: a register sale sent nothing, a paid payment link sent\n * nothing, and shipping, delivery, refunds and cancellations were silent\n * (`fulfill-order.ts` said so on purpose). Every path that moves an order now\n * makes one call here, and this decides what that moment owes the buyer:\n *\n * - whether the store turned the moment off (`buyerNotifications` on the\n * store settings; ON unless explicitly off — see the model),\n * - which channels can carry it (email when mail is configured and the\n * order has an address; a text when the platform's SMS provider is\n * configured and the order carries the buyer's phone),\n * - and whether it was already sent.\n *\n * ## ONCE PER MOMENT, PER OCCURRENCE, PER CHANNEL\n *\n * Stripe redelivers webhooks, admins click twice, a lost response is retried.\n * Each message is CLAIMED before it is sent: a transaction reads the order's\n * `buyerNotifications` map and writes a `sending` marker for\n * `event__occurrence__channel` only if none is there. Exactly one of two\n * racing callers wins the claim; the other returns `already`. The occurrence\n * is the shipment id for `shipped` and the refund id for `refunded`, so a\n * second parcel or a second partial refund is a new message, while a\n * redelivered one is not.\n *\n * A send that fails RELEASES its claim so the next attempt can try again. A\n * process that dies between claim and send leaves the marker in `sending` and\n * the message unsent — at most once, never twice, which is the right side to\n * fail on for mail a buyer reads as \"did they charge me again?\".\n *\n * ## NEVER THROWS\n *\n * Every caller is past its point of no return — money moved, an order\n * shipped — so a mail outage must not turn into a 500 that invites the\n * merchant to do it again. Failures are logged and returned as outcomes.\n *\n * Shared with the order-processing and POS lanes (AGL-3611, AGL-3607): call\n * {@link notifyOrderBuyer} from any new path that moves an order, and\n * {@link sendOrderReceipt} for an explicit, merchant-asked send.\n */\n\nexport type OrderBuyerEvent = CommerceModel.BuyerNotificationEvent\n\nexport interface OrderRef {\n hostId: string\n orderId: string\n}\n\nexport interface NotifyOrderBuyerOptions {\n /** `shipped`: which shipment. Absent means the order's latest one. */\n fulfillmentId?: string\n /** `refunded`: the refund's own id (Stripe's), the occurrence key. */\n refundId?: string\n /** `refunded`: what THIS refund moved, in cents. */\n refundCents?: number\n /** `refunded`: the line indexes refunded by name, when any were. */\n refundLineIndexes?: readonly number[]\n /** `refunded`: whether this refund closed the order. */\n fullyRefunded?: boolean\n /**\n * The buyer's address when the order document does not carry it — a POS\n * folio sale attributed to the reservation's guest, a payment link whose\n * payer Stripe named. The order's own `customerEmail` wins when present.\n */\n email?: string | null\n /** Injected in specs. */\n firestore?: FirebaseFirestore.Firestore\n}\n\nexport type OrderBuyerChannelOutcome =\n | { channel: CommerceModel.BuyerNotificationChannel; outcome: 'sent' }\n | { channel: CommerceModel.BuyerNotificationChannel; outcome: 'already' }\n | {\n channel: CommerceModel.BuyerNotificationChannel\n outcome: 'failed'\n error: string\n }\n\nexport type NotifyOrderBuyerOutcome =\n | { outcome: 'disabled' }\n | { outcome: 'no_such_order' }\n /** The moment does not apply to this order (a counter sale \"shipping\"). */\n | { outcome: 'not_applicable' }\n /** No channel could carry it: no address, no mail or text configured. */\n | { outcome: 'no_recipient' }\n | { outcome: 'handled'; channels: OrderBuyerChannelOutcome[] }\n\ninterface StoreContext {\n firestore: FirebaseFirestore.Firestore\n hostRef: FirebaseFirestore.DocumentReference\n host: Record<string, unknown>\n settings: Record<string, unknown>\n currency: string\n}\n\nasync function readStore(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n): Promise<StoreContext> {\n const hostRef = firestore.collection('hosts').doc(hostId)\n const [hostSnapshot, settingsSnapshot] = await Promise.all([\n hostRef.get().catch(() => null),\n hostRef.collection('settings').doc('store').get().catch(() => null),\n ])\n const settings = (settingsSnapshot?.data?.() ?? {}) as Record<string, unknown>\n return {\n firestore,\n hostRef,\n host: (hostSnapshot?.data?.() ?? {}) as Record<string, unknown>,\n settings,\n currency: String(settings['currency'] ?? 'USD') || 'USD',\n }\n}\n\nfunction lineLabel(line: CommerceModel.OrderLineItem): string {\n return `${line.quantity}× ${line.name}${\n line.variantLabel ? ` (${line.variantLabel})` : ''\n }`\n}\n\n/** The status link, or the store's home page when no link can be minted. */\nfunction statusLink(store: StoreContext, ref: OrderRef): string {\n return (\n orderStatusUrl(store.host as never, ref.hostId, ref.orderId) ??\n Aglyn.hostPublicOrigin({\n cname: typeof store.host['cname'] === 'string' ? store.host['cname'] : null,\n subdomain:\n typeof store.host['subdomain'] === 'string'\n ? store.host['subdomain']\n : null,\n }) ??\n ''\n )\n}\n\ninterface ComposedMessage {\n emailKey: string\n /** Tokens for the designed email. */\n tokens: Record<string, string>\n /** Subject when the template renders none. */\n subject: string\n /** Plain-text body when the template renders none. */\n text: string\n /** The text message, kept short: one or two segments. */\n sms: string\n /** The order timeline line recording the send, channel appended. */\n timelineDetail: string\n}\n\n/** What the moment says. `null` when it does not apply to this order. */\nexport function composeOrderBuyerMessage(input: {\n event: OrderBuyerEvent\n order: CommerceModel.HostOrder\n orderId: string\n businessName: string\n currency: string\n statusUrl: string\n receiptFooter?: string\n /** Absolute digital-delivery links for a receipt, by product id. */\n downloadLinks?: Record<string, string>\n options?: NotifyOrderBuyerOptions\n}): (ComposedMessage & { occurrence: string }) | null {\n const {\n event,\n order,\n orderId,\n businessName,\n currency,\n statusUrl,\n options = {},\n } = input\n const lines = order.lineItems ?? []\n const number = CommerceModel.formatOrderNumber(order, orderId)\n const money = (cents: number) =>\n CommerceModel.formatOrderMoney(cents, currency)\n const store = businessName || 'The store'\n const base = {\n 'order.number': number,\n 'order.statusUrl': statusUrl,\n 'order.ref': orderId,\n }\n const link = statusUrl ? `\\n\\nView your order: ${statusUrl}` : ''\n const smsLink = statusUrl ? ` ${statusUrl}` : ''\n\n if (event === 'receipt') {\n const totalCents =\n order.totals?.totalCents ?? Number(order.amountCents ?? 0)\n const licenseText = Object.entries(\n ((order as { licenseKeys?: Record<string, string[]> }).licenseKeys ??\n {}) as Record<string, string[]>,\n )\n .flatMap(([productId, keys]) => {\n const line = lines.find((item) => item.productId === productId)\n return (keys ?? []).map(\n (key) => `License key (${line?.name ?? 'product'}): ${key}`,\n )\n })\n .join('\\n')\n const downloads = Object.entries(input.downloadLinks ?? {})\n .map(([productId, url]) => {\n const line = lines.find((item) => item.productId === productId)\n return `Download ${line?.name ?? 'your file'}: ${url}`\n })\n .join('\\n')\n const linesText = lines\n .map(\n (line) =>\n `${lineLabel(line)} — ${money(line.unitAmountCents * line.quantity)}`,\n )\n .join('\\n')\n const summary = [linesText, licenseText, downloads]\n .filter(Boolean)\n .join('\\n\\n')\n const footer = String(input.receiptFooter ?? '')\n return {\n occurrence: 'order',\n emailKey: CommerceModel.BUYER_NOTIFICATION_EMAIL_KEYS.receipt,\n tokens: {\n ...base,\n 'order.summary': summary,\n 'order.total': money(totalCents),\n 'store.receiptFooter': footer,\n },\n subject: 'Receipt for your order',\n text:\n `Thanks for your purchase!\\n\\n${summary}\\n\\nTotal: ${money(totalCents)}\\n` +\n `Order ${number}` +\n (footer ? `\\n\\n${footer}` : '') +\n link,\n sms: `${store}: receipt for order ${number}, ${money(totalCents)}.${smsLink}`,\n timelineDetail: 'Receipt sent',\n }\n }\n\n if (event === 'shipped') {\n const fulfillments = order.fulfillments ?? []\n const fulfillment = options.fulfillmentId\n ? fulfillments.find((entry) => entry.id === options.fulfillmentId)\n : [...fulfillments].sort((a, b) => (b.atMs ?? 0) - (a.atMs ?? 0))[0]\n if (!fulfillment) return null\n // Collected at the counter or handed over by the store's driver\n // (AGL-3624): \"picked up\" and \"delivered\" say so, never \"shipped\".\n if (fulfillment.handover) return null\n // The units THIS shipment carried (AGL-3611): a partial shipment of a\n // line names its own count, not the line's.\n const shipped = CommerceModel.fulfillmentLineQuantities(order, fulfillment)\n .map((entry) =>\n lines[entry.lineItemId] ? { ...lines[entry.lineItemId], quantity: entry.quantity } : null,\n )\n .filter(Boolean) as CommerceModel.OrderLineItem[]\n const tracking = CommerceModel.fulfillmentTrackingUrl(fulfillment)\n const hasTracking = Boolean(fulfillment.trackingNumber)\n // Nothing physical left the building: a register sale handed over the\n // counter, or a digital-only order the merchant marked fulfilled. A\n // \"your order is on its way\" email for either is noise at best.\n const physical = shipped.some(\n (line) =>\n line.productType !== 'digital' && line.productType !== 'service',\n )\n if (!hasTracking && (order.channel === 'pos' || !physical)) return null\n // Shippable units still out, over every active shipment (AGL-3611).\n const remainingUnits = CommerceModel.remainingFulfillmentLines(order).reduce(\n (sum, entry) => sum + entry.quantity,\n 0,\n )\n const carrier = CommerceModel.carrierLabelFor(fulfillment.carrier)\n const trackingSentence = hasTracking\n ? `Tracking: ${[carrier, fulfillment.trackingNumber]\n .filter(Boolean)\n .join(' ')}${tracking ? ` — ${tracking}` : ''}`\n : ''\n const remainingSentence =\n remainingUnits > 0\n ? `${remainingUnits} more item${remainingUnits === 1 ? '' : 's'} will ship separately.`\n : ''\n const summary = shipped.map(lineLabel).join('\\n')\n return {\n occurrence: fulfillment.id,\n emailKey: CommerceModel.BUYER_NOTIFICATION_EMAIL_KEYS.shipped,\n tokens: {\n ...base,\n 'shipment.summary': summary,\n 'shipment.carrier': carrier,\n 'shipment.trackingNumber': String(fulfillment.trackingNumber ?? ''),\n 'shipment.tracking': trackingSentence,\n 'shipment.remaining': remainingSentence,\n },\n subject: `Your order ${number} has shipped`,\n text:\n `${store} shipped items from order ${number}.\\n\\n${summary}` +\n (trackingSentence ? `\\n\\n${trackingSentence}` : '') +\n (remainingSentence ? `\\n\\n${remainingSentence}` : '') +\n link,\n sms:\n `${store}: order ${number} has shipped.` +\n (tracking ? ` Track it: ${tracking}` : smsLink),\n timelineDetail: 'Shipping confirmation sent',\n }\n }\n\n if (event === 'delivered') {\n // A counter sale is \"delivered\" the moment it is handed over.\n if (order.channel === 'pos') return null\n const summary = lines.map(lineLabel).join('\\n')\n return {\n occurrence: 'order',\n emailKey: CommerceModel.BUYER_NOTIFICATION_EMAIL_KEYS.delivered,\n tokens: { ...base, 'order.summary': summary },\n subject: `Your order ${number} was delivered`,\n text:\n `${store} marked order ${number} as delivered.\\n\\n${summary}` + link,\n sms: `${store}: order ${number} was delivered.${smsLink}`,\n timelineDetail: 'Delivery confirmation sent',\n }\n }\n\n if (event === 'ready_for_pickup' || event === 'picked_up') {\n const pickup = order.pickup\n if (order.fulfillmentMethod !== 'pickup' || !pickup) return null\n const summary = lines.map(lineLabel).join('\\n')\n const where = `${pickup.locationName}${pickup.address ? `, ${pickup.address}` : ''}`\n const hours = pickup.hours ? `Pickup hours:\\n${pickup.hours}` : ''\n const instructions = pickup.instructions ?? ''\n if (event === 'picked_up') {\n return {\n occurrence: 'order',\n emailKey: CommerceModel.BUYER_NOTIFICATION_EMAIL_KEYS.picked_up,\n tokens: { ...base, 'order.summary': summary, 'pickup.location': where },\n subject: `You picked up order ${number}`,\n text: `Order ${number} was picked up from ${where}. Thanks for shopping with ${store}.\\n\\n${summary}` + link,\n sms: `${store}: order ${number} was picked up. Thank you!${smsLink}`,\n timelineDetail: 'Pickup confirmation sent',\n }\n }\n return {\n occurrence: 'order',\n emailKey: CommerceModel.BUYER_NOTIFICATION_EMAIL_KEYS.ready_for_pickup,\n tokens: {\n ...base,\n 'order.summary': summary,\n 'pickup.location': where,\n 'pickup.hours': hours,\n 'pickup.instructions': instructions,\n },\n subject: `Your order ${number} is ready for pickup`,\n text:\n `Your order ${number} is ready for pickup at ${where}.\\n\\n${summary}` +\n (hours ? `\\n\\n${hours}` : '') +\n (instructions ? `\\n\\n${instructions}` : '') +\n `\\n\\nBring your order number, ${number}.` +\n link,\n sms: `${store}: order ${number} is ready for pickup at ${pickup.locationName}.${smsLink}`,\n timelineDetail: 'Ready-for-pickup notice sent',\n }\n }\n\n if (event === 'out_for_delivery') {\n const delivery = order.localDelivery\n if (order.fulfillmentMethod !== 'local_delivery' || !delivery) return null\n const summary = lines.map(lineLabel).join('\\n')\n const window = delivery.windowLabel ?? ''\n return {\n // Each run out the door is its own message: a failed drop sent out\n // again tells the buyer again.\n occurrence: String(delivery.outForDeliveryAtMs ?? 'order'),\n emailKey: CommerceModel.BUYER_NOTIFICATION_EMAIL_KEYS.out_for_delivery,\n tokens: { ...base, 'order.summary': summary, 'delivery.window': window },\n subject: `Your order ${number} is out for delivery`,\n text:\n `${store} is on the way with order ${number}` +\n (window ? `, in your window ${window}` : '') +\n `.\\n\\n${summary}` +\n link,\n sms: `${store}: order ${number} is out for delivery${window ? ` (${window})` : ''}.${smsLink}`,\n timelineDetail: 'Out-for-delivery notice sent',\n }\n }\n\n if (event === 'refunded') {\n const refundCents = Math.max(0, Math.round(Number(options.refundCents ?? 0)))\n if (!(refundCents > 0)) return null\n const refundedLines = (options.refundLineIndexes ?? [])\n .map((index) => lines[index])\n .filter(Boolean) as CommerceModel.OrderLineItem[]\n const summary = refundedLines.map(lineLabel).join('\\n')\n const note = options.fullyRefunded\n ? 'Your order has been refunded in full.'\n : 'The rest of your order is unchanged.'\n return {\n // The refund's own id is the occurrence; without one, the running\n // total after this refund is (each settled refund raises it).\n occurrence:\n options.refundId ||\n `total-${Number(order.refundedCents ?? 0) || refundCents}`,\n emailKey: CommerceModel.BUYER_NOTIFICATION_EMAIL_KEYS.refunded,\n tokens: {\n ...base,\n 'refund.amount': money(refundCents),\n 'refund.summary': summary,\n 'refund.note': note,\n },\n subject: `Refund for your order ${number}`,\n text:\n `${store} refunded ${money(refundCents)} on order ${number}.` +\n (summary ? `\\n\\n${summary}` : '') +\n `\\n\\n${note}\\n\\nRefunds go back to the original payment method and ` +\n 'usually appear within 5 to 10 business days, depending on your bank.' +\n link,\n sms: `${store}: ${money(refundCents)} refunded on order ${number}.${smsLink}`,\n timelineDetail: `Refund confirmation sent (${money(refundCents)})`,\n }\n }\n\n // cancelled\n const summary = lines.map(lineLabel).join('\\n')\n const wasPaid = Boolean(\n order.paymentIntentId ||\n (order.channel === 'pos' && order.status !== 'pending') ||\n (order.timeline ?? []).some((entry) => entry?.event === 'paid'),\n )\n const note = wasPaid\n ? `Questions about a payment? Reply to this email or contact ${store}.`\n : ''\n return {\n occurrence: 'order',\n emailKey: CommerceModel.BUYER_NOTIFICATION_EMAIL_KEYS.cancelled,\n tokens: { ...base, 'order.summary': summary, 'cancel.note': note },\n subject: `Your order ${number} was canceled`,\n text:\n `${store} canceled order ${number}.\\n\\n${summary}` +\n (note ? `\\n\\n${note}` : '') +\n link,\n sms: `${store}: order ${number} was canceled.${smsLink}`,\n timelineDetail: 'Cancellation notice sent',\n }\n}\n\n/**\n * Claims one message in a transaction. `true` when this caller owns the send;\n * `false` when a marker is already there (sent, or being sent).\n */\nasync function claimMessage(\n firestore: FirebaseFirestore.Firestore,\n orderRef: FirebaseFirestore.DocumentReference,\n marker: string,\n channel: CommerceModel.BuyerNotificationChannel,\n): Promise<boolean> {\n return firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(orderRef)\n if (!snapshot.exists) return false\n const sent = (snapshot.get('buyerNotifications') ?? {}) as Record<\n string,\n unknown\n >\n if (sent[marker]) return false\n transaction.update(orderRef, {\n [`buyerNotifications.${marker}`]: {\n state: 'sending',\n channel,\n atMs: Date.now(),\n },\n })\n return true\n })\n}\n\n/** Marks a claimed message sent and records it on the order timeline. */\nasync function settleMessage(\n firestore: FirebaseFirestore.Firestore,\n orderRef: FirebaseFirestore.DocumentReference,\n marker: string | null,\n channel: CommerceModel.BuyerNotificationChannel,\n detail: string,\n): Promise<void> {\n await firestore\n .runTransaction(async (transaction) => {\n const snapshot = await transaction.get(orderRef)\n if (!snapshot.exists) return\n const order = CommerceModel.liftLegacyOrder(\n (snapshot.data() ?? {}) as never,\n )\n const atMs = Date.now()\n transaction.update(orderRef, {\n ...(marker\n ? {\n [`buyerNotifications.${marker}`]: { state: 'sent', channel, atMs },\n }\n : {}),\n timeline: CommerceModel.appendOrderEvent(\n order,\n 'buyer-notified',\n `${detail} by ${channel === 'sms' ? 'text' : 'email'}`,\n atMs,\n ),\n })\n })\n .catch((error) => {\n console.error('[order-notifications] settle failed', marker, error)\n })\n}\n\nasync function releaseMessage(\n orderRef: FirebaseFirestore.DocumentReference,\n marker: string,\n): Promise<void> {\n await orderRef\n .update({\n [`buyerNotifications.${marker}`]:\n firebaseAdmin.firestore.FieldValue.delete(),\n })\n .catch(() => undefined)\n}\n\n/** How long a buyer email waits on plugins asking to be copied on it. */\nconst EMAIL_COPIES_TIMEOUT_MS = 3_000\n\nasync function deliverEmail(\n store: StoreContext,\n ref: OrderRef,\n to: string,\n message: ComposedMessage,\n context: string,\n /** The moment and order, for plugins copied on it; absent for a merchant-asked resend. */\n about?: { event: OrderBuyerEvent; order: CommerceModel.HostOrder },\n): Promise<void> {\n const designed = await renderHostEmailWithTokens(\n store.firestore,\n ref.hostId,\n message.emailKey,\n message.tokens,\n )\n const org = await getOrgForHost(ref.hostId).catch(() => null)\n // Plugins copied on this email (AGL-3699): a review platform's invitation\n // address, with the data block it reads. Asked through core's seam, by\n // the email's key and moment; nothing answers unless a site connected one.\n const copies = about\n ? await resolvePluginOrderEmailCopies(\n {\n hostId: ref.hostId,\n recordId: ref.orderId,\n emailKey: message.emailKey,\n moment: about.event,\n recipient: to,\n order: orderViewFromData(ref.orderId, about.order as Record<string, any>),\n },\n { timeoutMs: EMAIL_COPIES_TIMEOUT_MS },\n )\n : { bcc: [] as string[], html: '', settle: async () => undefined }\n const subject = designed?.subject ?? message.subject\n const text = designed?.text || message.text\n // A data block lives in the HTML part, so a text-only email gets the same\n // HTML part `sendEmail` would have synthesized, carrying it.\n const html = copies.html\n ? withOrderEmailDataBlocks(designed?.html || renderTextEmailHtml(text, subject), copies.html)\n : designed?.html\n const result = await sendEmail({\n to,\n subject,\n text,\n ...(html ? { html } : {}),\n ...(copies.bcc.length ? { bcc: copies.bcc } : {}),\n fromName: Aglyn.resolveBrandingProfile(org?.org as never).fromName,\n sendingIdentity: await hostSendingIdentity(ref.hostId),\n audience: 'tenant',\n context,\n // Owed to the recipient by their own order: the phishing screen's soft\n // rules never hold it (AGL-3356).\n owedFor: 'order',\n })\n await copies.settle(Boolean(result?.sent))\n // A message that did not leave is NOT sent (AGL-4227): thrown, so the\n // caller releases the order's marker and reports this channel failed rather\n // than writing \"sent\" on the order's timeline — the workspace's email limit,\n // a suppression or a provider refusal all end here. Nothing is metered for\n // it either: an email that never left is not a cost.\n if (!result?.sent) {\n throw new Error(`Email not sent: ${describeUnsentEmail(result)}`)\n }\n // Cost meter (AGL-1438), as every transactional store email.\n await meterHostEmail(ref.hostId)\n}\n\n/** Why a store email did not leave, in the words the order's failure records. */\nfunction describeUnsentEmail(result: unknown): string {\n const failure = result as { reason?: string; detail?: string } | null | undefined\n if (failure?.reason === 'rate-limited') {\n return failure.detail || 'the workspace reached its email limit'\n }\n return failure?.detail || failure?.reason || 'delivery failed'\n}\n\n/**\n * What a text attempt came to: `refused` names why nothing went (null when it\n * went), and `scheduledForMs` says it was held for the buyer's morning.\n */\ninterface SmsDelivery {\n refused: string | null\n scheduledForMs?: number\n}\n\n/**\n * Sends one order text. A receipt goes at once — the buyer is at the counter\n * or the checkout waiting for it. Every later moment (shipped, delivered,\n * refunded, canceled) can fire at any hour, from a carrier scan or a late\n * packing shift, so it asks the provider to keep quiet hours in the STORE's\n * zone: the best stand-in the platform has for a buyer whose own zone it was\n * never told, and right for the local and regional stores most texts come\n * from. Held texts arrive at 8 AM there.\n */\nasync function deliverSms(\n ref: OrderRef,\n to: string,\n message: ComposedMessage,\n context: string,\n quiet: { host: Record<string, unknown> } | null,\n): Promise<SmsDelivery> {\n const sms = pluginSmsMessaging()\n if (!sms?.isConfigured()) return { refused: 'Text messages are not configured' }\n let timeZone: string | null = null\n if (quiet) {\n const owner = await getOrgForHost(ref.hostId).catch(() => null)\n timeZone = resolveSiteTimeZone(\n (owner?.org ?? null) as { timeZone?: string } | null,\n quiet.host as { timeZone?: string },\n )\n }\n const outcome = await sms.send({\n to,\n body: message.sms,\n hostId: ref.hostId,\n purpose: 'transactional',\n context,\n ...(timeZone ? { quietHours: { timeZone } } : {}),\n })\n if (outcome.status !== 'sent') return { refused: outcome.status }\n return {\n refused: null,\n ...(outcome.scheduledForMs ? { scheduledForMs: outcome.scheduledForMs } : {}),\n }\n}\n\n/** Absolute download links for a receipt's digital lines. */\nfunction downloadLinksFor(\n store: StoreContext,\n ref: OrderRef,\n order: CommerceModel.HostOrder,\n): Record<string, string> {\n const origin = Aglyn.hostPublicOrigin({\n cname: typeof store.host['cname'] === 'string' ? store.host['cname'] : null,\n subdomain:\n typeof store.host['subdomain'] === 'string' ? store.host['subdomain'] : null,\n })\n const digital = (order.lineItems ?? []).filter(\n (line) => line.productType === 'digital',\n )\n if (!origin || !digital.length) return {}\n let token: string\n try {\n token = mintDownloadToken(ref.hostId, ref.orderId)\n } catch {\n return {}\n }\n return Object.fromEntries(\n digital.map((line) => [\n line.productId,\n `${origin}/api/commerce/download?hostId=${encodeURIComponent(ref.hostId)}` +\n `&orderId=${encodeURIComponent(ref.orderId)}` +\n `&productId=${encodeURIComponent(line.productId)}&token=${token}`,\n ]),\n )\n}\n\nasync function readOrder(\n firestore: FirebaseFirestore.Firestore,\n ref: OrderRef,\n): Promise<{\n orderRef: FirebaseFirestore.DocumentReference\n order: CommerceModel.HostOrder | null\n}> {\n const orderRef = firestore\n .collection('hosts')\n .doc(ref.hostId)\n .collection('orders')\n .doc(ref.orderId)\n const snapshot = await orderRef.get()\n return {\n orderRef,\n order: snapshot.exists\n ? CommerceModel.liftLegacyOrder((snapshot.data() ?? {}) as never)\n : null,\n }\n}\n\nfunction emailOf(value: unknown): string {\n const email = String(value ?? '').trim()\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email) ? email : ''\n}\n\n/**\n * Tells the buyer about one moment in their order's life, once. See the\n * module header. Never throws.\n */\nexport async function notifyOrderBuyer(\n ref: OrderRef,\n event: OrderBuyerEvent,\n options: NotifyOrderBuyerOptions = {},\n): Promise<NotifyOrderBuyerOutcome> {\n try {\n if (!ref.hostId || !ref.orderId) return { outcome: 'no_such_order' }\n const firestore = options.firestore ?? firebaseAdmin.app().firestore()\n const store = await readStore(firestore, ref.hostId)\n const toggles = store.settings['buyerNotifications']\n if (!CommerceModel.buyerNotificationEnabled(toggles, event)) {\n return { outcome: 'disabled' }\n }\n const { orderRef, order } = await readOrder(firestore, ref)\n if (!order) return { outcome: 'no_such_order' }\n const message = composeOrderBuyerMessage({\n event,\n order,\n orderId: ref.orderId,\n businessName: String(\n resolveHostToken('businessName', store.host as HostTokenSource) ?? '',\n ),\n currency: store.currency,\n statusUrl: statusLink(store, ref),\n // A sale of card reader hardware states the terms it is sold under (AGL-4038).\n receiptFooter: withPosHardwareReceiptNotice(String(store.settings['receiptFooter'] ?? ''), order),\n downloadLinks:\n event === 'receipt' ? downloadLinksFor(store, ref, order) : undefined,\n options,\n })\n if (!message) return { outcome: 'not_applicable' }\n\n const email = emailOf(order.customerEmail) || emailOf(options.email)\n const phone = String(order.customerPhone ?? '').trim()\n const targets: {\n channel: CommerceModel.BuyerNotificationChannel\n to: string\n }[] = []\n if (email && isEmailConfigured()) targets.push({ channel: 'email', to: email })\n if (\n phone &&\n CommerceModel.buyerNotificationEnabled(toggles, 'texts') &&\n pluginSmsMessaging()?.isConfigured()\n ) {\n targets.push({ channel: 'sms', to: phone })\n }\n if (!targets.length) return { outcome: 'no_recipient' }\n\n const channels: OrderBuyerChannelOutcome[] = []\n for (const target of targets) {\n const marker = CommerceModel.buyerNotificationMarker(\n event,\n message.occurrence,\n target.channel,\n )\n const claimed = await claimMessage(\n firestore,\n orderRef,\n marker,\n target.channel,\n ).catch((error) => {\n console.error('[order-notifications] claim failed', marker, error)\n return false\n })\n if (!claimed) {\n channels.push({ channel: target.channel, outcome: 'already' })\n continue\n }\n const context = message.emailKey\n let held: number | null = null\n try {\n if (target.channel === 'email') {\n await deliverEmail(store, ref, target.to, message, context, { event, order })\n } else {\n const sent = await deliverSms(\n ref,\n target.to,\n message,\n context,\n event === 'receipt' ? null : { host: store.host },\n )\n if (sent.refused) throw new Error(sent.refused)\n held = sent.scheduledForMs ?? null\n }\n await settleMessage(\n firestore,\n orderRef,\n marker,\n target.channel,\n held\n ? `${message.timelineDetail} (held for the morning)`\n : message.timelineDetail,\n )\n channels.push({ channel: target.channel, outcome: 'sent' })\n } catch (error) {\n await releaseMessage(orderRef, marker)\n console.error('[order-notifications] send failed', {\n hostId: ref.hostId,\n orderId: ref.orderId,\n event,\n channel: target.channel,\n error,\n })\n channels.push({\n channel: target.channel,\n outcome: 'failed',\n error: error instanceof Error ? error.message : String(error),\n })\n }\n }\n return { outcome: 'handled', channels }\n } catch (error) {\n console.error('[order-notifications] notify failed', ref, event, error)\n return { outcome: 'handled', channels: [] }\n }\n}\n\nexport type SendOrderReceiptOutcome =\n | { outcome: 'sent'; channel: CommerceModel.BuyerNotificationChannel }\n | { outcome: 'no_such_order' }\n | { outcome: 'not_configured' }\n | { outcome: 'invalid_recipient' }\n | { outcome: 'failed'; error: string }\n\n/**\n * Sends the receipt again, on the merchant's say-so, to the address or number\n * they gave (AGL-3610) — the order dialog's \"Resend receipt\".\n *\n * NOT idempotent, on purpose: a resend IS the second send. The route in front\n * of it is rate-limited instead, and the send is recorded on the timeline so\n * the merchant can see it went. It does not consult the store's moment\n * switches either — a merchant who turned automatic receipts off can still\n * hand one to a customer who asks.\n */\nexport async function sendOrderReceipt(\n ref: OrderRef,\n input: {\n channel: CommerceModel.BuyerNotificationChannel\n to: string\n firestore?: FirebaseFirestore.Firestore\n },\n): Promise<SendOrderReceiptOutcome> {\n try {\n const firestore = input.firestore ?? firebaseAdmin.app().firestore()\n const { orderRef, order } = await readOrder(firestore, ref)\n if (!order) return { outcome: 'no_such_order' }\n if (input.channel === 'email') {\n if (!isEmailConfigured()) return { outcome: 'not_configured' }\n if (!emailOf(input.to)) return { outcome: 'invalid_recipient' }\n } else {\n if (!pluginSmsMessaging()?.isConfigured()) {\n return { outcome: 'not_configured' }\n }\n if (!Aglyn.normalizePhone(input.to)) {\n return { outcome: 'invalid_recipient' }\n }\n }\n const store = await readStore(firestore, ref.hostId)\n const message = composeOrderBuyerMessage({\n event: 'receipt',\n order,\n orderId: ref.orderId,\n businessName: String(\n resolveHostToken('businessName', store.host as HostTokenSource) ?? '',\n ),\n currency: store.currency,\n statusUrl: statusLink(store, ref),\n // A sale of card reader hardware states the terms it is sold under (AGL-4038).\n receiptFooter: withPosHardwareReceiptNotice(String(store.settings['receiptFooter'] ?? ''), order),\n downloadLinks: downloadLinksFor(store, ref, order),\n })\n if (!message) return { outcome: 'failed', error: 'Nothing to send' }\n if (input.channel === 'email') {\n await deliverEmail(store, ref, emailOf(input.to), message, 'order-receipt')\n } else {\n const sent = await deliverSms(ref, input.to, message, 'order-receipt', null)\n if (sent.refused) return { outcome: 'failed', error: sent.refused }\n }\n await settleMessage(firestore, orderRef, null, input.channel, 'Receipt re-sent')\n return { outcome: 'sent', channel: input.channel }\n } catch (error) {\n console.error('[order-notifications] receipt send failed', ref, error)\n return {\n outcome: 'failed',\n error: error instanceof Error ? error.message : String(error),\n }\n }\n}\n\n/**\n * What the online receipt sends needs from this module (AGL-3610): whether\n * the store left receipts on, and the `order.number` / `order.statusUrl`\n * tokens. The cart and buy-now receipts compose their own summary (license\n * keys and download links built from the Stripe session) inside the\n * webhook's redelivery guard, so they ask here rather than route through\n * {@link notifyOrderBuyer}.\n */\nexport async function onlineReceiptExtras(\n hostId: string,\n orderId: string,\n firestore: FirebaseFirestore.Firestore = firebaseAdmin.app().firestore(),\n): Promise<{ enabled: boolean; tokens: Record<string, string> }> {\n try {\n const store = await readStore(firestore, hostId)\n const { order } = await readOrder(firestore, { hostId, orderId })\n return {\n enabled: CommerceModel.buyerNotificationEnabled(\n store.settings['buyerNotifications'],\n 'receipt',\n ),\n tokens: {\n 'order.number': CommerceModel.formatOrderNumber(order ?? {}, orderId),\n 'order.statusUrl': statusLink(store, { hostId, orderId }),\n },\n }\n } catch (error) {\n console.error('[order-notifications] receipt extras failed', error)\n return { enabled: true, tokens: { 'order.number': '', 'order.statusUrl': '' } }\n }\n}\n"],"names":["Aglyn","withPosHardwareReceiptNotice","pluginSmsMessaging","resolveSiteTimeZone","resolveHostToken","firebaseAdmin","getOrgForHost","hostSendingIdentity","meterHostEmail","renderHostEmailWithTokens","isEmailConfigured","renderTextEmailHtml","sendEmail","resolvePluginOrderEmailCopies","withOrderEmailDataBlocks","CommerceModel","orderViewFromData","mintDownloadToken","orderStatusUrl","readStore","firestore","hostId","settings","settingsSnapshot","hostSnapshot","hostRef","collection","doc","Promise","all","get","catch","data","host","currency","String","lineLabel","line","quantity","name","variantLabel","statusLink","store","ref","orderId","hostPublicOrigin","cname","subdomain","composeOrderBuyerMessage","input","order","event","businessName","statusUrl","options","lines","lineItems","number","formatOrderNumber","money","cents","formatOrderMoney","base","link","smsLink","totalCents","totals","Number","amountCents","licenseText","Object","entries","licenseKeys","flatMap","productId","keys","find","item","map","key","join","downloads","downloadLinks","url","linesText","unitAmountCents","summary","filter","Boolean","footer","receiptFooter","occurrence","emailKey","BUYER_NOTIFICATION_EMAIL_KEYS","receipt","tokens","subject","text","sms","timelineDetail","fulfillment","fulfillments","fulfillmentId","entry","id","sort","a","b","atMs","handover","shipped","fulfillmentLineQuantities","lineItemId","tracking","fulfillmentTrackingUrl","hasTracking","trackingNumber","physical","some","productType","channel","remainingUnits","remainingFulfillmentLines","reduce","sum","carrier","carrierLabelFor","trackingSentence","remainingSentence","delivered","pickup","fulfillmentMethod","where","locationName","address","hours","instructions","picked_up","ready_for_pickup","delivery","localDelivery","window","windowLabel","outForDeliveryAtMs","out_for_delivery","refundCents","Math","max","round","refundedLines","refundLineIndexes","index","note","fullyRefunded","refundId","refundedCents","refunded","wasPaid","paymentIntentId","status","timeline","cancelled","claimMessage","orderRef","marker","runTransaction","transaction","snapshot","exists","sent","update","state","Date","now","settleMessage","detail","liftLegacyOrder","appendOrderEvent","error","console","releaseMessage","FieldValue","delete","undefined","EMAIL_COPIES_TIMEOUT_MS","deliverEmail","to","message","context","about","designed","org","copies","recordId","moment","recipient","timeoutMs","bcc","html","settle","result","length","fromName","resolveBrandingProfile","sendingIdentity","audience","owedFor","Error","describeUnsentEmail","failure","reason","deliverSms","quiet","isConfigured","refused","timeZone","owner","outcome","send","body","purpose","quietHours","scheduledForMs","downloadLinksFor","origin","digital","token","fromEntries","encodeURIComponent","readOrder","emailOf","value","email","trim","test","notifyOrderBuyer","app","toggles","buyerNotificationEnabled","customerEmail","phone","customerPhone","targets","push","channels","target","buyerNotificationMarker","claimed","held","sendOrderReceipt","normalizePhone","onlineReceiptExtras","enabled"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,sBAAqB;AAC5C,SAASC,4BAA4B,QAAQ,iCAA6B;AAC1E,SAASC,kBAAkB,QAAQ,mDAAkD;AACrF,SAASC,mBAAmB,QAAQ,+CAA8C;AAClF,SACEC,gBAAgB,QAEX,qCAAoC;AAC3C,SACEC,aAAa,EACbC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,EACdC,yBAAyB,QACpB,2BAA0B;AACjC,SACEC,iBAAiB,EACjBC,mBAAmB,EACnBC,SAAS,QACJ,2BAA0B;AACjC,SACEC,6BAA6B,EAC7BC,wBAAwB,QACnB,wDAAuD;AAC9D,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,iBAAiB,QAAQ,yBAAqB;AACvD,SAASC,iBAAiB,QAAQ,gBAAY;AAC9C,SAASC,cAAc,QAAQ,0BAAsB;AAmGrD,eAAeC,UACbC,SAAsC,EACtCC,MAAc;qBAaKC;QANDC,wBAITC;IATT,MAAMC,UAAUL,UAAUM,UAAU,CAAC,SAASC,GAAG,CAACN;IAClD,MAAM,CAACG,cAAcD,iBAAiB,GAAG,MAAMK,QAAQC,GAAG,CAAC;QACzDJ,QAAQK,GAAG,GAAGC,KAAK,CAAC,IAAM;QAC1BN,QAAQC,UAAU,CAAC,YAAYC,GAAG,CAAC,SAASG,GAAG,GAAGC,KAAK,CAAC,IAAM;KAC/D;IACD,MAAMT,mBAAYC,qCAAAA,yBAAAA,iBAAkBS,I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,MAAMlH,MAAMuE,OAAO,EAAE;QAC9D,OAAO;YAAEiG,SAAS;YAAQjG,SAASvE,MAAMuE,OAAO;QAAC;IACnD,EAAE,OAAO0D,OAAO;QACdC,QAAQD,KAAK,CAAC,6CAA6CvI,KAAKuI;QAChE,OAAO;YACLuC,SAAS;YACTvC,OAAOA,iBAAiB6B,QAAQ7B,MAAMS,OAAO,GAAGxJ,OAAO+I;QACzD;IACF;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,eAAeyE,oBACpBtO,MAAc,EACduB,OAAe,EACfxB,YAAyCf,cAAcuO,GAAG,GAAGxN,SAAS,EAAE;IAExE,IAAI;QACF,MAAMsB,QAAQ,MAAMvB,UAAUC,WAAWC;QACzC,MAAM,EAAE6B,KAAK,EAAE,GAAG,MAAMmL,UAAUjN,WAAW;YAAEC;YAAQuB;QAAQ;QAC/D,OAAO;YACLgN,SAAS7O,cAAc+N,wBAAwB,CAC7CpM,MAAMpB,QAAQ,CAAC,qBAAqB,EACpC;YAEFyE,QAAQ;gBACN,gBAAgBhF,cAAc2C,iBAAiB,CAACR,gBAAAA,QAAS,CAAC,GAAGN;gBAC7D,mBAAmBH,WAAWC,OAAO;oBAAErB;oBAAQuB;gBAAQ;YACzD;QACF;IACF,EAAE,OAAOsI,OAAO;QACdC,QAAQD,KAAK,CAAC,+CAA+CA;QAC7D,OAAO;YAAE0E,SAAS;YAAM7J,QAAQ;gBAAE,gBAAgB;gBAAI,mBAAmB;YAAG;QAAE;IAChF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/order-notifications.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 * as Aglyn from '@aglyn/aglyn/server'\nimport { withPosHardwareReceiptNotice } from '../model/pos-hardware-terms'\nimport { pluginSmsMessaging } from '@aglyn/aglyn/plugin-manager/plugin-sms-messaging'\nimport { resolveSiteTimeZone } from '@aglyn/aglyn/app-utils/collection-entry-date'\nimport {\n resolveHostToken,\n type HostTokenSource,\n} from '@aglyn/aglyn/app-utils/host-tokens'\nimport {\n firebaseAdmin,\n getOrgForHost,\n hostSendingIdentity,\n meterHostEmail,\n renderHostEmailWithTokens,\n} from '@aglyn/tenant-data-admin'\nimport {\n isEmailConfigured,\n renderTextEmailHtml,\n sendEmail,\n} from '@aglyn/shared-util-email'\nimport {\n resolvePluginOrderEmailCopies,\n withOrderEmailDataBlocks,\n} from '@aglyn/aglyn/plugin-manager/plugin-order-email-copies'\nimport * as CommerceModel from '../model'\nimport { orderViewFromData } from './api-v1/order-view'\nimport { mintDownloadToken } from './download'\nimport { orderStatusUrl } from './order-status-token'\n\n/**\n * Every message a buyer gets about their order, through ONE door (AGL-3610).\n *\n * Before this, the buyer heard about their order once — the online receipt —\n * and never again: a register sale sent nothing, a paid payment link sent\n * nothing, and shipping, delivery, refunds and cancellations were silent\n * (`fulfill-order.ts` said so on purpose). Every path that moves an order now\n * makes one call here, and this decides what that moment owes the buyer:\n *\n * - whether the store turned the moment off (`buyerNotifications` on the\n * store settings; ON unless explicitly off — see the model),\n * - which channels can carry it (email when mail is configured and the\n * order has an address; a text when the platform's SMS provider is\n * configured and the order carries the buyer's phone),\n * - and whether it was already sent.\n *\n * ## ONCE PER MOMENT, PER OCCURRENCE, PER CHANNEL\n *\n * Stripe redelivers webhooks, admins click twice, a lost response is retried.\n * Each message is CLAIMED before it is sent: a transaction reads the order's\n * `buyerNotifications` map and writes a `sending` marker for\n * `event__occurrence__channel` only if none is there. Exactly one of two\n * racing callers wins the claim; the other returns `already`. The occurrence\n * is the shipment id for `shipped` and the refund id for `refunded`, so a\n * second parcel or a second partial refund is a new message, while a\n * redelivered one is not.\n *\n * A send that fails RELEASES its claim so the next attempt can try again. A\n * process that dies between claim and send leaves the marker in `sending` and\n * the message unsent — at most once, never twice, which is the right side to\n * fail on for mail a buyer reads as \"did they charge me again?\".\n *\n * ## NEVER THROWS\n *\n * Every caller is past its point of no return — money moved, an order\n * shipped — so a mail outage must not turn into a 500 that invites the\n * merchant to do it again. Failures are logged and returned as outcomes.\n *\n * Shared with the order-processing and POS lanes (AGL-3611, AGL-3607): call\n * {@link notifyOrderBuyer} from any new path that moves an order, and\n * {@link sendOrderReceipt} for an explicit, merchant-asked send.\n */\n\nexport type OrderBuyerEvent = CommerceModel.BuyerNotificationEvent\n\nexport interface OrderRef {\n hostId: string\n orderId: string\n}\n\nexport interface NotifyOrderBuyerOptions {\n /** `shipped`: which shipment. Absent means the order's latest one. */\n fulfillmentId?: string\n /** `refunded`: the refund's own id (Stripe's), the occurrence key. */\n refundId?: string\n /** `refunded`: what THIS refund moved, in cents. */\n refundCents?: number\n /** `refunded`: the line indexes refunded by name, when any were. */\n refundLineIndexes?: readonly number[]\n /** `refunded`: whether this refund closed the order. */\n fullyRefunded?: boolean\n /**\n * The buyer's address when the order document does not carry it — a POS\n * folio sale attributed to the reservation's guest, a payment link whose\n * payer Stripe named. The order's own `customerEmail` wins when present.\n */\n email?: string | null\n /** Injected in specs. */\n firestore?: FirebaseFirestore.Firestore\n}\n\nexport type OrderBuyerChannelOutcome =\n | { channel: CommerceModel.BuyerNotificationChannel; outcome: 'sent' }\n | { channel: CommerceModel.BuyerNotificationChannel; outcome: 'already' }\n | {\n channel: CommerceModel.BuyerNotificationChannel\n outcome: 'failed'\n error: string\n }\n\nexport type NotifyOrderBuyerOutcome =\n | { outcome: 'disabled' }\n | { outcome: 'no_such_order' }\n /** The moment does not apply to this order (a counter sale \"shipping\"). */\n | { outcome: 'not_applicable' }\n /** No channel could carry it: no address, no mail or text configured. */\n | { outcome: 'no_recipient' }\n | { outcome: 'handled'; channels: OrderBuyerChannelOutcome[] }\n\ninterface StoreContext {\n firestore: FirebaseFirestore.Firestore\n hostRef: FirebaseFirestore.DocumentReference\n host: Record<string, unknown>\n settings: Record<string, unknown>\n currency: string\n}\n\nasync function readStore(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n): Promise<StoreContext> {\n const hostRef = firestore.collection('hosts').doc(hostId)\n const [hostSnapshot, settingsSnapshot] = await Promise.all([\n hostRef.get().catch(() => null),\n hostRef.collection('settings').doc('store').get().catch(() => null),\n ])\n const settings = (settingsSnapshot?.data?.() ?? {}) as Record<string, unknown>\n return {\n firestore,\n hostRef,\n host: (hostSnapshot?.data?.() ?? {}) as Record<string, unknown>,\n settings,\n currency: String(settings['currency'] ?? 'USD') || 'USD',\n }\n}\n\nfunction lineLabel(line: CommerceModel.OrderLineItem): string {\n return `${line.quantity}× ${line.name}${\n line.variantLabel ? ` (${line.variantLabel})` : ''\n }`\n}\n\n/** The status link, or the store's home page when no link can be minted. */\nfunction statusLink(store: StoreContext, ref: OrderRef): string {\n return (\n orderStatusUrl(store.host as never, ref.hostId, ref.orderId) ??\n Aglyn.hostPublicOrigin({\n cname: typeof store.host['cname'] === 'string' ? store.host['cname'] : null,\n subdomain:\n typeof store.host['subdomain'] === 'string'\n ? store.host['subdomain']\n : null,\n }) ??\n ''\n )\n}\n\ninterface ComposedMessage {\n emailKey: string\n /** Tokens for the designed email. */\n tokens: Record<string, string>\n /** Subject when the template renders none. */\n subject: string\n /** Plain-text body when the template renders none. */\n text: string\n /** The text message, kept short: one or two segments. */\n sms: string\n /** The order timeline line recording the send, channel appended. */\n timelineDetail: string\n}\n\n/** What the moment says. `null` when it does not apply to this order. */\nexport function composeOrderBuyerMessage(input: {\n event: OrderBuyerEvent\n order: CommerceModel.HostOrder\n orderId: string\n businessName: string\n currency: string\n statusUrl: string\n receiptFooter?: string\n /** Absolute digital-delivery links for a receipt, by product id. */\n downloadLinks?: Record<string, string>\n options?: NotifyOrderBuyerOptions\n}): (ComposedMessage & { occurrence: string }) | null {\n const {\n event,\n order,\n orderId,\n businessName,\n currency,\n statusUrl,\n options = {},\n } = input\n const lines = order.lineItems ?? []\n const number = CommerceModel.formatOrderNumber(order, orderId)\n const money = (cents: number) =>\n CommerceModel.formatOrderMoney(cents, currency)\n const store = businessName || 'The store'\n const base = {\n 'order.number': number,\n 'order.statusUrl': statusUrl,\n 'order.ref': orderId,\n }\n const link = statusUrl ? `\\n\\nView your order: ${statusUrl}` : ''\n const smsLink = statusUrl ? ` ${statusUrl}` : ''\n\n if (event === 'receipt') {\n const totalCents =\n order.totals?.totalCents ?? Number(order.amountCents ?? 0)\n const licenseText = Object.entries(\n ((order as { licenseKeys?: Record<string, string[]> }).licenseKeys ??\n {}) as Record<string, string[]>,\n )\n .flatMap(([productId, keys]) => {\n const line = lines.find((item) => item.productId === productId)\n return (keys ?? []).map(\n (key) => `License key (${line?.name ?? 'product'}): ${key}`,\n )\n })\n .join('\\n')\n const downloads = Object.entries(input.downloadLinks ?? {})\n .map(([productId, url]) => {\n const line = lines.find((item) => item.productId === productId)\n return `Download ${line?.name ?? 'your file'}: ${url}`\n })\n .join('\\n')\n const linesText = lines\n .map(\n (line) =>\n `${lineLabel(line)} — ${money(line.unitAmountCents * line.quantity)}`,\n )\n .join('\\n')\n const summary = [linesText, licenseText, downloads]\n .filter(Boolean)\n .join('\\n\\n')\n const footer = String(input.receiptFooter ?? '')\n return {\n occurrence: 'order',\n emailKey: CommerceModel.BUYER_NOTIFICATION_EMAIL_KEYS.receipt,\n tokens: {\n ...base,\n 'order.summary': summary,\n 'order.total': money(totalCents),\n 'store.receiptFooter': footer,\n },\n subject: 'Receipt for your order',\n text:\n `Thanks for your purchase!\\n\\n${summary}\\n\\nTotal: ${money(totalCents)}\\n` +\n `Order ${number}` +\n (footer ? `\\n\\n${footer}` : '') +\n link,\n sms: `${store}: receipt for order ${number}, ${money(totalCents)}.${smsLink}`,\n timelineDetail: 'Receipt sent',\n }\n }\n\n if (event === 'shipped') {\n const fulfillments = order.fulfillments ?? []\n const fulfillment = options.fulfillmentId\n ? fulfillments.find((entry) => entry.id === options.fulfillmentId)\n : [...fulfillments].sort((a, b) => (b.atMs ?? 0) - (a.atMs ?? 0))[0]\n if (!fulfillment) return null\n // Collected at the counter or handed over by the store's driver\n // (AGL-3624): \"picked up\" and \"delivered\" say so, never \"shipped\".\n if (fulfillment.handover) return null\n // The units THIS shipment carried (AGL-3611): a partial shipment of a\n // line names its own count, not the line's.\n const shipped = CommerceModel.fulfillmentLineQuantities(order, fulfillment)\n .map((entry) =>\n lines[entry.lineItemId] ? { ...lines[entry.lineItemId], quantity: entry.quantity } : null,\n )\n .filter(Boolean) as CommerceModel.OrderLineItem[]\n const tracking = CommerceModel.fulfillmentTrackingUrl(fulfillment)\n const hasTracking = Boolean(fulfillment.trackingNumber)\n // Nothing physical left the building: a register sale handed over the\n // counter, or a digital-only order the merchant marked fulfilled. A\n // \"your order is on its way\" email for either is noise at best.\n const physical = shipped.some(\n (line) =>\n line.productType !== 'digital' && line.productType !== 'service',\n )\n if (!hasTracking && (order.channel === 'pos' || !physical)) return null\n // Shippable units still out, over every active shipment (AGL-3611).\n const remainingUnits = CommerceModel.remainingFulfillmentLines(order).reduce(\n (sum, entry) => sum + entry.quantity,\n 0,\n )\n const carrier = CommerceModel.carrierLabelFor(fulfillment.carrier)\n const trackingSentence = hasTracking\n ? `Tracking: ${[carrier, fulfillment.trackingNumber]\n .filter(Boolean)\n .join(' ')}${tracking ? ` — ${tracking}` : ''}`\n : ''\n const remainingSentence =\n remainingUnits > 0\n ? `${remainingUnits} more item${remainingUnits === 1 ? '' : 's'} will ship separately.`\n : ''\n const summary = shipped.map(lineLabel).join('\\n')\n return {\n occurrence: fulfillment.id,\n emailKey: CommerceModel.BUYER_NOTIFICATION_EMAIL_KEYS.shipped,\n tokens: {\n ...base,\n 'shipment.summary': summary,\n 'shipment.carrier': carrier,\n 'shipment.trackingNumber': String(fulfillment.trackingNumber ?? ''),\n 'shipment.tracking': trackingSentence,\n 'shipment.remaining': remainingSentence,\n },\n subject: `Your order ${number} has shipped`,\n text:\n `${store} shipped items from order ${number}.\\n\\n${summary}` +\n (trackingSentence ? `\\n\\n${trackingSentence}` : '') +\n (remainingSentence ? `\\n\\n${remainingSentence}` : '') +\n link,\n sms:\n `${store}: order ${number} has shipped.` +\n (tracking ? ` Track it: ${tracking}` : smsLink),\n timelineDetail: 'Shipping confirmation sent',\n }\n }\n\n if (event === 'delivered') {\n // A counter sale is \"delivered\" the moment it is handed over.\n if (order.channel === 'pos') return null\n const summary = lines.map(lineLabel).join('\\n')\n return {\n occurrence: 'order',\n emailKey: CommerceModel.BUYER_NOTIFICATION_EMAIL_KEYS.delivered,\n tokens: { ...base, 'order.summary': summary },\n subject: `Your order ${number} was delivered`,\n text:\n `${store} marked order ${number} as delivered.\\n\\n${summary}` + link,\n sms: `${store}: order ${number} was delivered.${smsLink}`,\n timelineDetail: 'Delivery confirmation sent',\n }\n }\n\n if (event === 'ready_for_pickup' || event === 'picked_up') {\n const pickup = order.pickup\n if (order.fulfillmentMethod !== 'pickup' || !pickup) return null\n const summary = lines.map(lineLabel).join('\\n')\n const where = `${pickup.locationName}${pickup.address ? `, ${pickup.address}` : ''}`\n const hours = pickup.hours ? `Pickup hours:\\n${pickup.hours}` : ''\n const instructions = pickup.instructions ?? ''\n if (event === 'picked_up') {\n return {\n occurrence: 'order',\n emailKey: CommerceModel.BUYER_NOTIFICATION_EMAIL_KEYS.picked_up,\n tokens: { ...base, 'order.summary': summary, 'pickup.location': where },\n subject: `You picked up order ${number}`,\n text: `Order ${number} was picked up from ${where}. Thanks for shopping with ${store}.\\n\\n${summary}` + link,\n sms: `${store}: order ${number} was picked up. Thank you!${smsLink}`,\n timelineDetail: 'Pickup confirmation sent',\n }\n }\n return {\n occurrence: 'order',\n emailKey: CommerceModel.BUYER_NOTIFICATION_EMAIL_KEYS.ready_for_pickup,\n tokens: {\n ...base,\n 'order.summary': summary,\n 'pickup.location': where,\n 'pickup.hours': hours,\n 'pickup.instructions': instructions,\n },\n subject: `Your order ${number} is ready for pickup`,\n text:\n `Your order ${number} is ready for pickup at ${where}.\\n\\n${summary}` +\n (hours ? `\\n\\n${hours}` : '') +\n (instructions ? `\\n\\n${instructions}` : '') +\n `\\n\\nBring your order number, ${number}.` +\n link,\n sms: `${store}: order ${number} is ready for pickup at ${pickup.locationName}.${smsLink}`,\n timelineDetail: 'Ready-for-pickup notice sent',\n }\n }\n\n if (event === 'out_for_delivery') {\n const delivery = order.localDelivery\n if (order.fulfillmentMethod !== 'local_delivery' || !delivery) return null\n const summary = lines.map(lineLabel).join('\\n')\n const window = delivery.windowLabel ?? ''\n return {\n // Each run out the door is its own message: a failed drop sent out\n // again tells the buyer again.\n occurrence: String(delivery.outForDeliveryAtMs ?? 'order'),\n emailKey: CommerceModel.BUYER_NOTIFICATION_EMAIL_KEYS.out_for_delivery,\n tokens: { ...base, 'order.summary': summary, 'delivery.window': window },\n subject: `Your order ${number} is out for delivery`,\n text:\n `${store} is on the way with order ${number}` +\n (window ? `, in your window ${window}` : '') +\n `.\\n\\n${summary}` +\n link,\n sms: `${store}: order ${number} is out for delivery${window ? ` (${window})` : ''}.${smsLink}`,\n timelineDetail: 'Out-for-delivery notice sent',\n }\n }\n\n if (event === 'refunded') {\n const refundCents = Math.max(0, Math.round(Number(options.refundCents ?? 0)))\n if (!(refundCents > 0)) return null\n const refundedLines = (options.refundLineIndexes ?? [])\n .map((index) => lines[index])\n .filter(Boolean) as CommerceModel.OrderLineItem[]\n const summary = refundedLines.map(lineLabel).join('\\n')\n const note = options.fullyRefunded\n ? 'Your order has been refunded in full.'\n : 'The rest of your order is unchanged.'\n return {\n // The refund's own id is the occurrence; without one, the running\n // total after this refund is (each settled refund raises it).\n occurrence:\n options.refundId ||\n `total-${Number(order.refundedCents ?? 0) || refundCents}`,\n emailKey: CommerceModel.BUYER_NOTIFICATION_EMAIL_KEYS.refunded,\n tokens: {\n ...base,\n 'refund.amount': money(refundCents),\n 'refund.summary': summary,\n 'refund.note': note,\n },\n subject: `Refund for your order ${number}`,\n text:\n `${store} refunded ${money(refundCents)} on order ${number}.` +\n (summary ? `\\n\\n${summary}` : '') +\n `\\n\\n${note}\\n\\nRefunds go back to the original payment method and ` +\n 'usually appear within 5 to 10 business days, depending on your bank.' +\n link,\n sms: `${store}: ${money(refundCents)} refunded on order ${number}.${smsLink}`,\n timelineDetail: `Refund confirmation sent (${money(refundCents)})`,\n }\n }\n\n // cancelled\n const summary = lines.map(lineLabel).join('\\n')\n const wasPaid = Boolean(\n order.paymentIntentId ||\n (order.channel === 'pos' && order.status !== 'pending') ||\n (order.timeline ?? []).some((entry) => entry?.event === 'paid'),\n )\n const note = wasPaid\n ? `Questions about a payment? Reply to this email or contact ${store}.`\n : ''\n return {\n occurrence: 'order',\n emailKey: CommerceModel.BUYER_NOTIFICATION_EMAIL_KEYS.cancelled,\n tokens: { ...base, 'order.summary': summary, 'cancel.note': note },\n subject: `Your order ${number} was canceled`,\n text:\n `${store} canceled order ${number}.\\n\\n${summary}` +\n (note ? `\\n\\n${note}` : '') +\n link,\n sms: `${store}: order ${number} was canceled.${smsLink}`,\n timelineDetail: 'Cancellation notice sent',\n }\n}\n\n/**\n * Claims one message in a transaction. `true` when this caller owns the send;\n * `false` when a marker is already there (sent, or being sent).\n */\nasync function claimMessage(\n firestore: FirebaseFirestore.Firestore,\n orderRef: FirebaseFirestore.DocumentReference,\n marker: string,\n channel: CommerceModel.BuyerNotificationChannel,\n): Promise<boolean> {\n return firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(orderRef)\n if (!snapshot.exists) return false\n const sent = (snapshot.get('buyerNotifications') ?? {}) as Record<\n string,\n unknown\n >\n if (sent[marker]) return false\n transaction.update(orderRef, {\n [`buyerNotifications.${marker}`]: {\n state: 'sending',\n channel,\n atMs: Date.now(),\n },\n })\n return true\n })\n}\n\n/** Marks a claimed message sent and records it on the order timeline. */\nasync function settleMessage(\n firestore: FirebaseFirestore.Firestore,\n orderRef: FirebaseFirestore.DocumentReference,\n marker: string | null,\n channel: CommerceModel.BuyerNotificationChannel,\n detail: string,\n): Promise<void> {\n await firestore\n .runTransaction(async (transaction) => {\n const snapshot = await transaction.get(orderRef)\n if (!snapshot.exists) return\n const order = CommerceModel.liftLegacyOrder(\n (snapshot.data() ?? {}) as never,\n )\n const atMs = Date.now()\n transaction.update(orderRef, {\n ...(marker\n ? {\n [`buyerNotifications.${marker}`]: { state: 'sent', channel, atMs },\n }\n : {}),\n timeline: CommerceModel.appendOrderEvent(\n order,\n 'buyer-notified',\n `${detail} by ${channel === 'sms' ? 'text' : 'email'}`,\n atMs,\n ),\n })\n })\n .catch((error) => {\n console.error('[order-notifications] settle failed', marker, error)\n })\n}\n\nasync function releaseMessage(\n orderRef: FirebaseFirestore.DocumentReference,\n marker: string,\n): Promise<void> {\n await orderRef\n .update({\n [`buyerNotifications.${marker}`]:\n firebaseAdmin.firestore.FieldValue.delete(),\n })\n .catch(() => undefined)\n}\n\n/** How long a buyer email waits on plugins asking to be copied on it. */\nconst EMAIL_COPIES_TIMEOUT_MS = 3_000\n\nasync function deliverEmail(\n store: StoreContext,\n ref: OrderRef,\n to: string,\n message: ComposedMessage,\n context: string,\n /** The moment and order, for plugins copied on it; absent for a merchant-asked resend. */\n about?: { event: OrderBuyerEvent; order: CommerceModel.HostOrder },\n): Promise<void> {\n const designed = await renderHostEmailWithTokens(\n store.firestore,\n ref.hostId,\n message.emailKey,\n message.tokens,\n )\n const org = await getOrgForHost(ref.hostId).catch(() => null)\n // Plugins copied on this email (AGL-3699): a review platform's invitation\n // address, with the data block it reads. Asked through core's seam, by\n // the email's key and moment; nothing answers unless a site connected one.\n const copies = about\n ? await resolvePluginOrderEmailCopies(\n {\n hostId: ref.hostId,\n recordId: ref.orderId,\n emailKey: message.emailKey,\n moment: about.event,\n recipient: to,\n order: orderViewFromData(ref.orderId, about.order as Record<string, any>),\n },\n { timeoutMs: EMAIL_COPIES_TIMEOUT_MS },\n )\n : { bcc: [] as string[], html: '', settle: async () => undefined }\n const subject = designed?.subject ?? message.subject\n const text = designed?.text || message.text\n // A data block lives in the HTML part, so a text-only email gets the same\n // HTML part `sendEmail` would have synthesized, carrying it.\n const html = copies.html\n ? withOrderEmailDataBlocks(designed?.html || renderTextEmailHtml(text, subject), copies.html)\n : designed?.html\n const result = await sendEmail({\n to,\n subject,\n text,\n ...(html ? { html } : {}),\n ...(copies.bcc.length ? { bcc: copies.bcc } : {}),\n fromName: Aglyn.resolveBrandingProfile(org?.org as never).fromName,\n sendingIdentity: await hostSendingIdentity(ref.hostId),\n audience: 'tenant',\n context,\n // Owed to the recipient by their own order: the phishing screen's soft\n // rules never hold it (AGL-3356).\n owedFor: 'order',\n })\n await copies.settle(Boolean(result?.sent))\n // A message that did not leave is NOT sent (AGL-4227): thrown, so the\n // caller releases the order's marker and reports this channel failed rather\n // than writing \"sent\" on the order's timeline — the workspace's email limit,\n // a suppression or a provider refusal all end here. Nothing is metered for\n // it either: an email that never left is not a cost.\n if (!result?.sent) {\n throw new Error(`Email not sent: ${describeUnsentEmail(result)}`)\n }\n // Cost meter (AGL-1438), as every transactional store email.\n await meterHostEmail(ref.hostId)\n}\n\n/** Why a store email did not leave, in the words the order's failure records. */\nfunction describeUnsentEmail(result: unknown): string {\n const failure = result as { reason?: string; detail?: string } | null | undefined\n if (failure?.reason === 'rate-limited') {\n return failure.detail || 'the workspace reached its email limit'\n }\n return failure?.detail || failure?.reason || 'delivery failed'\n}\n\n/**\n * What a text attempt came to: `refused` names why nothing went (null when it\n * went), and `scheduledForMs` says it was held for the buyer's morning.\n */\ninterface SmsDelivery {\n refused: string | null\n scheduledForMs?: number\n}\n\n/**\n * Sends one order text. A receipt goes at once — the buyer is at the counter\n * or the checkout waiting for it. Every later moment (shipped, delivered,\n * refunded, canceled) can fire at any hour, from a carrier scan or a late\n * packing shift, so it asks the provider to keep quiet hours in the STORE's\n * zone: the best stand-in the platform has for a buyer whose own zone it was\n * never told, and right for the local and regional stores most texts come\n * from. Held texts arrive at 8 AM there.\n */\nasync function deliverSms(\n ref: OrderRef,\n to: string,\n message: ComposedMessage,\n context: string,\n quiet: { host: Record<string, unknown> } | null,\n): Promise<SmsDelivery> {\n const sms = pluginSmsMessaging()\n if (!sms?.isConfigured()) return { refused: 'Text messages are not configured' }\n let timeZone: string | null = null\n if (quiet) {\n const owner = await getOrgForHost(ref.hostId).catch(() => null)\n timeZone = resolveSiteTimeZone(\n (owner?.org ?? null) as { timeZone?: string } | null,\n quiet.host as { timeZone?: string },\n )\n }\n const outcome = await sms.send({\n to,\n body: message.sms,\n hostId: ref.hostId,\n purpose: 'transactional',\n context,\n ...(timeZone ? { quietHours: { timeZone } } : {}),\n })\n if (outcome.status !== 'sent') return { refused: outcome.status }\n return {\n refused: null,\n ...(outcome.scheduledForMs ? { scheduledForMs: outcome.scheduledForMs } : {}),\n }\n}\n\n/** Absolute download links for a receipt's digital lines. */\nfunction downloadLinksFor(\n store: StoreContext,\n ref: OrderRef,\n order: CommerceModel.HostOrder,\n): Record<string, string> {\n const origin = Aglyn.hostPublicOrigin({\n cname: typeof store.host['cname'] === 'string' ? store.host['cname'] : null,\n subdomain:\n typeof store.host['subdomain'] === 'string' ? store.host['subdomain'] : null,\n })\n const digital = (order.lineItems ?? []).filter(\n (line) => line.productType === 'digital',\n )\n if (!origin || !digital.length) return {}\n let token: string\n try {\n token = mintDownloadToken(ref.hostId, ref.orderId)\n } catch {\n return {}\n }\n return Object.fromEntries(\n digital.map((line) => [\n line.productId,\n `${origin}/api/commerce/download?hostId=${encodeURIComponent(ref.hostId)}` +\n `&orderId=${encodeURIComponent(ref.orderId)}` +\n `&productId=${encodeURIComponent(line.productId)}&token=${token}`,\n ]),\n )\n}\n\nasync function readOrder(\n firestore: FirebaseFirestore.Firestore,\n ref: OrderRef,\n): Promise<{\n orderRef: FirebaseFirestore.DocumentReference\n order: CommerceModel.HostOrder | null\n}> {\n const orderRef = firestore\n .collection('hosts')\n .doc(ref.hostId)\n .collection('orders')\n .doc(ref.orderId)\n const snapshot = await orderRef.get()\n return {\n orderRef,\n order: snapshot.exists\n ? CommerceModel.liftLegacyOrder((snapshot.data() ?? {}) as never)\n : null,\n }\n}\n\nfunction emailOf(value: unknown): string {\n const email = String(value ?? '').trim()\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email) ? email : ''\n}\n\n/**\n * Tells the buyer about one moment in their order's life, once. See the\n * module header. Never throws.\n */\nexport async function notifyOrderBuyer(\n ref: OrderRef,\n event: OrderBuyerEvent,\n options: NotifyOrderBuyerOptions = {},\n): Promise<NotifyOrderBuyerOutcome> {\n try {\n if (!ref.hostId || !ref.orderId) return { outcome: 'no_such_order' }\n const firestore = options.firestore ?? firebaseAdmin.app().firestore()\n const store = await readStore(firestore, ref.hostId)\n const toggles = store.settings['buyerNotifications']\n if (!CommerceModel.buyerNotificationEnabled(toggles, event)) {\n return { outcome: 'disabled' }\n }\n const { orderRef, order } = await readOrder(firestore, ref)\n if (!order) return { outcome: 'no_such_order' }\n const message = composeOrderBuyerMessage({\n event,\n order,\n orderId: ref.orderId,\n businessName: String(\n resolveHostToken('businessName', store.host as HostTokenSource) ?? '',\n ),\n // The currency the order was paid in, when not the store's (AGL-4248).\n currency: order.currency ? order.currency.toUpperCase() : store.currency,\n statusUrl: statusLink(store, ref),\n // A sale of card reader hardware states the terms it is sold under (AGL-4038).\n receiptFooter: withPosHardwareReceiptNotice(String(store.settings['receiptFooter'] ?? ''), order),\n downloadLinks:\n event === 'receipt' ? downloadLinksFor(store, ref, order) : undefined,\n options,\n })\n if (!message) return { outcome: 'not_applicable' }\n\n const email = emailOf(order.customerEmail) || emailOf(options.email)\n const phone = String(order.customerPhone ?? '').trim()\n const targets: {\n channel: CommerceModel.BuyerNotificationChannel\n to: string\n }[] = []\n if (email && isEmailConfigured()) targets.push({ channel: 'email', to: email })\n if (\n phone &&\n CommerceModel.buyerNotificationEnabled(toggles, 'texts') &&\n pluginSmsMessaging()?.isConfigured()\n ) {\n targets.push({ channel: 'sms', to: phone })\n }\n if (!targets.length) return { outcome: 'no_recipient' }\n\n const channels: OrderBuyerChannelOutcome[] = []\n for (const target of targets) {\n const marker = CommerceModel.buyerNotificationMarker(\n event,\n message.occurrence,\n target.channel,\n )\n const claimed = await claimMessage(\n firestore,\n orderRef,\n marker,\n target.channel,\n ).catch((error) => {\n console.error('[order-notifications] claim failed', marker, error)\n return false\n })\n if (!claimed) {\n channels.push({ channel: target.channel, outcome: 'already' })\n continue\n }\n const context = message.emailKey\n let held: number | null = null\n try {\n if (target.channel === 'email') {\n await deliverEmail(store, ref, target.to, message, context, { event, order })\n } else {\n const sent = await deliverSms(\n ref,\n target.to,\n message,\n context,\n event === 'receipt' ? null : { host: store.host },\n )\n if (sent.refused) throw new Error(sent.refused)\n held = sent.scheduledForMs ?? null\n }\n await settleMessage(\n firestore,\n orderRef,\n marker,\n target.channel,\n held\n ? `${message.timelineDetail} (held for the morning)`\n : message.timelineDetail,\n )\n channels.push({ channel: target.channel, outcome: 'sent' })\n } catch (error) {\n await releaseMessage(orderRef, marker)\n console.error('[order-notifications] send failed', {\n hostId: ref.hostId,\n orderId: ref.orderId,\n event,\n channel: target.channel,\n error,\n })\n channels.push({\n channel: target.channel,\n outcome: 'failed',\n error: error instanceof Error ? error.message : String(error),\n })\n }\n }\n return { outcome: 'handled', channels }\n } catch (error) {\n console.error('[order-notifications] notify failed', ref, event, error)\n return { outcome: 'handled', channels: [] }\n }\n}\n\nexport type SendOrderReceiptOutcome =\n | { outcome: 'sent'; channel: CommerceModel.BuyerNotificationChannel }\n | { outcome: 'no_such_order' }\n | { outcome: 'not_configured' }\n | { outcome: 'invalid_recipient' }\n | { outcome: 'failed'; error: string }\n\n/**\n * Sends the receipt again, on the merchant's say-so, to the address or number\n * they gave (AGL-3610) — the order dialog's \"Resend receipt\".\n *\n * NOT idempotent, on purpose: a resend IS the second send. The route in front\n * of it is rate-limited instead, and the send is recorded on the timeline so\n * the merchant can see it went. It does not consult the store's moment\n * switches either — a merchant who turned automatic receipts off can still\n * hand one to a customer who asks.\n */\nexport async function sendOrderReceipt(\n ref: OrderRef,\n input: {\n channel: CommerceModel.BuyerNotificationChannel\n to: string\n firestore?: FirebaseFirestore.Firestore\n },\n): Promise<SendOrderReceiptOutcome> {\n try {\n const firestore = input.firestore ?? firebaseAdmin.app().firestore()\n const { orderRef, order } = await readOrder(firestore, ref)\n if (!order) return { outcome: 'no_such_order' }\n if (input.channel === 'email') {\n if (!isEmailConfigured()) return { outcome: 'not_configured' }\n if (!emailOf(input.to)) return { outcome: 'invalid_recipient' }\n } else {\n if (!pluginSmsMessaging()?.isConfigured()) {\n return { outcome: 'not_configured' }\n }\n if (!Aglyn.normalizePhone(input.to)) {\n return { outcome: 'invalid_recipient' }\n }\n }\n const store = await readStore(firestore, ref.hostId)\n const message = composeOrderBuyerMessage({\n event: 'receipt',\n order,\n orderId: ref.orderId,\n businessName: String(\n resolveHostToken('businessName', store.host as HostTokenSource) ?? '',\n ),\n // The currency the order was paid in, when not the store's (AGL-4248).\n currency: order.currency ? order.currency.toUpperCase() : store.currency,\n statusUrl: statusLink(store, ref),\n // A sale of card reader hardware states the terms it is sold under (AGL-4038).\n receiptFooter: withPosHardwareReceiptNotice(String(store.settings['receiptFooter'] ?? ''), order),\n downloadLinks: downloadLinksFor(store, ref, order),\n })\n if (!message) return { outcome: 'failed', error: 'Nothing to send' }\n if (input.channel === 'email') {\n await deliverEmail(store, ref, emailOf(input.to), message, 'order-receipt')\n } else {\n const sent = await deliverSms(ref, input.to, message, 'order-receipt', null)\n if (sent.refused) return { outcome: 'failed', error: sent.refused }\n }\n await settleMessage(firestore, orderRef, null, input.channel, 'Receipt re-sent')\n return { outcome: 'sent', channel: input.channel }\n } catch (error) {\n console.error('[order-notifications] receipt send failed', ref, error)\n return {\n outcome: 'failed',\n error: error instanceof Error ? error.message : String(error),\n }\n }\n}\n\n/**\n * What the online receipt sends needs from this module (AGL-3610): whether\n * the store left receipts on, and the `order.number` / `order.statusUrl`\n * tokens. The cart and buy-now receipts compose their own summary (license\n * keys and download links built from the Stripe session) inside the\n * webhook's redelivery guard, so they ask here rather than route through\n * {@link notifyOrderBuyer}.\n */\nexport async function onlineReceiptExtras(\n hostId: string,\n orderId: string,\n firestore: FirebaseFirestore.Firestore = firebaseAdmin.app().firestore(),\n): Promise<{ enabled: boolean; tokens: Record<string, string> }> {\n try {\n const store = await readStore(firestore, hostId)\n const { order } = await readOrder(firestore, { hostId, orderId })\n return {\n enabled: CommerceModel.buyerNotificationEnabled(\n store.settings['buyerNotifications'],\n 'receipt',\n ),\n tokens: {\n 'order.number': CommerceModel.formatOrderNumber(order ?? {}, orderId),\n 'order.statusUrl': statusLink(store, { hostId, orderId }),\n },\n }\n } catch (error) {\n console.error('[order-notifications] receipt extras failed', error)\n return { enabled: true, tokens: { 'order.number': '', 'order.statusUrl': '' } }\n }\n}\n"],"names":["Aglyn","withPosHardwareReceiptNotice","pluginSmsMessaging","resolveSiteTimeZone","resolveHostToken","firebaseAdmin","getOrgForHost","hostSendingIdentity","meterHostEmail","renderHostEmailWithTokens","isEmailConfigured","renderTextEmailHtml","sendEmail","resolvePluginOrderEmailCopies","withOrderEmailDataBlocks","CommerceModel","orderViewFromData","mintDownloadToken","orderStatusUrl","readStore","firestore","hostId","settings","settingsSnapshot","hostSnapshot","hostRef","collection","doc","Promise","all","get","catch","data","host","currency","String","lineLabel","line","quantity","name","variantLabel","statusLink","store","ref","orderId","hostPublicOrigin","cname","subdomain","composeOrderBuyerMessage","input","order","event","businessName","statusUrl","options","lines","lineItems","number","formatOrderNumber","money","cents","formatOrderMoney","base","link","smsLink","totalCents","totals","Number","amountCents","licenseText","Object","entries","licenseKeys","flatMap","productId","keys","find","item","map","key","join","downloads","downloadLinks","url","linesText","unitAmountCents","summary","filter","Boolean","footer","receiptFooter","occurrence","emailKey","BUYER_NOTIFICATION_EMAIL_KEYS","receipt","tokens","subject","text","sms","timelineDetail","fulfillment","fulfillments","fulfillmentId","entry","id","sort","a","b","atMs","handover","shipped","fulfillmentLineQuantities","lineItemId","tracking","fulfillmentTrackingUrl","hasTracking","trackingNumber","physical","some","productType","channel","remainingUnits","remainingFulfillmentLines","reduce","sum","carrier","carrierLabelFor","trackingSentence","remainingSentence","delivered","pickup","fulfillmentMethod","where","locationName","address","hours","instructions","picked_up","ready_for_pickup","delivery","localDelivery","window","windowLabel","outForDeliveryAtMs","out_for_delivery","refundCents","Math","max","round","refundedLines","refundLineIndexes","index","note","fullyRefunded","refundId","refundedCents","refunded","wasPaid","paymentIntentId","status","timeline","cancelled","claimMessage","orderRef","marker","runTransaction","transaction","snapshot","exists","sent","update","state","Date","now","settleMessage","detail","liftLegacyOrder","appendOrderEvent","error","console","releaseMessage","FieldValue","delete","undefined","EMAIL_COPIES_TIMEOUT_MS","deliverEmail","to","message","context","about","designed","org","copies","recordId","moment","recipient","timeoutMs","bcc","html","settle","result","length","fromName","resolveBrandingProfile","sendingIdentity","audience","owedFor","Error","describeUnsentEmail","failure","reason","deliverSms","quiet","isConfigured","refused","timeZone","owner","outcome","send","body","purpose","quietHours","scheduledForMs","downloadLinksFor","origin","digital","token","fromEntries","encodeURIComponent","readOrder","emailOf","value","email","trim","test","notifyOrderBuyer","app","toggles","buyerNotificationEnabled","toUpperCase","customerEmail","phone","customerPhone","targets","push","channels","target","buyerNotificationMarker","claimed","held","sendOrderReceipt","normalizePhone","onlineReceiptExtras","enabled"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,sBAAqB;AAC5C,SAASC,4BAA4B,QAAQ,iCAA6B;AAC1E,SAASC,kBAAkB,QAAQ,mDAAkD;AACrF,SAASC,mBAAmB,QAAQ,+CAA8C;AAClF,SACEC,gBAAgB,QAEX,qCAAoC;AAC3C,SACEC,aAAa,EACbC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,EACdC,yBAAyB,QACpB,2BAA0B;AACjC,SAC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KAAK,EAAE,GAAG,MAAMmL,UAAUjN,WAAW;YAAEC;YAAQuB;QAAQ;QAC/D,OAAO;YACLiN,SAAS9O,cAAc+N,wBAAwB,CAC7CpM,MAAMpB,QAAQ,CAAC,qBAAqB,EACpC;YAEFyE,QAAQ;gBACN,gBAAgBhF,cAAc2C,iBAAiB,CAACR,gBAAAA,QAAS,CAAC,GAAGN;gBAC7D,mBAAmBH,WAAWC,OAAO;oBAAErB;oBAAQuB;gBAAQ;YACzD;QACF;IACF,EAAE,OAAOsI,OAAO;QACdC,QAAQD,KAAK,CAAC,+CAA+CA;QAC7D,OAAO;YAAE2E,SAAS;YAAM9J,QAAQ;gBAAE,gBAAgB;gBAAI,mBAAmB;YAAG;QAAE;IAChF;AACF"}
|
|
@@ -34,6 +34,8 @@ export interface PublicProductDetail {
|
|
|
34
34
|
*/
|
|
35
35
|
priceUsd: number | null;
|
|
36
36
|
compareAtPriceUsd?: number;
|
|
37
|
+
/** The merchant's own price per currency (AGL-4248), major units; it wins over conversion. */
|
|
38
|
+
fixedPrices?: Record<string, number>;
|
|
37
39
|
soldOut: boolean;
|
|
38
40
|
imageUrl?: string;
|
|
39
41
|
/**
|
|
@@ -96,6 +98,8 @@ export interface PublicModifierGroup {
|
|
|
96
98
|
priceCents: number;
|
|
97
99
|
/** What the choice adds on a variant priced differently, by variant id. */
|
|
98
100
|
priceCentsByVariant?: Record<string, number>;
|
|
101
|
+
/** What the choice adds in another currency (AGL-4248), minor units by ISO code. */
|
|
102
|
+
fixedPriceCents?: Record<string, number>;
|
|
99
103
|
/** The choice's card (AGL-4205): its picture, its note, and what a combo includes. */
|
|
100
104
|
imageUrl?: string;
|
|
101
105
|
note?: string;
|
|
@@ -106,6 +110,11 @@ export interface PublicModifierGroup {
|
|
|
106
110
|
export declare function publicModifierGroups(product: {
|
|
107
111
|
modifierGroups?: unknown;
|
|
108
112
|
}): PublicModifierGroup[];
|
|
113
|
+
/**
|
|
114
|
+
* Fixed prices per currency as a storefront may print them (AGL-4248): ISO
|
|
115
|
+
* codes to non-negative numbers, or nothing. The charge prices them again.
|
|
116
|
+
*/
|
|
117
|
+
export declare function publicFixedPrices(raw: unknown): Record<string, number> | undefined;
|
|
109
118
|
/**
|
|
110
119
|
* Map a lifted product onto the public PDP DTO.
|
|
111
120
|
*
|
|
@@ -39,6 +39,8 @@ import { readStoreDay } from "./store-day.js";
|
|
|
39
39
|
priceCents: option.priceCents
|
|
40
40
|
}, option.priceCentsByVariant && Object.keys(option.priceCentsByVariant).length ? {
|
|
41
41
|
priceCentsByVariant: _extends({}, option.priceCentsByVariant)
|
|
42
|
+
} : {}, publicFixedPrices(option.fixedPriceCents) ? {
|
|
43
|
+
fixedPriceCents: publicFixedPrices(option.fixedPriceCents)
|
|
42
44
|
} : {}, typeof option.imageUrl === 'string' && option.imageUrl ? {
|
|
43
45
|
imageUrl: option.imageUrl
|
|
44
46
|
} : {}, typeof option.note === 'string' && option.note.trim() ? {
|
|
@@ -51,6 +53,14 @@ import { readStoreDay } from "./store-day.js";
|
|
|
51
53
|
})
|
|
52
54
|
}));
|
|
53
55
|
}
|
|
56
|
+
/**
|
|
57
|
+
* Fixed prices per currency as a storefront may print them (AGL-4248): ISO
|
|
58
|
+
* codes to non-negative numbers, or nothing. The charge prices them again.
|
|
59
|
+
*/ export function publicFixedPrices(raw) {
|
|
60
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
|
|
61
|
+
const entries = Object.entries(raw).filter((entry)=>/^[A-Z]{3}$/.test(entry[0]) && typeof entry[1] === 'number' && Number.isFinite(entry[1]) && entry[1] >= 0);
|
|
62
|
+
return entries.length ? Object.fromEntries(entries) : undefined;
|
|
63
|
+
}
|
|
54
64
|
/**
|
|
55
65
|
* Map a lifted product onto the public PDP DTO.
|
|
56
66
|
*
|
|
@@ -87,6 +97,8 @@ import { readStoreDay } from "./store-day.js";
|
|
|
87
97
|
priceUsd: CommerceModel.variantHasPrice(variant) ? variant.priceUsd : null
|
|
88
98
|
}, variant.compareAtPriceUsd ? {
|
|
89
99
|
compareAtPriceUsd: variant.compareAtPriceUsd
|
|
100
|
+
} : {}, publicFixedPrices(variant.fixedPrices) ? {
|
|
101
|
+
fixedPrices: publicFixedPrices(variant.fixedPrices)
|
|
90
102
|
} : {}, {
|
|
91
103
|
soldOut: variant.inventory != null && Number(variant.inventory) <= 0 && product.oversellPolicy !== 'backorder'
|
|
92
104
|
}, variant.imageUrl ? {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/product.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 { PluginApiHandler } from '@aglyn/aglyn/server'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { readStoreDay } from './store-day'\n\nexport interface PublicProductDetail {\n id: string\n name: string\n slug: string\n description?: string\n type: CommerceModel.ProductType\n mediaUrls: string[]\n options: CommerceModel.ProductOption[]\n variants: Array<{\n id: string\n options?: Record<string, string>\n /**\n * `null` for a variant listed before it has a price (AGL-3676): the page\n * says \"Price coming soon\" and offers nothing to buy, as no sale door\n * would sell it.\n */\n priceUsd: number | null\n compareAtPriceUsd?: number\n soldOut: boolean\n imageUrl?: string\n /**\n * Merchant's stock-keeping unit (AGL-686). Carried into the public DTO\n * so the server can put `sku` on the Product structured data — Google\n * Merchant treats it as required for a product offer, and without it a\n * listing is simply ineligible for rich results rather than warned about.\n * It is already public information: it prints on receipts and invoices.\n */\n sku?: string\n /**\n * The buyer may choose the day they will use it (a pass bought ahead,\n * AGL-4043): the page offers an optional date. Absent when it does not.\n */\n asksUseDate?: true\n /** A short line on the variant's picture card (AGL-4205). */\n note?: string\n }>\n /**\n * The page offers \"Get a free mockup\" (AGL-4205): the request form the site\n * placed in the product block opens with the shopper's picks.\n */\n mockupRequests?: true\n /**\n * The store's time zone, sent only when a variant asks for a use day, so\n * the page offers no day that has passed on the store's calendar.\n */\n useDayTimeZone?: string\n tags?: string[]\n /** Recurring billing (AGL-303) so the PDP frames the price. */\n subscription?: { interval: 'month' | 'year'; trialDays?: number }\n /** Buyer may choose one-time OR subscribe (AGL-545). */\n subscriptionOptional?: boolean\n /**\n * The add-ons the page offers (AGL-4100): ONLY the groups switched to\n * \"Show on the website\". A register-only group never leaves the server, so\n * a shop's in-person choices and prices are not published. Absent: none.\n * Display-only like the prices above; every sale door prices them again\n * from the product.\n */\n modifierGroups?: PublicModifierGroup[]\n}\n\n/** An add-on group as the product page shows it (AGL-4100). */\nexport interface PublicModifierGroup {\n id: string\n name: string\n min: number\n max: number\n /** A write-in the shopper types (write-ins), with its length and whether it takes numbers only. */\n kind?: CommerceModel.ProductModifierGroupKind\n maxLength?: number\n digitsOnly?: boolean\n nameOnOrder?: boolean\n options: Array<{\n id: string\n name: string\n priceCents: number\n /** What the choice adds on a variant priced differently, by variant id. */\n priceCentsByVariant?: Record<string, number>\n /** The choice's card (AGL-4205): its picture, its note, and what a combo includes. */\n imageUrl?: string\n note?: string\n includes?: string[]\n }>\n}\n\n/** The website add-on groups of a product, in the page's shape (AGL-4100). */\nexport function publicModifierGroups(\n product: { modifierGroups?: unknown },\n): PublicModifierGroup[] {\n return CommerceModel.websiteModifierGroups(product).map((group) => ({\n id: group.id,\n name: group.name,\n min: group.min,\n max: group.max,\n ...(CommerceModel.modifierGroupIsWriteIn(group)\n ? {\n kind: 'text' as const,\n maxLength: CommerceModel.writeInMaxLength(group),\n ...(group.digitsOnly === true ? { digitsOnly: true } : {}),\n }\n : {}),\n ...(group.nameOnOrder === true ? { nameOnOrder: true } : {}),\n options: group.options.map((option) => ({\n id: option.id,\n name: option.name,\n priceCents: option.priceCents,\n ...(option.priceCentsByVariant && Object.keys(option.priceCentsByVariant).length\n ? { priceCentsByVariant: { ...option.priceCentsByVariant } }\n : {}),\n // Card fields are checked at save (`modifierCardsProblem`), not on this\n // read, so only well-formed values reach the page (AGL-4205).\n ...(typeof option.imageUrl === 'string' && option.imageUrl ? { imageUrl: option.imageUrl } : {}),\n ...(typeof option.note === 'string' && option.note.trim() ? { note: option.note.trim() } : {}),\n ...(CommerceModel.modifierOptionIsCombo(option) ? { includes: [...(option.includes ?? [])] } : {}),\n })),\n }))\n}\n\n/**\n * Map a lifted product onto the public PDP DTO.\n *\n * Extracted (AGL-659) so the site-page resolver can put the SAME payload\n * into page props as the API returns — the PDP block used to fetch this in\n * an effect, which meant the server rendered a skeleton and crawlers saw a\n * product page with no product in it. One definition keeps the server-\n * rendered and client-fetched shapes from drifting.\n *\n * Display-only by design: stock is a `soldOut` boolean rather than a raw\n * count, and the charge still prices server-side.\n */\nexport function toPublicProductDetail(\n id: string,\n product: ReturnType<typeof CommerceModel.liftLegacyProduct>,\n options: { timeZone?: string | null } = {},\n): PublicProductDetail {\n const asksUseDate = productAsksUseDateAnywhere(product)\n const modifierGroups = publicModifierGroups(product)\n return {\n id,\n name: product.name,\n slug: product.slug,\n ...(product.description ? { description: product.description } : {}),\n type: product.type,\n mediaUrls:\n product.mediaUrls ?? (product.imageUrl ? [product.imageUrl] : []),\n options: product.options ?? [],\n variants: product.variants.map((variant) => ({\n id: variant.id,\n ...(variant.options ? { options: variant.options } : {}),\n priceUsd: CommerceModel.variantHasPrice(variant) ? variant.priceUsd : null,\n ...(variant.compareAtPriceUsd\n ? { compareAtPriceUsd: variant.compareAtPriceUsd }\n : {}),\n soldOut:\n variant.inventory != null &&\n Number(variant.inventory) <= 0 &&\n product.oversellPolicy !== 'backorder',\n ...(variant.imageUrl ? { imageUrl: variant.imageUrl } : {}),\n ...(variant.sku ? { sku: variant.sku } : {}),\n ...(CommerceModel.productAsksUseDate(product, variant.id) ? { asksUseDate: true as const } : {}),\n ...(typeof variant.note === 'string' && variant.note.trim() ? { note: variant.note.trim() } : {}),\n })),\n ...(product.mockupRequests === true ? { mockupRequests: true as const } : {}),\n ...(asksUseDate ? { useDayTimeZone: options.timeZone || 'UTC' } : {}),\n ...(product.tags?.length ? { tags: product.tags } : {}),\n ...(product.subscription ? { subscription: product.subscription } : {}),\n ...(product.subscription && product.subscriptionOptional\n ? { subscriptionOptional: true }\n : {}),\n ...(modifierGroups.length ? { modifierGroups } : {}),\n }\n}\n\n/** Whether any variant of a product asks the buyer for a use day (AGL-4043). */\nexport function productAsksUseDateAnywhere(\n product: Pick<ReturnType<typeof CommerceModel.liftLegacyProduct>, 'variants' | 'checkIn'>,\n): boolean {\n return product.variants.some((variant) => CommerceModel.productAsksUseDate(product, variant.id))\n}\n\n/**\n * Public product detail by slug (AGL-292): everything the PDP block\n * needs — variants with per-option prices and stock booleans, never raw\n * counts. Display-only; the charge still prices server-side.\n */\nexport const productHandler: PluginApiHandler = async (req, res) => {\n const hostId = String(req.query.hostId ?? '')\n const slug = String(req.query.slug ?? '')\n if (!hostId || !slug) {\n return res.status(400).json({ error: 'Missing hostId or slug' })\n }\n try {\n const firestore = firebaseAdmin.app().firestore()\n const snapshot = await firestore\n .collection('hosts')\n .doc(hostId)\n .collection('products')\n .where('slug', '==', slug)\n .limit(1)\n .get()\n const docSnapshot = snapshot.docs[0]\n const raw = docSnapshot?.data() as any\n // A product sold in person only (AGL-4060) has no page online: the same\n // 404 as a draft, so its address says nothing about it.\n if (!CommerceModel.productListedOnline(raw)) {\n return res.status(404).json({ error: 'Unknown product' })\n }\n const product = CommerceModel.liftLegacyProduct(raw)\n // The store's calendar, only for a product that asks for a use day.\n const timeZone = productAsksUseDateAnywhere(product)\n ? (await readStoreDay(firestore.collection('hosts').doc(hostId))).timeZone\n : null\n const detail = toPublicProductDetail(docSnapshot.id, product, { timeZone })\n res.setHeader(\n 'Cache-Control',\n 'public, s-maxage=60, stale-while-revalidate=300',\n )\n return res.status(200).json({ product: detail })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Product unavailable' })\n }\n}\n"],"names":["CommerceModel","firebaseAdmin","readStoreDay","publicModifierGroups","product","websiteModifierGroups","map","group","id","name","min","max","modifierGroupIsWriteIn","kind","maxLength","writeInMaxLength","digitsOnly","nameOnOrder","options","option","priceCents","priceCentsByVariant","Object","keys","length","imageUrl","note","trim","modifierOptionIsCombo","includes","toPublicProductDetail","asksUseDate","productAsksUseDateAnywhere","modifierGroups","slug","description","type","mediaUrls","variants","variant","priceUsd","variantHasPrice","compareAtPriceUsd","soldOut","inventory","Number","oversellPolicy","sku","productAsksUseDate","mockupRequests","useDayTimeZone","timeZone","tags","subscription","subscriptionOptional","some","productHandler","req","res","hostId","String","query","status","json","error","firestore","app","snapshot","collection","doc","where","limit","get","docSnapshot","docs","raw","data","productListedOnline","liftLegacyProduct","detail","setHeader","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAID,YAAYA,mBAAmB,oBAAU;AACzC,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,YAAY,QAAQ,iBAAa;AAuF1C,4EAA4E,GAC5E,OAAO,SAASC,qBACdC,OAAqC;IAErC,OAAOJ,cAAcK,qBAAqB,CAACD,SAASE,GAAG,CAAC,CAACC,QAAW;YAClEC,IAAID,MAAMC,EAAE;YACZC,MAAMF,MAAME,IAAI;YAChBC,KAAKH,MAAMG,GAAG;YACdC,KAAKJ,MAAMI,GAAG;WACVX,cAAcY,sBAAsB,CAACL,SACrC;YACEM,MAAM;YACNC,WAAWd,cAAce,gBAAgB,CAACR;WACtCA,MAAMS,UAAU,KAAK,OAAO;YAAEA,YAAY;QAAK,IAAI,CAAC,KAE1D,CAAC,GACDT,MAAMU,WAAW,KAAK,OAAO;YAAEA,aAAa;QAAK,IAAI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;QACJ,MAAM4B,SAASjD,sBAAsB2C,YAAYjE,EAAE,EAAEJ,SAAS;YAAE+C;QAAS;QACzEO,IAAIsB,SAAS,CACX,iBACA;QAEF,OAAOtB,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAE3D,SAAS2E;QAAO;IAChD,EAAE,OAAOf,OAAO;QACdiB,QAAQjB,KAAK,CAACA;QACd,OAAON,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAsB;IAC7D;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/product.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 { PluginApiHandler } from '@aglyn/aglyn/server'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { readStoreDay } from './store-day'\n\nexport interface PublicProductDetail {\n id: string\n name: string\n slug: string\n description?: string\n type: CommerceModel.ProductType\n mediaUrls: string[]\n options: CommerceModel.ProductOption[]\n variants: Array<{\n id: string\n options?: Record<string, string>\n /**\n * `null` for a variant listed before it has a price (AGL-3676): the page\n * says \"Price coming soon\" and offers nothing to buy, as no sale door\n * would sell it.\n */\n priceUsd: number | null\n compareAtPriceUsd?: number\n /** The merchant's own price per currency (AGL-4248), major units; it wins over conversion. */\n fixedPrices?: Record<string, number>\n soldOut: boolean\n imageUrl?: string\n /**\n * Merchant's stock-keeping unit (AGL-686). Carried into the public DTO\n * so the server can put `sku` on the Product structured data — Google\n * Merchant treats it as required for a product offer, and without it a\n * listing is simply ineligible for rich results rather than warned about.\n * It is already public information: it prints on receipts and invoices.\n */\n sku?: string\n /**\n * The buyer may choose the day they will use it (a pass bought ahead,\n * AGL-4043): the page offers an optional date. Absent when it does not.\n */\n asksUseDate?: true\n /** A short line on the variant's picture card (AGL-4205). */\n note?: string\n }>\n /**\n * The page offers \"Get a free mockup\" (AGL-4205): the request form the site\n * placed in the product block opens with the shopper's picks.\n */\n mockupRequests?: true\n /**\n * The store's time zone, sent only when a variant asks for a use day, so\n * the page offers no day that has passed on the store's calendar.\n */\n useDayTimeZone?: string\n tags?: string[]\n /** Recurring billing (AGL-303) so the PDP frames the price. */\n subscription?: { interval: 'month' | 'year'; trialDays?: number }\n /** Buyer may choose one-time OR subscribe (AGL-545). */\n subscriptionOptional?: boolean\n /**\n * The add-ons the page offers (AGL-4100): ONLY the groups switched to\n * \"Show on the website\". A register-only group never leaves the server, so\n * a shop's in-person choices and prices are not published. Absent: none.\n * Display-only like the prices above; every sale door prices them again\n * from the product.\n */\n modifierGroups?: PublicModifierGroup[]\n}\n\n/** An add-on group as the product page shows it (AGL-4100). */\nexport interface PublicModifierGroup {\n id: string\n name: string\n min: number\n max: number\n /** A write-in the shopper types (write-ins), with its length and whether it takes numbers only. */\n kind?: CommerceModel.ProductModifierGroupKind\n maxLength?: number\n digitsOnly?: boolean\n nameOnOrder?: boolean\n options: Array<{\n id: string\n name: string\n priceCents: number\n /** What the choice adds on a variant priced differently, by variant id. */\n priceCentsByVariant?: Record<string, number>\n /** What the choice adds in another currency (AGL-4248), minor units by ISO code. */\n fixedPriceCents?: Record<string, number>\n /** The choice's card (AGL-4205): its picture, its note, and what a combo includes. */\n imageUrl?: string\n note?: string\n includes?: string[]\n }>\n}\n\n/** The website add-on groups of a product, in the page's shape (AGL-4100). */\nexport function publicModifierGroups(\n product: { modifierGroups?: unknown },\n): PublicModifierGroup[] {\n return CommerceModel.websiteModifierGroups(product).map((group) => ({\n id: group.id,\n name: group.name,\n min: group.min,\n max: group.max,\n ...(CommerceModel.modifierGroupIsWriteIn(group)\n ? {\n kind: 'text' as const,\n maxLength: CommerceModel.writeInMaxLength(group),\n ...(group.digitsOnly === true ? { digitsOnly: true } : {}),\n }\n : {}),\n ...(group.nameOnOrder === true ? { nameOnOrder: true } : {}),\n options: group.options.map((option) => ({\n id: option.id,\n name: option.name,\n priceCents: option.priceCents,\n ...(option.priceCentsByVariant && Object.keys(option.priceCentsByVariant).length\n ? { priceCentsByVariant: { ...option.priceCentsByVariant } }\n : {}),\n ...(publicFixedPrices(option.fixedPriceCents)\n ? { fixedPriceCents: publicFixedPrices(option.fixedPriceCents) }\n : {}),\n // Card fields are checked at save (`modifierCardsProblem`), not on this\n // read, so only well-formed values reach the page (AGL-4205).\n ...(typeof option.imageUrl === 'string' && option.imageUrl ? { imageUrl: option.imageUrl } : {}),\n ...(typeof option.note === 'string' && option.note.trim() ? { note: option.note.trim() } : {}),\n ...(CommerceModel.modifierOptionIsCombo(option) ? { includes: [...(option.includes ?? [])] } : {}),\n })),\n }))\n}\n\n/**\n * Fixed prices per currency as a storefront may print them (AGL-4248): ISO\n * codes to non-negative numbers, or nothing. The charge prices them again.\n */\nexport function publicFixedPrices(raw: unknown): Record<string, number> | undefined {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined\n const entries = Object.entries(raw as Record<string, unknown>).filter(\n (entry): entry is [string, number] =>\n /^[A-Z]{3}$/.test(entry[0]) && typeof entry[1] === 'number' && Number.isFinite(entry[1]) && entry[1] >= 0,\n )\n return entries.length ? Object.fromEntries(entries) : undefined\n}\n\n/**\n * Map a lifted product onto the public PDP DTO.\n *\n * Extracted (AGL-659) so the site-page resolver can put the SAME payload\n * into page props as the API returns — the PDP block used to fetch this in\n * an effect, which meant the server rendered a skeleton and crawlers saw a\n * product page with no product in it. One definition keeps the server-\n * rendered and client-fetched shapes from drifting.\n *\n * Display-only by design: stock is a `soldOut` boolean rather than a raw\n * count, and the charge still prices server-side.\n */\nexport function toPublicProductDetail(\n id: string,\n product: ReturnType<typeof CommerceModel.liftLegacyProduct>,\n options: { timeZone?: string | null } = {},\n): PublicProductDetail {\n const asksUseDate = productAsksUseDateAnywhere(product)\n const modifierGroups = publicModifierGroups(product)\n return {\n id,\n name: product.name,\n slug: product.slug,\n ...(product.description ? { description: product.description } : {}),\n type: product.type,\n mediaUrls:\n product.mediaUrls ?? (product.imageUrl ? [product.imageUrl] : []),\n options: product.options ?? [],\n variants: product.variants.map((variant) => ({\n id: variant.id,\n ...(variant.options ? { options: variant.options } : {}),\n priceUsd: CommerceModel.variantHasPrice(variant) ? variant.priceUsd : null,\n ...(variant.compareAtPriceUsd\n ? { compareAtPriceUsd: variant.compareAtPriceUsd }\n : {}),\n ...(publicFixedPrices(variant.fixedPrices) ? { fixedPrices: publicFixedPrices(variant.fixedPrices) } : {}),\n soldOut:\n variant.inventory != null &&\n Number(variant.inventory) <= 0 &&\n product.oversellPolicy !== 'backorder',\n ...(variant.imageUrl ? { imageUrl: variant.imageUrl } : {}),\n ...(variant.sku ? { sku: variant.sku } : {}),\n ...(CommerceModel.productAsksUseDate(product, variant.id) ? { asksUseDate: true as const } : {}),\n ...(typeof variant.note === 'string' && variant.note.trim() ? { note: variant.note.trim() } : {}),\n })),\n ...(product.mockupRequests === true ? { mockupRequests: true as const } : {}),\n ...(asksUseDate ? { useDayTimeZone: options.timeZone || 'UTC' } : {}),\n ...(product.tags?.length ? { tags: product.tags } : {}),\n ...(product.subscription ? { subscription: product.subscription } : {}),\n ...(product.subscription && product.subscriptionOptional\n ? { subscriptionOptional: true }\n : {}),\n ...(modifierGroups.length ? { modifierGroups } : {}),\n }\n}\n\n/** Whether any variant of a product asks the buyer for a use day (AGL-4043). */\nexport function productAsksUseDateAnywhere(\n product: Pick<ReturnType<typeof CommerceModel.liftLegacyProduct>, 'variants' | 'checkIn'>,\n): boolean {\n return product.variants.some((variant) => CommerceModel.productAsksUseDate(product, variant.id))\n}\n\n/**\n * Public product detail by slug (AGL-292): everything the PDP block\n * needs — variants with per-option prices and stock booleans, never raw\n * counts. Display-only; the charge still prices server-side.\n */\nexport const productHandler: PluginApiHandler = async (req, res) => {\n const hostId = String(req.query.hostId ?? '')\n const slug = String(req.query.slug ?? '')\n if (!hostId || !slug) {\n return res.status(400).json({ error: 'Missing hostId or slug' })\n }\n try {\n const firestore = firebaseAdmin.app().firestore()\n const snapshot = await firestore\n .collection('hosts')\n .doc(hostId)\n .collection('products')\n .where('slug', '==', slug)\n .limit(1)\n .get()\n const docSnapshot = snapshot.docs[0]\n const raw = docSnapshot?.data() as any\n // A product sold in person only (AGL-4060) has no page online: the same\n // 404 as a draft, so its address says nothing about it.\n if (!CommerceModel.productListedOnline(raw)) {\n return res.status(404).json({ error: 'Unknown product' })\n }\n const product = CommerceModel.liftLegacyProduct(raw)\n // The store's calendar, only for a product that asks for a use day.\n const timeZone = productAsksUseDateAnywhere(product)\n ? (await readStoreDay(firestore.collection('hosts').doc(hostId))).timeZone\n : null\n const detail = toPublicProductDetail(docSnapshot.id, product, { timeZone })\n res.setHeader(\n 'Cache-Control',\n 'public, s-maxage=60, stale-while-revalidate=300',\n )\n return res.status(200).json({ product: detail })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Product unavailable' })\n }\n}\n"],"names":["CommerceModel","firebaseAdmin","readStoreDay","publicModifierGroups","product","websiteModifierGroups","map","group","id","name","min","max","modifierGroupIsWriteIn","kind","maxLength","writeInMaxLength","digitsOnly","nameOnOrder","options","option","priceCents","priceCentsByVariant","Object","keys","length","publicFixedPrices","fixedPriceCents","imageUrl","note","trim","modifierOptionIsCombo","includes","raw","Array","isArray","undefined","entries","filter","entry","test","Number","isFinite","fromEntries","toPublicProductDetail","asksUseDate","productAsksUseDateAnywhere","modifierGroups","slug","description","type","mediaUrls","variants","variant","priceUsd","variantHasPrice","compareAtPriceUsd","fixedPrices","soldOut","inventory","oversellPolicy","sku","productAsksUseDate","mockupRequests","useDayTimeZone","timeZone","tags","subscription","subscriptionOptional","some","productHandler","req","res","hostId","String","query","status","json","error","firestore","app","snapshot","collection","doc","where","limit","get","docSnapshot","docs","data","productListedOnline","liftLegacyProduct","detail","setHeader","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAID,YAAYA,mBAAmB,oBAAU;AACzC,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,YAAY,QAAQ,iBAAa;AA2F1C,4EAA4E,GAC5E,OAAO,SAASC,qBACdC,OAAqC;IAErC,OAAOJ,cAAcK,qBAAqB,CAACD,SAASE,GAAG,CAAC,CAACC,QAAW;YAClEC,IAAID,MAAMC,EAAE;YACZC,MAAMF,MAAME,IAAI;YAChBC,KAAKH,MAAMG,GAAG;YACdC,KAAKJ,MAAMI,GAAG;WACVX,cAAcY,sBAAsB,CAACL,SACrC;YACEM,MAAM;YACNC,WAAWd,cAAce,gBAAgB,CAACR;WACtCA,MAAMS,UAAU,KAAK,OAAO;YAAEA,YAAY;QAAK,IAAI,CAAC,KAE1D,CAAC,GACDT,MAAMU,WAAW,KAAK,OAAO;YAAEA,aAAa;QAAK,IAAI,CAAC;YAC1DC,SAASX,MAAMW,OAAO,CAACZ,GAAG,CAAC,CAACa;oBAcyCA;uBAd7B;oBACtCX,IAAIW,OAAOX,EAAE;oBACbC,MAAMU,OAAOV,IAAI;oBACjBW,YAAYD,OAAOC,UAAU;mBACzBD,OAAOE,mBAAmB,IAAIC,OAAOC,IAAI,CAACJ,OAAOE,mBAAmB,EAAEG,MAAM,GAC5E;oBAAEH,qBAAqB,aAAKF,OAAOE,mBAAmB;gBAAG,IACzD,CAAC,GACDI,kBAAkBN,OAAOO,eAAe,IACxC;oBAAEA,iBAAiBD,kBAAkBN,OAAOO,eAAe;gBAAE,IAC7D,CAAC,GAGD,OAAOP,OAAOQ,QAAQ,KAAK,YAAYR,OAAOQ,QAAQ,GAAG;oBAAEA,UAAUR,OAAOQ,QAAQ;gBAAC,IAAI,CAAC,GAC1F,OA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,MAAMgC,WAAWnB,2BAA2BzC,WACxC,AAAC,CAAA,MAAMF,aAAa4E,UAAUG,UAAU,CAAC,SAASC,GAAG,CAACV,QAAO,EAAGR,QAAQ,GACxE;QACJ,MAAM2B,SAAShD,sBAAsB2C,YAAY9E,EAAE,EAAEJ,SAAS;YAAE4D;QAAS;QACzEO,IAAIqB,SAAS,CACX,iBACA;QAEF,OAAOrB,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAExE,SAASuF;QAAO;IAChD,EAAE,OAAOd,OAAO;QACdgB,QAAQhB,KAAK,CAACA;QACd,OAAON,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAsB;IAC7D;AACF,EAAC"}
|
|
@@ -489,11 +489,14 @@ const isBuildRefusal = (value)=>Boolean(value && typeof value === 'object' && 'r
|
|
|
489
489
|
const nowMs = deps.now();
|
|
490
490
|
const fields = productDuplicateFields(product, slug, nowMs);
|
|
491
491
|
const smartQuery = hostRef.collection('collections').where('kind', '==', 'catalog').where('mode', '==', 'smart');
|
|
492
|
+
// The MANUAL collections holding the source by id, which the copy joins.
|
|
493
|
+
const manualQuery = hostRef.collection('collections').where('productIds', 'array-contains', productId);
|
|
492
494
|
const outbox = outboxEntry(db, hostId);
|
|
493
495
|
const answer = await db.runTransaction(async (tx)=>{
|
|
494
|
-
const [existing, smart] = await Promise.all([
|
|
496
|
+
const [existing, smart, manual] = await Promise.all([
|
|
495
497
|
tx.get(copyRef),
|
|
496
|
-
tx.get(smartQuery)
|
|
498
|
+
tx.get(smartQuery),
|
|
499
|
+
tx.get(manualQuery)
|
|
497
500
|
]);
|
|
498
501
|
if (existing.exists) return {
|
|
499
502
|
status: 200,
|
|
@@ -529,6 +532,11 @@ const isBuildRefusal = (value)=>Boolean(value && typeof value === 'object' && 'r
|
|
|
529
532
|
updatedAt: FieldValue.serverTimestamp(),
|
|
530
533
|
createdBy: door.uid
|
|
531
534
|
}));
|
|
535
|
+
for (const held of manual.docs){
|
|
536
|
+
tx.update(held.ref, {
|
|
537
|
+
productIds: FieldValue.arrayUnion(newProductId)
|
|
538
|
+
});
|
|
539
|
+
}
|
|
532
540
|
tx.set(outbox.ref, outbox.data);
|
|
533
541
|
return {
|
|
534
542
|
status: 200,
|