@aglyn/plugins-commerce 1.14.0 → 1.15.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.
Files changed (152) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/account-subscriptions.d.ts +51 -0
  3. package/src/lib/components/account-subscriptions.js +168 -0
  4. package/src/lib/components/account-subscriptions.js.map +1 -0
  5. package/src/lib/components/account.js +12 -48
  6. package/src/lib/components/account.js.map +1 -1
  7. package/src/lib/components/cart.js +30 -6
  8. package/src/lib/components/cart.js.map +1 -1
  9. package/src/lib/components/commerce-console-page.js +6 -0
  10. package/src/lib/components/commerce-console-page.js.map +1 -1
  11. package/src/lib/components/commerce-console-sections.d.ts +1 -1
  12. package/src/lib/components/commerce-console-sections.js +5 -0
  13. package/src/lib/components/commerce-console-sections.js.map +1 -1
  14. package/src/lib/components/console/paid-media.d.ts +1 -0
  15. package/src/lib/components/console/paid-media.js +15 -4
  16. package/src/lib/components/console/paid-media.js.map +1 -1
  17. package/src/lib/components/console/payments-settings-card.component.js +1 -1
  18. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  19. package/src/lib/components/console/pos/pos-hardware-api.d.ts +10 -1
  20. package/src/lib/components/console/pos/pos-hardware-api.js.map +1 -1
  21. package/src/lib/components/console/pos/pos-hardware-buyer.component.js +2 -2
  22. package/src/lib/components/console/pos/pos-hardware-buyer.component.js.map +1 -1
  23. package/src/lib/components/console/pos/pos-hardware-sale-api.d.ts +2 -0
  24. package/src/lib/components/console/pos/pos-hardware-sale-api.js.map +1 -1
  25. package/src/lib/components/console/pos-cellular-control.component.d.ts +1 -1
  26. package/src/lib/components/console/pos-cellular-control.component.js +5 -5
  27. package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
  28. package/src/lib/components/console/pos-devices-card.component.js +2 -2
  29. package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
  30. package/src/lib/components/console/pos-hardware-card.component.d.ts +5 -0
  31. package/src/lib/components/console/pos-hardware-card.component.js +77 -8
  32. package/src/lib/components/console/pos-hardware-card.component.js.map +1 -1
  33. package/src/lib/components/console/pos-hardware-orders-staff-page.component.js +137 -19
  34. package/src/lib/components/console/pos-hardware-orders-staff-page.component.js.map +1 -1
  35. package/src/lib/components/console/pos-page.component.js +19 -2
  36. package/src/lib/components/console/pos-page.component.js.map +1 -1
  37. package/src/lib/components/console/product-editor-dialog.component.js +21 -2
  38. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  39. package/src/lib/components/console/subscription-detail-dialog.component.d.ts +58 -0
  40. package/src/lib/components/console/subscription-detail-dialog.component.js +201 -0
  41. package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -0
  42. package/src/lib/components/console/subscriptions-card.component.d.ts +60 -0
  43. package/src/lib/components/console/subscriptions-card.component.js +280 -0
  44. package/src/lib/components/console/subscriptions-card.component.js.map +1 -0
  45. package/src/lib/components/hardware-terms-consent.d.ts +22 -0
  46. package/src/lib/components/hardware-terms-consent.js +85 -0
  47. package/src/lib/components/hardware-terms-consent.js.map +1 -0
  48. package/src/lib/components/product-detail.js +25 -5
  49. package/src/lib/components/product-detail.js.map +1 -1
  50. package/src/lib/constants/operator-alerts.d.ts +1 -1
  51. package/src/lib/constants/operator-alerts.js +4 -4
  52. package/src/lib/constants/operator-alerts.js.map +1 -1
  53. package/src/lib/model/commerce-orders.d.ts +6 -2
  54. package/src/lib/model/commerce-orders.js.map +1 -1
  55. package/src/lib/model/commerce-payment-methods.d.ts +24 -0
  56. package/src/lib/model/commerce-payment-methods.js +35 -0
  57. package/src/lib/model/commerce-payment-methods.js.map +1 -1
  58. package/src/lib/model/commerce.d.ts +6 -0
  59. package/src/lib/model/commerce.js.map +1 -1
  60. package/src/lib/model/index.d.ts +1 -0
  61. package/src/lib/model/index.js +1 -0
  62. package/src/lib/model/index.js.map +1 -1
  63. package/src/lib/model/paid-media.d.ts +8 -0
  64. package/src/lib/model/paid-media.js +13 -0
  65. package/src/lib/model/paid-media.js.map +1 -1
  66. package/src/lib/model/pos-hardware-in-person.d.ts +23 -2
  67. package/src/lib/model/pos-hardware-in-person.js +52 -20
  68. package/src/lib/model/pos-hardware-in-person.js.map +1 -1
  69. package/src/lib/model/pos-hardware-tax-summary.d.ts +5 -1
  70. package/src/lib/model/pos-hardware-tax-summary.js +2 -1
  71. package/src/lib/model/pos-hardware-tax-summary.js.map +1 -1
  72. package/src/lib/model/pos-hardware-terms.d.ts +37 -2
  73. package/src/lib/model/pos-hardware-terms.js +68 -3
  74. package/src/lib/model/pos-hardware-terms.js.map +1 -1
  75. package/src/lib/model/pos-hardware.d.ts +101 -15
  76. package/src/lib/model/pos-hardware.js +128 -18
  77. package/src/lib/model/pos-hardware.js.map +1 -1
  78. package/src/lib/model/pos-reader-splash.js +2 -2
  79. package/src/lib/model/pos-reader-splash.js.map +1 -1
  80. package/src/lib/model/product-write.d.ts +3 -0
  81. package/src/lib/model/subscription-view.d.ts +90 -0
  82. package/src/lib/model/subscription-view.js +176 -0
  83. package/src/lib/model/subscription-view.js.map +1 -0
  84. package/src/lib/server/billing-webhook.d.ts +4 -6
  85. package/src/lib/server/billing-webhook.js +109 -51
  86. package/src/lib/server/billing-webhook.js.map +1 -1
  87. package/src/lib/server/cart-checkout.js +45 -10
  88. package/src/lib/server/cart-checkout.js.map +1 -1
  89. package/src/lib/server/cart.js +15 -3
  90. package/src/lib/server/cart.js.map +1 -1
  91. package/src/lib/server/checkout.js +58 -16
  92. package/src/lib/server/checkout.js.map +1 -1
  93. package/src/lib/server/draft-order.js +7 -3
  94. package/src/lib/server/draft-order.js.map +1 -1
  95. package/src/lib/server/membership-account.d.ts +22 -0
  96. package/src/lib/server/membership-account.js +52 -8
  97. package/src/lib/server/membership-account.js.map +1 -1
  98. package/src/lib/server/pos-auth.d.ts +3 -3
  99. package/src/lib/server/pos-auth.js +3 -3
  100. package/src/lib/server/pos-auth.js.map +1 -1
  101. package/src/lib/server/pos-cellular-billing.js +1 -1
  102. package/src/lib/server/pos-cellular-billing.js.map +1 -1
  103. package/src/lib/server/pos-cellular-notify.js +1 -1
  104. package/src/lib/server/pos-cellular-notify.js.map +1 -1
  105. package/src/lib/server/pos-cellular.js +1 -1
  106. package/src/lib/server/pos-cellular.js.map +1 -1
  107. package/src/lib/server/pos-hardware-admin.js +86 -13
  108. package/src/lib/server/pos-hardware-admin.js.map +1 -1
  109. package/src/lib/server/pos-hardware-attach.js +5 -5
  110. package/src/lib/server/pos-hardware-attach.js.map +1 -1
  111. package/src/lib/server/pos-hardware-cancel.js +65 -0
  112. package/src/lib/server/pos-hardware-cancel.js.map +1 -1
  113. package/src/lib/server/pos-hardware-closure-notices.js +2 -5
  114. package/src/lib/server/pos-hardware-closure-notices.js.map +1 -1
  115. package/src/lib/server/pos-hardware-closure.js +5 -8
  116. package/src/lib/server/pos-hardware-closure.js.map +1 -1
  117. package/src/lib/server/pos-hardware-in-person.d.ts +2 -1
  118. package/src/lib/server/pos-hardware-in-person.js +72 -17
  119. package/src/lib/server/pos-hardware-in-person.js.map +1 -1
  120. package/src/lib/server/pos-hardware-notify.d.ts +2 -0
  121. package/src/lib/server/pos-hardware-notify.js +30 -5
  122. package/src/lib/server/pos-hardware-notify.js.map +1 -1
  123. package/src/lib/server/pos-hardware-readers.d.ts +25 -0
  124. package/src/lib/server/pos-hardware-readers.js +206 -85
  125. package/src/lib/server/pos-hardware-readers.js.map +1 -1
  126. package/src/lib/server/pos-hardware-returns.d.ts +8 -3
  127. package/src/lib/server/pos-hardware-returns.js +39 -7
  128. package/src/lib/server/pos-hardware-returns.js.map +1 -1
  129. package/src/lib/server/pos-hardware-sale-fields.d.ts +76 -0
  130. package/src/lib/server/pos-hardware-sale-fields.js +114 -1
  131. package/src/lib/server/pos-hardware-sale-fields.js.map +1 -1
  132. package/src/lib/server/pos-hardware-sale.d.ts +2 -0
  133. package/src/lib/server/pos-hardware-sale.js +1 -0
  134. package/src/lib/server/pos-hardware-sale.js.map +1 -1
  135. package/src/lib/server/pos-hardware-tax-return-source.js +7 -4
  136. package/src/lib/server/pos-hardware-tax-return-source.js.map +1 -1
  137. package/src/lib/server/pos-hardware-webhook.js +16 -3
  138. package/src/lib/server/pos-hardware-webhook.js.map +1 -1
  139. package/src/lib/server/pos-hardware.d.ts +14 -3
  140. package/src/lib/server/pos-hardware.js +83 -18
  141. package/src/lib/server/pos-hardware.js.map +1 -1
  142. package/src/lib/server/pos-ops-routes.js +2 -10
  143. package/src/lib/server/pos-ops-routes.js.map +1 -1
  144. package/src/lib/server/quote-pay.js +8 -4
  145. package/src/lib/server/quote-pay.js.map +1 -1
  146. package/src/lib/server/stream.d.ts +2 -0
  147. package/src/lib/server/stream.js +22 -2
  148. package/src/lib/server/stream.js.map +1 -1
  149. package/src/lib/server/tax-return-source.js +5 -1
  150. package/src/lib/server/tax-return-source.js.map +1 -1
  151. package/src/lib/server.js +2 -2
  152. package/src/lib/server.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/tax-return-source.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\n/**\n * Storefront sales on the operator's sales tax return (AGL-1904, AGL-3080).\n *\n * The operator's return sums its own invoices; this is the storefront's half\n * of it, answered through the platform's tax return source contract\n * (`@aglyn/aglyn/plugin-manager/plugin-tax-return-sources`). It reads\n * `storefrontTaxCollected` — a SEPARATE collection from the operator's own\n * invoices, queried and reported separately, because a storefront row's\n * money is mostly the merchant's while an invoice row's is the operator's.\n * Summing the two would put other companies' receipts into the return's\n * total sales, which is why they never meet in one query and never share a\n * figure.\n *\n * What it answers, all worded for the filing jurisdiction the platform\n * resolved:\n *\n * - **The three liability buckets**, never summed — see\n * `model/storefront-tax-summary.ts`.\n * - **A blocking finding for the platform-liable tax** in the filing\n * jurisdiction. Every storefront checkout is created on the platform's\n * own account, so a `mode: 'stripe'` store's shopper is charged tax Stripe\n * computes against the PLATFORM's registrations — measured, not inferred.\n * That money is in the platform's balance and is NOT in the filing\n * figures, which sum the operator's own sales only. Filing those without\n * deciding what to do with this figure is exactly the shortfall an\n * auditor finds. It states the mechanics and asks for a decision; it does\n * NOT assert a marketplace-facilitator position — that attaches by\n * operation of law and belongs to counsel, not to this report.\n * - **Two lines beneath the filing figures** — the platform-liable tax and\n * the merchant's own rate, stated side by side and never folded into a\n * form item, because this report does not decide how storefront receipts\n * are reported and adding them to one would be deciding it silently.\n * - **Facilitated sales by buyer state** — the economic-nexus question\n * (AGL-1956), with the three buckets SUMMED per jurisdiction on purpose:\n * a threshold counts the sale whoever remits it. Who remits is still\n * carried per row.\n *\n * Truncation and rows no period can reach are reported, and the platform\n * raises each as a blocking finding of its own.\n */\n\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport {\n asRowDate,\n centsToDollars,\n} from '@aglyn/aglyn/app-utils/tax-jurisdiction-figures'\nimport type {\n TaxReturnExportBlock,\n TaxReturnFiling,\n TaxReturnFilingLine,\n TaxReturnFinding,\n TaxReturnSectionTable,\n TaxReturnSource,\n TaxReturnSourceAnswer,\n TaxReturnSourceRequest,\n} from '@aglyn/aglyn/plugin-manager/plugin-tax-return-sources'\nimport {\n storefrontTaxSummary,\n type StorefrontTaxReturnRowInput,\n type StorefrontTaxSummary,\n} from '../model/storefront-tax-summary'\nimport { readPosHardwareTaxReturn } from './pos-hardware-tax-return-source'\nimport { POS_HARDWARE_SALES_COLLECTION } from '../model/pos-hardware'\nimport {\n posHardwareStorefrontParts,\n storefrontRowsWithoutInPersonHardware,\n} from '../model/pos-hardware-tax-summary'\nimport { statedTaxableBase } from '../model/own-store-tax-summary'\nimport {\n ownStoreTaxReturnAnswer,\n readOwnStoreOrders,\n resolveOwnStores,\n type OwnStores,\n} from './own-store-tax-return-source'\n\n/**\n * How far either side of the period an in-person hardware record is read,\n * to meet the storefront row its register sale filed: the two are written\n * seconds apart, so a week is more than enough for either edge.\n */\nconst IN_PERSON_ROW_MARGIN_MS = 7 * 24 * 60 * 60 * 1000\n\n/** One row of the storefront listing, as the working papers carry it. */\nexport interface StorefrontTaxRow {\n id: string\n hostId: string | null\n orgId: string | null\n paidAt: string | null\n taxMode: string | null\n taxLiability: string | null\n grossCents: number\n taxCents: number\n taxableSalesCents: number\n state: string | null\n country: string | null\n}\n\n/** A liability bucket, ready to print. */\nexport interface StorefrontTaxBucketRow {\n id: 'aglynLiable' | 'merchantManual' | 'connectedAccountLiable'\n label: string\n /** Who owes it — the sentence that decides whether it is on this return. */\n liability: string\n transactionCount: number\n grossDollars: string\n taxableSalesDollars: string\n taxCollectedDollars: string\n /** True when this row is money in the platform's balance under its registration. */\n platformLiable: boolean\n}\n\n/** One state's facilitated storefront sales, for the nexus question. */\nexport interface StorefrontFacilitatedJurisdictionRow {\n jurisdiction: string\n /** True for the one jurisdiction this deployment files a return in. */\n isFilingJurisdiction: boolean\n transactionCount: number\n totalSalesDollars: string\n taxCollectedDollars: string\n /** The part of `taxCollectedDollars` the platform holds and must remit. */\n platformLiableTaxDollars: string\n /** True when NO tax was collected on any sale into this state. */\n untaxed: boolean\n}\n\n/**\n * Storefront tax in the FILING jurisdiction that Stripe computed against the\n * platform's own registrations.\n *\n * The one figure that decides whether a period can be filed from the filing\n * lines alone. Deliberately excludes `merchantManual` — a merchant's own\n * configured rate never touched those registrations. Read against the\n * configured jurisdiction rather than Texas, because a hard-coded key answers\n * `0.00` everywhere else — and a zero here reads as \"nothing to decide\" on\n * the one finding that blocks filing.\n */\nexport function storefrontPlatformLiableCents(\n summary: StorefrontTaxSummary | null | undefined,\n filing: TaxReturnFiling,\n): number {\n const figures = summary?.aglynLiable?.byJurisdiction?.[filing.code]\n const cents = Number(figures?.taxCollectedCents ?? 0)\n return Number.isFinite(cents) ? cents : 0\n}\n\n/** The merchant's own configured tax in the filing jurisdiction. */\nfunction merchantManualCents(\n summary: StorefrontTaxSummary | null | undefined,\n filing: TaxReturnFiling,\n): number {\n return Number(\n summary?.merchantManual?.byJurisdiction?.[filing.code]?.taxCollectedCents ?? 0,\n )\n}\n\n/** The storefront's findings. The platform raises the non-zero ones. */\nexport function storefrontTaxFindings(\n summary: StorefrontTaxSummary,\n filing: TaxReturnFiling,\n): TaxReturnFinding[] {\n const brand = PLATFORM_BRAND_NAME\n return [\n {\n // BLOCKING on purpose — see the module note.\n id: 'storefrontAglynLiableTax',\n severity: 'blocking',\n count: storefrontPlatformLiableCents(summary, filing),\n label: `${filing.label} storefront tax collected under ${brand}’s registration`,\n detail:\n 'Cents. Charged to shoppers on merchants’ storefront sales, computed ' +\n 'by Stripe Tax against THE PLATFORM’s registrations (the session is ' +\n 'created on the platform account), and settled into the platform’s ' +\n `balance. It is NOT included in ${filing.figuresName} below. Decide ` +\n 'with counsel how it is reported before filing — do not file as if ' +\n 'it were zero.',\n },\n {\n id: 'storefrontUnclassified',\n severity: 'blocking',\n count: Number(summary?.attention?.rowsUnclassified ?? 0),\n label: 'Storefront rows with an unrecognised tax mode',\n detail:\n 'Not counted in any storefront bucket, so they are in no figure at ' +\n 'all. Classify them before filing.',\n },\n {\n id: 'storefrontMissingTaxableBase',\n severity: 'review',\n count: Number(summary?.attention?.rowsMissingTaxableBase ?? 0),\n label: 'Storefront rows with tax but no stated base',\n detail:\n 'Tax was collected but Stripe’s taxable_amount could not be read, so ' +\n 'the storefront taxable-sales figure understates the base. Re-read ' +\n 'the session in Stripe with the tax breakdown expanded.',\n },\n ]\n}\n\n/**\n * The two lines beneath the filing figures: the platform-liable tax and the\n * merchant's own rate, separately, and outside every form item.\n */\nexport function storefrontFilingLines(\n summary: StorefrontTaxSummary,\n filing: TaxReturnFiling,\n): TaxReturnFilingLine[] {\n const brand = PLATFORM_BRAND_NAME\n const platformLiable = centsToDollars(storefrontPlatformLiableCents(summary, filing))\n const merchant = centsToDollars(merchantManualCents(summary, filing))\n if (filing.form === 'tx-webfile') {\n return [\n {\n item: '—',\n label: `${filing.label} storefront tax under ${brand}’s registration (NOT in ${filing.figuresName})`,\n dollars: platformLiable,\n note:\n `Collected from shoppers on merchants’ sales and held in ${brand}’s ` +\n 'balance. Excluded from every item above. Its treatment on the ' +\n 'return is a question for counsel — see AGL-1904.',\n },\n {\n item: '—',\n label: `${filing.label} storefront tax under the MERCHANT’s own rate (not ${brand}’s)`,\n dollars: merchant,\n note:\n `A manual-mode store’s own configured rate. ${brand}’s registrations ` +\n 'played no part in computing it. Shown so it is visibly NOT the line ' +\n 'above — the two must never be added together.',\n },\n ]\n }\n return [\n {\n item: '—',\n label: `${filing.code} storefront tax under the platform’s registration (NOT in the figures above)`,\n dollars: platformLiable,\n note:\n 'Collected from shoppers on merchants’ sales and held in the ' +\n 'platform’s balance. Excluded from every figure above. Its treatment ' +\n 'on the return is a question for the operator’s own counsel.',\n },\n {\n item: '—',\n label: `${filing.code} storefront tax under the MERCHANT’s own rate`,\n dollars: merchant,\n note:\n 'A manual-mode store’s own configured rate. The platform’s ' +\n 'registrations played no part in computing it. Shown so it is ' +\n 'visibly NOT the line above — the two must never be added together.',\n },\n ]\n}\n\n/** The three liability buckets, in the order a reader decides them. */\nexport function storefrontBucketRows(\n summary: StorefrontTaxSummary,\n): StorefrontTaxBucketRow[] {\n const brand = PLATFORM_BRAND_NAME\n const buckets: Array<{\n id: StorefrontTaxBucketRow['id']\n label: string\n liability: string\n platformLiable: boolean\n }> = [\n {\n id: 'aglynLiable',\n label: `Computed against ${brand}’s registrations`,\n liability: `In ${brand}’s balance. Stripe Tax computed it on ${brand}’s platform account.`,\n platformLiable: true,\n },\n {\n id: 'merchantManual',\n label: 'Merchant’s own configured rate',\n liability: `The merchant’s. It never touched an ${brand} registration and is not ${brand}’s to remit.`,\n platformLiable: false,\n },\n {\n id: 'connectedAccountLiable',\n label: 'Stripe Tax named the connected account liable',\n liability: 'The connected account’s. Empty today.',\n platformLiable: false,\n },\n ]\n return buckets.map((bucket) => {\n const figures = summary?.[bucket.id]\n return {\n id: bucket.id,\n label: bucket.label,\n liability: bucket.liability,\n transactionCount: Number(figures?.transactionCount ?? 0),\n grossDollars: centsToDollars(figures?.grossCents),\n taxableSalesDollars: centsToDollars(figures?.taxableSalesCents),\n taxCollectedDollars: centsToDollars(figures?.taxCollectedCents),\n platformLiable: bucket.platformLiable,\n }\n })\n}\n\n/**\n * FACILITATED SALES BY STATE — the economic-nexus question (AGL-1956).\n *\n * The question a state asks a marketplace facilitator is \"how much did you\n * facilitate INTO this state, and in how many transactions\" — not \"how much\n * tax did you collect there\". A state the operator is not registered in\n * collects nothing by definition, which is exactly why collection cannot be\n * the measure: the states worth watching are the ones showing $0 tax and a\n * rising sales figure.\n *\n * So this SUMS the three liability buckets per jurisdiction. The rule that\n * the operator's own invoices and storefront rows are never summed still\n * holds — nothing here touches the operator's own sales; within the\n * storefront collection the buckets differ only in WHO REMITS, and a nexus\n * threshold counts the sale whoever remits it. Who remits is still carried\n * per row, because \"do we have nexus here\" and \"what do we owe here\" are\n * answered off the same rows and must not blur.\n *\n * ⚠️ A LOWER BOUND, deliberately rather than silently: `storefront-tax-record.ts`\n * files no row at all for a sale whose `taxMode` resolves to `none`, so a\n * wholly untaxed storefront sale is invisible here — the population nexus\n * detection most needs. Closing it is a write-side change recorded on\n * AGL-1956. The filing jurisdiction does not depend on any of this: a filer\n * registered where it is established has no in-state threshold left to cross.\n */\nexport function storefrontFacilitatedJurisdictionRows(\n summary: StorefrontTaxSummary | null | undefined,\n filing: TaxReturnFiling,\n): StorefrontFacilitatedJurisdictionRow[] {\n if (!summary) return []\n const totals = new Map<\n string,\n { count: number; salesCents: number; taxCents: number; platformCents: number }\n >()\n const buckets: Array<[StorefrontTaxBucketRow['id'], boolean]> = [\n ['aglynLiable', true],\n ['merchantManual', false],\n ['connectedAccountLiable', false],\n ]\n for (const [id, platformLiable] of buckets) {\n const byJurisdiction = summary[id]?.byJurisdiction ?? {}\n for (const [jurisdiction, figures] of Object.entries(byJurisdiction)) {\n const entry = totals.get(jurisdiction) ?? {\n count: 0,\n salesCents: 0,\n taxCents: 0,\n platformCents: 0,\n }\n const taxCents = Number(figures?.taxCollectedCents ?? 0)\n entry.count += Number(figures?.transactionCount ?? 0)\n entry.salesCents += Number(figures?.totalSalesCents ?? 0)\n entry.taxCents += taxCents\n if (platformLiable) entry.platformCents += taxCents\n totals.set(jurisdiction, entry)\n }\n }\n return [...totals.entries()]\n .map(([jurisdiction, entry]) => ({\n jurisdiction,\n isFilingJurisdiction: jurisdiction === filing.code,\n transactionCount: entry.count,\n totalSalesDollars: centsToDollars(entry.salesCents),\n taxCollectedDollars: centsToDollars(entry.taxCents),\n platformLiableTaxDollars: centsToDollars(entry.platformCents),\n untaxed: entry.taxCents === 0,\n }))\n .sort(\n (a, b) =>\n // The filing jurisdiction first — it is the one obligation that does\n // not wait on a threshold — then by the figure a threshold is\n // actually measured against.\n Number(b.isFilingJurisdiction) - Number(a.isFilingJurisdiction) ||\n Number(b.totalSalesDollars) - Number(a.totalSalesDollars) ||\n a.jurisdiction.localeCompare(b.jurisdiction),\n )\n}\n\n/** The storefront's two tables on the return's screen. */\nfunction storefrontTables(\n summary: StorefrontTaxSummary,\n filing: TaxReturnFiling,\n): TaxReturnSectionTable[] {\n const brand = PLATFORM_BRAND_NAME\n return [\n {\n // Split by who owes it, never summed — one \"storefront tax\" total would\n // merge two facts into a number that is true of neither.\n columns: [\n { label: 'Bucket' },\n { label: 'Sales', numeric: true },\n { label: 'Gross', numeric: true, money: true },\n { label: 'Taxable sales', numeric: true, money: true },\n { label: 'Tax collected', numeric: true, money: true },\n ],\n rows: storefrontBucketRows(summary).map((row) => ({\n key: row.id,\n cells: [\n {\n text: row.label,\n caption: row.liability,\n ...(row.platformLiable\n ? { tag: { label: `${brand} holds this`, tone: 'attention' as const } }\n : {}),\n },\n { text: String(row.transactionCount) },\n { text: `$${row.grossDollars}` },\n { text: `$${row.taxableSalesDollars}` },\n { text: `$${row.taxCollectedDollars}`, strong: row.platformLiable },\n ],\n })),\n empty: 'This period’s response carries no storefront figures.',\n },\n {\n heading: 'Facilitated sales by buyer state',\n description:\n `What ${brand} facilitated into each state, whoever remits the ` +\n 'tax — the figure an economic-nexus threshold is measured ' +\n `against. ${filing.code} needs no threshold: the filer is ` +\n 'established there, so the obligation is unconditional. A ' +\n 'region showing sales and no tax is the one to watch.',\n columns: [\n { label: 'Buyer state' },\n { label: 'Sales', numeric: true },\n { label: 'Total sales', numeric: true, money: true },\n { label: 'Tax collected', numeric: true, money: true },\n { label: `Of which ${brand} owes`, numeric: true, money: true },\n ],\n rows: storefrontFacilitatedJurisdictionRows(summary, filing).map((row) => ({\n key: row.jurisdiction,\n cells: [\n {\n text: row.jurisdiction === 'unknown' ? 'Not stated' : row.jurisdiction,\n ...(row.isFilingJurisdiction\n ? { tag: { label: 'Registered', tone: 'attention' as const } }\n : row.untaxed\n ? { tag: { label: 'No tax collected', tone: 'neutral' as const } }\n : {}),\n },\n { text: String(row.transactionCount) },\n { text: `$${row.totalSalesDollars}` },\n { text: `$${row.taxCollectedDollars}` },\n {\n text: `$${row.platformLiableTaxDollars}`,\n strong: Number(row.platformLiableTaxDollars) > 0,\n },\n ],\n })),\n empty: 'No storefront sales recorded in this period.',\n footnote:\n 'A LOWER BOUND. A storefront sale that collected no tax at ' +\n 'all files no row, so it is missing here — which is exactly ' +\n 'the population a nexus check wants. Recorded on AGL-1956.',\n },\n ]\n}\n\n/**\n * The storefront's blocks of the working-papers export: the nexus figures\n * beside the operator's own sales by jurisdiction — a different taxpayer's\n * money and never summed with them — and the liability buckets after the\n * working papers.\n */\nfunction storefrontExports(\n summary: StorefrontTaxSummary,\n filing: TaxReturnFiling,\n): TaxReturnExportBlock[] {\n const brand = PLATFORM_BRAND_NAME\n const facilitated = storefrontFacilitatedJurisdictionRows(summary, filing)\n return [\n {\n placement: 'jurisdictions',\n rows: [\n ['Facilitated sales by buyer state (merchants’ storefronts)'],\n [\n 'Buyer state',\n 'Sales',\n 'Total sales (USD)',\n 'Tax collected (USD)',\n `Of which ${brand} owes (USD)`,\n ],\n ...(facilitated.length\n ? facilitated.map((row) => [\n row.jurisdiction,\n String(row.transactionCount),\n row.totalSalesDollars,\n row.taxCollectedDollars,\n row.platformLiableTaxDollars,\n ])\n : [['—', '0', '0.00', '0.00', '0.00']]),\n [\n 'LOWER BOUND — a storefront sale that collected no tax files no row, ' +\n `so it is absent here. ${filing.code} needs no threshold: the filer ` +\n 'is established there.',\n ],\n ],\n },\n {\n placement: 'sections',\n rows: [\n [\n 'Storefront commerce tax by liability (AGL-1904) — NOT in ' +\n (filing.form === 'tx-webfile' ? 'the Webfile figures' : 'the breakdown above'),\n ],\n [\n 'Bucket',\n 'Who owes it',\n 'Transactions',\n 'Gross (USD)',\n 'Taxable sales (USD)',\n 'Tax collected (USD)',\n ],\n ...storefrontBucketRows(summary).map((row) => [\n row.label,\n row.liability,\n String(row.transactionCount),\n row.grossDollars,\n row.taxableSalesDollars,\n row.taxCollectedDollars,\n ]),\n ],\n },\n ]\n}\n\n/** One storefront row as the working papers carry it. */\nfunction projectRow(row: StorefrontTaxReturnRowInput): StorefrontTaxRow {\n return {\n id: row.id,\n hostId: typeof row.hostId === 'string' ? row.hostId : null,\n orgId: row.orgId ?? null,\n paidAt: asRowDate(row.paidAt)?.toISOString() ?? null,\n taxMode: typeof row.taxMode === 'string' ? row.taxMode : null,\n taxLiability: typeof row.taxLiability === 'string' ? row.taxLiability : null,\n grossCents: Number(row.grossCents ?? 0),\n taxCents: Number(row.taxCents ?? 0),\n taxableSalesCents: (Array.isArray(row.taxLines) ? row.taxLines : [])\n .map((line) => Number(line?.taxableAmountCents ?? 0))\n .reduce((sum, base) => sum + (Number.isFinite(base) ? base : 0), 0),\n state: typeof row.customerAddress?.state === 'string' ? row.customerAddress.state : null,\n country:\n typeof row.customerAddress?.country === 'string' ? row.customerAddress.country : null,\n }\n}\n\n/**\n * The storefront's answer for one period, from rows already read. Pure, so\n * the section a preparer reads can be proved from fixtures.\n */\nexport function storefrontTaxReturnAnswer(\n read: {\n rows: readonly StorefrontTaxReturnRowInput[]\n truncated: boolean\n undatedRows: number\n /** Rows of the operator's own stores, which their own card folds in instead (AGL-4038). */\n ownStoreRows?: number\n },\n request: TaxReturnSourceRequest,\n): TaxReturnSourceAnswer {\n const brand = PLATFORM_BRAND_NAME\n const { filing } = request\n const summary = storefrontTaxSummary(read.rows, request)\n return {\n id: 'storefront',\n name: 'Storefront',\n title: 'Storefront commerce tax — merchants’ sales',\n help:\n 'Tax charged to shoppers on merchants’ storefronts, split by who owes it. None of it is in the filing figures above.',\n intro:\n `None of this is in the ${\n filing.form === 'tx-webfile' ? 'Webfile' : 'breakdown'\n } figures above, which sum ` +\n `${brand}’s OWN sales only. The first row is the one that ` +\n `needs a decision: those sessions are created on ${brand}’s ` +\n `platform account, so Stripe computed that tax against ` +\n `${brand}’s registrations and it settled into ${brand}’s balance.`,\n truncated: read.truncated,\n undatedRows: read.undatedRows,\n findings: storefrontTaxFindings(summary, filing),\n filingLines: storefrontFilingLines(summary, filing),\n tables: storefrontTables(summary, filing),\n figures: read.ownStoreRows\n ? [\n {\n label: `Rows of ${brand}’s own stores`,\n value: String(read.ownStoreRows),\n note: `${brand}’s own sales, not a merchant’s: on the own stores card and folded into the filing figures, never here.`,\n },\n ]\n : [],\n exports: storefrontExports(summary, filing),\n summary,\n rows: read.rows.map(projectRow),\n }\n}\n\n/**\n * Commerce's source, registered on the console's API surface: the staff\n * return awaits that surface before it asks. It answers three sections, one\n * per kind of sale commerce records apart:\n *\n * - the storefront's FACILITATED sales — merchants' money (below);\n * - the POS hardware shop's, the operator's own\n * (`pos-hardware-tax-return-source.ts`, AGL-4038);\n * - the operator's own stores', its own too (`own-store-tax-return-source.ts`,\n * AGL-4038).\n *\n * The operator's own stores are resolved FIRST, because each of the others\n * leaves their sales to the third: the storefront drops their tax rows (and\n * hands their stated bases over), and the hardware section folds in no\n * reader sold at their registers. So every sale is counted once. Any read\n * failing refuses all three, so a half-read commerce never reads as a\n * complete one.\n */\nexport const commerceTaxReturnSource: TaxReturnSource = {\n async read(request) {\n const own = await resolveOwnStores()\n const ownHostIds = new Set(own.stores.map((store) => store.hostId))\n const [storefrontRead, hardware, ownOrders] = await Promise.all([\n readStorefrontTaxRows(request),\n readPosHardwareTaxReturn(request, { ownHostIds }),\n readOwnStoreOrders(request, own.stores),\n ])\n const isOwn = (row: StorefrontTaxReturnRowInput) => isOwnStoreRow(row, own)\n const ownRows = storefrontRead.rows.filter(isOwn)\n const storefront = storefrontTaxReturnAnswer(\n { ...storefrontRead, rows: storefrontRead.rows.filter((row) => !isOwn(row)), ownStoreRows: ownRows.length },\n request,\n )\n // The base Stripe stated on an own store's online sale, by its order id\n // (an online order is keyed by its Checkout Session, as its row is).\n const statedBases = new Map<string, number>()\n for (const row of ownRows) {\n const base = statedTaxableBase(Array.isArray(row.taxLines) ? row.taxLines : [])\n if (base !== null) statedBases.set(row.id, base)\n }\n const ownStores = ownStoreTaxReturnAnswer({ own, read: ownOrders, statedBases }, request)\n return [storefront, hardware, ownStores]\n },\n}\n\n/** Whether a storefront tax row is one of the operator's own stores' (AGL-4038). */\nexport function isOwnStoreRow(\n row: Pick<StorefrontTaxReturnRowInput, 'hostId' | 'orgId'>,\n own: OwnStores,\n): boolean {\n if (typeof row.hostId === 'string' && own.stores.some((store) => store.hostId === row.hostId)) return true\n return Boolean(own.orgId) && row.orgId === own.orgId\n}\n\n/**\n * The storefront's section.\n *\n * Two queries, and the second is the honesty check: the period query ranges\n * on `paidAt`, and a Firestore range query CANNOT match a document whose\n * field is null — so a row that failed to date itself would be invisible to\n * every period. The equality probe counts those rows, over all of them, and\n * the platform blocks the return on any.\n */\nexport async function readStorefrontTaxReturn(\n request: TaxReturnSourceRequest,\n): Promise<TaxReturnSourceAnswer> {\n return storefrontTaxReturnAnswer(await readStorefrontTaxRows(request), request)\n}\n\n/** The storefront's rows for the period, before any is set aside. See {@link readStorefrontTaxReturn}. */\nexport async function readStorefrontTaxRows(request: TaxReturnSourceRequest): Promise<{\n rows: StorefrontTaxReturnRowInput[]\n truncated: boolean\n undatedRows: number\n}> {\n const firestore = firebaseAdmin.app().firestore()\n const collection = firestore.collection('storefrontTaxCollected')\n const [inPeriod, undated, inPerson] = await Promise.all([\n collection\n .where('paidAt', '>=', request.start)\n .where('paidAt', '<', request.end)\n .limit(request.rowCap + 1)\n .get(),\n collection.where('paidAt', '==', null).count().get(),\n // The platform's own in-person hardware sales around the period\n // (AGL-4038): the hardware section counts them, so their part of the\n // register sale's storefront row comes out here (`posHardwareSales`\n // `source, paidAtMs`).\n firestore\n .collection(POS_HARDWARE_SALES_COLLECTION)\n .where('source', '==', 'in_person')\n .where('paidAtMs', '>=', request.start.getTime() - IN_PERSON_ROW_MARGIN_MS)\n .where('paidAtMs', '<', request.end.getTime() + IN_PERSON_ROW_MARGIN_MS)\n .limit(request.rowCap)\n .get(),\n ])\n const rows: StorefrontTaxReturnRowInput[] = storefrontRowsWithoutInPersonHardware(\n inPeriod.docs.slice(0, request.rowCap).map((doc) => ({\n id: doc.id,\n ...(doc.data() as Omit<StorefrontTaxReturnRowInput, 'id'>),\n })),\n posHardwareStorefrontParts(inPerson.docs.map((doc) => doc.data())),\n )\n return {\n rows,\n truncated: inPeriod.size > request.rowCap,\n undatedRows: Number(undated.data().count ?? 0),\n }\n}\n"],"names":["firebaseAdmin","PLATFORM_BRAND_NAME","asRowDate","centsToDollars","storefrontTaxSummary","readPosHardwareTaxReturn","POS_HARDWARE_SALES_COLLECTION","posHardwareStorefrontParts","storefrontRowsWithoutInPersonHardware","statedTaxableBase","ownStoreTaxReturnAnswer","readOwnStoreOrders","resolveOwnStores","IN_PERSON_ROW_MARGIN_MS","storefrontPlatformLiableCents","summary","filing","figures","aglynLiable","byJurisdiction","code","cents","Number","taxCollectedCents","isFinite","merchantManualCents","merchantManual","storefrontTaxFindings","brand","id","severity","count","label","detail","figuresName","attention","rowsUnclassified","rowsMissingTaxableBase","storefrontFilingLines","platformLiable","merchant","form","item","dollars","note","storefrontBucketRows","buckets","liability","map","bucket","transactionCount","grossDollars","grossCents","taxableSalesDollars","taxableSalesCents","taxCollectedDollars","storefrontFacilitatedJurisdictionRows","totals","Map","jurisdiction","Object","entries","entry","get","salesCents","taxCents","platformCents","totalSalesCents","set","isFilingJurisdiction","totalSalesDollars","platformLiableTaxDollars","untaxed","sort","a","b","localeCompare","storefrontTables","columns","numeric","money","rows","row","key","cells","text","caption","tag","tone","String","strong","empty","heading","description","footnote","storefrontExports","facilitated","placement","length","projectRow","hostId","orgId","paidAt","toISOString","taxMode","taxLiability","Array","isArray","taxLines","line","taxableAmountCents","reduce","sum","base","state","customerAddress","country","storefrontTaxReturnAnswer","read","request","name","title","help","intro","truncated","undatedRows","findings","filingLines","tables","ownStoreRows","value","exports","commerceTaxReturnSource","own","ownHostIds","Set","stores","store","storefrontRead","hardware","ownOrders","Promise","all","readStorefrontTaxRows","isOwn","isOwnStoreRow","ownRows","filter","storefront","statedBases","ownStores","some","Boolean","readStorefrontTaxReturn","undated","firestore","app","collection","inPeriod","inPerson","where","start","end","limit","rowCap","getTime","docs","slice","doc","data","size"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuCC,GAED,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SACEC,SAAS,EACTC,cAAc,QACT,kDAAiD;AAWxD,SACEC,oBAAoB,QAGf,qCAAiC;AACxC,SAASC,wBAAwB,QAAQ,sCAAkC;AAC3E,SAASC,6BAA6B,QAAQ,2BAAuB;AACrE,SACEC,0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MzC,QAAQ0C,KAAK,CAACI,OAAO,KAAKxJ,yBAClDmJ,KAAK,CAAC,YAAY,KAAKzC,QAAQ2C,GAAG,CAACG,OAAO,KAAKxJ,yBAC/CsJ,KAAK,CAAC5C,QAAQ6C,MAAM,EACpBrG,GAAG;KACP;IACD,MAAMkB,OAAsCzE,sCAC1CsJ,SAASQ,IAAI,CAACC,KAAK,CAAC,GAAGhD,QAAQ6C,MAAM,EAAEpH,GAAG,CAAC,CAACwH,MAAS;YACnD3I,IAAI2I,IAAI3I,EAAE;WACN2I,IAAIC,IAAI,MAEdlK,2BAA2BwJ,SAASO,IAAI,CAACtH,GAAG,CAAC,CAACwH,MAAQA,IAAIC,IAAI;IAEhE,OAAO;QACLxF;QACA2C,WAAWkC,SAASY,IAAI,GAAGnD,QAAQ6C,MAAM;QACzCvC,aAAavG,QAAOoI,sBAAAA,QAAQe,IAAI,GAAG1I,KAAK,YAApB2H,sBAAwB;IAC9C;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/tax-return-source.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\n/**\n * Storefront sales on the operator's sales tax return (AGL-1904, AGL-3080).\n *\n * The operator's return sums its own invoices; this is the storefront's half\n * of it, answered through the platform's tax return source contract\n * (`@aglyn/aglyn/plugin-manager/plugin-tax-return-sources`). It reads\n * `storefrontTaxCollected` — a SEPARATE collection from the operator's own\n * invoices, queried and reported separately, because a storefront row's\n * money is mostly the merchant's while an invoice row's is the operator's.\n * Summing the two would put other companies' receipts into the return's\n * total sales, which is why they never meet in one query and never share a\n * figure.\n *\n * What it answers, all worded for the filing jurisdiction the platform\n * resolved:\n *\n * - **The three liability buckets**, never summed — see\n * `model/storefront-tax-summary.ts`.\n * - **A blocking finding for the platform-liable tax** in the filing\n * jurisdiction. Every storefront checkout is created on the platform's\n * own account, so a `mode: 'stripe'` store's shopper is charged tax Stripe\n * computes against the PLATFORM's registrations — measured, not inferred.\n * That money is in the platform's balance and is NOT in the filing\n * figures, which sum the operator's own sales only. Filing those without\n * deciding what to do with this figure is exactly the shortfall an\n * auditor finds. It states the mechanics and asks for a decision; it does\n * NOT assert a marketplace-facilitator position — that attaches by\n * operation of law and belongs to counsel, not to this report.\n * - **Two lines beneath the filing figures** — the platform-liable tax and\n * the merchant's own rate, stated side by side and never folded into a\n * form item, because this report does not decide how storefront receipts\n * are reported and adding them to one would be deciding it silently.\n * - **Facilitated sales by buyer state** — the economic-nexus question\n * (AGL-1956), with the three buckets SUMMED per jurisdiction on purpose:\n * a threshold counts the sale whoever remits it. Who remits is still\n * carried per row.\n *\n * Truncation and rows no period can reach are reported, and the platform\n * raises each as a blocking finding of its own.\n */\n\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport {\n asRowDate,\n centsToDollars,\n} from '@aglyn/aglyn/app-utils/tax-jurisdiction-figures'\nimport type {\n TaxReturnExportBlock,\n TaxReturnFiling,\n TaxReturnFilingLine,\n TaxReturnFinding,\n TaxReturnSectionTable,\n TaxReturnSource,\n TaxReturnSourceAnswer,\n TaxReturnSourceRequest,\n} from '@aglyn/aglyn/plugin-manager/plugin-tax-return-sources'\nimport {\n storefrontTaxSummary,\n type StorefrontTaxReturnRowInput,\n type StorefrontTaxSummary,\n} from '../model/storefront-tax-summary'\nimport { readPosHardwareTaxReturn } from './pos-hardware-tax-return-source'\nimport { POS_HARDWARE_SALES_COLLECTION } from '../model/pos-hardware'\nimport {\n posHardwareStorefrontParts,\n storefrontRowsWithoutInPersonHardware,\n} from '../model/pos-hardware-tax-summary'\nimport { statedTaxableBase } from '../model/own-store-tax-summary'\nimport {\n ownStoreTaxReturnAnswer,\n readOwnStoreOrders,\n resolveOwnStores,\n type OwnStores,\n} from './own-store-tax-return-source'\n\n/**\n * How far either side of the period an in-person hardware record is read,\n * to meet the storefront row its register sale filed: the two are written\n * seconds apart, so a week is more than enough for either edge.\n */\nconst IN_PERSON_ROW_MARGIN_MS = 7 * 24 * 60 * 60 * 1000\n\n/** One row of the storefront listing, as the working papers carry it. */\nexport interface StorefrontTaxRow {\n id: string\n hostId: string | null\n orgId: string | null\n paidAt: string | null\n taxMode: string | null\n taxLiability: string | null\n grossCents: number\n taxCents: number\n taxableSalesCents: number\n state: string | null\n country: string | null\n}\n\n/** A liability bucket, ready to print. */\nexport interface StorefrontTaxBucketRow {\n id: 'aglynLiable' | 'merchantManual' | 'connectedAccountLiable'\n label: string\n /** Who owes it — the sentence that decides whether it is on this return. */\n liability: string\n transactionCount: number\n grossDollars: string\n taxableSalesDollars: string\n taxCollectedDollars: string\n /** True when this row is money in the platform's balance under its registration. */\n platformLiable: boolean\n}\n\n/** One state's facilitated storefront sales, for the nexus question. */\nexport interface StorefrontFacilitatedJurisdictionRow {\n jurisdiction: string\n /** True for the one jurisdiction this deployment files a return in. */\n isFilingJurisdiction: boolean\n transactionCount: number\n totalSalesDollars: string\n taxCollectedDollars: string\n /** The part of `taxCollectedDollars` the platform holds and must remit. */\n platformLiableTaxDollars: string\n /** True when NO tax was collected on any sale into this state. */\n untaxed: boolean\n}\n\n/**\n * Storefront tax in the FILING jurisdiction that Stripe computed against the\n * platform's own registrations.\n *\n * The one figure that decides whether a period can be filed from the filing\n * lines alone. Deliberately excludes `merchantManual` — a merchant's own\n * configured rate never touched those registrations. Read against the\n * configured jurisdiction rather than Texas, because a hard-coded key answers\n * `0.00` everywhere else — and a zero here reads as \"nothing to decide\" on\n * the one finding that blocks filing.\n */\nexport function storefrontPlatformLiableCents(\n summary: StorefrontTaxSummary | null | undefined,\n filing: TaxReturnFiling,\n): number {\n const figures = summary?.aglynLiable?.byJurisdiction?.[filing.code]\n const cents = Number(figures?.taxCollectedCents ?? 0)\n return Number.isFinite(cents) ? cents : 0\n}\n\n/** The merchant's own configured tax in the filing jurisdiction. */\nfunction merchantManualCents(\n summary: StorefrontTaxSummary | null | undefined,\n filing: TaxReturnFiling,\n): number {\n return Number(\n summary?.merchantManual?.byJurisdiction?.[filing.code]?.taxCollectedCents ?? 0,\n )\n}\n\n/** The storefront's findings. The platform raises the non-zero ones. */\nexport function storefrontTaxFindings(\n summary: StorefrontTaxSummary,\n filing: TaxReturnFiling,\n): TaxReturnFinding[] {\n const brand = PLATFORM_BRAND_NAME\n return [\n {\n // BLOCKING on purpose — see the module note.\n id: 'storefrontAglynLiableTax',\n severity: 'blocking',\n count: storefrontPlatformLiableCents(summary, filing),\n label: `${filing.label} storefront tax collected under ${brand}’s registration`,\n detail:\n 'Cents. Charged to shoppers on merchants’ storefront sales, computed ' +\n 'by Stripe Tax against THE PLATFORM’s registrations (the session is ' +\n 'created on the platform account), and settled into the platform’s ' +\n `balance. It is NOT included in ${filing.figuresName} below. Decide ` +\n 'with counsel how it is reported before filing — do not file as if ' +\n 'it were zero.',\n },\n {\n id: 'storefrontUnclassified',\n severity: 'blocking',\n count: Number(summary?.attention?.rowsUnclassified ?? 0),\n label: 'Storefront rows with an unrecognised tax mode',\n detail:\n 'Not counted in any storefront bucket, so they are in no figure at ' +\n 'all. Classify them before filing.',\n },\n {\n id: 'storefrontMissingTaxableBase',\n severity: 'review',\n count: Number(summary?.attention?.rowsMissingTaxableBase ?? 0),\n label: 'Storefront rows with tax but no stated base',\n detail:\n 'Tax was collected but Stripe’s taxable_amount could not be read, so ' +\n 'the storefront taxable-sales figure understates the base. Re-read ' +\n 'the session in Stripe with the tax breakdown expanded.',\n },\n ]\n}\n\n/**\n * The two lines beneath the filing figures: the platform-liable tax and the\n * merchant's own rate, separately, and outside every form item.\n */\nexport function storefrontFilingLines(\n summary: StorefrontTaxSummary,\n filing: TaxReturnFiling,\n): TaxReturnFilingLine[] {\n const brand = PLATFORM_BRAND_NAME\n const platformLiable = centsToDollars(storefrontPlatformLiableCents(summary, filing))\n const merchant = centsToDollars(merchantManualCents(summary, filing))\n if (filing.form === 'tx-webfile') {\n return [\n {\n item: '—',\n label: `${filing.label} storefront tax under ${brand}’s registration (NOT in ${filing.figuresName})`,\n dollars: platformLiable,\n note:\n `Collected from shoppers on merchants’ sales and held in ${brand}’s ` +\n 'balance. Excluded from every item above. Its treatment on the ' +\n 'return is a question for counsel — see AGL-1904.',\n },\n {\n item: '—',\n label: `${filing.label} storefront tax under the MERCHANT’s own rate (not ${brand}’s)`,\n dollars: merchant,\n note:\n `A manual-mode store’s own configured rate. ${brand}’s registrations ` +\n 'played no part in computing it. Shown so it is visibly NOT the line ' +\n 'above — the two must never be added together.',\n },\n ]\n }\n return [\n {\n item: '—',\n label: `${filing.code} storefront tax under the platform’s registration (NOT in the figures above)`,\n dollars: platformLiable,\n note:\n 'Collected from shoppers on merchants’ sales and held in the ' +\n 'platform’s balance. Excluded from every figure above. Its treatment ' +\n 'on the return is a question for the operator’s own counsel.',\n },\n {\n item: '—',\n label: `${filing.code} storefront tax under the MERCHANT’s own rate`,\n dollars: merchant,\n note:\n 'A manual-mode store’s own configured rate. The platform’s ' +\n 'registrations played no part in computing it. Shown so it is ' +\n 'visibly NOT the line above — the two must never be added together.',\n },\n ]\n}\n\n/** The three liability buckets, in the order a reader decides them. */\nexport function storefrontBucketRows(\n summary: StorefrontTaxSummary,\n): StorefrontTaxBucketRow[] {\n const brand = PLATFORM_BRAND_NAME\n const buckets: Array<{\n id: StorefrontTaxBucketRow['id']\n label: string\n liability: string\n platformLiable: boolean\n }> = [\n {\n id: 'aglynLiable',\n label: `Computed against ${brand}’s registrations`,\n liability: `In ${brand}’s balance. Stripe Tax computed it on ${brand}’s platform account.`,\n platformLiable: true,\n },\n {\n id: 'merchantManual',\n label: 'Merchant’s own configured rate',\n liability: `The merchant’s. It never touched an ${brand} registration and is not ${brand}’s to remit.`,\n platformLiable: false,\n },\n {\n id: 'connectedAccountLiable',\n label: 'Stripe Tax named the connected account liable',\n liability: 'The connected account’s. Empty today.',\n platformLiable: false,\n },\n ]\n return buckets.map((bucket) => {\n const figures = summary?.[bucket.id]\n return {\n id: bucket.id,\n label: bucket.label,\n liability: bucket.liability,\n transactionCount: Number(figures?.transactionCount ?? 0),\n grossDollars: centsToDollars(figures?.grossCents),\n taxableSalesDollars: centsToDollars(figures?.taxableSalesCents),\n taxCollectedDollars: centsToDollars(figures?.taxCollectedCents),\n platformLiable: bucket.platformLiable,\n }\n })\n}\n\n/**\n * FACILITATED SALES BY STATE — the economic-nexus question (AGL-1956).\n *\n * The question a state asks a marketplace facilitator is \"how much did you\n * facilitate INTO this state, and in how many transactions\" — not \"how much\n * tax did you collect there\". A state the operator is not registered in\n * collects nothing by definition, which is exactly why collection cannot be\n * the measure: the states worth watching are the ones showing $0 tax and a\n * rising sales figure.\n *\n * So this SUMS the three liability buckets per jurisdiction. The rule that\n * the operator's own invoices and storefront rows are never summed still\n * holds — nothing here touches the operator's own sales; within the\n * storefront collection the buckets differ only in WHO REMITS, and a nexus\n * threshold counts the sale whoever remits it. Who remits is still carried\n * per row, because \"do we have nexus here\" and \"what do we owe here\" are\n * answered off the same rows and must not blur.\n *\n * ⚠️ A LOWER BOUND, deliberately rather than silently: `storefront-tax-record.ts`\n * files no row at all for a sale whose `taxMode` resolves to `none`, so a\n * wholly untaxed storefront sale is invisible here — the population nexus\n * detection most needs. Closing it is a write-side change recorded on\n * AGL-1956. The filing jurisdiction does not depend on any of this: a filer\n * registered where it is established has no in-state threshold left to cross.\n */\nexport function storefrontFacilitatedJurisdictionRows(\n summary: StorefrontTaxSummary | null | undefined,\n filing: TaxReturnFiling,\n): StorefrontFacilitatedJurisdictionRow[] {\n if (!summary) return []\n const totals = new Map<\n string,\n { count: number; salesCents: number; taxCents: number; platformCents: number }\n >()\n const buckets: Array<[StorefrontTaxBucketRow['id'], boolean]> = [\n ['aglynLiable', true],\n ['merchantManual', false],\n ['connectedAccountLiable', false],\n ]\n for (const [id, platformLiable] of buckets) {\n const byJurisdiction = summary[id]?.byJurisdiction ?? {}\n for (const [jurisdiction, figures] of Object.entries(byJurisdiction)) {\n const entry = totals.get(jurisdiction) ?? {\n count: 0,\n salesCents: 0,\n taxCents: 0,\n platformCents: 0,\n }\n const taxCents = Number(figures?.taxCollectedCents ?? 0)\n entry.count += Number(figures?.transactionCount ?? 0)\n entry.salesCents += Number(figures?.totalSalesCents ?? 0)\n entry.taxCents += taxCents\n if (platformLiable) entry.platformCents += taxCents\n totals.set(jurisdiction, entry)\n }\n }\n return [...totals.entries()]\n .map(([jurisdiction, entry]) => ({\n jurisdiction,\n isFilingJurisdiction: jurisdiction === filing.code,\n transactionCount: entry.count,\n totalSalesDollars: centsToDollars(entry.salesCents),\n taxCollectedDollars: centsToDollars(entry.taxCents),\n platformLiableTaxDollars: centsToDollars(entry.platformCents),\n untaxed: entry.taxCents === 0,\n }))\n .sort(\n (a, b) =>\n // The filing jurisdiction first — it is the one obligation that does\n // not wait on a threshold — then by the figure a threshold is\n // actually measured against.\n Number(b.isFilingJurisdiction) - Number(a.isFilingJurisdiction) ||\n Number(b.totalSalesDollars) - Number(a.totalSalesDollars) ||\n a.jurisdiction.localeCompare(b.jurisdiction),\n )\n}\n\n/** The storefront's two tables on the return's screen. */\nfunction storefrontTables(\n summary: StorefrontTaxSummary,\n filing: TaxReturnFiling,\n): TaxReturnSectionTable[] {\n const brand = PLATFORM_BRAND_NAME\n return [\n {\n // Split by who owes it, never summed — one \"storefront tax\" total would\n // merge two facts into a number that is true of neither.\n columns: [\n { label: 'Bucket' },\n { label: 'Sales', numeric: true },\n { label: 'Gross', numeric: true, money: true },\n { label: 'Taxable sales', numeric: true, money: true },\n { label: 'Tax collected', numeric: true, money: true },\n ],\n rows: storefrontBucketRows(summary).map((row) => ({\n key: row.id,\n cells: [\n {\n text: row.label,\n caption: row.liability,\n ...(row.platformLiable\n ? { tag: { label: `${brand} holds this`, tone: 'attention' as const } }\n : {}),\n },\n { text: String(row.transactionCount) },\n { text: `$${row.grossDollars}` },\n { text: `$${row.taxableSalesDollars}` },\n { text: `$${row.taxCollectedDollars}`, strong: row.platformLiable },\n ],\n })),\n empty: 'This period’s response carries no storefront figures.',\n },\n {\n heading: 'Facilitated sales by buyer state',\n description:\n `What ${brand} facilitated into each state, whoever remits the ` +\n 'tax — the figure an economic-nexus threshold is measured ' +\n `against. ${filing.code} needs no threshold: the filer is ` +\n 'established there, so the obligation is unconditional. A ' +\n 'region showing sales and no tax is the one to watch.',\n columns: [\n { label: 'Buyer state' },\n { label: 'Sales', numeric: true },\n { label: 'Total sales', numeric: true, money: true },\n { label: 'Tax collected', numeric: true, money: true },\n { label: `Of which ${brand} owes`, numeric: true, money: true },\n ],\n rows: storefrontFacilitatedJurisdictionRows(summary, filing).map((row) => ({\n key: row.jurisdiction,\n cells: [\n {\n text: row.jurisdiction === 'unknown' ? 'Not stated' : row.jurisdiction,\n ...(row.isFilingJurisdiction\n ? { tag: { label: 'Registered', tone: 'attention' as const } }\n : row.untaxed\n ? { tag: { label: 'No tax collected', tone: 'neutral' as const } }\n : {}),\n },\n { text: String(row.transactionCount) },\n { text: `$${row.totalSalesDollars}` },\n { text: `$${row.taxCollectedDollars}` },\n {\n text: `$${row.platformLiableTaxDollars}`,\n strong: Number(row.platformLiableTaxDollars) > 0,\n },\n ],\n })),\n empty: 'No storefront sales recorded in this period.',\n footnote:\n 'A LOWER BOUND. A storefront sale that collected no tax at ' +\n 'all files no row, so it is missing here — which is exactly ' +\n 'the population a nexus check wants. Recorded on AGL-1956.',\n },\n ]\n}\n\n/**\n * The storefront's blocks of the working-papers export: the nexus figures\n * beside the operator's own sales by jurisdiction — a different taxpayer's\n * money and never summed with them — and the liability buckets after the\n * working papers.\n */\nfunction storefrontExports(\n summary: StorefrontTaxSummary,\n filing: TaxReturnFiling,\n): TaxReturnExportBlock[] {\n const brand = PLATFORM_BRAND_NAME\n const facilitated = storefrontFacilitatedJurisdictionRows(summary, filing)\n return [\n {\n placement: 'jurisdictions',\n rows: [\n ['Facilitated sales by buyer state (merchants’ storefronts)'],\n [\n 'Buyer state',\n 'Sales',\n 'Total sales (USD)',\n 'Tax collected (USD)',\n `Of which ${brand} owes (USD)`,\n ],\n ...(facilitated.length\n ? facilitated.map((row) => [\n row.jurisdiction,\n String(row.transactionCount),\n row.totalSalesDollars,\n row.taxCollectedDollars,\n row.platformLiableTaxDollars,\n ])\n : [['—', '0', '0.00', '0.00', '0.00']]),\n [\n 'LOWER BOUND — a storefront sale that collected no tax files no row, ' +\n `so it is absent here. ${filing.code} needs no threshold: the filer ` +\n 'is established there.',\n ],\n ],\n },\n {\n placement: 'sections',\n rows: [\n [\n 'Storefront commerce tax by liability (AGL-1904) — NOT in ' +\n (filing.form === 'tx-webfile' ? 'the Webfile figures' : 'the breakdown above'),\n ],\n [\n 'Bucket',\n 'Who owes it',\n 'Transactions',\n 'Gross (USD)',\n 'Taxable sales (USD)',\n 'Tax collected (USD)',\n ],\n ...storefrontBucketRows(summary).map((row) => [\n row.label,\n row.liability,\n String(row.transactionCount),\n row.grossDollars,\n row.taxableSalesDollars,\n row.taxCollectedDollars,\n ]),\n ],\n },\n ]\n}\n\n/** One storefront row as the working papers carry it. */\nfunction projectRow(row: StorefrontTaxReturnRowInput): StorefrontTaxRow {\n return {\n id: row.id,\n hostId: typeof row.hostId === 'string' ? row.hostId : null,\n orgId: row.orgId ?? null,\n paidAt: asRowDate(row.paidAt)?.toISOString() ?? null,\n taxMode: typeof row.taxMode === 'string' ? row.taxMode : null,\n taxLiability: typeof row.taxLiability === 'string' ? row.taxLiability : null,\n grossCents: Number(row.grossCents ?? 0),\n taxCents: Number(row.taxCents ?? 0),\n taxableSalesCents: (Array.isArray(row.taxLines) ? row.taxLines : [])\n .map((line) => Number(line?.taxableAmountCents ?? 0))\n .reduce((sum, base) => sum + (Number.isFinite(base) ? base : 0), 0),\n state: typeof row.customerAddress?.state === 'string' ? row.customerAddress.state : null,\n country:\n typeof row.customerAddress?.country === 'string' ? row.customerAddress.country : null,\n }\n}\n\n/**\n * The storefront's answer for one period, from rows already read. Pure, so\n * the section a preparer reads can be proved from fixtures.\n */\nexport function storefrontTaxReturnAnswer(\n read: {\n rows: readonly StorefrontTaxReturnRowInput[]\n truncated: boolean\n undatedRows: number\n /** Rows of the operator's own stores, which their own card folds in instead (AGL-4038). */\n ownStoreRows?: number\n },\n request: TaxReturnSourceRequest,\n): TaxReturnSourceAnswer {\n const brand = PLATFORM_BRAND_NAME\n const { filing } = request\n const summary = storefrontTaxSummary(read.rows, request)\n return {\n id: 'storefront',\n name: 'Storefront',\n title: 'Storefront commerce tax — merchants’ sales',\n help:\n 'Tax charged to shoppers on merchants’ storefronts, split by who owes it. None of it is in the filing figures above.',\n intro:\n `None of this is in the ${\n filing.form === 'tx-webfile' ? 'Webfile' : 'breakdown'\n } figures above, which sum ` +\n `${brand}’s OWN sales only. The first row is the one that ` +\n `needs a decision: those sessions are created on ${brand}’s ` +\n `platform account, so Stripe computed that tax against ` +\n `${brand}’s registrations and it settled into ${brand}’s balance.`,\n truncated: read.truncated,\n undatedRows: read.undatedRows,\n findings: storefrontTaxFindings(summary, filing),\n filingLines: storefrontFilingLines(summary, filing),\n tables: storefrontTables(summary, filing),\n figures: read.ownStoreRows\n ? [\n {\n label: `Rows of ${brand}’s own stores`,\n value: String(read.ownStoreRows),\n note: `${brand}’s own sales, not a merchant’s: on the own stores card and folded into the filing figures, never here.`,\n },\n ]\n : [],\n exports: storefrontExports(summary, filing),\n summary,\n rows: read.rows.map(projectRow),\n }\n}\n\n/**\n * Commerce's source, registered on the console's API surface: the staff\n * return awaits that surface before it asks. It answers three sections, one\n * per kind of sale commerce records apart:\n *\n * - the storefront's FACILITATED sales — merchants' money (below);\n * - the POS hardware shop's, the operator's own\n * (`pos-hardware-tax-return-source.ts`, AGL-4038);\n * - the operator's own stores', its own too (`own-store-tax-return-source.ts`,\n * AGL-4038).\n *\n * The operator's own stores are resolved FIRST, because each of the others\n * leaves their sales to the third: the storefront drops their tax rows (and\n * hands their stated bases over), and the hardware section folds in no\n * reader sold at their registers. So every sale is counted once. Any read\n * failing refuses all three, so a half-read commerce never reads as a\n * complete one.\n */\nexport const commerceTaxReturnSource: TaxReturnSource = {\n async read(request) {\n const own = await resolveOwnStores()\n const ownHostIds = new Set(own.stores.map((store) => store.hostId))\n const [storefrontRead, hardware, ownOrders] = await Promise.all([\n readStorefrontTaxRows(request),\n readPosHardwareTaxReturn(request, { ownHostIds }),\n readOwnStoreOrders(request, own.stores),\n ])\n const isOwn = (row: StorefrontTaxReturnRowInput) => isOwnStoreRow(row, own)\n const ownRows = storefrontRead.rows.filter(isOwn)\n const storefront = storefrontTaxReturnAnswer(\n { ...storefrontRead, rows: storefrontRead.rows.filter((row) => !isOwn(row)), ownStoreRows: ownRows.length },\n request,\n )\n // The base Stripe stated on an own store's online sale, by its order id\n // (an online order is keyed by its Checkout Session, as its row is).\n const statedBases = new Map<string, number>()\n for (const row of ownRows) {\n const base = statedTaxableBase(Array.isArray(row.taxLines) ? row.taxLines : [])\n if (base !== null) statedBases.set(row.id, base)\n }\n const ownStores = ownStoreTaxReturnAnswer({ own, read: ownOrders, statedBases }, request)\n return [storefront, hardware, ownStores]\n },\n}\n\n/** Whether a storefront tax row is one of the operator's own stores' (AGL-4038). */\nexport function isOwnStoreRow(\n row: Pick<StorefrontTaxReturnRowInput, 'hostId' | 'orgId'>,\n own: OwnStores,\n): boolean {\n if (typeof row.hostId === 'string' && own.stores.some((store) => store.hostId === row.hostId)) return true\n return Boolean(own.orgId) && row.orgId === own.orgId\n}\n\n/**\n * The storefront's section.\n *\n * Two queries, and the second is the honesty check: the period query ranges\n * on `paidAt`, and a Firestore range query CANNOT match a document whose\n * field is null — so a row that failed to date itself would be invisible to\n * every period. The equality probe counts those rows, over all of them, and\n * the platform blocks the return on any.\n */\nexport async function readStorefrontTaxReturn(\n request: TaxReturnSourceRequest,\n): Promise<TaxReturnSourceAnswer> {\n return storefrontTaxReturnAnswer(await readStorefrontTaxRows(request), request)\n}\n\n/** The storefront's rows for the period, before any is set aside. See {@link readStorefrontTaxReturn}. */\nexport async function readStorefrontTaxRows(request: TaxReturnSourceRequest): Promise<{\n rows: StorefrontTaxReturnRowInput[]\n truncated: boolean\n undatedRows: number\n}> {\n const firestore = firebaseAdmin.app().firestore()\n const collection = firestore.collection('storefrontTaxCollected')\n const [inPeriod, undated, inPerson] = await Promise.all([\n collection\n .where('paidAt', '>=', request.start)\n .where('paidAt', '<', request.end)\n .limit(request.rowCap + 1)\n .get(),\n collection.where('paidAt', '==', null).count().get(),\n // The platform's own in-person hardware sales around the period\n // (AGL-4038): the hardware section counts them, so their part of the\n // register sale's storefront row comes out here (`posHardwareSales`\n // `source, paidAtMs`).\n firestore\n .collection(POS_HARDWARE_SALES_COLLECTION)\n // In person or online from its own store (AGL-4038): the same index.\n .where('source', 'in', ['in_person', 'storefront'])\n .where('paidAtMs', '>=', request.start.getTime() - IN_PERSON_ROW_MARGIN_MS)\n .where('paidAtMs', '<', request.end.getTime() + IN_PERSON_ROW_MARGIN_MS)\n .limit(request.rowCap)\n .get(),\n ])\n const rows: StorefrontTaxReturnRowInput[] = storefrontRowsWithoutInPersonHardware(\n inPeriod.docs.slice(0, request.rowCap).map((doc) => ({\n id: doc.id,\n ...(doc.data() as Omit<StorefrontTaxReturnRowInput, 'id'>),\n })),\n posHardwareStorefrontParts(inPerson.docs.map((doc) => doc.data())),\n )\n return {\n rows,\n truncated: inPeriod.size > request.rowCap,\n undatedRows: Number(undated.data().count ?? 0),\n }\n}\n"],"names":["firebaseAdmin","PLATFORM_BRAND_NAME","asRowDate","centsToDollars","storefrontTaxSummary","readPosHardwareTaxReturn","POS_HARDWARE_SALES_COLLECTION","posHardwareStorefrontParts","storefrontRowsWithoutInPersonHardware","statedTaxableBase","ownStoreTaxReturnAnswer","readOwnStoreOrders","resolveOwnStores","IN_PERSON_ROW_MARGIN_MS","storefrontPlatformLiableCents","summary","filing","figures","aglynLiable","byJurisdiction","code","cents","Number","taxCollectedCents","isFinite","merchantManualCents","merchantManual","storefrontTaxFindings","brand","id","severity","count","label","detail","figuresName","attention","rowsUnclassified","rowsMissingTaxableBase","storefrontFilingLines","platformLiable","merchant","form","item","dollars","note","storefrontBucketRows","buckets","liability","map","bucket","transactionCount","grossDollars","grossCents","taxableSalesDollars","taxableSalesCents","taxCollectedDollars","storefrontFacilitatedJurisdictionRows","totals","Map","jurisdiction","Object","entries","entry","get","salesCents","taxCents","platformCents","totalSalesCents","set","isFilingJurisdiction","totalSalesDollars","platformLiableTaxDollars","untaxed","sort","a","b","localeCompare","storefrontTables","columns","numeric","money","rows","row","key","cells","text","caption","tag","tone","String","strong","empty","heading","description","footnote","storefrontExports","facilitated","placement","length","projectRow","hostId","orgId","paidAt","toISOString","taxMode","taxLiability","Array","isArray","taxLines","line","taxableAmountCents","reduce","sum","base","state","customerAddress","country","storefrontTaxReturnAnswer","read","request","name","title","help","intro","truncated","undatedRows","findings","filingLines","tables","ownStoreRows","value","exports","commerceTaxReturnSource","own","ownHostIds","Set","stores","store","storefrontRead","hardware","ownOrders","Promise","all","readStorefrontTaxRows","isOwn","isOwnStoreRow","ownRows","filter","storefront","statedBases","ownStores","some","Boolean","readStorefrontTaxReturn","undated","firestore","app","collection","inPeriod","inPerson","where","start","end","limit","rowCap","getTime","docs","slice","doc","data","size"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuCC,GAED,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SACEC,SAAS,EACTC,cAAc,QACT,kDAAiD;AAWxD,SACEC,oBAAoB,QAGf,qCAAiC;AACxC,SAASC,wBAAwB,QAAQ,sCAA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qEAAqE;SACpE0J,KAAK,CAAC,UAAU,MAAM;YAAC;YAAa;SAAa,EACjDA,KAAK,CAAC,YAAY,MAAMzC,QAAQ0C,KAAK,CAACI,OAAO,KAAKxJ,yBAClDmJ,KAAK,CAAC,YAAY,KAAKzC,QAAQ2C,GAAG,CAACG,OAAO,KAAKxJ,yBAC/CsJ,KAAK,CAAC5C,QAAQ6C,MAAM,EACpBrG,GAAG;KACP;IACD,MAAMkB,OAAsCzE,sCAC1CsJ,SAASQ,IAAI,CAACC,KAAK,CAAC,GAAGhD,QAAQ6C,MAAM,EAAEpH,GAAG,CAAC,CAACwH,MAAS;YACnD3I,IAAI2I,IAAI3I,EAAE;WACN2I,IAAIC,IAAI,MAEdlK,2BAA2BwJ,SAASO,IAAI,CAACtH,GAAG,CAAC,CAACwH,MAAQA,IAAIC,IAAI;IAEhE,OAAO;QACLxF;QACA2C,WAAWkC,SAASY,IAAI,GAAGnD,QAAQ6C,MAAM;QACzCvC,aAAavG,QAAOoI,sBAAAA,QAAQe,IAAI,GAAG1I,KAAK,YAApB2H,sBAAwB;IAC9C;AACF"}
package/src/lib/server.js CHANGED
@@ -267,7 +267,7 @@ registerPluginJob({
267
267
  }
268
268
  });
269
269
  /**
270
- * The monthly 4G charge for Stripe Reader S710s (AGL-4038): each workspace
270
+ * The monthly 4G charge for S710 readers (AGL-4038): each workspace
271
271
  * whose readers had 4G in the month just ended is charged once, through
272
272
  * core's usage-invoice charge. Every six hours, so the charge goes out early
273
273
  * on the 1st and one that could not reach Stripe is tried again the same
@@ -278,7 +278,7 @@ registerPluginJob({
278
278
  pluginId: BUNDLE_ID,
279
279
  name: 'pos-cellular-billing',
280
280
  intervalMinutes: 6 * 60,
281
- description: 'Charge each workspace for 4G on its Stripe Reader S710s for the month just ended, once (AGL-4038).',
281
+ description: 'Charge each workspace for 4G on its S710 readers for the month just ended, once (AGL-4038).',
282
282
  lockdown: {
283
283
  scope: 'per-host'
284
284
  },
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/plugins/commerce/src/lib/server.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\n\n/**\n * Server half of the commerce plugin (AGL-396): the site-facing storefront\n * API handlers, registered with the plugin API registry and served by the\n * tenant dispatcher at their unchanged `/api/commerce/*` URLs. This module\n * pulls in firebase-admin + Stripe, so it is NOT re-exported from the client\n * barrel — apps import `@aglyn/plugins-commerce/server` only from their\n * (server-only) API dispatcher registration.\n */\n\nimport {\n registerBillingWebhookHandler,\n registerPluginApiRoute,\n registerPluginJob,\n registerSitePageEnricher,\n registerSitePageResolver,\n registerPluginPermissions,\n registerPluginConfigSchema,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport { isEmailConfigured } from '@aglyn/shared-util-email'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { registerCommerceMediaPublishGuard } from './server/media-publish-guard'\nimport { registerCommerceRecurringCharges } from './server/recurring-charges'\nimport { registerProductCardReader } from './server/product-card'\nimport { registerProductAiCapability } from './server/product-ai-capability'\nimport { registerStoreSetupAiCapabilities } from './server/store-setup-ai-capability'\nimport { registerStoreSetupAiWriter } from './server/store-setup-ai-writer.console'\nimport { registerProductDraftWriter } from './server/product-drafts'\nimport { registerCommerceTaxProfile } from './server/tax-profile'\nimport { registerTaxReturnSource } from '@aglyn/aglyn/plugin-manager/plugin-tax-return-sources'\nimport { commerceTaxReturnSource } from './server/tax-return-source'\nimport { taxSummaryHandler } from './server/tax-summary'\nimport { registerRevenueSource } from '@aglyn/aglyn/plugin-manager/plugin-revenue-sources'\nimport { commerceRevenueSource } from './server/revenue-source'\nimport { commerceBillingWebhookHandler } from './server/billing-webhook'\nimport { registerOrderFigureReaders } from './server/order-figures'\nimport { COMMERCE_PERMISSIONS } from './model/plugin-permissions'\nimport { COMMERCE_CONFIG_SCHEMA } from './plugin-config'\nimport { commerceSitePageEnricher } from './server/site-page-enricher'\nimport { commerceSitePageResolver } from './server/site-page-resolver'\nimport { cartCheckoutHandler } from './server/cart-checkout'\nimport { cartHandler } from './server/cart'\nimport { cartExtrasHandler } from './server/checkout-extras'\nimport { catalogHandler } from './server/catalog'\nimport { checkoutHandler } from './server/checkout'\nimport { downloadHandler } from './server/download'\nimport { newsletterHandler } from './server/newsletter'\nimport { notifyRestockHandler } from './server/notify-restock'\nimport { productHandler } from './server/product'\nimport { relatedHandler } from './server/related'\nimport { reservationAvailabilityHandler } from './server/reservation-availability'\nimport { gateHandler } from './server/gate'\nimport { memberFeedHandler } from './server/member-feed'\nimport { membershipAccountHandler } from './server/membership-account'\nimport { membershipAdminPasswordHandler } from './server/membership-admin-password'\nimport { membershipAdminRemoveHandler } from './server/membership-admin-remove'\nimport { membershipContentHandler } from './server/membership-content'\nimport { membershipLoginHandler } from './server/membership-login'\nimport { membershipLogoutHandler } from './server/membership-logout'\nimport { membershipRecoverHandler } from './server/membership-recover'\nimport { membershipRegisterHandler } from './server/membership-register'\nimport { membershipResetHandler } from './server/membership-reset'\nimport { membershipWishlistHandler } from './server/membership-wishlist'\nimport { reserveHandler } from './server/reserve'\nimport { streamHandler } from './server/stream'\nimport { subscriptionPortalHandler } from './server/subscription-portal'\nimport { reviewsHandler } from './server/reviews'\nimport { connectHandler } from './server/connect'\nimport { cancelOrderHandler } from './server/cancel-order'\nimport { carrierRatesAvailabilityHandler } from './server/carrier-rates-availability'\nimport { collectionMembershipHandler } from './server/collection-membership'\nimport { draftOrderHandler } from './server/draft-order'\nimport { fulfillOrderHandler } from './server/fulfill-order'\nimport { orderReceiptSendHandler } from './server/order-receipt-send'\nimport { orderStatusHandler, registerOrderStatusActions } from './server/order-status'\nimport { returnRequestStatusAction } from './server/return-status-action'\nimport { giftCardsHandler } from './server/gift-cards'\nimport { memberPostHandler } from './server/member-post'\nimport { orderAnalyticsHandler } from './server/order-analytics'\nimport { checkoutStatusHandler } from './server/checkout-status'\nimport { posOrderHandler } from './server/pos-order'\nimport { printersHandler } from './server/printers'\nimport { posPaymentHandler } from './server/pos-payment'\nimport { posReadersHandler } from './server/pos-readers'\nimport { posTerminalConnectionTokenHandler } from './server/pos-terminal-connection-token'\nimport { posDisplayHandler } from './server/pos-display'\nimport { posKioskHandler } from './server/pos-kiosk'\nimport { registerPosOpsRoutes } from './server/pos-ops-routes'\nimport {\n processAbandonedHandler,\n scanAbandonedCheckouts,\n} from './server/process-abandoned'\nimport { processRestockHandler, scanRestockAlerts } from './server/process-restock'\nimport { scanStockDecrements } from './server/reconcile-stock'\nimport { refundHandler } from './server/refund'\nimport { orderWebhooksHandler } from './server/order-webhooks'\nimport { returnRequestHandler, returnsHandler } from './server/returns'\nimport { scanSupplierDeliveries } from './server/supplier-outbox'\nimport { supplierUpdateHandler } from './server/supplier-update'\n\n/**\n * The two commerce beats (AGL-2227).\n *\n * `commerce/process-abandoned` and `commerce/process-restock` have existed\n * since AGL-323/326 as `x-cron-secret` HTTP doors, and `registerCommerceConsoleApi`\n * below has called them \"the scheduler-driven jobs\" in a comment that whole\n * time. **Nothing scheduled them.** Not `scheduled-crons.yml` (its table names\n * 11 paths; neither of these), not `vercel.json` (no `crons` key at all), not\n * `registerPluginJob` — the only two registrations in the repo were scheduled\n * publishing and the bookings hold-expiry.\n *\n * The cost was a Pro-tier entitlement (`abandonedCart`) that had never sent an\n * email, and a storefront \"notify me when it's back\" form writing into a queue\n * with no drain. AGL-1793 had already added the collection-group indexes these\n * two scans need, which is the clearest evidence they were always meant to run.\n *\n * Module scope, like the bookings job beside it: the runner route reaches jobs\n * through `ensureAll(['tenantApi'])`, and a registration inside a `register*`\n * function would depend on which entry point happened to be loaded.\n *\n * 15 minutes, not 1: `process-abandoned` will not remind a checkout younger\n * than an hour and `process-restock` only mails alerts whose product already\n * has stock, so a tighter beat buys nothing and costs two collection-group\n * scans a minute. Both are bounded (200 docs) and idempotent — each pass\n * stamps what it sent — so an overlapping or repeated beat cannot double-send.\n */\nconst RECOVERY_JOB_INTERVAL_MINUTES = 15\n\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'abandoned-checkout-recovery',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description:\n 'Email one recovery reminder per stalled checkout (abandonedCart plans).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n // Quietly, not as an error: email is optional per deployment, and a beat\n // that logs every minute on a self-host without Resend buries everything\n // else in the log.\n if (!isEmailConfigured()) return\n const { sent } = await scanAbandonedCheckouts(gate)\n if (sent) console.info(`commerce: sent ${sent} abandoned-cart reminders`)\n },\n})\n\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'back-in-stock-alerts',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description: 'Email shoppers whose requested product is in stock again.',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!isEmailConfigured()) return\n const { sent } = await scanRestockAlerts(gate)\n if (sent) console.info(`commerce: sent ${sent} back-in-stock alerts`)\n },\n})\n\n/**\n * The review-request email (AGL-3736). HOURLY: a request is owed days after\n * fulfilment, so an hour's lateness is invisible, and the scan is one\n * collection-group range query over `reviewRequestDueAtMs` — a field only\n * orders still owed a request carry, so an empty beat costs one read.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'review-request-emails',\n intervalMinutes: 60,\n description:\n 'Email each buyer one review request, with a single-use link per product, ' +\n 'days after their order is fulfilled (AGL-3736).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!isEmailConfigured()) return\n const { scanReviewRequests } = await import('./server/review-requests')\n const { sent } = await scanReviewRequests(gate)\n if (sent) console.info(`commerce: sent ${sent} review requests`)\n },\n})\n\n/**\n * The missing-decrement detector (AGL-2358).\n *\n * HOURLY, not on the 15-minute recovery beat: it is a detector for a rare\n * process death, not a queue drain, and nothing it finds gets less true for\n * waiting an hour. The cost of the beat is what sets the interval — one\n * collection-group read of the platform's most recent orders, plus two\n * queries per host that has any — and an hour keeps that off the same tick as\n * the two scans above.\n *\n * NOT gated on `isEmailConfigured()`, unlike its two neighbours. Those send\n * mail; this writes a console notification and a log line, both of which work\n * on a self-host with no mail provider at all — and a stock count that is\n * silently wrong is exactly what a self-hoster least wants suppressed by a\n * setting about email.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'stock-decrement-reconciliation',\n intervalMinutes: 60,\n description:\n 'Report paid orders whose stock decrement never landed (AGL-2358).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const scan = await scanStockDecrements(gate)\n if (scan.missingLines || scan.truncatedHosts) {\n console.warn(\n `commerce: ${scan.missingLines} order lines across ${scan.hosts} ` +\n `sites have no sale ledger row (${scan.reportedOrders} newly ` +\n `reported, ${scan.truncatedHosts} sites' ledger window truncated)`,\n )\n }\n },\n})\n\n/**\n * The dropship supplier outbox drain (AGL-2473).\n *\n * EVERY MINUTE, unlike the three above, and the interval is the point rather\n * than an oversight. This is the only one of the four that a BUYER is waiting\n * on: the row it drains is a paid order that has not been routed to whoever\n * ships it, and every minute it sits is a minute the parcel is not moving. The\n * first backoff step is also 60s, so a supplier that blipped is retried on the\n * next tick.\n *\n * The cost that set fifteen minutes for the recovery pair does not apply. Those\n * are collection-GROUP scans across every site on the platform; this is one\n * ordinary equality query against a top-level collection that is EMPTY in the\n * ordinary case — an empty result bills a single read, so the whole beat is\n * ~1,440 reads a day whether or not anyone is dropshipping.\n *\n * Not gated on `isEmailConfigured()`. The supplier notification is an HTTP POST\n * to the merchant's own supplier, and a self-host with no mail provider still\n * has dropship orders to route.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'supplier-webhook-delivery',\n intervalMinutes: 1,\n description:\n 'Deliver queued dropship supplier notifications, with backoff and a ' +\n 'dead letter that tells the merchant (AGL-2473).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const scan = await scanSupplierDeliveries(gate)\n if (scan.deadLettered) {\n console.warn(\n `commerce: ${scan.deadLettered} dropship orders could not be routed ` +\n `to their supplier and have been reported on the order`,\n )\n }\n },\n})\n\n/**\n * Stripe payment method domains for every connected custom domain (AGL-3629).\n *\n * The backfill for domains connected before registration existed, and the\n * repair for a connect whose event was lost, in one daily pass. A domain\n * already registered costs a document read and no Stripe call, so the beat is\n * cheap; a day's delay costs only the Apple Pay button on a domain connected\n * while Stripe was unreachable, and the first in-page checkout there registers\n * it anyway.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'payment-method-domains',\n intervalMinutes: 24 * 60,\n description:\n 'Register connected custom domains with Stripe so Apple Pay, Google Pay ' +\n 'and Link show on them (AGL-3629).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!process.env.STRIPE_SECRET_KEY) return\n const { reconcileCustomDomains } = await import('./server/payment-method-domains')\n const result = await reconcileCustomDomains(gate)\n if (result.registered || result.failed) {\n console.info(\n `commerce: payment method domains — ${result.registered} registered, ` +\n `${result.failed} failed across ${result.hosts} sites`,\n )\n }\n },\n})\n\n/**\n * The monthly 4G charge for Stripe Reader S710s (AGL-4038): each workspace\n * whose readers had 4G in the month just ended is charged once, through\n * core's usage-invoice charge. Every six hours, so the charge goes out early\n * on the 1st and one that could not reach Stripe is tried again the same\n * day; a month already settled costs a read per workspace. Nothing runs\n * where 4G is not offered (`POS_CELLULAR_MONTHLY_COST_CENTS` unset).\n * Per-host: a store locked for security or abuse is not charged while it is.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'pos-cellular-billing',\n intervalMinutes: 6 * 60,\n description:\n 'Charge each workspace for 4G on its Stripe Reader S710s for the month just ended, once (AGL-4038).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!process.env.STRIPE_SECRET_KEY || !process.env.POS_CELLULAR_MONTHLY_COST_CENTS) return\n const { runPosCellularBilling } = await import('./server/pos-cellular-billing')\n const report = await runPosCellularBilling(gate)\n if (report.workspaces || report.storesGone || report.warned || report.turnedOff || report.paidLate) {\n console.info(\n `commerce: 4G for ${report.month} — ${report.paid} paid, ${report.open} left open, ` +\n `${report.failed} not reached, ${report.unbillable} not billable, ${report.deferred} deferred, ` +\n `${report.storesGone} deleted stores turned off; unpaid charges: ${report.warned} warned, ` +\n `${report.paidLate} paid since, ${report.turnedOff} turned off`,\n )\n }\n },\n})\n\n/**\n * Card reader start-up screens (AGL-4048) that went stale with nobody opening\n * the POS devices card: a logo changed on the organization profile or the\n * white-label brand, or the logo's file replaced in the media library. Every\n * 15 minutes, like the recovery pair: a store whose screen did not move costs\n * a few reads and no Stripe call, and nothing a merchant saves waits on it.\n * A screen Stripe refused is retried after six hours here, and at once when\n * the card is opened.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'pos-reader-splash-refresh',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description:\n 'Bring card reader start-up screens up to date after a logo change (AGL-4048).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!process.env.STRIPE_SECRET_KEY) return\n const { refreshPosReaderSplashes } = await import('./server/pos-reader-splash')\n const result = await refreshPosReaderSplashes(gate)\n if (result.applied || result.failed || result.more) {\n console.info(\n `commerce: reader start-up screens — ${result.applied} updated, ` +\n `${result.failed} failed${result.more ? ', more stores than one pass reaches' : ''}`,\n )\n }\n },\n})\n\n/**\n * Cards taken offline whose sale never synced (AGL-4039).\n *\n * HOURLY. The alert falls due six hours after the intent was first seen, and\n * Stripe's authorization lasts about two days, so an hour's delay costs\n * nothing and leaves the beat one collection-group range read that is empty in\n * the ordinary case. It never captures: without the sale there is no fee to\n * capture with, so it tells the operator and the site's managers instead.\n *\n * Not gated on `isEmailConfigured()`: the console notification and the\n * operator alert both work without mail.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'offline-card-unsynced',\n intervalMinutes: 60,\n description:\n 'Tell the operator and the site when a card taken offline reached Stripe but its sale never synced (AGL-4039).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const { scanUnsyncedOfflineCards } = await import('./server/pos-offline-card-reconcile')\n const scan = await scanUnsyncedOfflineCards(gate)\n if (scan.alerted) {\n console.warn(`commerce: ${scan.alerted} cards taken offline have no synced sale`)\n }\n },\n})\n\n/**\n * A visitor's payment door: it opens a Stripe Checkout Session for whoever\n * calls it, so the dispatcher holds it to the card-testing counters\n * (AGL-3363). Declared here, beside the registration, so the door cannot\n * exist without it.\n */\nconst CARD_PAYMENT_DOOR = { cardPayment: true } as const\n\n/**\n * The quote page's Pay button (AGL-4094): a fresh Checkout Session for a\n * quote, for whoever holds its signed pay link. Loaded on first call.\n */\nconst quotePayDoor: PluginApiHandler = async (req, res) =>\n (await import('./server/quote-pay')).quotePayHandler(req, res)\n\n/** Registers the commerce plugin's storefront API routes. */\nexport function registerCommerceApi(): void {\n registerProductCardReader()\n // The merchant's tax rule, for every plugin that prices a charge here.\n registerCommerceTaxProfile()\n registerPluginPermissions(COMMERCE_PERMISSIONS)\n // Merchant-settable register discount ceiling (AGL-2161). Registered on\n // BOTH surfaces, like the permissions above: the POS route reads it\n // server-side, and the settings card renders it from the same schema.\n registerPluginConfigSchema(COMMERCE_CONFIG_SCHEMA)\n // PDP/PLP template pages (AGL-418): /products/* + /collections/*.\n registerSitePageResolver(commerceSitePageResolver)\n // Seeds product grids on ordinary screens (AGL-659) — the resolver above\n // only covers /products/* and /collections/*, so /products itself, and any\n // designed page with a grid on it, needed this to render server-side.\n registerSitePageEnricher(commerceSitePageEnricher)\n registerPluginApiRoute('commerce/cart-checkout', cartCheckoutHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/cart', cartHandler)\n // What the cart offers besides shipping (AGL-3624): pickup locations, and\n // local delivery's fee, minimum and windows for a postal code.\n registerPluginApiRoute('commerce/local-fulfillment-options', async (req, res) =>\n (await import('./server/local-fulfillment')).localFulfillmentOptionsHandler(req, res),\n )\n // Optional lines another plugin offers at the cart (AGL-3635).\n registerPluginApiRoute('commerce/cart-extras', cartExtrasHandler)\n registerPluginApiRoute('commerce/catalog', catalogHandler)\n registerPluginApiRoute('commerce/checkout', checkoutHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/download', downloadHandler)\n // The pre-channels Google feed address (AGL-299), now written by the\n // catalog's feed publisher (AGL-3637); the module loads with a fetch.\n registerPluginApiRoute('commerce/feed', {\n web: async (request) => (await import('./server/legacy-feed')).legacyFeedRoute(request),\n })\n registerPluginApiRoute('commerce/newsletter', newsletterHandler)\n registerPluginApiRoute('commerce/notify-restock', notifyRestockHandler)\n // GA-safe order projection for the storefront `purchase` (AGL-1641).\n registerPluginApiRoute('commerce/order-analytics', orderAnalyticsHandler)\n // The guest order-status page's data (AGL-3610), behind the signed link in\n // every buyer email — a recipient link, so it outlives the site's gates.\n registerPluginApiRoute('commerce/order-status', orderStatusHandler, { recipientLink: true })\n // …and its \"Request a return\" button (AGL-3611), on an order that can\n // still send something back.\n registerOrderStatusActions(returnRequestStatusAction)\n // The customer's quote page (AGL-4094), behind the signed pay link a\n // business sends: the quote, and its Pay button. The page's data is a\n // recipient link, so it outlives the site's gates like the order status.\n registerPluginApiRoute(\n 'commerce/quote-view',\n async (req, res) => (await import('./server/quote-pay')).quoteViewHandler(req, res),\n { recipientLink: true },\n )\n registerPluginApiRoute('commerce/quote-pay', quotePayDoor, CARD_PAYMENT_DOOR)\n // The quote as a PDF (AGL-4095), by the same signed link and on the same\n // terms as the page's data. Loaded on first call, with sharp and the PDF\n // writer behind it.\n registerPluginApiRoute(\n 'commerce/quote-pdf',\n async (req, res) => (await import('./server/commerce-pdf')).quotePdfHandler(req, res),\n { recipientLink: true },\n )\n // The quote's proofs (AGL-4096), by the same signed link and on the same\n // terms as the page's data; and the customer's answer to them, with any\n // artwork they send through the shared visitor upload. The two writes are\n // ordinary visitor writes: the dispatcher's cross-origin check, lockdown\n // and visitor-write limit stand in front of their own. Loaded on first call.\n registerPluginApiRoute(\n 'commerce/quote-proof',\n async (req, res) => (await import('./server/quote-proofs')).quoteProofHandler(req, res),\n { recipientLink: true },\n )\n registerPluginApiRoute('commerce/quote-upload', async (req, res) =>\n (await import('./server/quote-proofs')).quoteUploadHandler(req, res),\n )\n registerPluginApiRoute('commerce/quote-respond', async (req, res) =>\n (await import('./server/quote-proofs')).quoteRespondHandler(req, res),\n )\n // What became of a session the shopper was returned from (AGL-3606).\n registerPluginApiRoute('commerce/checkout-status', checkoutStatusHandler)\n registerPluginApiRoute('commerce/product', productHandler)\n registerPluginApiRoute('commerce/related', relatedHandler)\n registerPluginApiRoute('commerce/reservation-availability', reservationAvailabilityHandler)\n registerPluginApiRoute('commerce/reserve', reserveHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/gate', gateHandler)\n registerPluginApiRoute('commerce/member-feed', memberFeedHandler)\n registerPluginApiRoute('commerce/stream', streamHandler)\n registerPluginApiRoute('commerce/subscription-portal', subscriptionPortalHandler)\n registerPluginApiRoute('commerce/reviews', reviewsHandler)\n // A buyer's return request (AGL-3611), from their account or the signed\n // order-status link.\n registerPluginApiRoute('commerce/return-request', returnRequestHandler)\n registerPluginApiRoute('membership/account', membershipAccountHandler)\n registerPluginApiRoute('membership/content', membershipContentHandler)\n registerPluginApiRoute('membership/login', membershipLoginHandler)\n registerPluginApiRoute('membership/logout', membershipLogoutHandler)\n // Password recovery pair (AGL-552): request + complete.\n registerPluginApiRoute('membership/recover', membershipRecoverHandler)\n registerPluginApiRoute('membership/register', membershipRegisterHandler)\n registerPluginApiRoute('membership/reset', membershipResetHandler)\n registerPluginApiRoute('membership/wishlist', membershipWishlistHandler)\n}\n\n/**\n * Registers the commerce plugin's console-side API routes (AGL-396):\n * merchant/staff operations (Connect onboarding, refunds, draft & POS\n * orders, member posts), the supplier tracking callback, and the HTTP doors\n * for the abandoned-cart / restock passes.\n *\n * Those last two are NOT what schedules them — the `registerPluginJob` calls\n * above are (AGL-2227). This comment used to call them \"the scheduler-driven\n * jobs\", which is how they stayed dark for months: it asserted the wiring\n * instead of having it.\n */\nexport function registerCommerceConsoleApi(): void {\n // The register's gate (`managePos`) is resolved on THIS surface: every POS\n // route below runs in the console, and a key no surface registered here is\n // absent from the resolved map, which reads as refused — the site's own\n // owner was answered 403 at the register.\n registerPluginPermissions(COMMERCE_PERMISSIONS)\n // What a product looks like to a surface that is not this plugin's — a\n // campaign email that features one asks here rather than importing the model.\n registerProductCardReader()\n // …and a draft product another plugin asks for by name (AGL-3616): an AI\n // build setting a store up from a brief, unpriced unless the brief priced it.\n // The console runs AI jobs (AGL-3026).\n registerProductDraftWriter()\n // …and the operation an AI build plans for it, which that writer executes.\n registerProductAiCapability()\n // …and the store's shipping, pickup, local delivery and tax settings an AI\n // build sets up (AGL-3749), written live as the console's cards write them,\n // with the four operations that writer executes.\n registerStoreSetupAiWriter()\n registerStoreSetupAiCapabilities()\n // …and why a file somebody is SELLING may not be made public (AGL-3080).\n // The media library asks before it hands an asset its permanent CDN URL\n // back; what a product is, and which of its fields hold paid media, is\n // this plugin's to know.\n registerCommerceMediaPublishGuard()\n // …and which memberships a site sells, for a security lockdown to pause\n // (AGL-3364). The lockdown route runs on this surface.\n registerCommerceRecurringCharges()\n // …and the tax rule, for the webhook that confirms what they charged.\n registerCommerceTaxProfile()\n // …and its sales on the operator's own sales tax return (AGL-3080): the\n // tax a storefront checkout collected under the platform's registrations.\n // The staff return awaits this surface before it asks, and refuses to be\n // filed without this source — commerce declares `taxReturnSource`.\n registerTaxReturnSource(commerceTaxReturnSource, { pluginId: BUNDLE_ID })\n // …and the take its orders earn the operator, on the staff revenue report\n // (AGL-3080) — commerce declares `revenueSource`, so the report names this\n // source as unread rather than counting it as zero if it is missing.\n registerRevenueSource(commerceRevenueSource, { pluginId: BUNDLE_ID })\n // Stripe webhook sections (AGL-418): orders/carts/drafts/reservations/\n // subscriptions ride the platform webhook via the hook registry.\n registerBillingWebhookHandler(commerceBillingWebhookHandler)\n // A paid card-reader order from the POS hardware shop (AGL-4038), on the\n // same platform webhook: its own handler, self-selecting on the session's\n // `metadata.type`, so the storefront sections above never see it.\n registerBillingWebhookHandler(async (event) =>\n (await import('./server/pos-hardware-webhook')).posHardwareBillingWebhookHandler(event),\n )\n // A card the Aglyn POS app took offline (AGL-4039): its PaymentIntent can\n // reach Stripe before the sale reaches the server, so every event on one is\n // kept by the sale's key. Self-selecting on `metadata.kind`.\n registerBillingWebhookHandler(async (event) =>\n (await import('./server/pos-offline-card-reconcile')).posOfflineCardBillingWebhookHandler(event),\n )\n // Cancel + stock release in one transaction (AGL-1808). Server-side because\n // the release depends on the transition rule, and a client write could not\n // re-ask it under the same lock that flips the status.\n registerPluginApiRoute('commerce/cancel-order', cancelOrderHandler)\n // Whether live carrier rates can be offered on this site (AGL-3612).\n registerPluginApiRoute('commerce/shipping/carrier-rates', carrierRatesAvailabilityHandler)\n registerPluginApiRoute('commerce/connect', connectHandler)\n registerPluginApiRoute('commerce/draft-order', draftOrderHandler)\n // Quotes (AGL-4093): create, edit and delete a quote, and find the customer\n // it is for, under \"Create and edit quotes\". Loaded on first call.\n registerPluginApiRoute('commerce/quote', async (req, res) =>\n (await import('./server/quote')).quoteHandler(req, res),\n )\n // Send invoice (AGL-4099) for an order or a quote, under \"Send quotes and\n // invoices to customers\": an unpaid one with the order's lasting pay link,\n // a paid one as the record. The email, the PDF and sharp load on first\n // call only.\n registerPluginApiRoute('commerce/order-invoice-send', async (req, res) =>\n (await import('./server/order-invoice-send')).orderInvoiceSendHandler(req, res),\n )\n // Fulfil + mark-delivered with the transition re-asked under the write\n // (AGL-1819) — the same stale-dialog hole cancel-order closes, minus the\n // stock release those two transitions never had. The customer REST API's\n // `PATCH /v1/sites/{id}/orders/{id}` records a shipment through the same\n // transaction (`server/api-v1/orders-and-products.ts`).\n registerPluginApiRoute('commerce/fulfill-order', fulfillOrderHandler)\n // Pickup and local delivery steps (AGL-3624) — ready, picked up, out for\n // delivery, delivered — from the console queue, the order dialog and the\n // native Aglyn app. Loaded on first call.\n registerPluginApiRoute('commerce/local-fulfillment', async (req, res) =>\n (await import('./server/local-fulfillment-status')).localFulfillmentHandler(req, res),\n )\n // \"Resend receipt\" from the order dialog (AGL-3610): by email, or by text\n // when the platform's SMS provider is configured. Rate-limited per member\n // and per order.\n registerPluginApiRoute('commerce/order-receipt-send', orderReceiptSendHandler)\n // The product editor's save and Adjust stock for the native apps (AGL-3652):\n // the console's own product-write computation under the rules' gate. Loaded\n // on first call.\n registerPluginApiRoute('commerce/products/save', async (req, res) =>\n (await import('./server/products-write')).productSaveHandler(req, res),\n )\n registerPluginApiRoute('commerce/products/stock', async (req, res) =>\n (await import('./server/products-write')).productStockHandler(req, res),\n )\n // A staff walk-in from the Reservations card and the native apps\n // (AGL-4046): availability re-asked inside the transaction that writes, so\n // two staff cannot hand out the last unit at once. Loaded on first call.\n registerPluginApiRoute('commerce/reservations/walk-in', async (req, res) =>\n (await import('./server/reservation-walk-in')).reservationWalkInHandler(req, res),\n )\n // A stay's guest count after it is booked (AGL-4043), from the Reservations\n // card and the check-in screen: the walk-in's gate, and the stay's\n // check-ins for today on brought in line in the same transaction. Loaded\n // on first call.\n registerPluginApiRoute('commerce/reservations/guests', async (req, res) =>\n (await import('./server/reservation-guests')).reservationGuestsHandler(req, res),\n )\n // The products list's Duplicate and Delete for the native apps (AGL-3841):\n // the console's own copy and soft delete, with the site-wide cache drop.\n registerPluginApiRoute('commerce/products/duplicate', async (req, res) =>\n (await import('./server/products-write')).productDuplicateHandler(req, res),\n )\n registerPluginApiRoute('commerce/products/delete', async (req, res) =>\n (await import('./server/products-write')).productDeleteHandler(req, res),\n )\n // The order dialog's note and restock answer for the native apps\n // (AGL-3651, AGL-3652): the console's own timeline computation, in one\n // transaction on the stored order. Loaded on first call.\n registerPluginApiRoute('commerce/order-note', async (req, res) =>\n (await import('./server/order-annotations')).orderNoteHandler(req, res),\n )\n registerPluginApiRoute('commerce/order-restock-answer', async (req, res) =>\n (await import('./server/order-annotations')).orderRestockAnswerHandler(req, res),\n )\n // The order dialog's Packing slip and Invoice for the native apps\n // (AGL-3841): the console's own two pages over the stored order, which the\n // apps print on the device's print sheet; and the invoice as a PDF file\n // (`kind=invoice-pdf`, AGL-4095) for the console and the apps. Loaded on\n // first call.\n registerPluginApiRoute('commerce/order-print', async (req, res) =>\n (await import('./server/order-print')).orderPrintHandler(req, res),\n )\n // Issue / void store credit (AGL-2226). Server-side because the host\n // catch-all in the Firestore rules would otherwise let a client write\n // its own `balanceCents`, which checkout applies as amount-off.\n registerPluginApiRoute('commerce/gift-cards', giftCardsHandler)\n // The merchant's own storefront sales tax, by who owes it (AGL-2440): the\n // same rows and classifier the operator's return reads, fenced to one site.\n registerPluginApiRoute('commerce/tax-summary', { web: taxSummaryHandler })\n // The payment methods card (AGL-3629): toggles, the platform's offer, the\n // payout account's capabilities and the site's wallet domains. Loaded with\n // the first request, so a console that never opens Settings never imports it.\n registerPluginApiRoute('commerce/payment-methods', {\n web: async (request) =>\n (await import('./server/payment-methods')).paymentMethodsHandler(request),\n })\n // A smart collection's rules changed or it was deleted: re-stamp which\n // products it holds (AGL-3321), the membership the storefront queries.\n registerPluginApiRoute('commerce/collection-membership', collectionMembershipHandler)\n // A site member's password help (AGL-914) and removal (AGL-3308), from the\n // Users page drawer and the Inbox. Console-auth, not the visitor cookie the\n // storefront's `membership/*` routes take, so they are served where the\n // console posts: the console's own dispatcher loads this surface only.\n registerPluginApiRoute(\n 'membership/admin-password',\n membershipAdminPasswordHandler,\n )\n registerPluginApiRoute('membership/admin-remove', membershipAdminRemoveHandler)\n registerPluginApiRoute('commerce/member-post', memberPostHandler)\n registerPluginApiRoute('commerce/pos-order', posOrderHandler)\n // A register's cloud receipt printers and the jobs a manager sends them\n // (AGL-3619), and the two doors the printers themselves poll. The doors are\n // MACHINE routes: a printer is no member and names no site cookie, so it\n // authenticates with the per-printer secret in its URL and its own device id,\n // and the route asks the plan before it hands over a job. Loaded with the\n // first poll, so a console that has no printers never imports them.\n registerPluginApiRoute('commerce/printers', printersHandler)\n registerPluginApiRoute(\n 'commerce/cloudprnt/:hostId/:printerId/:secret',\n {\n web: async (request, context) =>\n (await import('./server/printer-poll')).cloudPrntRoute(request, context),\n },\n { machine: true },\n )\n registerPluginApiRoute(\n 'commerce/epson-sdp/:hostId/:printerId/:secret',\n {\n web: async (request, context) =>\n (await import('./server/printer-poll')).epsonServerDirectPrintRoute(request, context),\n },\n { machine: true },\n )\n // The register's tenders against an open sale, its Stripe Terminal card\n // readers, and the paired customer display (AGL-3607, AGL-3608). The\n // display's `pair`/`poll`/`respond` take a display token and no console\n // session; every other action is gated like a sale.\n registerPluginApiRoute('commerce/pos-payment', posPaymentHandler)\n registerPluginApiRoute('commerce/pos-readers', posReadersHandler)\n registerPluginApiRoute('commerce/pos-display', posDisplayHandler)\n // The POS hardware shop (AGL-4038): the Hardware card's catalog, Checkout\n // and order list, gated like a sale and hidden until the deployment prices\n // it; and the staff page's orders, which name no site. Loaded on first call.\n registerPluginApiRoute('commerce/pos-hardware', async (req, res) =>\n (await import('./server/pos-hardware')).posHardwareHandler(req, res),\n )\n // Selling a card reader in person at the platform's own store's register\n // (AGL-4038): whether this store is that seller. Gated like a sale, and\n // silent about the configuration on every other store. Loaded on first call.\n registerPluginApiRoute('commerce/pos-hardware-sale', async (req, res) =>\n (await import('./server/pos-hardware-sale')).posHardwareSaleHandler(req, res),\n )\n // A store's card reader start-up screen (AGL-4048): the POS devices card's\n // setting, gated like a sale, and the staff page's platform default. Each\n // loads with its first call; the drawing they ask for is the images\n // route's, below.\n registerPluginApiRoute('commerce/pos-reader-splash', async (req, res) =>\n (await import('./server/pos-reader-splash')).posReaderSplashHandler(req, res),\n )\n registerPluginApiRoute('commerce/admin/reader-splash', {\n web: async (request) =>\n (await import('./server/pos-reader-splash-admin')).posReaderSplashAdmin(request),\n })\n // The image work behind both (AGL-4048): drawing a screen and reading an\n // uploaded one take `sharp`, whose native library only the console's\n // plugins' image function ships (`/api/plugin-images/…`), so the plugin\n // API's function does not carry it. Called by our own servers, signed; a\n // machine's door.\n registerPluginApiRoute(\n 'commerce/pos-reader-splash-images',\n {\n web: async (request) =>\n (await import('./server/pos-reader-splash-images-route')).posReaderSplashImagesRoute(request),\n },\n { machine: true, images: true },\n )\n registerPluginApiRoute('commerce/admin/hardware-orders', {\n web: async (request) =>\n (await import('./server/pos-hardware-admin')).posHardwareAdminOrders(request),\n })\n // The self-service kiosk (AGL-3623): a register's paired screen where the\n // customer orders and pays. Its device token, never a staff session; the\n // register's queue of \"pay at counter\" orders is gated like a sale.\n registerPluginApiRoute('commerce/pos-kiosk', posKioskHandler)\n // Shifts, staff PINs, the customer lookup and returns (AGL-3609).\n registerPosOpsRoutes()\n // The offline register (AGL-3625): the kit a register caches to sell cash\n // while the connection is down, and the sync that records those sales once.\n // Gated like a sale; loaded with its first call.\n registerPluginApiRoute('commerce/pos-offline-sync', async (req, res) =>\n (await import('./server/pos-offline-sync')).posOfflineSyncHandler(req, res),\n )\n // The native Aglyn POS app's Stripe Terminal SDK: a connection token scoped\n // to the site's Location, and the Location itself (AGL-3618). Gated like a\n // sale.\n registerPluginApiRoute('commerce/pos-terminal-connection-token', posTerminalConnectionTokenHandler)\n registerPluginApiRoute('commerce/process-abandoned', processAbandonedHandler)\n registerPluginApiRoute('commerce/process-restock', processRestockHandler)\n registerPluginApiRoute('commerce/refund', refundHandler)\n // Returns (AGL-3611): approve, decline, receive with restock, refund\n // through the route above, a label from a shipping plugin.\n registerPluginApiRoute('commerce/returns', returnsHandler)\n // The merchant's outbound order webhooks (AGL-3611): endpoints, secrets,\n // a test ping and a resend from the delivery log.\n registerPluginApiRoute('commerce/order-webhooks', orderWebhooksHandler)\n registerPluginApiRoute('commerce/supplier-update', supplierUpdateHandler)\n // Stamps the open orders that predate the shipping fields, before an\n // export for shipping (AGL-3613).\n registerPluginApiRoute('commerce/orders-shipping-prepare', async (req, res) =>\n (await import('./server/orders-shipping-prepare')).ordersShippingPrepareHandler(req, res),\n )\n // ShipStation's Custom Store endpoint (AGL-3613): ShipStation's servers\n // pull the order feed and post shipments back with the site's own Basic\n // credentials, so it is a MACHINE's route and asks the site's commerce,\n // plan, release and lockdown gates itself once the credentials prove the\n // site. Loaded on its first call, never with the console API surface.\n registerPluginApiRoute(\n 'commerce/shipstation/:hostId',\n {\n web: async (request, context) =>\n (await import('./server/shipstation')).shipStationRoute(request, context),\n },\n { machine: true },\n )\n // ShippingEasy's shipment callback (AGL-3633): ShippingEasy's servers post\n // each label bought for an order this store sent them, signed with the\n // merchant's own API secret, so it is a MACHINE's route like ShipStation's\n // above and asks the same gates once the signature proves the site.\n registerPluginApiRoute(\n 'commerce/shippingeasy/:hostId',\n {\n web: async (request, context) =>\n (await import('./server/shippingeasy')).shippingEasyRoute(request, context),\n },\n { machine: true },\n )\n // The ShipStation and ShippingEasy cards' connect, show, new password,\n // send open orders and disconnect.\n registerPluginApiRoute('commerce/shipping-connectors', async (req, res) =>\n (await import('./server/shipping-connectors')).shippingConnectorsHandler(req, res),\n )\n // The store's sales as figure tables (AGL-2915), for the AI plugin's\n // insights to read by id rather than by reading orders. The console runs\n // insight jobs, so the console surface registers them.\n registerOrderFigureReaders(() => firebaseAdmin.app().firestore())\n}\n\n// Shared with the (still app-side) membership/account route.\nexport { mintDownloadToken } from './server/download'\n\n// Site-member session primitives, shared with the (still app-side)\n// membership/* routes until those migrate too (AGL-396).\nexport * from './server/membership'\n\n// Type-only (AGL-3080): the plugin's entitlement keys, declared by module\n// augmentation, for every program that loads this entry point.\nexport type { commercePlanEntitlements } from './plan-entitlements'\n"],"names":["registerBillingWebhookHandler","registerPluginApiRoute","registerPluginJob","registerSitePageEnricher","registerSitePageResolver","registerPluginPermissions","registerPluginConfigSchema","isEmailConfigured","firebaseAdmin","BUNDLE_ID","registerCommerceMediaPublishGuard","registerCommerceRecurringCharges","registerProductCardReader","registerProductAiCapability","registerStoreSetupAiCapabilities","registerStoreSetupAiWriter","registerProductDraftWriter","registerCommerceTaxProfile","registerTaxReturnSource","commerceTaxReturnSource","taxSummaryHandler","registerRevenueSource","commerceRevenueSource","commerceBillingWebhookHandler","registerOrderFigureReaders","COMMERCE_PERMISSIONS","COMMERCE_CONFIG_SCHEMA","commerceSitePageEnricher","commerceSitePageResolver","cartCheckoutHandler","cartHandler","cartExtrasHandler","catalogHandler","checkoutHandler","downloadHandler","newsletterHandler","notifyRestockHandler","productHandler","relatedHandler","reservationAvailabilityHandler","gateHandler","memberFeedHandler","membershipAccountHandler","membershipAdminPasswordHandler","membershipAdminRemoveHandler","membershipContentHandler","membershipLoginHandler","membershipLogoutHandler","membershipRecoverHandler","membershipRegisterHandler","membershipResetHandler","membershipWishlistHandler","reserveHandler","streamHandler","subscriptionPortalHandler","reviewsHandler","connectHandler","cancelOrderHandler","carrierRatesAvailabilityHandler","collectionMembershipHandler","draftOrderHandler","fulfillOrderHandler","orderReceiptSendHandler","orderStatusHandler","registerOrderStatusActions","returnRequestStatusAction","giftCardsHandler","memberPostHandler","orderAnalyticsHandler","checkoutStatusHandler","posOrderHandler","printersHandler","posPaymentHandler","posReadersHandler","posTerminalConnectionTokenHandler","posDisplayHandler","posKioskHandler","registerPosOpsRoutes","processAbandonedHandler","scanAbandonedCheckouts","processRestockHandler","scanRestockAlerts","scanStockDecrements","refundHandler","orderWebhooksHandler","returnRequestHandler","returnsHandler","scanSupplierDeliveries","supplierUpdateHandler","RECOVERY_JOB_INTERVAL_MINUTES","pluginId","name","intervalMinutes","description","lockdown","scope","handler","gate","sent","console","info","scanReviewRequests","scan","missingLines","truncatedHosts","warn","hosts","reportedOrders","deadLettered","process","env","STRIPE_SECRET_KEY","reconcileCustomDomains","result","registered","failed","POS_CELLULAR_MONTHLY_COST_CENTS","runPosCellularBilling","report","workspaces","storesGone","warned","turnedOff","paidLate","month","paid","open","unbillable","deferred","refreshPosReaderSplashes","applied","more","scanUnsyncedOfflineCards","alerted","CARD_PAYMENT_DOOR","cardPayment","quotePayDoor","req","res","quotePayHandler","registerCommerceApi","localFulfillmentOptionsHandler","web","request","legacyFeedRoute","recipientLink","quoteViewHandler","quotePdfHandler","quoteProofHandler","quoteUploadHandler","quoteRespondHandler","registerCommerceConsoleApi","event","posHardwareBillingWebhookHandler","posOfflineCardBillingWebhookHandler","quoteHandler","orderInvoiceSendHandler","localFulfillmentHandler","productSaveHandler","productStockHandler","reservationWalkInHandler","reservationGuestsHandler","productDuplicateHandler","productDeleteHandler","orderNoteHandler","orderRestockAnswerHandler","orderPrintHandler","paymentMethodsHandler","context","cloudPrntRoute","machine","epsonServerDirectPrintRoute","posHardwareHandler","posHardwareSaleHandler","posReaderSplashHandler","posReaderSplashAdmin","posReaderSplashImagesRoute","images","posHardwareAdminOrders","posOfflineSyncHandler","ordersShippingPrepareHandler","shipStationRoute","shippingEasyRoute","shippingConnectorsHandler","app","firestore","mintDownloadToken"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD;;;;;;;CAOC,GAED,SACEA,6BAA6B,EAC7BC,sBAAsB,EACtBC,iBAAiB,EACjBC,wBAAwB,EACxBC,wBAAwB,EACxBC,yBAAyB,EACzBC,0BAA0B,QAErB,sBAAqB;AAC5B,SAASC,iBAAiB,QAAQ,2BAA0B;AAC5D,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,iCAAiC,QAAQ,kCAA8B;AAChF,SAASC,gCAAgC,QAAQ,gCAA4B;AAC7E,SAASC,yBAAyB,QAAQ,2BAAuB;AACjE,SAASC,2BAA2B,QAAQ,oCAAgC;AAC5E,SAASC,gCAAgC,QAAQ,wCAAoC;AACrF,SAASC,0BAA0B,QAAQ,4CAAwC;AACnF,SAASC,0BAA0B,QAAQ,6BAAyB;AACpE,SAASC,0BAA0B,QAAQ,0BA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iB,QAAQ,uBAAmB;AAErD,mEAAmE;AACnE,yDAAyD;AACzD,cAAc,yBAAqB"}
1
+ {"version":3,"sources":["../../../../../../libs/plugins/commerce/src/lib/server.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\n\n/**\n * Server half of the commerce plugin (AGL-396): the site-facing storefront\n * API handlers, registered with the plugin API registry and served by the\n * tenant dispatcher at their unchanged `/api/commerce/*` URLs. This module\n * pulls in firebase-admin + Stripe, so it is NOT re-exported from the client\n * barrel — apps import `@aglyn/plugins-commerce/server` only from their\n * (server-only) API dispatcher registration.\n */\n\nimport {\n registerBillingWebhookHandler,\n registerPluginApiRoute,\n registerPluginJob,\n registerSitePageEnricher,\n registerSitePageResolver,\n registerPluginPermissions,\n registerPluginConfigSchema,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport { isEmailConfigured } from '@aglyn/shared-util-email'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { registerCommerceMediaPublishGuard } from './server/media-publish-guard'\nimport { registerCommerceRecurringCharges } from './server/recurring-charges'\nimport { registerProductCardReader } from './server/product-card'\nimport { registerProductAiCapability } from './server/product-ai-capability'\nimport { registerStoreSetupAiCapabilities } from './server/store-setup-ai-capability'\nimport { registerStoreSetupAiWriter } from './server/store-setup-ai-writer.console'\nimport { registerProductDraftWriter } from './server/product-drafts'\nimport { registerCommerceTaxProfile } from './server/tax-profile'\nimport { registerTaxReturnSource } from '@aglyn/aglyn/plugin-manager/plugin-tax-return-sources'\nimport { commerceTaxReturnSource } from './server/tax-return-source'\nimport { taxSummaryHandler } from './server/tax-summary'\nimport { registerRevenueSource } from '@aglyn/aglyn/plugin-manager/plugin-revenue-sources'\nimport { commerceRevenueSource } from './server/revenue-source'\nimport { commerceBillingWebhookHandler } from './server/billing-webhook'\nimport { registerOrderFigureReaders } from './server/order-figures'\nimport { COMMERCE_PERMISSIONS } from './model/plugin-permissions'\nimport { COMMERCE_CONFIG_SCHEMA } from './plugin-config'\nimport { commerceSitePageEnricher } from './server/site-page-enricher'\nimport { commerceSitePageResolver } from './server/site-page-resolver'\nimport { cartCheckoutHandler } from './server/cart-checkout'\nimport { cartHandler } from './server/cart'\nimport { cartExtrasHandler } from './server/checkout-extras'\nimport { catalogHandler } from './server/catalog'\nimport { checkoutHandler } from './server/checkout'\nimport { downloadHandler } from './server/download'\nimport { newsletterHandler } from './server/newsletter'\nimport { notifyRestockHandler } from './server/notify-restock'\nimport { productHandler } from './server/product'\nimport { relatedHandler } from './server/related'\nimport { reservationAvailabilityHandler } from './server/reservation-availability'\nimport { gateHandler } from './server/gate'\nimport { memberFeedHandler } from './server/member-feed'\nimport { membershipAccountHandler } from './server/membership-account'\nimport { membershipAdminPasswordHandler } from './server/membership-admin-password'\nimport { membershipAdminRemoveHandler } from './server/membership-admin-remove'\nimport { membershipContentHandler } from './server/membership-content'\nimport { membershipLoginHandler } from './server/membership-login'\nimport { membershipLogoutHandler } from './server/membership-logout'\nimport { membershipRecoverHandler } from './server/membership-recover'\nimport { membershipRegisterHandler } from './server/membership-register'\nimport { membershipResetHandler } from './server/membership-reset'\nimport { membershipWishlistHandler } from './server/membership-wishlist'\nimport { reserveHandler } from './server/reserve'\nimport { streamHandler } from './server/stream'\nimport { subscriptionPortalHandler } from './server/subscription-portal'\nimport { reviewsHandler } from './server/reviews'\nimport { connectHandler } from './server/connect'\nimport { cancelOrderHandler } from './server/cancel-order'\nimport { carrierRatesAvailabilityHandler } from './server/carrier-rates-availability'\nimport { collectionMembershipHandler } from './server/collection-membership'\nimport { draftOrderHandler } from './server/draft-order'\nimport { fulfillOrderHandler } from './server/fulfill-order'\nimport { orderReceiptSendHandler } from './server/order-receipt-send'\nimport { orderStatusHandler, registerOrderStatusActions } from './server/order-status'\nimport { returnRequestStatusAction } from './server/return-status-action'\nimport { giftCardsHandler } from './server/gift-cards'\nimport { memberPostHandler } from './server/member-post'\nimport { orderAnalyticsHandler } from './server/order-analytics'\nimport { checkoutStatusHandler } from './server/checkout-status'\nimport { posOrderHandler } from './server/pos-order'\nimport { printersHandler } from './server/printers'\nimport { posPaymentHandler } from './server/pos-payment'\nimport { posReadersHandler } from './server/pos-readers'\nimport { posTerminalConnectionTokenHandler } from './server/pos-terminal-connection-token'\nimport { posDisplayHandler } from './server/pos-display'\nimport { posKioskHandler } from './server/pos-kiosk'\nimport { registerPosOpsRoutes } from './server/pos-ops-routes'\nimport {\n processAbandonedHandler,\n scanAbandonedCheckouts,\n} from './server/process-abandoned'\nimport { processRestockHandler, scanRestockAlerts } from './server/process-restock'\nimport { scanStockDecrements } from './server/reconcile-stock'\nimport { refundHandler } from './server/refund'\nimport { orderWebhooksHandler } from './server/order-webhooks'\nimport { returnRequestHandler, returnsHandler } from './server/returns'\nimport { scanSupplierDeliveries } from './server/supplier-outbox'\nimport { supplierUpdateHandler } from './server/supplier-update'\n\n/**\n * The two commerce beats (AGL-2227).\n *\n * `commerce/process-abandoned` and `commerce/process-restock` have existed\n * since AGL-323/326 as `x-cron-secret` HTTP doors, and `registerCommerceConsoleApi`\n * below has called them \"the scheduler-driven jobs\" in a comment that whole\n * time. **Nothing scheduled them.** Not `scheduled-crons.yml` (its table names\n * 11 paths; neither of these), not `vercel.json` (no `crons` key at all), not\n * `registerPluginJob` — the only two registrations in the repo were scheduled\n * publishing and the bookings hold-expiry.\n *\n * The cost was a Pro-tier entitlement (`abandonedCart`) that had never sent an\n * email, and a storefront \"notify me when it's back\" form writing into a queue\n * with no drain. AGL-1793 had already added the collection-group indexes these\n * two scans need, which is the clearest evidence they were always meant to run.\n *\n * Module scope, like the bookings job beside it: the runner route reaches jobs\n * through `ensureAll(['tenantApi'])`, and a registration inside a `register*`\n * function would depend on which entry point happened to be loaded.\n *\n * 15 minutes, not 1: `process-abandoned` will not remind a checkout younger\n * than an hour and `process-restock` only mails alerts whose product already\n * has stock, so a tighter beat buys nothing and costs two collection-group\n * scans a minute. Both are bounded (200 docs) and idempotent — each pass\n * stamps what it sent — so an overlapping or repeated beat cannot double-send.\n */\nconst RECOVERY_JOB_INTERVAL_MINUTES = 15\n\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'abandoned-checkout-recovery',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description:\n 'Email one recovery reminder per stalled checkout (abandonedCart plans).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n // Quietly, not as an error: email is optional per deployment, and a beat\n // that logs every minute on a self-host without Resend buries everything\n // else in the log.\n if (!isEmailConfigured()) return\n const { sent } = await scanAbandonedCheckouts(gate)\n if (sent) console.info(`commerce: sent ${sent} abandoned-cart reminders`)\n },\n})\n\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'back-in-stock-alerts',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description: 'Email shoppers whose requested product is in stock again.',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!isEmailConfigured()) return\n const { sent } = await scanRestockAlerts(gate)\n if (sent) console.info(`commerce: sent ${sent} back-in-stock alerts`)\n },\n})\n\n/**\n * The review-request email (AGL-3736). HOURLY: a request is owed days after\n * fulfilment, so an hour's lateness is invisible, and the scan is one\n * collection-group range query over `reviewRequestDueAtMs` — a field only\n * orders still owed a request carry, so an empty beat costs one read.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'review-request-emails',\n intervalMinutes: 60,\n description:\n 'Email each buyer one review request, with a single-use link per product, ' +\n 'days after their order is fulfilled (AGL-3736).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!isEmailConfigured()) return\n const { scanReviewRequests } = await import('./server/review-requests')\n const { sent } = await scanReviewRequests(gate)\n if (sent) console.info(`commerce: sent ${sent} review requests`)\n },\n})\n\n/**\n * The missing-decrement detector (AGL-2358).\n *\n * HOURLY, not on the 15-minute recovery beat: it is a detector for a rare\n * process death, not a queue drain, and nothing it finds gets less true for\n * waiting an hour. The cost of the beat is what sets the interval — one\n * collection-group read of the platform's most recent orders, plus two\n * queries per host that has any — and an hour keeps that off the same tick as\n * the two scans above.\n *\n * NOT gated on `isEmailConfigured()`, unlike its two neighbours. Those send\n * mail; this writes a console notification and a log line, both of which work\n * on a self-host with no mail provider at all — and a stock count that is\n * silently wrong is exactly what a self-hoster least wants suppressed by a\n * setting about email.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'stock-decrement-reconciliation',\n intervalMinutes: 60,\n description:\n 'Report paid orders whose stock decrement never landed (AGL-2358).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const scan = await scanStockDecrements(gate)\n if (scan.missingLines || scan.truncatedHosts) {\n console.warn(\n `commerce: ${scan.missingLines} order lines across ${scan.hosts} ` +\n `sites have no sale ledger row (${scan.reportedOrders} newly ` +\n `reported, ${scan.truncatedHosts} sites' ledger window truncated)`,\n )\n }\n },\n})\n\n/**\n * The dropship supplier outbox drain (AGL-2473).\n *\n * EVERY MINUTE, unlike the three above, and the interval is the point rather\n * than an oversight. This is the only one of the four that a BUYER is waiting\n * on: the row it drains is a paid order that has not been routed to whoever\n * ships it, and every minute it sits is a minute the parcel is not moving. The\n * first backoff step is also 60s, so a supplier that blipped is retried on the\n * next tick.\n *\n * The cost that set fifteen minutes for the recovery pair does not apply. Those\n * are collection-GROUP scans across every site on the platform; this is one\n * ordinary equality query against a top-level collection that is EMPTY in the\n * ordinary case — an empty result bills a single read, so the whole beat is\n * ~1,440 reads a day whether or not anyone is dropshipping.\n *\n * Not gated on `isEmailConfigured()`. The supplier notification is an HTTP POST\n * to the merchant's own supplier, and a self-host with no mail provider still\n * has dropship orders to route.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'supplier-webhook-delivery',\n intervalMinutes: 1,\n description:\n 'Deliver queued dropship supplier notifications, with backoff and a ' +\n 'dead letter that tells the merchant (AGL-2473).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const scan = await scanSupplierDeliveries(gate)\n if (scan.deadLettered) {\n console.warn(\n `commerce: ${scan.deadLettered} dropship orders could not be routed ` +\n `to their supplier and have been reported on the order`,\n )\n }\n },\n})\n\n/**\n * Stripe payment method domains for every connected custom domain (AGL-3629).\n *\n * The backfill for domains connected before registration existed, and the\n * repair for a connect whose event was lost, in one daily pass. A domain\n * already registered costs a document read and no Stripe call, so the beat is\n * cheap; a day's delay costs only the Apple Pay button on a domain connected\n * while Stripe was unreachable, and the first in-page checkout there registers\n * it anyway.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'payment-method-domains',\n intervalMinutes: 24 * 60,\n description:\n 'Register connected custom domains with Stripe so Apple Pay, Google Pay ' +\n 'and Link show on them (AGL-3629).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!process.env.STRIPE_SECRET_KEY) return\n const { reconcileCustomDomains } = await import('./server/payment-method-domains')\n const result = await reconcileCustomDomains(gate)\n if (result.registered || result.failed) {\n console.info(\n `commerce: payment method domains — ${result.registered} registered, ` +\n `${result.failed} failed across ${result.hosts} sites`,\n )\n }\n },\n})\n\n/**\n * The monthly 4G charge for S710 readers (AGL-4038): each workspace\n * whose readers had 4G in the month just ended is charged once, through\n * core's usage-invoice charge. Every six hours, so the charge goes out early\n * on the 1st and one that could not reach Stripe is tried again the same\n * day; a month already settled costs a read per workspace. Nothing runs\n * where 4G is not offered (`POS_CELLULAR_MONTHLY_COST_CENTS` unset).\n * Per-host: a store locked for security or abuse is not charged while it is.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'pos-cellular-billing',\n intervalMinutes: 6 * 60,\n description:\n 'Charge each workspace for 4G on its S710 readers for the month just ended, once (AGL-4038).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!process.env.STRIPE_SECRET_KEY || !process.env.POS_CELLULAR_MONTHLY_COST_CENTS) return\n const { runPosCellularBilling } = await import('./server/pos-cellular-billing')\n const report = await runPosCellularBilling(gate)\n if (report.workspaces || report.storesGone || report.warned || report.turnedOff || report.paidLate) {\n console.info(\n `commerce: 4G for ${report.month} — ${report.paid} paid, ${report.open} left open, ` +\n `${report.failed} not reached, ${report.unbillable} not billable, ${report.deferred} deferred, ` +\n `${report.storesGone} deleted stores turned off; unpaid charges: ${report.warned} warned, ` +\n `${report.paidLate} paid since, ${report.turnedOff} turned off`,\n )\n }\n },\n})\n\n/**\n * Card reader start-up screens (AGL-4048) that went stale with nobody opening\n * the POS devices card: a logo changed on the organization profile or the\n * white-label brand, or the logo's file replaced in the media library. Every\n * 15 minutes, like the recovery pair: a store whose screen did not move costs\n * a few reads and no Stripe call, and nothing a merchant saves waits on it.\n * A screen Stripe refused is retried after six hours here, and at once when\n * the card is opened.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'pos-reader-splash-refresh',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description:\n 'Bring card reader start-up screens up to date after a logo change (AGL-4048).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!process.env.STRIPE_SECRET_KEY) return\n const { refreshPosReaderSplashes } = await import('./server/pos-reader-splash')\n const result = await refreshPosReaderSplashes(gate)\n if (result.applied || result.failed || result.more) {\n console.info(\n `commerce: reader start-up screens — ${result.applied} updated, ` +\n `${result.failed} failed${result.more ? ', more stores than one pass reaches' : ''}`,\n )\n }\n },\n})\n\n/**\n * Cards taken offline whose sale never synced (AGL-4039).\n *\n * HOURLY. The alert falls due six hours after the intent was first seen, and\n * Stripe's authorization lasts about two days, so an hour's delay costs\n * nothing and leaves the beat one collection-group range read that is empty in\n * the ordinary case. It never captures: without the sale there is no fee to\n * capture with, so it tells the operator and the site's managers instead.\n *\n * Not gated on `isEmailConfigured()`: the console notification and the\n * operator alert both work without mail.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'offline-card-unsynced',\n intervalMinutes: 60,\n description:\n 'Tell the operator and the site when a card taken offline reached Stripe but its sale never synced (AGL-4039).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const { scanUnsyncedOfflineCards } = await import('./server/pos-offline-card-reconcile')\n const scan = await scanUnsyncedOfflineCards(gate)\n if (scan.alerted) {\n console.warn(`commerce: ${scan.alerted} cards taken offline have no synced sale`)\n }\n },\n})\n\n/**\n * A visitor's payment door: it opens a Stripe Checkout Session for whoever\n * calls it, so the dispatcher holds it to the card-testing counters\n * (AGL-3363). Declared here, beside the registration, so the door cannot\n * exist without it.\n */\nconst CARD_PAYMENT_DOOR = { cardPayment: true } as const\n\n/**\n * The quote page's Pay button (AGL-4094): a fresh Checkout Session for a\n * quote, for whoever holds its signed pay link. Loaded on first call.\n */\nconst quotePayDoor: PluginApiHandler = async (req, res) =>\n (await import('./server/quote-pay')).quotePayHandler(req, res)\n\n/** Registers the commerce plugin's storefront API routes. */\nexport function registerCommerceApi(): void {\n registerProductCardReader()\n // The merchant's tax rule, for every plugin that prices a charge here.\n registerCommerceTaxProfile()\n registerPluginPermissions(COMMERCE_PERMISSIONS)\n // Merchant-settable register discount ceiling (AGL-2161). Registered on\n // BOTH surfaces, like the permissions above: the POS route reads it\n // server-side, and the settings card renders it from the same schema.\n registerPluginConfigSchema(COMMERCE_CONFIG_SCHEMA)\n // PDP/PLP template pages (AGL-418): /products/* + /collections/*.\n registerSitePageResolver(commerceSitePageResolver)\n // Seeds product grids on ordinary screens (AGL-659) — the resolver above\n // only covers /products/* and /collections/*, so /products itself, and any\n // designed page with a grid on it, needed this to render server-side.\n registerSitePageEnricher(commerceSitePageEnricher)\n registerPluginApiRoute('commerce/cart-checkout', cartCheckoutHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/cart', cartHandler)\n // What the cart offers besides shipping (AGL-3624): pickup locations, and\n // local delivery's fee, minimum and windows for a postal code.\n registerPluginApiRoute('commerce/local-fulfillment-options', async (req, res) =>\n (await import('./server/local-fulfillment')).localFulfillmentOptionsHandler(req, res),\n )\n // Optional lines another plugin offers at the cart (AGL-3635).\n registerPluginApiRoute('commerce/cart-extras', cartExtrasHandler)\n registerPluginApiRoute('commerce/catalog', catalogHandler)\n registerPluginApiRoute('commerce/checkout', checkoutHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/download', downloadHandler)\n // The pre-channels Google feed address (AGL-299), now written by the\n // catalog's feed publisher (AGL-3637); the module loads with a fetch.\n registerPluginApiRoute('commerce/feed', {\n web: async (request) => (await import('./server/legacy-feed')).legacyFeedRoute(request),\n })\n registerPluginApiRoute('commerce/newsletter', newsletterHandler)\n registerPluginApiRoute('commerce/notify-restock', notifyRestockHandler)\n // GA-safe order projection for the storefront `purchase` (AGL-1641).\n registerPluginApiRoute('commerce/order-analytics', orderAnalyticsHandler)\n // The guest order-status page's data (AGL-3610), behind the signed link in\n // every buyer email — a recipient link, so it outlives the site's gates.\n registerPluginApiRoute('commerce/order-status', orderStatusHandler, { recipientLink: true })\n // …and its \"Request a return\" button (AGL-3611), on an order that can\n // still send something back.\n registerOrderStatusActions(returnRequestStatusAction)\n // The customer's quote page (AGL-4094), behind the signed pay link a\n // business sends: the quote, and its Pay button. The page's data is a\n // recipient link, so it outlives the site's gates like the order status.\n registerPluginApiRoute(\n 'commerce/quote-view',\n async (req, res) => (await import('./server/quote-pay')).quoteViewHandler(req, res),\n { recipientLink: true },\n )\n registerPluginApiRoute('commerce/quote-pay', quotePayDoor, CARD_PAYMENT_DOOR)\n // The quote as a PDF (AGL-4095), by the same signed link and on the same\n // terms as the page's data. Loaded on first call, with sharp and the PDF\n // writer behind it.\n registerPluginApiRoute(\n 'commerce/quote-pdf',\n async (req, res) => (await import('./server/commerce-pdf')).quotePdfHandler(req, res),\n { recipientLink: true },\n )\n // The quote's proofs (AGL-4096), by the same signed link and on the same\n // terms as the page's data; and the customer's answer to them, with any\n // artwork they send through the shared visitor upload. The two writes are\n // ordinary visitor writes: the dispatcher's cross-origin check, lockdown\n // and visitor-write limit stand in front of their own. Loaded on first call.\n registerPluginApiRoute(\n 'commerce/quote-proof',\n async (req, res) => (await import('./server/quote-proofs')).quoteProofHandler(req, res),\n { recipientLink: true },\n )\n registerPluginApiRoute('commerce/quote-upload', async (req, res) =>\n (await import('./server/quote-proofs')).quoteUploadHandler(req, res),\n )\n registerPluginApiRoute('commerce/quote-respond', async (req, res) =>\n (await import('./server/quote-proofs')).quoteRespondHandler(req, res),\n )\n // What became of a session the shopper was returned from (AGL-3606).\n registerPluginApiRoute('commerce/checkout-status', checkoutStatusHandler)\n registerPluginApiRoute('commerce/product', productHandler)\n registerPluginApiRoute('commerce/related', relatedHandler)\n registerPluginApiRoute('commerce/reservation-availability', reservationAvailabilityHandler)\n registerPluginApiRoute('commerce/reserve', reserveHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/gate', gateHandler)\n registerPluginApiRoute('commerce/member-feed', memberFeedHandler)\n registerPluginApiRoute('commerce/stream', streamHandler)\n registerPluginApiRoute('commerce/subscription-portal', subscriptionPortalHandler)\n registerPluginApiRoute('commerce/reviews', reviewsHandler)\n // A buyer's return request (AGL-3611), from their account or the signed\n // order-status link.\n registerPluginApiRoute('commerce/return-request', returnRequestHandler)\n registerPluginApiRoute('membership/account', membershipAccountHandler)\n registerPluginApiRoute('membership/content', membershipContentHandler)\n registerPluginApiRoute('membership/login', membershipLoginHandler)\n registerPluginApiRoute('membership/logout', membershipLogoutHandler)\n // Password recovery pair (AGL-552): request + complete.\n registerPluginApiRoute('membership/recover', membershipRecoverHandler)\n registerPluginApiRoute('membership/register', membershipRegisterHandler)\n registerPluginApiRoute('membership/reset', membershipResetHandler)\n registerPluginApiRoute('membership/wishlist', membershipWishlistHandler)\n}\n\n/**\n * Registers the commerce plugin's console-side API routes (AGL-396):\n * merchant/staff operations (Connect onboarding, refunds, draft & POS\n * orders, member posts), the supplier tracking callback, and the HTTP doors\n * for the abandoned-cart / restock passes.\n *\n * Those last two are NOT what schedules them — the `registerPluginJob` calls\n * above are (AGL-2227). This comment used to call them \"the scheduler-driven\n * jobs\", which is how they stayed dark for months: it asserted the wiring\n * instead of having it.\n */\nexport function registerCommerceConsoleApi(): void {\n // The register's gate (`managePos`) is resolved on THIS surface: every POS\n // route below runs in the console, and a key no surface registered here is\n // absent from the resolved map, which reads as refused — the site's own\n // owner was answered 403 at the register.\n registerPluginPermissions(COMMERCE_PERMISSIONS)\n // What a product looks like to a surface that is not this plugin's — a\n // campaign email that features one asks here rather than importing the model.\n registerProductCardReader()\n // …and a draft product another plugin asks for by name (AGL-3616): an AI\n // build setting a store up from a brief, unpriced unless the brief priced it.\n // The console runs AI jobs (AGL-3026).\n registerProductDraftWriter()\n // …and the operation an AI build plans for it, which that writer executes.\n registerProductAiCapability()\n // …and the store's shipping, pickup, local delivery and tax settings an AI\n // build sets up (AGL-3749), written live as the console's cards write them,\n // with the four operations that writer executes.\n registerStoreSetupAiWriter()\n registerStoreSetupAiCapabilities()\n // …and why a file somebody is SELLING may not be made public (AGL-3080).\n // The media library asks before it hands an asset its permanent CDN URL\n // back; what a product is, and which of its fields hold paid media, is\n // this plugin's to know.\n registerCommerceMediaPublishGuard()\n // …and which memberships a site sells, for a security lockdown to pause\n // (AGL-3364). The lockdown route runs on this surface.\n registerCommerceRecurringCharges()\n // …and the tax rule, for the webhook that confirms what they charged.\n registerCommerceTaxProfile()\n // …and its sales on the operator's own sales tax return (AGL-3080): the\n // tax a storefront checkout collected under the platform's registrations.\n // The staff return awaits this surface before it asks, and refuses to be\n // filed without this source — commerce declares `taxReturnSource`.\n registerTaxReturnSource(commerceTaxReturnSource, { pluginId: BUNDLE_ID })\n // …and the take its orders earn the operator, on the staff revenue report\n // (AGL-3080) — commerce declares `revenueSource`, so the report names this\n // source as unread rather than counting it as zero if it is missing.\n registerRevenueSource(commerceRevenueSource, { pluginId: BUNDLE_ID })\n // Stripe webhook sections (AGL-418): orders/carts/drafts/reservations/\n // subscriptions ride the platform webhook via the hook registry.\n registerBillingWebhookHandler(commerceBillingWebhookHandler)\n // A paid card-reader order from the POS hardware shop (AGL-4038), on the\n // same platform webhook: its own handler, self-selecting on the session's\n // `metadata.type`, so the storefront sections above never see it.\n registerBillingWebhookHandler(async (event) =>\n (await import('./server/pos-hardware-webhook')).posHardwareBillingWebhookHandler(event),\n )\n // A card the Aglyn POS app took offline (AGL-4039): its PaymentIntent can\n // reach Stripe before the sale reaches the server, so every event on one is\n // kept by the sale's key. Self-selecting on `metadata.kind`.\n registerBillingWebhookHandler(async (event) =>\n (await import('./server/pos-offline-card-reconcile')).posOfflineCardBillingWebhookHandler(event),\n )\n // Cancel + stock release in one transaction (AGL-1808). Server-side because\n // the release depends on the transition rule, and a client write could not\n // re-ask it under the same lock that flips the status.\n registerPluginApiRoute('commerce/cancel-order', cancelOrderHandler)\n // Whether live carrier rates can be offered on this site (AGL-3612).\n registerPluginApiRoute('commerce/shipping/carrier-rates', carrierRatesAvailabilityHandler)\n registerPluginApiRoute('commerce/connect', connectHandler)\n registerPluginApiRoute('commerce/draft-order', draftOrderHandler)\n // Quotes (AGL-4093): create, edit and delete a quote, and find the customer\n // it is for, under \"Create and edit quotes\". Loaded on first call.\n registerPluginApiRoute('commerce/quote', async (req, res) =>\n (await import('./server/quote')).quoteHandler(req, res),\n )\n // Send invoice (AGL-4099) for an order or a quote, under \"Send quotes and\n // invoices to customers\": an unpaid one with the order's lasting pay link,\n // a paid one as the record. The email, the PDF and sharp load on first\n // call only.\n registerPluginApiRoute('commerce/order-invoice-send', async (req, res) =>\n (await import('./server/order-invoice-send')).orderInvoiceSendHandler(req, res),\n )\n // Fulfil + mark-delivered with the transition re-asked under the write\n // (AGL-1819) — the same stale-dialog hole cancel-order closes, minus the\n // stock release those two transitions never had. The customer REST API's\n // `PATCH /v1/sites/{id}/orders/{id}` records a shipment through the same\n // transaction (`server/api-v1/orders-and-products.ts`).\n registerPluginApiRoute('commerce/fulfill-order', fulfillOrderHandler)\n // Pickup and local delivery steps (AGL-3624) — ready, picked up, out for\n // delivery, delivered — from the console queue, the order dialog and the\n // native Aglyn app. Loaded on first call.\n registerPluginApiRoute('commerce/local-fulfillment', async (req, res) =>\n (await import('./server/local-fulfillment-status')).localFulfillmentHandler(req, res),\n )\n // \"Resend receipt\" from the order dialog (AGL-3610): by email, or by text\n // when the platform's SMS provider is configured. Rate-limited per member\n // and per order.\n registerPluginApiRoute('commerce/order-receipt-send', orderReceiptSendHandler)\n // The product editor's save and Adjust stock for the native apps (AGL-3652):\n // the console's own product-write computation under the rules' gate. Loaded\n // on first call.\n registerPluginApiRoute('commerce/products/save', async (req, res) =>\n (await import('./server/products-write')).productSaveHandler(req, res),\n )\n registerPluginApiRoute('commerce/products/stock', async (req, res) =>\n (await import('./server/products-write')).productStockHandler(req, res),\n )\n // A staff walk-in from the Reservations card and the native apps\n // (AGL-4046): availability re-asked inside the transaction that writes, so\n // two staff cannot hand out the last unit at once. Loaded on first call.\n registerPluginApiRoute('commerce/reservations/walk-in', async (req, res) =>\n (await import('./server/reservation-walk-in')).reservationWalkInHandler(req, res),\n )\n // A stay's guest count after it is booked (AGL-4043), from the Reservations\n // card and the check-in screen: the walk-in's gate, and the stay's\n // check-ins for today on brought in line in the same transaction. Loaded\n // on first call.\n registerPluginApiRoute('commerce/reservations/guests', async (req, res) =>\n (await import('./server/reservation-guests')).reservationGuestsHandler(req, res),\n )\n // The products list's Duplicate and Delete for the native apps (AGL-3841):\n // the console's own copy and soft delete, with the site-wide cache drop.\n registerPluginApiRoute('commerce/products/duplicate', async (req, res) =>\n (await import('./server/products-write')).productDuplicateHandler(req, res),\n )\n registerPluginApiRoute('commerce/products/delete', async (req, res) =>\n (await import('./server/products-write')).productDeleteHandler(req, res),\n )\n // The order dialog's note and restock answer for the native apps\n // (AGL-3651, AGL-3652): the console's own timeline computation, in one\n // transaction on the stored order. Loaded on first call.\n registerPluginApiRoute('commerce/order-note', async (req, res) =>\n (await import('./server/order-annotations')).orderNoteHandler(req, res),\n )\n registerPluginApiRoute('commerce/order-restock-answer', async (req, res) =>\n (await import('./server/order-annotations')).orderRestockAnswerHandler(req, res),\n )\n // The order dialog's Packing slip and Invoice for the native apps\n // (AGL-3841): the console's own two pages over the stored order, which the\n // apps print on the device's print sheet; and the invoice as a PDF file\n // (`kind=invoice-pdf`, AGL-4095) for the console and the apps. Loaded on\n // first call.\n registerPluginApiRoute('commerce/order-print', async (req, res) =>\n (await import('./server/order-print')).orderPrintHandler(req, res),\n )\n // Issue / void store credit (AGL-2226). Server-side because the host\n // catch-all in the Firestore rules would otherwise let a client write\n // its own `balanceCents`, which checkout applies as amount-off.\n registerPluginApiRoute('commerce/gift-cards', giftCardsHandler)\n // The merchant's own storefront sales tax, by who owes it (AGL-2440): the\n // same rows and classifier the operator's return reads, fenced to one site.\n registerPluginApiRoute('commerce/tax-summary', { web: taxSummaryHandler })\n // The payment methods card (AGL-3629): toggles, the platform's offer, the\n // payout account's capabilities and the site's wallet domains. Loaded with\n // the first request, so a console that never opens Settings never imports it.\n registerPluginApiRoute('commerce/payment-methods', {\n web: async (request) =>\n (await import('./server/payment-methods')).paymentMethodsHandler(request),\n })\n // A smart collection's rules changed or it was deleted: re-stamp which\n // products it holds (AGL-3321), the membership the storefront queries.\n registerPluginApiRoute('commerce/collection-membership', collectionMembershipHandler)\n // A site member's password help (AGL-914) and removal (AGL-3308), from the\n // Users page drawer and the Inbox. Console-auth, not the visitor cookie the\n // storefront's `membership/*` routes take, so they are served where the\n // console posts: the console's own dispatcher loads this surface only.\n registerPluginApiRoute(\n 'membership/admin-password',\n membershipAdminPasswordHandler,\n )\n registerPluginApiRoute('membership/admin-remove', membershipAdminRemoveHandler)\n registerPluginApiRoute('commerce/member-post', memberPostHandler)\n registerPluginApiRoute('commerce/pos-order', posOrderHandler)\n // A register's cloud receipt printers and the jobs a manager sends them\n // (AGL-3619), and the two doors the printers themselves poll. The doors are\n // MACHINE routes: a printer is no member and names no site cookie, so it\n // authenticates with the per-printer secret in its URL and its own device id,\n // and the route asks the plan before it hands over a job. Loaded with the\n // first poll, so a console that has no printers never imports them.\n registerPluginApiRoute('commerce/printers', printersHandler)\n registerPluginApiRoute(\n 'commerce/cloudprnt/:hostId/:printerId/:secret',\n {\n web: async (request, context) =>\n (await import('./server/printer-poll')).cloudPrntRoute(request, context),\n },\n { machine: true },\n )\n registerPluginApiRoute(\n 'commerce/epson-sdp/:hostId/:printerId/:secret',\n {\n web: async (request, context) =>\n (await import('./server/printer-poll')).epsonServerDirectPrintRoute(request, context),\n },\n { machine: true },\n )\n // The register's tenders against an open sale, its Stripe Terminal card\n // readers, and the paired customer display (AGL-3607, AGL-3608). The\n // display's `pair`/`poll`/`respond` take a display token and no console\n // session; every other action is gated like a sale.\n registerPluginApiRoute('commerce/pos-payment', posPaymentHandler)\n registerPluginApiRoute('commerce/pos-readers', posReadersHandler)\n registerPluginApiRoute('commerce/pos-display', posDisplayHandler)\n // The POS hardware shop (AGL-4038): the Hardware card's catalog, Checkout\n // and order list, gated like a sale and hidden until the deployment prices\n // it; and the staff page's orders, which name no site. Loaded on first call.\n registerPluginApiRoute('commerce/pos-hardware', async (req, res) =>\n (await import('./server/pos-hardware')).posHardwareHandler(req, res),\n )\n // Selling a card reader in person at the platform's own store's register\n // (AGL-4038): whether this store is that seller. Gated like a sale, and\n // silent about the configuration on every other store. Loaded on first call.\n registerPluginApiRoute('commerce/pos-hardware-sale', async (req, res) =>\n (await import('./server/pos-hardware-sale')).posHardwareSaleHandler(req, res),\n )\n // A store's card reader start-up screen (AGL-4048): the POS devices card's\n // setting, gated like a sale, and the staff page's platform default. Each\n // loads with its first call; the drawing they ask for is the images\n // route's, below.\n registerPluginApiRoute('commerce/pos-reader-splash', async (req, res) =>\n (await import('./server/pos-reader-splash')).posReaderSplashHandler(req, res),\n )\n registerPluginApiRoute('commerce/admin/reader-splash', {\n web: async (request) =>\n (await import('./server/pos-reader-splash-admin')).posReaderSplashAdmin(request),\n })\n // The image work behind both (AGL-4048): drawing a screen and reading an\n // uploaded one take `sharp`, whose native library only the console's\n // plugins' image function ships (`/api/plugin-images/…`), so the plugin\n // API's function does not carry it. Called by our own servers, signed; a\n // machine's door.\n registerPluginApiRoute(\n 'commerce/pos-reader-splash-images',\n {\n web: async (request) =>\n (await import('./server/pos-reader-splash-images-route')).posReaderSplashImagesRoute(request),\n },\n { machine: true, images: true },\n )\n registerPluginApiRoute('commerce/admin/hardware-orders', {\n web: async (request) =>\n (await import('./server/pos-hardware-admin')).posHardwareAdminOrders(request),\n })\n // The self-service kiosk (AGL-3623): a register's paired screen where the\n // customer orders and pays. Its device token, never a staff session; the\n // register's queue of \"pay at counter\" orders is gated like a sale.\n registerPluginApiRoute('commerce/pos-kiosk', posKioskHandler)\n // Shifts, staff PINs, the customer lookup and returns (AGL-3609).\n registerPosOpsRoutes()\n // The offline register (AGL-3625): the kit a register caches to sell cash\n // while the connection is down, and the sync that records those sales once.\n // Gated like a sale; loaded with its first call.\n registerPluginApiRoute('commerce/pos-offline-sync', async (req, res) =>\n (await import('./server/pos-offline-sync')).posOfflineSyncHandler(req, res),\n )\n // The native Aglyn POS app's Stripe Terminal SDK: a connection token scoped\n // to the site's Location, and the Location itself (AGL-3618). Gated like a\n // sale.\n registerPluginApiRoute('commerce/pos-terminal-connection-token', posTerminalConnectionTokenHandler)\n registerPluginApiRoute('commerce/process-abandoned', processAbandonedHandler)\n registerPluginApiRoute('commerce/process-restock', processRestockHandler)\n registerPluginApiRoute('commerce/refund', refundHandler)\n // Returns (AGL-3611): approve, decline, receive with restock, refund\n // through the route above, a label from a shipping plugin.\n registerPluginApiRoute('commerce/returns', returnsHandler)\n // The merchant's outbound order webhooks (AGL-3611): endpoints, secrets,\n // a test ping and a resend from the delivery log.\n registerPluginApiRoute('commerce/order-webhooks', orderWebhooksHandler)\n registerPluginApiRoute('commerce/supplier-update', supplierUpdateHandler)\n // Stamps the open orders that predate the shipping fields, before an\n // export for shipping (AGL-3613).\n registerPluginApiRoute('commerce/orders-shipping-prepare', async (req, res) =>\n (await import('./server/orders-shipping-prepare')).ordersShippingPrepareHandler(req, res),\n )\n // ShipStation's Custom Store endpoint (AGL-3613): ShipStation's servers\n // pull the order feed and post shipments back with the site's own Basic\n // credentials, so it is a MACHINE's route and asks the site's commerce,\n // plan, release and lockdown gates itself once the credentials prove the\n // site. Loaded on its first call, never with the console API surface.\n registerPluginApiRoute(\n 'commerce/shipstation/:hostId',\n {\n web: async (request, context) =>\n (await import('./server/shipstation')).shipStationRoute(request, context),\n },\n { machine: true },\n )\n // ShippingEasy's shipment callback (AGL-3633): ShippingEasy's servers post\n // each label bought for an order this store sent them, signed with the\n // merchant's own API secret, so it is a MACHINE's route like ShipStation's\n // above and asks the same gates once the signature proves the site.\n registerPluginApiRoute(\n 'commerce/shippingeasy/:hostId',\n {\n web: async (request, context) =>\n (await import('./server/shippingeasy')).shippingEasyRoute(request, context),\n },\n { machine: true },\n )\n // The ShipStation and ShippingEasy cards' connect, show, new password,\n // send open orders and disconnect.\n registerPluginApiRoute('commerce/shipping-connectors', async (req, res) =>\n (await import('./server/shipping-connectors')).shippingConnectorsHandler(req, res),\n )\n // The store's sales as figure tables (AGL-2915), for the AI plugin's\n // insights to read by id rather than by reading orders. The console runs\n // insight jobs, so the console surface registers them.\n registerOrderFigureReaders(() => firebaseAdmin.app().firestore())\n}\n\n// Shared with the (still app-side) membership/account route.\nexport { mintDownloadToken } from './server/download'\n\n// Site-member session primitives, shared with the (still app-side)\n// membership/* routes until those migrate too (AGL-396).\nexport * from './server/membership'\n\n// Type-only (AGL-3080): the plugin's entitlement keys, declared by module\n// augmentation, for every program that loads this entry point.\nexport type { commercePlanEntitlements } from './plan-entitlements'\n"],"names":["registerBillingWebhookHandler","registerPluginApiRoute","registerPluginJob","registerSitePageEnricher","registerSitePageResolver","registerPluginPermissions","registerPluginConfigSchema","isEmailConfigured","firebaseAdmin","BUNDLE_ID","registerCommerceMediaPublishGuard","registerCommerceRecurringCharges","registerProductCardReader","registerProductAiCapability","registerStoreSetupAiCapabilities","registerStoreSetupAiWriter","registerProductDraftWriter","registerCommerceTaxProfile","registerTaxReturnSource","commerceTaxReturnSource","taxSummaryHandler","registerRevenueSource","commerceRevenueSource","commerceBillingWebhookHandler","registerOrderFigureReaders","COMMERCE_PERMISSIONS","COMMERCE_CONFIG_SCHEMA","commerceSitePageEnricher","commerceSitePageResolver","cartCheckoutHandler","cartHandler","cartExtrasHandler","catalogHandler","checkoutHandler","downloadHandler","newsletterHandler","notifyRestockHandler","productHandler","relatedHandler","reservationAvailabilityHandler","gateHandler","memberFeedHandler","membershipAccountHandler","membershipAdminPasswordHandler","membershipAdminRemoveHandler","membershipContentHandler","membershipLoginHandler","membershipLogoutHandler","membershipRecoverHandler","membershipRegisterHandler","membershipResetHandler","membershipWishlistHandler","reserveHandler","streamHandler","subscriptionPortalHandler","reviewsHandler","connectHandler","cancelOrderHandler","carrierRatesAvailabilityHandler","collectionMembershipHandler","draftOrderHandler","fulfillOrderHandler","orderReceiptSendHandler","orderStatusHandler","registerOrderStatusActions","returnRequestStatusAction","giftCardsHandler","memberPostHandler","orderAnalyticsHandler","checkoutStatusHandler","posOrderHandler","printersHandler","posPaymentHandler","posReadersHandler","posTerminalConnectionTokenHandler","posDisplayHandler","posKioskHandler","registerPosOpsRoutes","processAbandonedHandler","scanAbandonedCheckouts","processRestockHandler","scanRestockAlerts","scanStockDecrements","refundHandler","orderWebhooksHandler","returnRequestHandler","returnsHandler","scanSupplierDeliveries","supplierUpdateHandler","RECOVERY_JOB_INTERVAL_MINUTES","pluginId","name","intervalMinutes","description","lockdown","scope","handler","gate","sent","console","info","scanReviewRequests","scan","missingLines","truncatedHosts","warn","hosts","reportedOrders","deadLettered","process","env","STRIPE_SECRET_KEY","reconcileCustomDomains","result","registered","failed","POS_CELLULAR_MONTHLY_COST_CENTS","runPosCellularBilling","report","workspaces","storesGone","warned","turnedOff","paidLate","month","paid","open","unbillable","deferred","refreshPosReaderSplashes","applied","more","scanUnsyncedOfflineCards","alerted","CARD_PAYMENT_DOOR","cardPayment","quotePayDoor","req","res","quotePayHandler","registerCommerceApi","localFulfillmentOptionsHandler","web","request","legacyFeedRoute","recipientLink","quoteViewHandler","quotePdfHandler","quoteProofHandler","quoteUploadHandler","quoteRespondHandler","registerCommerceConsoleApi","event","posHardwareBillingWebhookHandler","posOfflineCardBillingWebhookHandler","quoteHandler","orderInvoiceSendHandler","localFulfillmentHandler","productSaveHandler","productStockHandler","reservationWalkInHandler","reservationGuestsHandler","productDuplicateHandler","productDeleteHandler","orderNoteHandler","orderRestockAnswerHandler","orderPrintHandler","paymentMethodsHandler","context","cloudPrntRoute","machine","epsonServerDirectPrintRoute","posHardwareHandler","posHardwareSaleHandler","posReaderSplashHandler","posReaderSplashAdmin","posReaderSplashImagesRoute","images","posHardwareAdminOrders","posOfflineSyncHandler","ordersShippingPrepareHandler","shipStationRoute","shippingEasyRoute","shippingConnectorsHandler","app","firestore","mintDownloadToken"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD;;;;;;;CAOC,GAED,SACEA,6BAA6B,EAC7BC,sBAAsB,EACtBC,iBAAiB,EACjBC,wBAAwB,EACxBC,wBAAwB,EACxBC,yBAAyB,EACzBC,0BAA0B,QAErB,sBAAqB;AAC5B,SAASC,iBAAiB,QAAQ,2BAA0B;AAC5D,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,iCAAiC,QAAQ,kCAA8B;AAChF,SAASC,gCAAgC,QAAQ,gCAA4B;AAC7E,SAASC,yBAAyB,QAAQ,2BAAuB;AACjE,SAASC,2BAA2B,QAAQ,oCAAgC;AAC5E,SAASC,gCAAgC,QAAQ,wCAAoC;AACrF,SAASC,0BAA0B,QAAQ,4CAA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