@aglyn/plugins-commerce 1.15.1 → 1.16.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 (212) hide show
  1. package/README.md +1 -1
  2. package/package.json +13 -13
  3. package/src/lib/components/cart.js +2 -1
  4. package/src/lib/components/cart.js.map +1 -1
  5. package/src/lib/components/console/payments-settings-card.component.js +6 -1
  6. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  7. package/src/lib/components/console/pos/pos-api.d.ts +5 -0
  8. package/src/lib/components/console/pos/pos-api.js.map +1 -1
  9. package/src/lib/components/console/pos/pos-tender-dialogs.component.d.ts +2 -0
  10. package/src/lib/components/console/pos/pos-tender-dialogs.component.js +13 -6
  11. package/src/lib/components/console/pos/pos-tender-dialogs.component.js.map +1 -1
  12. package/src/lib/components/console/pos/pos-tender-panel.component.js +7 -4
  13. package/src/lib/components/console/pos/pos-tender-panel.component.js.map +1 -1
  14. package/src/lib/components/console/product-add-ons-fields.component.d.ts +13 -0
  15. package/src/lib/components/console/product-add-ons-fields.component.js +96 -3
  16. package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
  17. package/src/lib/components/console/product-builder-fields.component.d.ts +39 -0
  18. package/src/lib/components/console/product-builder-fields.component.js +195 -0
  19. package/src/lib/components/console/product-builder-fields.component.js.map +1 -0
  20. package/src/lib/components/console/product-editor-dialog.component.js +35 -2
  21. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  22. package/src/lib/components/console/quote-editor-dialog.component.js +43 -6
  23. package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
  24. package/src/lib/components/console/quote-messages.component.d.ts +21 -0
  25. package/src/lib/components/console/quote-messages.component.js +185 -0
  26. package/src/lib/components/console/quote-messages.component.js.map +1 -0
  27. package/src/lib/components/console/quote-pay-link.component.js +1 -1
  28. package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
  29. package/src/lib/components/console/quote-proofs.component.js +30 -3
  30. package/src/lib/components/console/quote-proofs.component.js.map +1 -1
  31. package/src/lib/components/console/quote-settings-card.component.d.ts +7 -3
  32. package/src/lib/components/console/quote-settings-card.component.js +154 -24
  33. package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
  34. package/src/lib/components/product-builder-context.d.ts +22 -0
  35. package/src/lib/components/product-builder-context.js +21 -0
  36. package/src/lib/components/product-builder-context.js.map +1 -0
  37. package/src/lib/components/product-builder-mockup.d.ts +42 -0
  38. package/src/lib/components/product-builder-mockup.js +120 -0
  39. package/src/lib/components/product-builder-mockup.js.map +1 -0
  40. package/src/lib/components/product-builder-sample.d.ts +63 -0
  41. package/src/lib/components/product-builder-sample.js +96 -0
  42. package/src/lib/components/product-builder-sample.js.map +1 -0
  43. package/src/lib/components/product-choice-cards.d.ts +51 -0
  44. package/src/lib/components/product-choice-cards.js +311 -0
  45. package/src/lib/components/product-choice-cards.js.map +1 -0
  46. package/src/lib/components/product-detail-panels.d.ts +42 -0
  47. package/src/lib/components/product-detail-panels.js +185 -0
  48. package/src/lib/components/product-detail-panels.js.map +1 -0
  49. package/src/lib/components/product-detail.d.ts +20 -12
  50. package/src/lib/components/product-detail.js +136 -221
  51. package/src/lib/components/product-detail.js.map +1 -1
  52. package/src/lib/components/product-grid.d.ts +7 -0
  53. package/src/lib/components/product-grid.js +11 -8
  54. package/src/lib/components/product-grid.js.map +1 -1
  55. package/src/lib/components/product-options-field-body.d.ts +9 -8
  56. package/src/lib/components/product-options-field-body.js +152 -3
  57. package/src/lib/components/product-options-field-body.js.map +1 -1
  58. package/src/lib/components/product-options-field.js +1 -1
  59. package/src/lib/components/product-options-field.js.map +1 -1
  60. package/src/lib/components/product-photo-fit.d.ts +49 -0
  61. package/src/lib/components/product-photo-fit.js +58 -0
  62. package/src/lib/components/product-photo-fit.js.map +1 -0
  63. package/src/lib/components/product-restock-notify.d.ts +12 -0
  64. package/src/lib/components/product-restock-notify.js +86 -0
  65. package/src/lib/components/product-restock-notify.js.map +1 -0
  66. package/src/lib/components/quote-messages-panel.d.ts +21 -0
  67. package/src/lib/components/quote-messages-panel.js +191 -0
  68. package/src/lib/components/quote-messages-panel.js.map +1 -0
  69. package/src/lib/components/quote-page-body.js +15 -1
  70. package/src/lib/components/quote-page-body.js.map +1 -1
  71. package/src/lib/components/quote-proof-panel.d.ts +6 -3
  72. package/src/lib/components/quote-proof-panel.js +139 -14
  73. package/src/lib/components/quote-proof-panel.js.map +1 -1
  74. package/src/lib/components/related-products.d.ts +7 -0
  75. package/src/lib/components/related-products.js +8 -6
  76. package/src/lib/components/related-products.js.map +1 -1
  77. package/src/lib/constants/quote-page.d.ts +8 -0
  78. package/src/lib/constants/quote-page.js +11 -0
  79. package/src/lib/constants/quote-page.js.map +1 -1
  80. package/src/lib/model/commerce-cart.d.ts +6 -1
  81. package/src/lib/model/commerce-cart.js +5 -1
  82. package/src/lib/model/commerce-cart.js.map +1 -1
  83. package/src/lib/model/commerce-invoices.js +5 -1
  84. package/src/lib/model/commerce-invoices.js.map +1 -1
  85. package/src/lib/model/commerce-pos-ops.d.ts +3 -0
  86. package/src/lib/model/commerce-pos-ops.js +3 -0
  87. package/src/lib/model/commerce-pos-ops.js.map +1 -1
  88. package/src/lib/model/commerce-pos.d.ts +8 -0
  89. package/src/lib/model/commerce-pos.js.map +1 -1
  90. package/src/lib/model/commerce-quote-messages.d.ts +106 -0
  91. package/src/lib/model/commerce-quote-messages.js +146 -0
  92. package/src/lib/model/commerce-quote-messages.js.map +1 -0
  93. package/src/lib/model/commerce-quote-pay.d.ts +31 -2
  94. package/src/lib/model/commerce-quote-pay.js +31 -7
  95. package/src/lib/model/commerce-quote-pay.js.map +1 -1
  96. package/src/lib/model/commerce-quote-proofs.d.ts +47 -8
  97. package/src/lib/model/commerce-quote-proofs.js +73 -18
  98. package/src/lib/model/commerce-quote-proofs.js.map +1 -1
  99. package/src/lib/model/commerce-quote-request.d.ts +14 -4
  100. package/src/lib/model/commerce-quote-request.js +25 -2
  101. package/src/lib/model/commerce-quote-request.js.map +1 -1
  102. package/src/lib/model/commerce-quotes.d.ts +56 -3
  103. package/src/lib/model/commerce-quotes.js +47 -2
  104. package/src/lib/model/commerce-quotes.js.map +1 -1
  105. package/src/lib/model/commerce.d.ts +12 -1
  106. package/src/lib/model/commerce.js.map +1 -1
  107. package/src/lib/model/index.d.ts +1 -0
  108. package/src/lib/model/index.js +1 -0
  109. package/src/lib/model/index.js.map +1 -1
  110. package/src/lib/model/pos-cellular.d.ts +5 -0
  111. package/src/lib/model/pos-cellular.js.map +1 -1
  112. package/src/lib/model/product-card-rules.d.ts +41 -0
  113. package/src/lib/model/product-card-rules.js +90 -0
  114. package/src/lib/model/product-card-rules.js.map +1 -0
  115. package/src/lib/model/product-modifiers.d.ts +11 -0
  116. package/src/lib/model/product-modifiers.js +10 -0
  117. package/src/lib/model/product-modifiers.js.map +1 -1
  118. package/src/lib/model/product-write.d.ts +3 -0
  119. package/src/lib/server/billing-webhook.js +6 -2
  120. package/src/lib/server/billing-webhook.js.map +1 -1
  121. package/src/lib/server/cancel-order.js +15 -0
  122. package/src/lib/server/cancel-order.js.map +1 -1
  123. package/src/lib/server/channel-order-updates.js +15 -1
  124. package/src/lib/server/channel-order-updates.js.map +1 -1
  125. package/src/lib/server/channel-orders.js +20 -0
  126. package/src/lib/server/channel-orders.js.map +1 -1
  127. package/src/lib/server/checkout.js +1 -1
  128. package/src/lib/server/checkout.js.map +1 -1
  129. package/src/lib/server/local-fulfillment.js +1 -1
  130. package/src/lib/server/local-fulfillment.js.map +1 -1
  131. package/src/lib/server/pos-cellular-billing.d.ts +1 -1
  132. package/src/lib/server/pos-cellular-billing.js +2 -1
  133. package/src/lib/server/pos-cellular-billing.js.map +1 -1
  134. package/src/lib/server/pos-cellular.d.ts +3 -1
  135. package/src/lib/server/pos-cellular.js +15 -8
  136. package/src/lib/server/pos-cellular.js.map +1 -1
  137. package/src/lib/server/pos-offline-sync.d.ts +3 -3
  138. package/src/lib/server/pos-offline-sync.js +17 -4
  139. package/src/lib/server/pos-offline-sync.js.map +1 -1
  140. package/src/lib/server/pos-order.js +17 -6
  141. package/src/lib/server/pos-order.js.map +1 -1
  142. package/src/lib/server/pos-payment.js +27 -11
  143. package/src/lib/server/pos-payment.js.map +1 -1
  144. package/src/lib/server/pos-reader-splash.js +10 -5
  145. package/src/lib/server/pos-reader-splash.js.map +1 -1
  146. package/src/lib/server/pos-readers.js +34 -10
  147. package/src/lib/server/pos-readers.js.map +1 -1
  148. package/src/lib/server/pos-return.js +19 -3
  149. package/src/lib/server/pos-return.js.map +1 -1
  150. package/src/lib/server/pos-stripe.d.ts +14 -0
  151. package/src/lib/server/pos-stripe.js +6 -2
  152. package/src/lib/server/pos-stripe.js.map +1 -1
  153. package/src/lib/server/pos-terminal-connection-token.js +23 -9
  154. package/src/lib/server/pos-terminal-connection-token.js.map +1 -1
  155. package/src/lib/server/pos-terminal.d.ts +80 -14
  156. package/src/lib/server/pos-terminal.js +393 -123
  157. package/src/lib/server/pos-terminal.js.map +1 -1
  158. package/src/lib/server/product-drafts.d.ts +1 -1
  159. package/src/lib/server/product-drafts.js +4 -3
  160. package/src/lib/server/product-drafts.js.map +1 -1
  161. package/src/lib/server/product-writer.js +5 -4
  162. package/src/lib/server/product-writer.js.map +1 -1
  163. package/src/lib/server/product.d.ts +11 -0
  164. package/src/lib/server/product.js +18 -3
  165. package/src/lib/server/product.js.map +1 -1
  166. package/src/lib/server/products-write.js +4 -3
  167. package/src/lib/server/products-write.js.map +1 -1
  168. package/src/lib/server/quote-email.d.ts +26 -0
  169. package/src/lib/server/quote-email.js +73 -7
  170. package/src/lib/server/quote-email.js.map +1 -1
  171. package/src/lib/server/quote-messages.d.ts +72 -0
  172. package/src/lib/server/quote-messages.js +356 -0
  173. package/src/lib/server/quote-messages.js.map +1 -0
  174. package/src/lib/server/quote-pay.d.ts +42 -0
  175. package/src/lib/server/quote-pay.js +81 -4
  176. package/src/lib/server/quote-pay.js.map +1 -1
  177. package/src/lib/server/quote-proofs.d.ts +1 -1
  178. package/src/lib/server/quote-proofs.js +63 -19
  179. package/src/lib/server/quote-proofs.js.map +1 -1
  180. package/src/lib/server/quote.d.ts +12 -0
  181. package/src/lib/server/quote.js +44 -14
  182. package/src/lib/server/quote.js.map +1 -1
  183. package/src/lib/server/refund.js +3 -1
  184. package/src/lib/server/refund.js.map +1 -1
  185. package/src/lib/server/reserve-stock.js +9 -0
  186. package/src/lib/server/reserve-stock.js.map +1 -1
  187. package/src/lib/server/returns.js +15 -1
  188. package/src/lib/server/returns.js.map +1 -1
  189. package/src/lib/server/reviews.js +15 -0
  190. package/src/lib/server/reviews.js.map +1 -1
  191. package/src/lib/server/sold-out-drop.d.ts +58 -0
  192. package/src/lib/server/sold-out-drop.js +81 -0
  193. package/src/lib/server/sold-out-drop.js.map +1 -0
  194. package/src/lib/server/stock-levels.js +9 -0
  195. package/src/lib/server/stock-levels.js.map +1 -1
  196. package/src/lib/server/stripe-refund.d.ts +7 -0
  197. package/src/lib/server/stripe-refund.js +26 -7
  198. package/src/lib/server/stripe-refund.js.map +1 -1
  199. package/src/lib/server.js +2 -0
  200. package/src/lib/server.js.map +1 -1
  201. package/src/lib/tenant-emails.js +85 -2
  202. package/src/lib/tenant-emails.js.map +1 -1
  203. package/src/lib/testing/fake-seller-payment-account.d.ts +29 -0
  204. package/src/lib/testing/fake-seller-payment-account.js +40 -0
  205. package/src/lib/testing/fake-seller-payment-account.js.map +1 -0
  206. package/src/lib/transfer/product-transfer.js +6 -5
  207. package/src/lib/transfer/product-transfer.js.map +1 -1
  208. package/src/lib/transfer/products.server.js +4 -3
  209. package/src/lib/transfer/products.server.js.map +1 -1
  210. package/src/lib/utils/quote-email-content.d.ts +6 -0
  211. package/src/lib/utils/quote-email-content.js +6 -3
  212. package/src/lib/utils/quote-email-content.js.map +1 -1
@@ -132,7 +132,7 @@ function cellularReadersRef() {
132
132
  * reader twice. Idempotent, and cheap where the store never had 4G: one
133
133
  * read of its settings and one of its (empty) records.
134
134
  */ export async function syncPosCellularReaders(input) {
135
- var _input_now, _terminal_get;
135
+ var _input_now, _terminal_get, _terminal_get1;
136
136
  const now = (_input_now = input.now) != null ? _input_now : Date.now();
137
137
  const [terminal, readers] = await Promise.all([
138
138
  terminalConfigRef(input.hostId).get(),
@@ -140,6 +140,9 @@ function cellularReadersRef() {
140
140
  ]);
141
141
  const enabled = terminal.get('cellularEnabled') === true;
142
142
  const configurationId = String((_terminal_get = terminal.get('stripeConfigurationId')) != null ? _terminal_get : '') || null;
143
+ // The account that configuration lives on: the store's own for a
144
+ // direct-charge store's Location, absent for the platform's.
145
+ const configurationAccount = String((_terminal_get1 = terminal.get('stripeLocationAccount')) != null ? _terminal_get1 : '').trim() || null;
143
146
  const capable = new Map();
144
147
  for (const doc of readers.docs){
145
148
  if (isPosCellularDeviceType(doc.get('deviceType'))) {
@@ -159,18 +162,20 @@ function cellularReadersRef() {
159
162
  let closed = 0;
160
163
  if (enabled) {
161
164
  for (const [readerId, reader] of capable){
162
- var _records_get;
165
+ var _records_get, _existing_stripeConfigurationAccount;
163
166
  const id = posCellularReaderId(input.hostId, readerId);
164
167
  const existing = (_records_get = records.get(id)) != null ? _records_get : null;
165
- const next = openPosCellularPeriod({
168
+ const next = openPosCellularPeriod(_extends({
166
169
  orgId: input.orgId,
167
170
  hostId: input.hostId,
168
171
  readerId,
169
172
  serialNumber: reader.serialNumber,
170
173
  stripeConfigurationId: configurationId
171
- }, existing, now);
174
+ }, configurationAccount ? {
175
+ stripeConfigurationAccount: configurationAccount
176
+ } : {}), existing, now);
172
177
  open += 1;
173
- const unchanged = (existing == null ? void 0 : existing.enabled) === true && existing.periods.some((period)=>period.toMs === null) && existing.orgId === input.orgId && existing.serialNumber === reader.serialNumber && existing.stripeConfigurationId === configurationId;
178
+ const unchanged = (existing == null ? void 0 : existing.enabled) === true && existing.periods.some((period)=>period.toMs === null) && existing.orgId === input.orgId && existing.serialNumber === reader.serialNumber && existing.stripeConfigurationId === configurationId && ((_existing_stripeConfigurationAccount = existing.stripeConfigurationAccount) != null ? _existing_stripeConfigurationAccount : null) === configurationAccount;
174
179
  if (unchanged) continue;
175
180
  transaction.set(cellularReadersRef().doc(id), next);
176
181
  }
@@ -326,13 +331,15 @@ function cellularReadersRef() {
326
331
  * Turns 4G off at Stripe on a store's Configuration, by its id: for a store
327
332
  * or workspace that is being deleted, whose settings may be gone already.
328
333
  * True when Stripe took it, or the Configuration no longer exists.
329
- */ export async function turnOffPosCellularConfiguration(configurationId) {
334
+ */ export async function turnOffPosCellularConfiguration(configurationId, /** The store's own account the Configuration is on; null for the platform. */ stripeAccount = null) {
330
335
  if (!/^tmc_[A-Za-z0-9]+$/.test(configurationId)) return false;
331
- const answer = await posStripe('POST', `terminal/configurations/${configurationId}`, {
336
+ const answer = await posStripe('POST', `terminal/configurations/${configurationId}`, _extends({
332
337
  params: {
333
338
  'cellular[enabled]': false
334
339
  }
335
- });
340
+ }, stripeAccount ? {
341
+ stripeAccount
342
+ } : {}));
336
343
  return answer.ok || answer.status === 404;
337
344
  }
338
345
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-cellular.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { firebaseAdmin, readOrgBilling } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n closePosCellularPeriod,\n isPosCellularDeviceType,\n openPosCellularPeriod,\n parsePosCellularConfig,\n posCellularReaderId,\n posCellularMonthLabel,\n posCellularReaderMonthlyCents,\n POS_CELLULAR_CHARGES_COLLECTION,\n POS_CELLULAR_READERS_COLLECTION,\n type PosCellularCharge,\n type PosCellularReaderRecord,\n} from '../model/pos-cellular'\nimport type { PosStaff } from './pos-auth'\nimport { posStripe, posTerminalAvailable } from './pos-stripe'\nimport { savePosReaderConfiguration } from './pos-terminal'\n\n/*==========================================\n * TURNING 4G ON AND OFF FOR A STORE (AGL-4038).\n *\n * The POS devices card's \"Turn on 4G\" sets `cellular[enabled]` on the\n * store's ONE Terminal Configuration (`savePosReaderConfiguration`, where\n * tipping, offline mode and the start-up screen also live), so every Stripe\n * Reader S710 at the store has 4G from the next time it connects. See\n * `model/pos-cellular.ts` for why it is per store and what it costs.\n *\n * Each S710 at a store with 4G on has an open period on its\n * `posCellularReaders` record, which is what the month's charge counts\n * (`pos-cellular-billing.ts`). The records follow the store: turning 4G on\n * or off, and adding or removing a reader, re-reads the store's readers and\n * opens or closes each one's period ({@link syncPosCellularReaders}).\n *\n * Turning it on needs the workspace to be billable (a Stripe customer, so a\n * card on file) and the person's agreement to the monthly charge, which the\n * store's terminal settings record with the price they agreed to. It is\n * charged to the workspace, so turning it ON also takes the workspace's\n * \"Manage billing\" key (`billing.manage`) beside the card's \"Registers and\n * devices\"; turning it off takes only the card's key. While a month's charge\n * is unpaid past its grace period (`pos-cellular-billing.ts`), it cannot be\n * turned on again: paying it, then turning it on, is the way back.\n *=========================================*/\n\n/** The workspace key turning 4G on takes, beside \"Registers and devices\". */\nexport const POS_CELLULAR_BILLING_PERMISSION = 'billing.manage'\n\n/** What a member without it is told, naming the permission. */\nexport const POS_CELLULAR_BILLING_REFUSAL =\n 'Your role does not include \"Manage billing\" — ask an organization admin. 4G is charged to the workspace.'\n\n/** Whether the member may turn 4G on for a store: the workspace's \"Manage billing\", resolved for that store. */\nexport async function mayTurnOnPosCellular(uid: string, hostId: string): Promise<boolean> {\n const resolved = await resolveOrgPermissions(uid, { hostId }).catch(() => null)\n return resolved?.permissions?.[POS_CELLULAR_BILLING_PERMISSION] === true\n}\n\n/**\n * A charge's invoice as Stripe has it now: its status and what it collected,\n * or null when Stripe could not be asked (which is never read as \"unpaid\n * long enough to act on\" nor as \"paid\").\n */\nexport async function posCellularInvoiceStatus(\n invoiceId: string,\n): Promise<{ status: string; amountPaidCents: number } | null> {\n if (!/^in_[A-Za-z0-9]+$/.test(invoiceId)) return null\n const answer = await posStripe('GET', `invoices/${invoiceId}`).catch(() => null)\n if (!answer?.ok) return null\n const body = answer.body as { status?: unknown; amount_paid?: unknown }\n const status = String(body.status ?? '')\n return status ? { status, amountPaidCents: Math.max(0, Math.round(Number(body.amount_paid) || 0)) } : null\n}\n\n/**\n * The month whose unpaid charge turned 4G off for the workspace and is STILL\n * unpaid, or null. Asks Stripe about each, so one paid since is settled as\n * paid here, and its stores' notices cleared, rather than waiting for the\n * next daily run.\n */\nexport async function unpaidPosCellularSuspension(\n orgId: string,\n now: number,\n invoiceStatus: (invoiceId: string) => Promise<{ status: string; amountPaidCents: number } | null> = posCellularInvoiceStatus,\n): Promise<{ month: string } | null> {\n const snapshot = await firestore()\n .collection(POS_CELLULAR_CHARGES_COLLECTION)\n .where('orgId', '==', orgId)\n .where('state', '==', 'suspended')\n .limit(24)\n .get()\n for (const doc of snapshot.docs as unknown as Array<{ id: string; data: () => PosCellularCharge }>) {\n const charge = doc.data()\n const invoice = charge.invoiceId ? await invoiceStatus(charge.invoiceId) : null\n if (invoice?.status === 'paid' || invoice?.status === 'void') {\n await settleSuspendedPosCellularCharge(String(doc.id), charge, invoice.status === 'paid' ? 'paid' : 'voided', invoice.amountPaidCents, now)\n continue\n }\n return { month: charge.month }\n }\n return null\n}\n\n/**\n * A suspended month that was paid (or voided by staff): settled, and the\n * notice on each store it turned 4G off for taken down. 4G stays off until\n * the merchant turns it on again.\n */\nexport async function settleSuspendedPosCellularCharge(\n chargeId: string,\n charge: PosCellularCharge,\n state: 'paid' | 'voided',\n paidCents: number,\n now: number,\n): Promise<void> {\n await firestore()\n .collection(POS_CELLULAR_CHARGES_COLLECTION)\n .doc(chargeId)\n .set({ state, ...(state === 'paid' ? { paidCents } : {}), updatedAtMs: now }, { merge: true })\n for (const hostId of charge.suspendedHostIds ?? []) {\n const ref = terminalConfigRef(hostId)\n const terminal = await ref.get()\n const notice = terminal.exists ? (terminal.get('cellularSuspended') as { month?: unknown } | null) : null\n if (notice?.month === charge.month) await ref.set({ cellularSuspended: null }, { merge: true })\n }\n}\n\nfunction firestore() {\n return firebaseAdmin.app().firestore()\n}\n\nfunction terminalConfigRef(hostId: string) {\n return firestore().collection('hosts').doc(hostId).collection('terminal').doc('config')\n}\n\nfunction readersRef(hostId: string) {\n return firestore().collection('hosts').doc(hostId).collection('terminalReaders')\n}\n\nfunction cellularReadersRef() {\n return firestore().collection(POS_CELLULAR_READERS_COLLECTION)\n}\n\nexport interface PosCellularAnswer {\n status: number\n body: { ok: true; enabled: boolean } | { error: string; code?: string }\n}\n\n/**\n * Opens a 4G period for every S710 the store has while 4G is on, and closes\n * every open one that should not be: 4G off, or the reader gone. In one\n * transaction over the store's records, so two calls at once never open a\n * reader twice. Idempotent, and cheap where the store never had 4G: one\n * read of its settings and one of its (empty) records.\n */\nexport async function syncPosCellularReaders(input: {\n hostId: string\n orgId: string\n now?: number\n}): Promise<{ open: number; closed: number }> {\n const now = input.now ?? Date.now()\n const [terminal, readers] = await Promise.all([\n terminalConfigRef(input.hostId).get(),\n readersRef(input.hostId).limit(50).get(),\n ])\n const enabled = terminal.get('cellularEnabled') === true\n const configurationId = String(terminal.get('stripeConfigurationId') ?? '') || null\n const capable = new Map<string, { serialNumber: string | null }>()\n for (const doc of readers.docs as Array<{ id: string; get: (field: string) => unknown }>) {\n if (isPosCellularDeviceType(doc.get('deviceType'))) {\n capable.set(String(doc.id), { serialNumber: String(doc.get('serialNumber') ?? '') || null })\n }\n }\n return firestore().runTransaction(async (transaction: any) => {\n const known = await transaction.get(cellularReadersRef().where('hostId', '==', input.hostId).limit(100))\n const records = new Map<string, PosCellularReaderRecord>()\n for (const doc of known.docs as Array<{ id: string; data: () => PosCellularReaderRecord }>) {\n records.set(String(doc.id), doc.data())\n }\n let open = 0\n let closed = 0\n if (enabled) {\n for (const [readerId, reader] of capable) {\n const id = posCellularReaderId(input.hostId, readerId)\n const existing = records.get(id) ?? null\n const next = openPosCellularPeriod(\n {\n orgId: input.orgId,\n hostId: input.hostId,\n readerId,\n serialNumber: reader.serialNumber,\n stripeConfigurationId: configurationId,\n },\n existing,\n now,\n )\n open += 1\n const unchanged =\n existing?.enabled === true &&\n existing.periods.some((period) => period.toMs === null) &&\n existing.orgId === input.orgId &&\n existing.serialNumber === reader.serialNumber &&\n existing.stripeConfigurationId === configurationId\n if (unchanged) continue\n transaction.set(cellularReadersRef().doc(id), next)\n }\n }\n for (const [id, record] of records) {\n const keep = enabled && capable.has(record.readerId)\n if (keep || !record.enabled) continue\n transaction.set(cellularReadersRef().doc(id), closePosCellularPeriod(record, now))\n closed += 1\n }\n return { open, closed }\n })\n}\n\n/**\n * `cellular` on the card readers route: turns 4G on (`enabled: true`, with\n * `consent: true`) or off for the caller's store. The route has already\n * checked the \"Registers and devices\" key on the store.\n */\nexport async function setPosStoreCellular(\n staff: PosStaff,\n body: Record<string, unknown>,\n): Promise<PosCellularAnswer> {\n const config = parsePosCellularConfig(process.env)\n // Not offered: answered as unknown, the way the card never shows it.\n if (!config || !posTerminalAvailable()) {\n return { status: 404, body: { error: '4G is not available.', code: 'cellular-unavailable' } }\n }\n if (typeof body['enabled'] !== 'boolean') return { status: 400, body: { error: 'Say whether 4G is on or off.' } }\n const enable = body['enabled'] === true\n const terminalRef = terminalConfigRef(staff.hostId)\n const terminal = await terminalRef.get()\n if (!terminal.get('stripeLocationId')) {\n return { status: 409, body: { error: 'Add a card reader to this store first.', code: 'no-location' } }\n }\n if (enable) {\n // Charged to the workspace: its billing key, as well as the card's own.\n if (!(await mayTurnOnPosCellular(staff.uid, staff.hostId))) {\n return { status: 403, body: { error: POS_CELLULAR_BILLING_REFUSAL, code: 'billing-permission' } }\n }\n if (body['consent'] !== true) {\n return {\n status: 400,\n body: { error: 'Agree to the monthly charge for each reader to turn 4G on.', code: 'consent-required' },\n }\n }\n const readers = await readersRef(staff.hostId).limit(50).get()\n const capable = (readers.docs as Array<{ get: (field: string) => unknown }>).some((doc) =>\n isPosCellularDeviceType(doc.get('deviceType')),\n )\n if (!capable) {\n return {\n status: 409,\n body: { error: '4G works on the S710 reader. Add one to this store first.', code: 'no-capable-reader' },\n }\n }\n const billing = (await readOrgBilling(staff.orgId).catch(() => ({}))) as { stripeCustomerId?: unknown }\n if (!String(billing.stripeCustomerId ?? '')) {\n return {\n status: 409,\n body: {\n error: 'Add a payment method in Billing first: 4G is charged to this workspace each month.',\n code: 'no-billing',\n },\n }\n }\n // Turned off for an unpaid month: paid first, then on again.\n const unpaid = await unpaidPosCellularSuspension(staff.orgId, Date.now())\n if (unpaid) {\n return {\n status: 409,\n body: {\n error: `4G was turned off because the 4G charge for ${posCellularMonthLabel(unpaid.month)} wasn't paid. Pay it on the Billing page, then turn 4G on again.`,\n code: 'cellular-unpaid',\n },\n }\n }\n }\n const already =\n (terminal.get('cellularEnabled') === true) === enable &&\n (!enable || terminal.get('cellularConfigurationId') === terminal.get('stripeConfigurationId'))\n const now = Date.now()\n if (!already) {\n // Each direction keys its own first create: one key sent with other\n // parameters is refused by Stripe for a day.\n const saved = await savePosReaderConfiguration(\n staff.hostId,\n { 'cellular[enabled]': enable },\n enable ? 'cellular-on' : 'cellular-off',\n )\n if ('error' in saved) {\n console.error('[pos-cellular] Stripe refused the cellular setting', staff.hostId, saved.error)\n return {\n status: 502,\n body: { error: enable ? 'Stripe did not turn 4G on. Try again.' : 'Stripe did not turn 4G off. Try again.' },\n }\n }\n await terminalRef.set(\n {\n cellularEnabled: enable,\n cellularConfigurationId: saved.configurationId,\n cellularChangedAtMs: now,\n cellularChangedBy: staff.uid,\n // What they agreed to, and when: the price per reader at the time.\n ...(enable ? { cellularConsent: { atMs: now, uid: staff.uid, readerMonthlyCents: posCellularReaderMonthlyCents(config) } } : {}),\n // On again: the notice of an unpaid month that turned it off is done.\n ...(enable ? { cellularSuspended: null } : {}),\n },\n { merge: true },\n )\n }\n await syncPosCellularReaders({ hostId: staff.hostId, orgId: staff.orgId, now })\n return { status: 200, body: { ok: true, enabled: enable } }\n}\n\n/**\n * Turns 4G off at Stripe on a store's Configuration, by its id: for a store\n * or workspace that is being deleted, whose settings may be gone already.\n * True when Stripe took it, or the Configuration no longer exists.\n */\nexport async function turnOffPosCellularConfiguration(configurationId: string): Promise<boolean> {\n if (!/^tmc_[A-Za-z0-9]+$/.test(configurationId)) return false\n const answer = await posStripe('POST', `terminal/configurations/${configurationId}`, {\n params: { 'cellular[enabled]': false },\n })\n return answer.ok || answer.status === 404\n}\n"],"names":["firebaseAdmin","readOrgBilling","resolveOrgPermissions","closePosCellularPeriod","isPosCellularDeviceType","openPosCellularPeriod","parsePosCellularConfig","posCellularReaderId","posCellularMonthLabel","posCellularReaderMonthlyCents","POS_CELLULAR_CHARGES_COLLECTION","POS_CELLULAR_READERS_COLLECTION","posStripe","posTerminalAvailable","savePosReaderConfiguration","POS_CELLULAR_BILLING_PERMISSION","POS_CELLULAR_BILLING_REFUSAL","mayTurnOnPosCellular","uid","hostId","resolved","catch","permissions","posCellularInvoiceStatus","invoiceId","body","test","answer","ok","status","String","amountPaidCents","Math","max","round","Number","amount_paid","unpaidPosCellularSuspension","orgId","now","invoiceStatus","snapshot","firestore","collection","where","limit","get","doc","docs","charge","data","invoice","settleSuspendedPosCellularCharge","id","month","chargeId","state","paidCents","set","updatedAtMs","merge","suspendedHostIds","ref","terminalConfigRef","terminal","notice","exists","cellularSuspended","app","readersRef","cellularReadersRef","syncPosCellularReaders","input","Date","readers","Promise","all","enabled","configurationId","capable","Map","serialNumber","runTransaction","transaction","known","records","open","closed","readerId","reader","existing","next","stripeConfigurationId","unchanged","periods","some","period","toMs","record","keep","has","setPosStoreCellular","staff","config","process","env","error","code","enable","terminalRef","billing","stripeCustomerId","unpaid","already","saved","console","cellularEnabled","cellularConfigurationId","cellularChangedAtMs","cellularChangedBy","cellularConsent","atMs","readerMonthlyCents","turnOffPosCellularConfiguration","params"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,EAAEC,cAAc,QAAQ,2BAA0B;AACxE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,sBAAsB,EACtBC,uBAAuB,EACvBC,qBAAqB,EACrBC,sBAAsB,EACtBC,mBAAmB,EACnBC,qBAAqB,EACrBC,6BAA6B,EAC7BC,+BAA+B,EAC/BC,+BAA+B,QAG1B,2BAAuB;AAE9B,SAASC,SAAS,EAAEC,oBAAoB,QAAQ,kBAAc;AAC9D,SAASC,0BAA0B,QAAQ,oBAAgB;AAE3D;;;;;;;;;;;;;;;;;;;;;;;2CAuB2C,GAE3C,2EAA2E,GAC3E,OAAO,MAAMC,kCAAkC,iBAAgB;AAE/D,6DAA6D,GAC7D,OAAO,MAAMC,+BACX,2GAA0G;AAE5G,8GAA8G,GAC9G,OAAO,eAAeC,qBAAqBC,GAAW,EAAEC,MAAc;QAE7DC;IADP,MAAMA,WAAW,MAAMlB,sBAAsBgB,KAAK;QAAEC;IAAO,GAAGE,KAAK,CAAC,IAAM;IAC1E,OAAOD,CAAAA,6BAAAA,wBAAAA,SAAUE,WAAW,qBAArBF,qBAAuB,CAACL,gCAAgC,MAAK;AACtE;AAEA;;;;CAIC,GACD,OAAO,eAAeQ,yBACpBC,SAAiB;QAMKC;IAJtB,IAAI,CAAC,oBAAoBC,IAAI,CAACF,YAAY,OAAO;IACjD,MAAMG,SAAS,MAAMf,UAAU,OAAO,CAAC,SAAS,EAAEY,WAAW,EAAEH,KAAK,CAAC,IAAM;IAC3E,IAAI,EAACM,0BAAAA,OAAQC,EAAE,GAAE,OAAO;IACxB,MAAMH,OAAOE,OAAOF,IAAI;IACxB,MAAMI,SAASC,QAAOL,eAAAA,KAAKI,MAAM,YAAXJ,eAAe;IAC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AAI,WAAWM,OAAO;YACpBC,QAAQT,KAAK,CAAC,sDAAsDJ,MAAMnF,MAAM,EAAE+F,MAAMR,KAAK;YAC7F,OAAO;gBACL7E,QAAQ;gBACRJ,MAAM;oBAAEiF,OAAOE,SAAS,0CAA0C;gBAAyC;YAC7G;QACF;QACA,MAAMC,YAAYnD,GAAG,CACnB;YACE0D,iBAAiBR;YACjBS,yBAAyBH,MAAMpC,eAAe;YAC9CwC,qBAAqB/E;YACrBgF,mBAAmBjB,MAAMpF,GAAG;WAExB0F,SAAS;YAAEY,iBAAiB;gBAAEC,MAAMlF;gBAAKrB,KAAKoF,MAAMpF,GAAG;gBAAEwG,oBAAoBjH,8BAA8B8F;YAAQ;QAAE,IAAI,CAAC,GAE1HK,SAAS;YAAEzC,mBAAmB;QAAK,IAAI,CAAC,IAE9C;YAAEP,OAAO;QAAK;IAElB;IACA,MAAMW,uBAAuB;QAAEpD,QAAQmF,MAAMnF,MAAM;QAAEmB,OAAOgE,MAAMhE,KAAK;QAAEC;IAAI;IAC7E,OAAO;QAAEV,QAAQ;QAAKJ,MAAM;YAAEG,IAAI;YAAMiD,SAAS+B;QAAO;IAAE;AAC5D;AAEA;;;;CAIC,GACD,OAAO,eAAee,gCAAgC7C,eAAuB;IAC3E,IAAI,CAAC,qBAAqBpD,IAAI,CAACoD,kBAAkB,OAAO;IACxD,MAAMnD,SAAS,MAAMf,UAAU,QAAQ,CAAC,wBAAwB,EAAEkE,iBAAiB,EAAE;QACnF8C,QAAQ;YAAE,qBAAqB;QAAM;IACvC;IACA,OAAOjG,OAAOC,EAAE,IAAID,OAAOE,MAAM,KAAK;AACxC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-cellular.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { firebaseAdmin, readOrgBilling } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n closePosCellularPeriod,\n isPosCellularDeviceType,\n openPosCellularPeriod,\n parsePosCellularConfig,\n posCellularReaderId,\n posCellularMonthLabel,\n posCellularReaderMonthlyCents,\n POS_CELLULAR_CHARGES_COLLECTION,\n POS_CELLULAR_READERS_COLLECTION,\n type PosCellularCharge,\n type PosCellularReaderRecord,\n} from '../model/pos-cellular'\nimport type { PosStaff } from './pos-auth'\nimport { posStripe, posTerminalAvailable } from './pos-stripe'\nimport { savePosReaderConfiguration } from './pos-terminal'\n\n/*==========================================\n * TURNING 4G ON AND OFF FOR A STORE (AGL-4038).\n *\n * The POS devices card's \"Turn on 4G\" sets `cellular[enabled]` on the\n * store's ONE Terminal Configuration (`savePosReaderConfiguration`, where\n * tipping, offline mode and the start-up screen also live), so every Stripe\n * Reader S710 at the store has 4G from the next time it connects. See\n * `model/pos-cellular.ts` for why it is per store and what it costs.\n *\n * Each S710 at a store with 4G on has an open period on its\n * `posCellularReaders` record, which is what the month's charge counts\n * (`pos-cellular-billing.ts`). The records follow the store: turning 4G on\n * or off, and adding or removing a reader, re-reads the store's readers and\n * opens or closes each one's period ({@link syncPosCellularReaders}).\n *\n * Turning it on needs the workspace to be billable (a Stripe customer, so a\n * card on file) and the person's agreement to the monthly charge, which the\n * store's terminal settings record with the price they agreed to. It is\n * charged to the workspace, so turning it ON also takes the workspace's\n * \"Manage billing\" key (`billing.manage`) beside the card's \"Registers and\n * devices\"; turning it off takes only the card's key. While a month's charge\n * is unpaid past its grace period (`pos-cellular-billing.ts`), it cannot be\n * turned on again: paying it, then turning it on, is the way back.\n *=========================================*/\n\n/** The workspace key turning 4G on takes, beside \"Registers and devices\". */\nexport const POS_CELLULAR_BILLING_PERMISSION = 'billing.manage'\n\n/** What a member without it is told, naming the permission. */\nexport const POS_CELLULAR_BILLING_REFUSAL =\n 'Your role does not include \"Manage billing\" — ask an organization admin. 4G is charged to the workspace.'\n\n/** Whether the member may turn 4G on for a store: the workspace's \"Manage billing\", resolved for that store. */\nexport async function mayTurnOnPosCellular(uid: string, hostId: string): Promise<boolean> {\n const resolved = await resolveOrgPermissions(uid, { hostId }).catch(() => null)\n return resolved?.permissions?.[POS_CELLULAR_BILLING_PERMISSION] === true\n}\n\n/**\n * A charge's invoice as Stripe has it now: its status and what it collected,\n * or null when Stripe could not be asked (which is never read as \"unpaid\n * long enough to act on\" nor as \"paid\").\n */\nexport async function posCellularInvoiceStatus(\n invoiceId: string,\n): Promise<{ status: string; amountPaidCents: number } | null> {\n if (!/^in_[A-Za-z0-9]+$/.test(invoiceId)) return null\n const answer = await posStripe('GET', `invoices/${invoiceId}`).catch(() => null)\n if (!answer?.ok) return null\n const body = answer.body as { status?: unknown; amount_paid?: unknown }\n const status = String(body.status ?? '')\n return status ? { status, amountPaidCents: Math.max(0, Math.round(Number(body.amount_paid) || 0)) } : null\n}\n\n/**\n * The month whose unpaid charge turned 4G off for the workspace and is STILL\n * unpaid, or null. Asks Stripe about each, so one paid since is settled as\n * paid here, and its stores' notices cleared, rather than waiting for the\n * next daily run.\n */\nexport async function unpaidPosCellularSuspension(\n orgId: string,\n now: number,\n invoiceStatus: (invoiceId: string) => Promise<{ status: string; amountPaidCents: number } | null> = posCellularInvoiceStatus,\n): Promise<{ month: string } | null> {\n const snapshot = await firestore()\n .collection(POS_CELLULAR_CHARGES_COLLECTION)\n .where('orgId', '==', orgId)\n .where('state', '==', 'suspended')\n .limit(24)\n .get()\n for (const doc of snapshot.docs as unknown as Array<{ id: string; data: () => PosCellularCharge }>) {\n const charge = doc.data()\n const invoice = charge.invoiceId ? await invoiceStatus(charge.invoiceId) : null\n if (invoice?.status === 'paid' || invoice?.status === 'void') {\n await settleSuspendedPosCellularCharge(String(doc.id), charge, invoice.status === 'paid' ? 'paid' : 'voided', invoice.amountPaidCents, now)\n continue\n }\n return { month: charge.month }\n }\n return null\n}\n\n/**\n * A suspended month that was paid (or voided by staff): settled, and the\n * notice on each store it turned 4G off for taken down. 4G stays off until\n * the merchant turns it on again.\n */\nexport async function settleSuspendedPosCellularCharge(\n chargeId: string,\n charge: PosCellularCharge,\n state: 'paid' | 'voided',\n paidCents: number,\n now: number,\n): Promise<void> {\n await firestore()\n .collection(POS_CELLULAR_CHARGES_COLLECTION)\n .doc(chargeId)\n .set({ state, ...(state === 'paid' ? { paidCents } : {}), updatedAtMs: now }, { merge: true })\n for (const hostId of charge.suspendedHostIds ?? []) {\n const ref = terminalConfigRef(hostId)\n const terminal = await ref.get()\n const notice = terminal.exists ? (terminal.get('cellularSuspended') as { month?: unknown } | null) : null\n if (notice?.month === charge.month) await ref.set({ cellularSuspended: null }, { merge: true })\n }\n}\n\nfunction firestore() {\n return firebaseAdmin.app().firestore()\n}\n\nfunction terminalConfigRef(hostId: string) {\n return firestore().collection('hosts').doc(hostId).collection('terminal').doc('config')\n}\n\nfunction readersRef(hostId: string) {\n return firestore().collection('hosts').doc(hostId).collection('terminalReaders')\n}\n\nfunction cellularReadersRef() {\n return firestore().collection(POS_CELLULAR_READERS_COLLECTION)\n}\n\nexport interface PosCellularAnswer {\n status: number\n body: { ok: true; enabled: boolean } | { error: string; code?: string }\n}\n\n/**\n * Opens a 4G period for every S710 the store has while 4G is on, and closes\n * every open one that should not be: 4G off, or the reader gone. In one\n * transaction over the store's records, so two calls at once never open a\n * reader twice. Idempotent, and cheap where the store never had 4G: one\n * read of its settings and one of its (empty) records.\n */\nexport async function syncPosCellularReaders(input: {\n hostId: string\n orgId: string\n now?: number\n}): Promise<{ open: number; closed: number }> {\n const now = input.now ?? Date.now()\n const [terminal, readers] = await Promise.all([\n terminalConfigRef(input.hostId).get(),\n readersRef(input.hostId).limit(50).get(),\n ])\n const enabled = terminal.get('cellularEnabled') === true\n const configurationId = String(terminal.get('stripeConfigurationId') ?? '') || null\n // The account that configuration lives on: the store's own for a\n // direct-charge store's Location, absent for the platform's.\n const configurationAccount = String(terminal.get('stripeLocationAccount') ?? '').trim() || null\n const capable = new Map<string, { serialNumber: string | null }>()\n for (const doc of readers.docs as Array<{ id: string; get: (field: string) => unknown }>) {\n if (isPosCellularDeviceType(doc.get('deviceType'))) {\n capable.set(String(doc.id), { serialNumber: String(doc.get('serialNumber') ?? '') || null })\n }\n }\n return firestore().runTransaction(async (transaction: any) => {\n const known = await transaction.get(cellularReadersRef().where('hostId', '==', input.hostId).limit(100))\n const records = new Map<string, PosCellularReaderRecord>()\n for (const doc of known.docs as Array<{ id: string; data: () => PosCellularReaderRecord }>) {\n records.set(String(doc.id), doc.data())\n }\n let open = 0\n let closed = 0\n if (enabled) {\n for (const [readerId, reader] of capable) {\n const id = posCellularReaderId(input.hostId, readerId)\n const existing = records.get(id) ?? null\n const next = openPosCellularPeriod(\n {\n orgId: input.orgId,\n hostId: input.hostId,\n readerId,\n serialNumber: reader.serialNumber,\n stripeConfigurationId: configurationId,\n ...(configurationAccount ? { stripeConfigurationAccount: configurationAccount } : {}),\n },\n existing,\n now,\n )\n open += 1\n const unchanged =\n existing?.enabled === true &&\n existing.periods.some((period) => period.toMs === null) &&\n existing.orgId === input.orgId &&\n existing.serialNumber === reader.serialNumber &&\n existing.stripeConfigurationId === configurationId &&\n (existing.stripeConfigurationAccount ?? null) === configurationAccount\n if (unchanged) continue\n transaction.set(cellularReadersRef().doc(id), next)\n }\n }\n for (const [id, record] of records) {\n const keep = enabled && capable.has(record.readerId)\n if (keep || !record.enabled) continue\n transaction.set(cellularReadersRef().doc(id), closePosCellularPeriod(record, now))\n closed += 1\n }\n return { open, closed }\n })\n}\n\n/**\n * `cellular` on the card readers route: turns 4G on (`enabled: true`, with\n * `consent: true`) or off for the caller's store. The route has already\n * checked the \"Registers and devices\" key on the store.\n */\nexport async function setPosStoreCellular(\n staff: PosStaff,\n body: Record<string, unknown>,\n): Promise<PosCellularAnswer> {\n const config = parsePosCellularConfig(process.env)\n // Not offered: answered as unknown, the way the card never shows it.\n if (!config || !posTerminalAvailable()) {\n return { status: 404, body: { error: '4G is not available.', code: 'cellular-unavailable' } }\n }\n if (typeof body['enabled'] !== 'boolean') return { status: 400, body: { error: 'Say whether 4G is on or off.' } }\n const enable = body['enabled'] === true\n const terminalRef = terminalConfigRef(staff.hostId)\n const terminal = await terminalRef.get()\n if (!terminal.get('stripeLocationId')) {\n return { status: 409, body: { error: 'Add a card reader to this store first.', code: 'no-location' } }\n }\n if (enable) {\n // Charged to the workspace: its billing key, as well as the card's own.\n if (!(await mayTurnOnPosCellular(staff.uid, staff.hostId))) {\n return { status: 403, body: { error: POS_CELLULAR_BILLING_REFUSAL, code: 'billing-permission' } }\n }\n if (body['consent'] !== true) {\n return {\n status: 400,\n body: { error: 'Agree to the monthly charge for each reader to turn 4G on.', code: 'consent-required' },\n }\n }\n const readers = await readersRef(staff.hostId).limit(50).get()\n const capable = (readers.docs as Array<{ get: (field: string) => unknown }>).some((doc) =>\n isPosCellularDeviceType(doc.get('deviceType')),\n )\n if (!capable) {\n return {\n status: 409,\n body: { error: '4G works on the S710 reader. Add one to this store first.', code: 'no-capable-reader' },\n }\n }\n const billing = (await readOrgBilling(staff.orgId).catch(() => ({}))) as { stripeCustomerId?: unknown }\n if (!String(billing.stripeCustomerId ?? '')) {\n return {\n status: 409,\n body: {\n error: 'Add a payment method in Billing first: 4G is charged to this workspace each month.',\n code: 'no-billing',\n },\n }\n }\n // Turned off for an unpaid month: paid first, then on again.\n const unpaid = await unpaidPosCellularSuspension(staff.orgId, Date.now())\n if (unpaid) {\n return {\n status: 409,\n body: {\n error: `4G was turned off because the 4G charge for ${posCellularMonthLabel(unpaid.month)} wasn't paid. Pay it on the Billing page, then turn 4G on again.`,\n code: 'cellular-unpaid',\n },\n }\n }\n }\n const already =\n (terminal.get('cellularEnabled') === true) === enable &&\n (!enable || terminal.get('cellularConfigurationId') === terminal.get('stripeConfigurationId'))\n const now = Date.now()\n if (!already) {\n // Each direction keys its own first create: one key sent with other\n // parameters is refused by Stripe for a day.\n const saved = await savePosReaderConfiguration(\n staff.hostId,\n { 'cellular[enabled]': enable },\n enable ? 'cellular-on' : 'cellular-off',\n )\n if ('error' in saved) {\n console.error('[pos-cellular] Stripe refused the cellular setting', staff.hostId, saved.error)\n return {\n status: 502,\n body: { error: enable ? 'Stripe did not turn 4G on. Try again.' : 'Stripe did not turn 4G off. Try again.' },\n }\n }\n await terminalRef.set(\n {\n cellularEnabled: enable,\n cellularConfigurationId: saved.configurationId,\n cellularChangedAtMs: now,\n cellularChangedBy: staff.uid,\n // What they agreed to, and when: the price per reader at the time.\n ...(enable ? { cellularConsent: { atMs: now, uid: staff.uid, readerMonthlyCents: posCellularReaderMonthlyCents(config) } } : {}),\n // On again: the notice of an unpaid month that turned it off is done.\n ...(enable ? { cellularSuspended: null } : {}),\n },\n { merge: true },\n )\n }\n await syncPosCellularReaders({ hostId: staff.hostId, orgId: staff.orgId, now })\n return { status: 200, body: { ok: true, enabled: enable } }\n}\n\n/**\n * Turns 4G off at Stripe on a store's Configuration, by its id: for a store\n * or workspace that is being deleted, whose settings may be gone already.\n * True when Stripe took it, or the Configuration no longer exists.\n */\nexport async function turnOffPosCellularConfiguration(\n configurationId: string,\n /** The store's own account the Configuration is on; null for the platform. */\n stripeAccount: string | null = null,\n): Promise<boolean> {\n if (!/^tmc_[A-Za-z0-9]+$/.test(configurationId)) return false\n const answer = await posStripe('POST', `terminal/configurations/${configurationId}`, {\n params: { 'cellular[enabled]': false },\n ...(stripeAccount ? { stripeAccount } : {}),\n })\n return answer.ok || answer.status === 404\n}\n"],"names":["firebaseAdmin","readOrgBilling","resolveOrgPermissions","closePosCellularPeriod","isPosCellularDeviceType","openPosCellularPeriod","parsePosCellularConfig","posCellularReaderId","posCellularMonthLabel","posCellularReaderMonthlyCents","POS_CELLULAR_CHARGES_COLLECTION","POS_CELLULAR_READERS_COLLECTION","posStripe","posTerminalAvailable","savePosReaderConfiguration","POS_CELLULAR_BILLING_PERMISSION","POS_CELLULAR_BILLING_REFUSAL","mayTurnOnPosCellular","uid","hostId","resolved","catch","permissions","posCellularInvoiceStatus","invoiceId","body","test","answer","ok","status","String","amountPaidCents","Math","max","round","Number","amount_paid","unpaidPosCellularSuspension","orgId","now","invoiceStatus","snapshot","firestore","collection","where","limit","get","doc","docs","charge","data","invoice","settleSuspendedPosCellularCharge","id","month","chargeId","state","paidCents","set","updatedAtMs","merge","suspendedHostIds","ref","terminalConfigRef","terminal","notice","exists","cellularSuspended","app","readersRef","cellularReadersRef","syncPosCellularReaders","input","Date","readers","Promise","all","enabled","configurationId","configurationAccount","trim","capable","Map","serialNumber","runTransaction","transaction","known","records","open","closed","readerId","reader","existing","next","stripeConfigurationId","stripeConfigurationAccount","unchanged","periods","some","period","toMs","record","keep","has","setPosStoreCellular","staff","config","process","env","error","code","enable","terminalRef","billing","stripeCustomerId","unpaid","already","saved","console","cellularEnabled","cellularConfigurationId","cellularChangedAtMs","cellularChangedBy","cellularConsent","atMs","readerMonthlyCents","turnOffPosCellularConfiguration","stripeAccount","params"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,EAAEC,cAAc,QAAQ,2BAA0B;AACxE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,sBAAsB,EACtBC,uBAAuB,EACvBC,qBAAqB,EACrBC,sBAAsB,EACtBC,mBAAmB,EACnBC,qBAAqB,EACrBC,6BAA6B,EAC7BC,+BAA+B,EAC/BC,+BAA+B,QAG1B,2BAAuB;AAE9B,SAASC,SAAS,EAAEC,oBAAoB,QAAQ,kBAAc;AAC9D,SAASC,0BAA0B,QAAQ,oBAAgB;AAE3D;;;;;;;;;;;;;;;;;;;;;;;2CAuB2C,GAE3C,2EAA2E,GAC3E,OAAO,MAAMC,kCAAkC,i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vF,GAAG;WAExB6F,SAAS;YAAEY,iBAAiB;gBAAEC,MAAMrF;gBAAKrB,KAAKuF,MAAMvF,GAAG;gBAAE2G,oBAAoBpH,8BAA8BiG;YAAQ;QAAE,IAAI,CAAC,GAE1HK,SAAS;YAAE5C,mBAAmB;QAAK,IAAI,CAAC,IAE9C;YAAEP,OAAO;QAAK;IAElB;IACA,MAAMW,uBAAuB;QAAEpD,QAAQsF,MAAMtF,MAAM;QAAEmB,OAAOmE,MAAMnE,KAAK;QAAEC;IAAI;IAC7E,OAAO;QAAEV,QAAQ;QAAKJ,MAAM;YAAEG,IAAI;YAAMiD,SAASkC;QAAO;IAAE;AAC5D;AAEA;;;;CAIC,GACD,OAAO,eAAee,gCACpBhD,eAAuB,EACvB,4EAA4E,GAC5EiD,gBAA+B,IAAI;IAEnC,IAAI,CAAC,qBAAqBrG,IAAI,CAACoD,kBAAkB,OAAO;IACxD,MAAMnD,SAAS,MAAMf,UAAU,QAAQ,CAAC,wBAAwB,EAAEkE,iBAAiB,EAAE;QACnFkD,QAAQ;YAAE,qBAAqB;QAAM;OACjCD,gBAAgB;QAAEA;IAAc,IAAI,CAAC;IAE3C,OAAOpG,OAAOC,EAAE,IAAID,OAAOE,MAAM,KAAK;AACxC"}
@@ -19,7 +19,7 @@ import type { PluginApiHandler, PluginApiRequest } from '@aglyn/aglyn/server';
19
19
  import * as CommerceModel from '../model';
20
20
  import { type PosOfflineFlag, type PosOfflineKit, type PosOfflineStockConflict } from '../model/commerce-pos-offline';
21
21
  import { type PosOpsDeps, type PosOpsStaff } from './pos-ops-gate';
22
- import { type PosOfflineCardIntent } from './pos-terminal';
22
+ import { type PosMerchant, type PosOfflineCardIntent } from './pos-terminal';
23
23
  import { type StockDecrementOutcome } from './reserve-stock';
24
24
  /** The register's sync record: no customer data, only what dedupe and resume need. */
25
25
  export interface PosOfflineSyncRecord {
@@ -74,8 +74,8 @@ export interface PosOfflineCardDeps {
74
74
  available: boolean;
75
75
  locationId: string | null;
76
76
  }>;
77
- /** The merchant's connected account, when it can take card payments. */
78
- merchantAccount(hostId: string, org: Record<string, any> | null): Promise<string | null>;
77
+ /** The merchant's connected account and how it sells, when it can take card payments. */
78
+ merchantAccount(hostId: string, org: Record<string, any> | null): Promise<PosMerchant | null>;
79
79
  /** Turns Stripe's offline mode on for the site's readers; false when Stripe refused. */
80
80
  enableOffline(hostId: string): Promise<boolean>;
81
81
  retrieve(paymentIntentId: string): Promise<{
@@ -256,8 +256,16 @@ async function readStoreTax(staff) {
256
256
  const terminal = await deps.card.terminal(staff.hostId);
257
257
  if (!terminal.available) return off('Card readers are not set up for this store yet.');
258
258
  if (!terminal.locationId) return off('Connect a card reader once while online, then cards keep working offline.');
259
- const destination = await deps.card.merchantAccount(staff.hostId, staff.org);
260
- if (!destination) return off('Finish connecting Stripe to take cards.');
259
+ const merchant = await deps.card.merchantAccount(staff.hostId, staff.org);
260
+ if (!merchant) return off('Finish connecting Stripe to take cards.');
261
+ // The app makes an offline card's intent itself, as a DESTINATION charge
262
+ // to `destination`. A store selling on its own Stripe account needs the
263
+ // intent made on that account with no transfer at all, which the app does
264
+ // not do yet: offline cards stay off there rather than fail at the counter.
265
+ if (merchant.chargeModel === 'direct') {
266
+ return off('Card sales offline are not available for this store’s payment account yet. Take cards while online.');
267
+ }
268
+ const destination = merchant.accountId;
261
269
  if (!await deps.card.enableOffline(staff.hostId)) {
262
270
  return off('Card sales offline could not be turned on for this store’s readers yet. Try again later.');
263
271
  }
@@ -348,11 +356,16 @@ async function readStoreTax(staff) {
348
356
  // or a register tampered with. Money that holds or has moved is only ever
349
357
  // captured into, or recorded as paid to, the store's account as it is now.
350
358
  if (INTENT_HOLDS_MONEY.has(intent.status)) {
351
- const expected = await deps.card.merchantAccount(staff.hostId, staff.org);
359
+ var _ref;
360
+ const merchant = await deps.card.merchantAccount(staff.hostId, staff.org);
361
+ // A direct-charge store is offered no offline kit, so an intent the app
362
+ // made out to a destination is never its account's money: it reads as
363
+ // made out elsewhere, like a kit gone stale.
364
+ const expected = (_ref = merchant == null ? void 0 : merchant.accountId) != null ? _ref : null;
352
365
  if (!expected) {
353
366
  return wait('This store’s Stripe account cannot take card payments right now. The card syncs once it can.');
354
367
  }
355
- if (intent.destination !== expected) {
368
+ if ((merchant == null ? void 0 : merchant.chargeModel) === 'direct' || intent.destination !== expected) {
356
369
  return _extends({
357
370
  kind: 'unpaid',
358
371
  flag: 'card-not-charged',