@aglyn/plugins-commerce 1.0.0-beta.232 → 1.0.0-beta.233

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 (228) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/cart-extras.d.ts +6 -0
  3. package/src/lib/components/cart-extras.js +4 -1
  4. package/src/lib/components/cart-extras.js.map +1 -1
  5. package/src/lib/components/cart-fulfillment.d.ts +117 -0
  6. package/src/lib/components/cart-fulfillment.js +367 -0
  7. package/src/lib/components/cart-fulfillment.js.map +1 -0
  8. package/src/lib/components/cart.js +52 -10
  9. package/src/lib/components/cart.js.map +1 -1
  10. package/src/lib/components/commerce-console-page.js +42 -1
  11. package/src/lib/components/commerce-console-page.js.map +1 -1
  12. package/src/lib/components/console/host-orders-card.component.js +38 -10
  13. package/src/lib/components/console/host-orders-card.component.js.map +1 -1
  14. package/src/lib/components/console/local-delivery-settings-card.component.d.ts +37 -0
  15. package/src/lib/components/console/local-delivery-settings-card.component.js +542 -0
  16. package/src/lib/components/console/local-delivery-settings-card.component.js.map +1 -0
  17. package/src/lib/components/console/locations-card.component.js +177 -3
  18. package/src/lib/components/console/locations-card.component.js.map +1 -1
  19. package/src/lib/components/console/order-detail-dialog.component.js +10 -0
  20. package/src/lib/components/console/order-detail-dialog.component.js.map +1 -1
  21. package/src/lib/components/console/order-local-fulfillment-panel.component.d.ts +44 -0
  22. package/src/lib/components/console/order-local-fulfillment-panel.component.js +265 -0
  23. package/src/lib/components/console/order-local-fulfillment-panel.component.js.map +1 -0
  24. package/src/lib/components/console/order-offline-notice.component.d.ts +12 -0
  25. package/src/lib/components/console/order-offline-notice.component.js +53 -0
  26. package/src/lib/components/console/order-offline-notice.component.js.map +1 -0
  27. package/src/lib/components/console/pickup-delivery-queue-card.component.d.ts +35 -0
  28. package/src/lib/components/console/pickup-delivery-queue-card.component.js +222 -0
  29. package/src/lib/components/console/pickup-delivery-queue-card.component.js.map +1 -0
  30. package/src/lib/components/console/pos/pos-api.d.ts +24 -1
  31. package/src/lib/components/console/pos/pos-api.js +13 -0
  32. package/src/lib/components/console/pos/pos-api.js.map +1 -1
  33. package/src/lib/components/console/pos/pos-item-dialog.component.d.ts +12 -0
  34. package/src/lib/components/console/pos/pos-item-dialog.component.js +10 -8
  35. package/src/lib/components/console/pos/pos-item-dialog.component.js.map +1 -1
  36. package/src/lib/components/console/pos/pos-kiosk-queue.component.d.ts +22 -0
  37. package/src/lib/components/console/pos/pos-kiosk-queue.component.js +168 -0
  38. package/src/lib/components/console/pos/pos-kiosk-queue.component.js.map +1 -0
  39. package/src/lib/components/console/pos/pos-tender-dialogs.component.d.ts +18 -0
  40. package/src/lib/components/console/pos/pos-tender-dialogs.component.js +116 -1
  41. package/src/lib/components/console/pos/pos-tender-dialogs.component.js.map +1 -1
  42. package/src/lib/components/console/pos/pos-tender-panel.component.d.ts +8 -0
  43. package/src/lib/components/console/pos/pos-tender-panel.component.js +77 -18
  44. package/src/lib/components/console/pos/pos-tender-panel.component.js.map +1 -1
  45. package/src/lib/components/console/pos/use-pos-display.d.ts +5 -2
  46. package/src/lib/components/console/pos/use-pos-display.js +3 -2
  47. package/src/lib/components/console/pos/use-pos-display.js.map +1 -1
  48. package/src/lib/components/console/pos-devices-card.component.js +2 -2
  49. package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
  50. package/src/lib/components/console/pos-display/pairing-screen.d.ts +5 -2
  51. package/src/lib/components/console/pos-display/pairing-screen.js +7 -5
  52. package/src/lib/components/console/pos-display/pairing-screen.js.map +1 -1
  53. package/src/lib/components/console/pos-display/pos-display-api.d.ts +7 -1
  54. package/src/lib/components/console/pos-display/pos-display-api.js +7 -2
  55. package/src/lib/components/console/pos-display/pos-display-api.js.map +1 -1
  56. package/src/lib/components/console/pos-kiosk/kiosk-checkout.d.ts +41 -0
  57. package/src/lib/components/console/pos-kiosk/kiosk-checkout.js +275 -0
  58. package/src/lib/components/console/pos-kiosk/kiosk-checkout.js.map +1 -0
  59. package/src/lib/components/console/pos-kiosk/kiosk-menu.d.ts +32 -0
  60. package/src/lib/components/console/pos-kiosk/kiosk-menu.js +344 -0
  61. package/src/lib/components/console/pos-kiosk/kiosk-menu.js.map +1 -0
  62. package/src/lib/components/console/pos-kiosk/kiosk-staff.d.ts +12 -0
  63. package/src/lib/components/console/pos-kiosk/kiosk-staff.js +257 -0
  64. package/src/lib/components/console/pos-kiosk/kiosk-staff.js.map +1 -0
  65. package/src/lib/components/console/pos-kiosk/pos-kiosk-api.d.ts +114 -0
  66. package/src/lib/components/console/pos-kiosk/pos-kiosk-api.js +189 -0
  67. package/src/lib/components/console/pos-kiosk/pos-kiosk-api.js.map +1 -0
  68. package/src/lib/components/console/pos-kiosk/use-kiosk-idle.d.ts +16 -0
  69. package/src/lib/components/console/pos-kiosk/use-kiosk-idle.js +80 -0
  70. package/src/lib/components/console/pos-kiosk/use-kiosk-idle.js.map +1 -0
  71. package/src/lib/components/console/pos-kiosk-page.component.d.ts +28 -0
  72. package/src/lib/components/console/pos-kiosk-page.component.js +791 -0
  73. package/src/lib/components/console/pos-kiosk-page.component.js.map +1 -0
  74. package/src/lib/components/console/pos-offline/pos-offline-api.d.ts +44 -0
  75. package/src/lib/components/console/pos-offline/pos-offline-api.js +69 -0
  76. package/src/lib/components/console/pos-offline/pos-offline-api.js.map +1 -0
  77. package/src/lib/components/console/pos-offline/pos-offline-banner.component.d.ts +7 -0
  78. package/src/lib/components/console/pos-offline/pos-offline-banner.component.js +135 -0
  79. package/src/lib/components/console/pos-offline/pos-offline-banner.component.js.map +1 -0
  80. package/src/lib/components/console/pos-offline/pos-offline-checkout.component.d.ts +32 -0
  81. package/src/lib/components/console/pos-offline/pos-offline-checkout.component.js +287 -0
  82. package/src/lib/components/console/pos-offline/pos-offline-checkout.component.js.map +1 -0
  83. package/src/lib/components/console/pos-offline/pos-offline-store.d.ts +63 -0
  84. package/src/lib/components/console/pos-offline/pos-offline-store.js +145 -0
  85. package/src/lib/components/console/pos-offline/pos-offline-store.js.map +1 -0
  86. package/src/lib/components/console/pos-offline/register-offline.d.ts +24 -0
  87. package/src/lib/components/console/pos-offline/register-offline.js +24 -0
  88. package/src/lib/components/console/pos-offline/register-offline.js.map +1 -0
  89. package/src/lib/components/console/pos-offline/use-pos-offline.d.ts +85 -0
  90. package/src/lib/components/console/pos-offline/use-pos-offline.js +542 -0
  91. package/src/lib/components/console/pos-offline/use-pos-offline.js.map +1 -0
  92. package/src/lib/components/console/pos-ops/pos-shift-history-card.component.js +72 -17
  93. package/src/lib/components/console/pos-ops/pos-shift-history-card.component.js.map +1 -1
  94. package/src/lib/components/console/pos-page.component.js +174 -27
  95. package/src/lib/components/console/pos-page.component.js.map +1 -1
  96. package/src/lib/components/console/products-hub-card.component.js +35 -10
  97. package/src/lib/components/console/products-hub-card.component.js.map +1 -1
  98. package/src/lib/components/console/shipping-settings-card.component.js +1 -1
  99. package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
  100. package/src/lib/components/console/stock-movements-card.component.js +48 -16
  101. package/src/lib/components/console/stock-movements-card.component.js.map +1 -1
  102. package/src/lib/components/console/store-zones.d.ts +8 -1
  103. package/src/lib/components/console/store-zones.js +11 -1
  104. package/src/lib/components/console/store-zones.js.map +1 -1
  105. package/src/lib/components/order-status.js +66 -0
  106. package/src/lib/components/order-status.js.map +1 -1
  107. package/src/lib/components/product-detail.js +42 -15
  108. package/src/lib/components/product-detail.js.map +1 -1
  109. package/src/lib/constants/local-fulfillment-list-query.d.ts +48 -0
  110. package/src/lib/constants/local-fulfillment-list-query.js +84 -0
  111. package/src/lib/constants/local-fulfillment-list-query.js.map +1 -0
  112. package/src/lib/constants/orders-list-query.d.ts +7 -2
  113. package/src/lib/constants/orders-list-query.js +89 -8
  114. package/src/lib/constants/orders-list-query.js.map +1 -1
  115. package/src/lib/constants/pos-shift-list-query.d.ts +22 -0
  116. package/src/lib/constants/pos-shift-list-query.js +115 -0
  117. package/src/lib/constants/pos-shift-list-query.js.map +1 -0
  118. package/src/lib/constants/product-list-query.d.ts +6 -1
  119. package/src/lib/constants/product-list-query.js +77 -8
  120. package/src/lib/constants/product-list-query.js.map +1 -1
  121. package/src/lib/constants/stock-movement-query.d.ts +3 -2
  122. package/src/lib/constants/stock-movement-query.js +52 -8
  123. package/src/lib/constants/stock-movement-query.js.map +1 -1
  124. package/src/lib/model/buyer-notifications.d.ts +5 -3
  125. package/src/lib/model/buyer-notifications.js +25 -4
  126. package/src/lib/model/buyer-notifications.js.map +1 -1
  127. package/src/lib/model/commerce-orders.d.ts +59 -0
  128. package/src/lib/model/commerce-orders.js.map +1 -1
  129. package/src/lib/model/commerce-pos-kiosk.d.ts +175 -0
  130. package/src/lib/model/commerce-pos-kiosk.js +147 -0
  131. package/src/lib/model/commerce-pos-kiosk.js.map +1 -0
  132. package/src/lib/model/commerce-pos-offline.d.ts +234 -0
  133. package/src/lib/model/commerce-pos-offline.js +301 -0
  134. package/src/lib/model/commerce-pos-offline.js.map +1 -0
  135. package/src/lib/model/commerce-pos-ops.d.ts +16 -6
  136. package/src/lib/model/commerce-pos-ops.js +12 -4
  137. package/src/lib/model/commerce-pos-ops.js.map +1 -1
  138. package/src/lib/model/commerce-pos.d.ts +13 -1
  139. package/src/lib/model/commerce-pos.js +5 -4
  140. package/src/lib/model/commerce-pos.js.map +1 -1
  141. package/src/lib/model/commerce-stock-holds.d.ts +24 -3
  142. package/src/lib/model/commerce-stock-holds.js +26 -8
  143. package/src/lib/model/commerce-stock-holds.js.map +1 -1
  144. package/src/lib/model/commerce.d.ts +3 -0
  145. package/src/lib/model/commerce.js.map +1 -1
  146. package/src/lib/model/index.d.ts +4 -0
  147. package/src/lib/model/index.js +4 -0
  148. package/src/lib/model/index.js.map +1 -1
  149. package/src/lib/model/local-fulfillment-settings.d.ts +178 -0
  150. package/src/lib/model/local-fulfillment-settings.js +361 -0
  151. package/src/lib/model/local-fulfillment-settings.js.map +1 -0
  152. package/src/lib/model/order-list-fields.d.ts +10 -1
  153. package/src/lib/model/order-list-fields.js +1 -0
  154. package/src/lib/model/order-list-fields.js.map +1 -1
  155. package/src/lib/model/order-local-fulfillment.d.ts +131 -0
  156. package/src/lib/model/order-local-fulfillment.js +125 -0
  157. package/src/lib/model/order-local-fulfillment.js.map +1 -0
  158. package/src/lib/model/order-shipping-export.js +4 -0
  159. package/src/lib/model/order-shipping-export.js.map +1 -1
  160. package/src/lib/model/order-status-view.d.ts +20 -1
  161. package/src/lib/model/order-status-view.js +60 -6
  162. package/src/lib/model/order-status-view.js.map +1 -1
  163. package/src/lib/plugin-config.js +6 -2
  164. package/src/lib/plugin-config.js.map +1 -1
  165. package/src/lib/plugin.js +8 -0
  166. package/src/lib/plugin.js.map +1 -1
  167. package/src/lib/pos-kiosk-config.d.ts +26 -0
  168. package/src/lib/pos-kiosk-config.js +59 -0
  169. package/src/lib/pos-kiosk-config.js.map +1 -0
  170. package/src/lib/server/api-v1/openapi.js +8 -0
  171. package/src/lib/server/api-v1/openapi.js.map +1 -1
  172. package/src/lib/server/api-v1/order-view.d.ts +19 -0
  173. package/src/lib/server/api-v1/order-view.js +35 -0
  174. package/src/lib/server/api-v1/order-view.js.map +1 -1
  175. package/src/lib/server/billing-webhook.js +238 -87
  176. package/src/lib/server/billing-webhook.js.map +1 -1
  177. package/src/lib/server/cart-checkout.d.ts +2 -0
  178. package/src/lib/server/cart-checkout.js +173 -13
  179. package/src/lib/server/cart-checkout.js.map +1 -1
  180. package/src/lib/server/checkout-extras.js +18 -4
  181. package/src/lib/server/checkout-extras.js.map +1 -1
  182. package/src/lib/server/checkout.js +71 -14
  183. package/src/lib/server/checkout.js.map +1 -1
  184. package/src/lib/server/local-fulfillment-status.d.ts +86 -0
  185. package/src/lib/server/local-fulfillment-status.js +379 -0
  186. package/src/lib/server/local-fulfillment-status.js.map +1 -0
  187. package/src/lib/server/local-fulfillment.d.ts +190 -0
  188. package/src/lib/server/local-fulfillment.js +580 -0
  189. package/src/lib/server/local-fulfillment.js.map +1 -0
  190. package/src/lib/server/membership-register.js +3 -1
  191. package/src/lib/server/membership-register.js.map +1 -1
  192. package/src/lib/server/order-notifications.js +61 -0
  193. package/src/lib/server/order-notifications.js.map +1 -1
  194. package/src/lib/server/pos-display.d.ts +27 -1
  195. package/src/lib/server/pos-display.js +50 -9
  196. package/src/lib/server/pos-display.js.map +1 -1
  197. package/src/lib/server/pos-kiosk-principal.d.ts +29 -0
  198. package/src/lib/server/pos-kiosk-principal.js +42 -0
  199. package/src/lib/server/pos-kiosk-principal.js.map +1 -0
  200. package/src/lib/server/pos-kiosk.d.ts +54 -0
  201. package/src/lib/server/pos-kiosk.js +972 -0
  202. package/src/lib/server/pos-kiosk.js.map +1 -0
  203. package/src/lib/server/pos-offline-sync.d.ts +85 -0
  204. package/src/lib/server/pos-offline-sync.js +765 -0
  205. package/src/lib/server/pos-offline-sync.js.map +1 -0
  206. package/src/lib/server/pos-order.js +22 -4
  207. package/src/lib/server/pos-order.js.map +1 -1
  208. package/src/lib/server/pos-payment.d.ts +6 -0
  209. package/src/lib/server/pos-payment.js +225 -6
  210. package/src/lib/server/pos-payment.js.map +1 -1
  211. package/src/lib/server/pos-print.js +5 -0
  212. package/src/lib/server/pos-print.js.map +1 -1
  213. package/src/lib/server/pos-return.js +27 -0
  214. package/src/lib/server/pos-return.js.map +1 -1
  215. package/src/lib/server/pos-sale.d.ts +6 -0
  216. package/src/lib/server/pos-sale.js +2 -0
  217. package/src/lib/server/pos-sale.js.map +1 -1
  218. package/src/lib/server/pos-shift.js +8 -1
  219. package/src/lib/server/pos-shift.js.map +1 -1
  220. package/src/lib/server/refund.js +3 -0
  221. package/src/lib/server/refund.js.map +1 -1
  222. package/src/lib/server/stock-hold.d.ts +9 -1
  223. package/src/lib/server/stock-hold.js +15 -7
  224. package/src/lib/server/stock-hold.js.map +1 -1
  225. package/src/lib/server.js +16 -0
  226. package/src/lib/server.js.map +1 -1
  227. package/src/lib/tenant-emails.js +161 -0
  228. package/src/lib/tenant-emails.js.map +1 -1
@@ -18,6 +18,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
18
18
  import { buildRoute, Route } from "@aglyn/aglyn/server";
19
19
  import recordCapturedContact from "@aglyn/aglyn/plugin-manager/record-captured-contact";
20
20
  import { pluginSmsAvailable } from "@aglyn/aglyn/plugin-manager/plugin-sms-messaging";
21
+ import { checkoutCreditProvider, checkoutCreditProviderForCode, normalizeCheckoutCreditAccount, normalizeCheckoutCreditCode, offeredCheckoutCredits } from "@aglyn/aglyn/plugin-manager/plugin-checkout-credits";
21
22
  import { finishPosDisplayReceipt } from "./pos-display.js";
22
23
  import * as CommerceModel from "../model/index.js";
23
24
  import { posRegisterSettings } from "../plugin-config.js";
@@ -59,6 +60,9 @@ import { cancelPosCardPayment, createCardPresentIntent, refreshPosCardPayment, r
59
60
  if (action === 'gift-card-balance') {
60
61
  return await giftCardBalance(staff, body, res);
61
62
  }
63
+ if (action === 'credit-lookup') {
64
+ return await creditLookup(staff, body, res);
65
+ }
62
66
  if (action === 'context') {
63
67
  var _process_env_NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY;
64
68
  // What the register needs to draw its tenders: the site's tip and
@@ -85,7 +89,12 @@ import { cancelPosCardPayment, createCardPresentIntent, refreshPosCardPayment, r
85
89
  readers,
86
90
  publishableKey: String((_process_env_NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY = process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY) != null ? _process_env_NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY : ''),
87
91
  // A text receipt is offered only when an SMS provider is on (AGL-3610).
88
- smsReceipts: pluginSmsAvailable()
92
+ smsReceipts: pluginSmsAvailable(),
93
+ // Store credit other plugins keep — rewards (AGL-3640) — offered here.
94
+ credits: await offeredCheckoutCredits({
95
+ hostId,
96
+ channel: 'pos'
97
+ })
89
98
  });
90
99
  }
91
100
  if (!orderId) return res.status(400).json({
@@ -95,6 +104,7 @@ import { cancelPosCardPayment, createCardPresentIntent, refreshPosCardPayment, r
95
104
  'card-present-sdk',
96
105
  'cash',
97
106
  'gift-card',
107
+ 'credit',
98
108
  'folio',
99
109
  'card-present',
100
110
  'card-keyed',
@@ -146,6 +156,9 @@ import { cancelPosCardPayment, createCardPresentIntent, refreshPosCardPayment, r
146
156
  case 'gift-card':
147
157
  outcome = await takeGiftCard(staff, orderId, paymentId, body);
148
158
  break;
159
+ case 'credit':
160
+ outcome = await takeCredit(staff, orderId, paymentId, body);
161
+ break;
149
162
  case 'folio':
150
163
  outcome = await takeFolio(staff, orderId, paymentId, body);
151
164
  break;
@@ -483,6 +496,175 @@ function giftCardRef(hostId, code) {
483
496
  }
484
497
  });
485
498
  }
499
+ /**
500
+ * Staff search for a store-credit account at the register (AGL-3640): a
501
+ * customer's email or code, answered by the plugin that keeps the account.
502
+ * Only staff reach it — `authorizePosStaff` above — so a provider may look
503
+ * accounts up by email here, which it never does for a shopper.
504
+ */ async function creditLookup(staff, body, res) {
505
+ var _body_providerId, _body_query;
506
+ const entry = checkoutCreditProvider(String((_body_providerId = body['providerId']) != null ? _body_providerId : ''));
507
+ if (!(entry == null ? void 0 : entry.provider.lookup)) return res.status(404).json({
508
+ error: 'That kind of credit is not taken here.'
509
+ });
510
+ const rate = await consumeRateLimit(`pos-credit-lookup:${staff.uid}`, {
511
+ limit: 60,
512
+ windowMs: 60000
513
+ });
514
+ if (!rate.allowed) return res.status(429).json({
515
+ error: 'Too many lookups. Wait a moment.'
516
+ });
517
+ if (!await entry.provider.offered({
518
+ hostId: staff.hostId,
519
+ channel: 'pos'
520
+ }).catch(()=>false)) {
521
+ return res.status(404).json({
522
+ error: 'That kind of credit is not taken here.'
523
+ });
524
+ }
525
+ const found = await entry.provider.lookup({
526
+ hostId: staff.hostId,
527
+ query: String((_body_query = body['query']) != null ? _body_query : '').slice(0, 120)
528
+ }).catch((error)=>{
529
+ console.error('[pos-payment] credit lookup failed', entry.providerId, error);
530
+ return [];
531
+ });
532
+ const accounts = found.slice(0, 10).map((account)=>normalizeCheckoutCreditAccount(account)).filter((account)=>!('error' in account));
533
+ return res.status(200).json({
534
+ providerId: entry.providerId,
535
+ accounts
536
+ });
537
+ }
538
+ /**
539
+ * Store credit another plugin keeps (AGL-3640) — a rewards balance, a friend's
540
+ * referral credit — by the customer's code, or by the account a staff lookup
541
+ * found. The provider's stage reads the account INSIDE the sale's transaction
542
+ * and its debit writes there, so the credit is taken with the payment or not
543
+ * at all; a retried press finds its own payment and takes nothing more.
544
+ */ async function takeCredit(staff, orderId, paymentId, body) {
545
+ var _body_providerId, _body_reference, _sale_customerEmail, _body_amountCents;
546
+ const code = normalizeCheckoutCreditCode(body['code']);
547
+ const entry = code ? checkoutCreditProviderForCode(code) : checkoutCreditProvider(String((_body_providerId = body['providerId']) != null ? _body_providerId : ''));
548
+ if (!entry) return {
549
+ ok: false,
550
+ status: 404,
551
+ error: 'That code is not one this store takes.'
552
+ };
553
+ if (!await entry.provider.offered({
554
+ hostId: staff.hostId,
555
+ channel: 'pos'
556
+ }).catch(()=>false)) {
557
+ return {
558
+ ok: false,
559
+ status: 404,
560
+ error: 'That kind of credit is not taken here.'
561
+ };
562
+ }
563
+ const sale = await readPosSale(staff.hostId, orderId);
564
+ if (!sale) return {
565
+ ok: false,
566
+ status: 404,
567
+ error: 'Unknown sale'
568
+ };
569
+ const account = normalizeCheckoutCreditAccount(await entry.provider.resolve(_extends({
570
+ hostId: staff.hostId
571
+ }, code ? {
572
+ code
573
+ } : {
574
+ reference: String((_body_reference = body['reference']) != null ? _body_reference : '')
575
+ }, {
576
+ channel: 'pos',
577
+ customerEmail: (_sale_customerEmail = sale.customerEmail) != null ? _sale_customerEmail : null,
578
+ staff: true
579
+ })).catch((error)=>{
580
+ console.error('[pos-payment] credit resolve failed', entry.providerId, error);
581
+ return null;
582
+ }));
583
+ if ('error' in account) return {
584
+ ok: false,
585
+ status: account.status,
586
+ error: account.error
587
+ };
588
+ const askedCents = Math.round(Number((_body_amountCents = body['amountCents']) != null ? _body_amountCents : 0));
589
+ return await applyPosPayment({
590
+ hostId: staff.hostId,
591
+ orderId,
592
+ paymentId,
593
+ prepare: async (transaction)=>entry.provider.stage({
594
+ transaction,
595
+ hostId: staff.hostId,
596
+ reference: account.reference,
597
+ orderId,
598
+ nowMs: Date.now()
599
+ }),
600
+ decide: ({ order, payments, existing, context: stage })=>{
601
+ var _order_posTakeFeeCents, _ref;
602
+ var _order_totals;
603
+ if (existing) return {
604
+ kind: 'keep'
605
+ };
606
+ if (order.status !== 'pending') return NOT_OPEN;
607
+ if (!stage) return {
608
+ kind: 'refuse',
609
+ status: 404,
610
+ error: `That ${account.label.toLowerCase()} account no longer exists.`
611
+ };
612
+ const open = tenderable(order, payments);
613
+ if (open <= 0) return {
614
+ kind: 'refuse',
615
+ status: 409,
616
+ error: 'Nothing is left to pay on this sale.'
617
+ };
618
+ const amountCents = Math.min(stage.availableCents, open, askedCents > 0 ? askedCents : open);
619
+ if (!(amountCents > 0)) {
620
+ return {
621
+ kind: 'refuse',
622
+ status: 409,
623
+ error: `This ${account.label.toLowerCase()} account has nothing to spend.`
624
+ };
625
+ }
626
+ const now = Date.now();
627
+ return {
628
+ kind: 'put',
629
+ payment: _extends({
630
+ id: paymentId,
631
+ method: 'credit',
632
+ amountCents,
633
+ status: 'succeeded',
634
+ atMs: now,
635
+ settledAtMs: now,
636
+ creditProviderId: entry.providerId,
637
+ creditReference: account.reference,
638
+ creditLabel: account.label
639
+ }, account.last4 ? {
640
+ last4: account.last4
641
+ } : {}, {
642
+ takeFeeCents: CommerceModel.posTakeShareCents({
643
+ takeFeeCents: Number((_order_posTakeFeeCents = order.posTakeFeeCents) != null ? _order_posTakeFeeCents : 0),
644
+ totalCents: Number((_ref = (_order_totals = order.totals) == null ? void 0 : _order_totals.totalCents) != null ? _ref : 0),
645
+ amountCents
646
+ }),
647
+ feeCents: 0,
648
+ cashierId: staff.uid
649
+ })
650
+ };
651
+ },
652
+ write: (_transaction, stage, payment)=>{
653
+ // The stage writes through the sale's own transaction. Taking less than
654
+ // the payment records would leave the sale paid by money that did not
655
+ // move, so a short debit aborts the whole commit instead.
656
+ const taken = stage ? stage.debit({
657
+ cents: payment.amountCents,
658
+ key: payment.id,
659
+ orderId,
660
+ channel: 'pos'
661
+ }) : 0;
662
+ if (taken !== payment.amountCents) {
663
+ throw new Error(`credit debit ${taken} short of payment ${payment.amountCents}`);
664
+ }
665
+ }
666
+ });
667
+ }
486
668
  function reservationRef(hostId, reservationId) {
487
669
  return firebaseAdmin.app().firestore().collection('hosts').doc(hostId).collection('reservations').doc(reservationId);
488
670
  }
@@ -693,6 +875,18 @@ function reservationRef(hostId, reservationId) {
693
875
  }
694
876
  const cardRef = payment.giftCardId ? giftCardRef(hostId, payment.giftCardId) : null;
695
877
  const stayRef = payment.reservationId ? reservationRef(hostId, payment.reservationId) : null;
878
+ // Store credit goes back to the plugin that keeps it (AGL-3640), in the
879
+ // same commit as the reversal. A provider that is gone cannot take it
880
+ // back, so the void stops with the sale still open rather than cancelling
881
+ // over credit that did not come back.
882
+ const creditEntry = payment.method === 'credit' && payment.creditProviderId ? checkoutCreditProvider(payment.creditProviderId) : null;
883
+ if (payment.method === 'credit' && (!creditEntry || !payment.creditReference)) {
884
+ return {
885
+ ok: false,
886
+ status: 409,
887
+ error: 'The store credit on this sale cannot be handed back right now. The sale is still open.'
888
+ };
889
+ }
696
890
  return await applyPosPayment({
697
891
  hostId,
698
892
  orderId: order.$id,
@@ -702,7 +896,8 @@ function reservationRef(hostId, reservationId) {
702
896
  const snapshot = await transaction.get(cardRef);
703
897
  return {
704
898
  card: snapshot.exists ? snapshot.data() : null,
705
- folio: null
899
+ folio: null,
900
+ credit: null
706
901
  };
707
902
  }
708
903
  if (payment.method === 'folio' && stayRef) {
@@ -710,12 +905,28 @@ function reservationRef(hostId, reservationId) {
710
905
  const snapshot = await transaction.get(stayRef);
711
906
  return {
712
907
  card: null,
713
- folio: snapshot.exists ? (_snapshot_get = snapshot.get('folio')) != null ? _snapshot_get : [] : null
908
+ folio: snapshot.exists ? (_snapshot_get = snapshot.get('folio')) != null ? _snapshot_get : [] : null,
909
+ credit: null
910
+ };
911
+ }
912
+ if (payment.method === 'credit' && creditEntry && payment.creditReference) {
913
+ const credit = await creditEntry.provider.stage({
914
+ transaction,
915
+ hostId,
916
+ reference: payment.creditReference,
917
+ orderId: order.$id,
918
+ nowMs: Date.now()
919
+ });
920
+ return {
921
+ card: null,
922
+ folio: null,
923
+ credit
714
924
  };
715
925
  }
716
926
  return {
717
927
  card: null,
718
- folio: null
928
+ folio: null,
929
+ credit: null
719
930
  };
720
931
  },
721
932
  decide: ({ existing })=>{
@@ -752,6 +963,12 @@ function reservationRef(hostId, reservationId) {
752
963
  folio: context.folio.filter((entry)=>(entry == null ? void 0 : entry.paymentId) !== reversed.id)
753
964
  });
754
965
  }
966
+ if (reversed.method === 'credit' && context.credit) {
967
+ context.credit.reverse({
968
+ key: reversed.id,
969
+ orderId: order.$id
970
+ });
971
+ }
755
972
  }
756
973
  });
757
974
  }
@@ -760,7 +977,7 @@ function reservationRef(hostId, reservationId) {
760
977
  * How the customer wants their receipt, from the cashier or the customer
761
978
  * display. Kept on the order; an email chosen after the sale is paid is sent
762
979
  * at once, and one chosen before is sent when it completes.
763
- */ async function recordReceiptChoice(staff, orderId, body) {
980
+ */ export async function recordReceiptChoice(staff, orderId, body) {
764
981
  var _body_channel;
765
982
  const channel = String((_body_channel = body['channel']) != null ? _body_channel : '');
766
983
  if (![
@@ -850,7 +1067,9 @@ function reservationRef(hostId, reservationId) {
850
1067
  // printer, under the sale's own key so it never prints twice (AGL-3609).
851
1068
  await printPosSaleReceipt(staff.hostId, orderId);
852
1069
  }
853
- if (order.status === 'paid' && order.registerId) {
1070
+ // A kiosk's own receipt screen (AGL-3623) is not the register's display:
1071
+ // the display may be asking the cashier's customer right now.
1072
+ if (order.status === 'paid' && order.registerId && order.posSource !== 'kiosk') {
854
1073
  // The customer has answered (or the cashier for them): the display says
855
1074
  // thank you and drops the address they typed (AGL-3608).
856
1075
  await finishPosDisplayReceipt(staff.hostId, order.registerId).catch((error)=>console.error('[pos-payment] display finish failed', error));
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-payment.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 {\n consumeRateLimit,\n firebaseAdmin,\n getPluginConfig,\n} from '@aglyn/tenant-data-admin'\nimport { buildRoute, Route, type PluginApiHandler } from '@aglyn/aglyn/server'\nimport recordCapturedContact from '@aglyn/aglyn/plugin-manager/record-captured-contact'\nimport { pluginSmsAvailable } from '@aglyn/aglyn/plugin-manager/plugin-sms-messaging'\nimport { finishPosDisplayReceipt } from './pos-display'\nimport * as CommerceModel from '../model'\nimport { posRegisterSettings } from '../plugin-config'\nimport {\n authorizePosStaff,\n posIdempotencyKey,\n posQueryBody,\n posRequestBody,\n type PosStaff,\n} from './pos-auth'\nimport {\n applyPosPayment,\n deliverChosenPosReceipt,\n posPaymentId,\n posSaleSummary,\n readPosSale,\n releasePosSaleDiscount,\n type PosLiftedOrder,\n type PosPaymentOutcome,\n} from './pos-sale'\nimport { posPaymentCashierId } from './pos-sale-stamp'\nimport { printPosSaleReceipt } from './pos-print'\nimport {\n POS_CURRENCY,\n posStripe,\n posStripeErrorMessage,\n posStripeTestMode,\n posTerminalAvailable,\n} from './pos-stripe'\nimport {\n cancelPosCardPayment,\n createCardPresentIntent,\n refreshPosCardPayment,\n retryCardPresentPayment,\n simulatePosReaderTap,\n startCardKeyedPayment,\n startCardLinkPayment,\n startCardPresentPayment,\n} from './pos-terminal'\n\n/**\n * `POST /api/commerce/pos-payment` (AGL-3607): every tender against an OPEN\n * register sale, one `action` per request.\n *\n * The sale was priced by `pos-order.ts` (`payment: 'open'`); nothing here\n * re-prices it or lets the register name a total. Each payment-starting action\n * needs the register's `Idempotency-Key`, from which the payment's id is\n * derived: pressing a tender twice, or retrying after a lost response, finds\n * the payment the first press started instead of taking the money twice.\n */\nexport const posPaymentHandler: PluginApiHandler = async (req, res) => {\n // `sale` is a read and may be a GET, so a register re-reading its sale does\n // not spend the console's write budget; everything else moves money.\n const body = req.method === 'GET' ? posQueryBody(req) : posRequestBody(req)\n if (\n !(\n req.method === 'POST' ||\n (req.method === 'GET' && (body['action'] === 'sale' || body['action'] === 'context'))\n )\n ) {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(body['hostId'] ?? '')\n const gate = await authorizePosStaff(req, hostId)\n if ('error' in gate) return res.status(gate.status).json({ error: gate.error })\n let staff = gate.staff\n const action = String(body['action'] ?? '')\n const orderId = String(body['orderId'] ?? '')\n try {\n if (action === 'gift-card-balance') {\n return await giftCardBalance(staff, body, res)\n }\n if (action === 'context') {\n // What the register needs to draw its tenders: the site's tip and\n // receipt settings, whether card readers are offered at all, and the\n // key the typed-card form loads Stripe with.\n const readers = posTerminalAvailable()\n ? (\n await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('terminalReaders')\n .limit(50)\n .get()\n ).docs.map((doc: any) => ({\n id: doc.id as string,\n label: String(doc.get('label') ?? 'Card reader'),\n registerId: (doc.get('registerId') as string | undefined) ?? null,\n status: String(doc.get('status') ?? 'offline'),\n livemode: Boolean(doc.get('livemode')),\n }))\n : []\n return res.status(200).json({\n settings: posRegisterSettings(\n await getPluginConfig(staff.orgId || undefined, 'commerce', { hostId }),\n ),\n terminal: { available: posTerminalAvailable(), testMode: posStripeTestMode() },\n readers,\n publishableKey: String(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY ?? ''),\n // A text receipt is offered only when an SMS provider is on (AGL-3610).\n smsReceipts: pluginSmsAvailable(),\n })\n }\n if (!orderId) return res.status(400).json({ error: 'Missing orderId' })\n const startsPayment = [\n 'card-present-sdk',\n 'cash',\n 'gift-card',\n 'folio',\n 'card-present',\n 'card-keyed',\n 'card-link',\n ].includes(action)\n const attemptKey = posIdempotencyKey(req)\n if (startsPayment && !attemptKey) {\n return res.status(400).json({ error: 'Missing Idempotency-Key' })\n }\n const paymentId = startsPayment\n ? posPaymentId(orderId, attemptKey)\n : String(body['paymentId'] ?? '')\n // The cashier a PIN switched in takes the payment (AGL-3609).\n if (startsPayment && body['cashierAssertion']) {\n staff = {\n ...staff,\n uid: await posPaymentCashierId({\n hostId,\n orderId,\n signedInUid: staff.uid,\n assertion: body['cashierAssertion'],\n }),\n }\n }\n const amountCents = Math.round(Number(body['amountCents'] ?? 0))\n const tipCents = Math.round(Number(body['tipCents'] ?? 0)) || 0\n const settings = posRegisterSettings(\n await getPluginConfig(staff.orgId || undefined, 'commerce', { hostId }),\n )\n let outcome: (PosPaymentOutcome & { clientSecret?: string; paymentIntentId?: string }) | null = null\n switch (action) {\n case 'sale': {\n const order = await readPosSale(hostId, orderId)\n if (!order) return res.status(404).json({ error: 'Unknown sale' })\n outcome = { ok: true, order, payment: null, completed: false, changed: false }\n break\n }\n case 'cash':\n outcome = await takeCash(staff, orderId, paymentId, body, tipCents)\n break\n case 'gift-card':\n outcome = await takeGiftCard(staff, orderId, paymentId, body)\n break\n case 'folio':\n outcome = await takeFolio(staff, orderId, paymentId, body)\n break\n case 'card-present':\n outcome = await startCardPresentPayment({\n hostId,\n orderId,\n paymentId,\n amountCents,\n tipCents,\n cashierId: staff.uid,\n org: staff.org,\n readerId: String(body['readerId'] ?? ''),\n settings,\n })\n break\n case 'card-present-sdk':\n // Collected by a native app's Stripe Terminal SDK (Tap to Pay or a\n // Bluetooth reader, AGL-3618) against this server-made intent; it\n // settles exactly like a smart-reader payment.\n outcome = await createCardPresentIntent({\n hostId,\n orderId,\n paymentId,\n amountCents,\n tipCents,\n cashierId: staff.uid,\n org: staff.org,\n })\n break\n case 'card-keyed':\n outcome = await startCardKeyedPayment({\n hostId,\n orderId,\n paymentId,\n amountCents,\n tipCents,\n cashierId: staff.uid,\n org: staff.org,\n })\n break\n case 'card-link':\n outcome = await startCardLinkPayment({\n hostId,\n orderId,\n paymentId,\n amountCents,\n tipCents,\n cashierId: staff.uid,\n org: staff.org,\n returnUrl: await registerReturnUrl(req.headers.host, hostId, staff),\n })\n break\n case 'status':\n outcome = await refreshPosCardPayment({ hostId, orderId, paymentId })\n break\n case 'cancel':\n outcome = await cancelPosCardPayment({ hostId, orderId, paymentId })\n break\n case 'retry':\n outcome = await retryCardPresentPayment({ hostId, orderId, paymentId, settings })\n break\n case 'simulate':\n outcome = await simulatePosReaderTap({\n hostId,\n orderId,\n paymentId,\n cardNumber: String(body['cardNumber'] ?? ''),\n })\n break\n case 'void':\n outcome = await voidPosSale(staff, orderId)\n break\n case 'receipt':\n outcome = await recordReceiptChoice(staff, orderId, body)\n break\n default:\n return res.status(400).json({ error: 'Unknown action' })\n }\n if ('error' in outcome) return res.status(outcome.status).json({ error: outcome.error })\n return res.status(200).json({\n sale: posSaleSummary(outcome.order),\n ...(outcome.payment ? { paymentId: outcome.payment.id } : {}),\n completed: outcome.order.status === 'paid',\n ...(outcome.clientSecret ? { clientSecret: outcome.clientSecret } : {}),\n ...(outcome.paymentIntentId ? { paymentIntentId: outcome.paymentIntentId } : {}),\n })\n } catch (error) {\n console.error('[pos-payment]', action, error)\n return res.status(500).json({ error: 'Payment failed — check the sale before trying again' })\n }\n}\n\n/** Where a QR payment page sends the customer back to: the register. */\nasync function registerReturnUrl(\n requestHost: string | string[] | undefined,\n hostId: string,\n staff: PosStaff,\n): Promise<string> {\n const origin = `https://${String(requestHost ?? '')}`\n const subdomain = (\n await firebaseAdmin.app().firestore().collection('hostIndex').doc(hostId).get()\n ).get('subdomain') as string | undefined\n const orgSlug = staff.org?.['slug'] as string | undefined\n return orgSlug && subdomain\n ? `${origin}${buildRoute(Route.HOST_PLUGIN, { orgSlug, host: subdomain, pluginSlug: 'pos' })}`\n : origin\n}\n\n/** The balance a new tender may take, or a refusal. */\nfunction tenderable(\n order: PosLiftedOrder,\n payments: CommerceModel.OrderPayment[],\n): number {\n return CommerceModel.posTenderableCents(Number(order.totals?.totalCents ?? 0), payments)\n}\n\nconst NOT_OPEN = { kind: 'refuse' as const, status: 409, error: 'This sale is no longer open' }\n\n/**\n * Cash: the amount defaults to whatever is left, the change is what the\n * customer handed over beyond it (and beyond any tip they chose).\n */\nasync function takeCash(\n staff: PosStaff,\n orderId: string,\n paymentId: string,\n body: Record<string, any>,\n tipCents: number,\n): Promise<PosPaymentOutcome> {\n const tenderedCents = Math.round(Number(body['tenderedCents'] ?? 0))\n const askedCents = Math.round(Number(body['amountCents'] ?? 0))\n return await applyPosPayment({\n hostId: staff.hostId,\n orderId,\n paymentId,\n decide: ({ order, payments, existing }) => {\n if (existing) return { kind: 'keep' }\n if (order.status !== 'pending') return NOT_OPEN\n if (!Number.isFinite(tenderedCents) || tenderedCents <= 0) {\n return { kind: 'refuse', status: 400, error: 'Enter the cash received.' }\n }\n const open = tenderable(order, payments)\n if (open <= 0) return { kind: 'refuse', status: 409, error: 'Nothing is left to pay on this sale.' }\n const amountCents =\n askedCents > 0 ? Math.min(askedCents, open) : Math.min(open, Math.max(0, tenderedCents - tipCents))\n if (!(amountCents > 0)) {\n return { kind: 'refuse', status: 400, error: 'The cash received does not cover the tip.' }\n }\n const tipProblem = CommerceModel.posTipProblem(tipCents, amountCents)\n if (tipProblem) return { kind: 'refuse', status: 400, error: tipProblem }\n if (tenderedCents < amountCents + tipCents) {\n return { kind: 'refuse', status: 400, error: 'Cash received is short' }\n }\n const total = Number(order.totals?.totalCents ?? 0)\n const now = Date.now()\n return {\n kind: 'put',\n payment: {\n id: paymentId,\n method: 'cash',\n amountCents,\n ...(tipCents > 0 ? { tipCents } : {}),\n status: 'succeeded',\n atMs: now,\n settledAtMs: now,\n cashTenderedCents: tenderedCents,\n changeCents: tenderedCents - amountCents - tipCents,\n takeFeeCents: CommerceModel.posTakeShareCents({\n takeFeeCents: Number(order.posTakeFeeCents ?? 0),\n totalCents: total,\n amountCents,\n }),\n feeCents: 0,\n cashierId: staff.uid,\n },\n }\n },\n })\n}\n\nfunction giftCardRef(hostId: string, code: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('giftCards')\n .doc(code)\n}\n\n/** A gift card's spendable balance, for the cashier to read to the customer. */\nasync function giftCardBalance(\n staff: PosStaff,\n body: Record<string, any>,\n res: Parameters<PluginApiHandler>[1],\n): Promise<void> {\n const code = CommerceModel.giftCardCodeOf(body['code'])\n const rate = await consumeRateLimit(`pos-gift-balance:${staff.uid}`, {\n limit: 30,\n windowMs: 60_000,\n })\n if (!rate.allowed) {\n return res.status(429).json({ error: 'Too many balance checks. Wait a minute and try again.' })\n }\n if (CommerceModel.giftCardCodeProblem(code)) {\n return res.status(404).json({ error: 'No gift card has that code.' })\n }\n const snapshot = await giftCardRef(staff.hostId, code).get()\n if (!snapshot.exists) return res.status(404).json({ error: 'No gift card has that code.' })\n const card = snapshot.data() as CommerceModel.HostGiftCard\n return res.status(200).json({\n availableCents: CommerceModel.giftCardAvailableCents(card, Date.now()),\n frozen: CommerceModel.isGiftCardFrozen(card),\n voided: Number(card.voidedAtMs) > 0,\n last4: code.slice(-4),\n })\n}\n\n/**\n * A gift card: takes the smaller of what the card can give and what is left\n * to pay, in ONE transaction with the sale. The card's spendable balance\n * honours every live hold an online checkout placed on it (AGL-2449), and a\n * frozen card gives nothing (AGL-3363), so the till and the website can\n * never spend the same dollars.\n */\nasync function takeGiftCard(\n staff: PosStaff,\n orderId: string,\n paymentId: string,\n body: Record<string, any>,\n): Promise<PosPaymentOutcome> {\n const code = CommerceModel.giftCardCodeOf(body['code'])\n if (CommerceModel.giftCardCodeProblem(code)) {\n return { ok: false, status: 404, error: 'No gift card has that code.' }\n }\n const askedCents = Math.round(Number(body['amountCents'] ?? 0))\n const cardRef = giftCardRef(staff.hostId, code)\n return await applyPosPayment({\n hostId: staff.hostId,\n orderId,\n paymentId,\n prepare: async (transaction) => {\n const snapshot = await transaction.get(cardRef)\n return snapshot.exists ? (snapshot.data() as CommerceModel.HostGiftCard) : null\n },\n decide: ({ order, payments, existing, context: card }) => {\n if (existing) return { kind: 'keep' }\n if (order.status !== 'pending') return NOT_OPEN\n if (!card) return { kind: 'refuse', status: 404, error: 'No gift card has that code.' }\n const available = CommerceModel.giftCardAvailableCents(card, Date.now())\n if (available <= 0) {\n return {\n kind: 'refuse',\n status: 409,\n error: CommerceModel.isGiftCardFrozen(card)\n ? 'This gift card is on hold and cannot be used right now.'\n : 'This gift card has no balance left.',\n }\n }\n const open = tenderable(order, payments)\n const amountCents = Math.min(available, open, askedCents > 0 ? askedCents : open)\n if (!(amountCents > 0)) {\n return { kind: 'refuse', status: 409, error: 'Nothing is left to pay on this sale.' }\n }\n const now = Date.now()\n return {\n kind: 'put',\n payment: {\n id: paymentId,\n method: 'gift_card',\n amountCents,\n status: 'succeeded',\n atMs: now,\n settledAtMs: now,\n giftCardId: code,\n last4: code.slice(-4),\n takeFeeCents: CommerceModel.posTakeShareCents({\n takeFeeCents: Number(order.posTakeFeeCents ?? 0),\n totalCents: Number(order.totals?.totalCents ?? 0),\n amountCents,\n }),\n feeCents: 0,\n cashierId: staff.uid,\n },\n }\n },\n write: (transaction, card, payment) => {\n transaction.set(\n cardRef,\n {\n balanceCents: Math.max(0, Number(card?.balanceCents ?? 0) - payment.amountCents),\n lastUsedAtMs: Date.now(),\n },\n { merge: true },\n )\n },\n })\n}\n\nfunction reservationRef(hostId: string, reservationId: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('reservations')\n .doc(reservationId)\n}\n\n/** Charged to a checked-in stay's folio, in the same commit as the payment. */\nasync function takeFolio(\n staff: PosStaff,\n orderId: string,\n paymentId: string,\n body: Record<string, any>,\n): Promise<PosPaymentOutcome> {\n const reservationId = String(body['reservationId'] ?? '')\n if (!/^[A-Za-z0-9_-]{1,128}$/.test(reservationId)) {\n return { ok: false, status: 400, error: 'Pick a reservation' }\n }\n const askedCents = Math.round(Number(body['amountCents'] ?? 0))\n const stayRef = reservationRef(staff.hostId, reservationId)\n return await applyPosPayment({\n hostId: staff.hostId,\n orderId,\n paymentId,\n prepare: async (transaction) => (await transaction.get(stayRef)).exists as boolean,\n decide: ({ order, payments, existing, context: stayExists }) => {\n if (existing) return { kind: 'keep' }\n if (order.status !== 'pending') return NOT_OPEN\n if (!stayExists) return { kind: 'refuse', status: 404, error: 'Unknown reservation' }\n const open = tenderable(order, payments)\n const amountCents = Math.min(open, askedCents > 0 ? askedCents : open)\n if (!(amountCents > 0)) {\n return { kind: 'refuse', status: 409, error: 'Nothing is left to pay on this sale.' }\n }\n const now = Date.now()\n return {\n kind: 'put',\n payment: {\n id: paymentId,\n method: 'folio',\n amountCents,\n status: 'succeeded',\n atMs: now,\n settledAtMs: now,\n reservationId,\n folioAtMs: now,\n takeFeeCents: CommerceModel.posTakeShareCents({\n takeFeeCents: Number(order.posTakeFeeCents ?? 0),\n totalCents: Number(order.totals?.totalCents ?? 0),\n amountCents,\n }),\n feeCents: 0,\n cashierId: staff.uid,\n },\n event: { event: 'folio', detail: `Charged to reservation ${reservationId}` },\n }\n },\n write: (transaction, _stay, payment) => {\n // `update`, never a merge-set: a missing stay must not be minted as a\n // stub holding one folio line (AGL-1760). It exists — read above.\n transaction.update(stayRef, {\n folio: firebaseAdmin.firestore.FieldValue.arrayUnion({\n orderId,\n paymentId: payment.id,\n amountCents: payment.amountCents,\n note: 'Register sale',\n atMs: payment.folioAtMs ?? Date.now(),\n }),\n })\n },\n })\n}\n\n/**\n * Abandons an open sale: everything it took is handed back first — cards\n * refunded in full (tip included, fee and transfer reversed), gift cards\n * re-credited, the room charge taken off the folio, cash marked as returned —\n * and only then is the order cancelled. A refund Stripe refuses stops the void\n * with the sale still open and its payment still recorded, never cancelled\n * over money that did not come back.\n */\nexport async function voidPosSale(\n staff: PosStaff,\n orderId: string,\n): Promise<PosPaymentOutcome> {\n const hostId = staff.hostId\n const order = await readPosSale(hostId, orderId)\n if (!order) return { ok: false, status: 404, error: 'Unknown sale' }\n if (order.status === 'cancelled') return { ok: true, order, payment: null, completed: false, changed: false }\n if (order.status !== 'pending' || !Array.isArray(order.payments)) {\n return {\n ok: false,\n status: 409,\n error: 'This sale is already paid. Refund it from the order instead.',\n }\n }\n for (const payment of CommerceModel.orderPayments(order)) {\n if (payment.status === 'pending' && CommerceModel.isCardPaymentMethod(payment.method)) {\n const cancelled = await cancelPosCardPayment({ hostId, orderId, paymentId: payment.id })\n if (!cancelled.ok) return cancelled\n }\n }\n // Re-read after the cancels: one may have completed the sale in the gap.\n const current = await readPosSale(hostId, orderId)\n if (!current) return { ok: false, status: 404, error: 'Unknown sale' }\n if (current.status !== 'pending') {\n return {\n ok: false,\n status: 409,\n error: 'The last card payment went through and the sale is paid. Refund it from the order instead.',\n }\n }\n for (const payment of CommerceModel.orderPayments(current)) {\n if (payment.status !== 'succeeded') continue\n const reversed = await reversePayment(staff, current, payment)\n if (!reversed.ok) return reversed\n }\n const firestore = firebaseAdmin.app().firestore()\n const orderRef = firestore.collection('hosts').doc(hostId).collection('orders').doc(orderId)\n const cancelled = await firestore.runTransaction(async (transaction: any) => {\n const fresh = {\n ...(CommerceModel.liftLegacyOrder(((await transaction.get(orderRef)).data() ?? {}) as any) as any),\n $id: orderId,\n } as PosLiftedOrder\n if (fresh.status !== 'pending') return null\n const open = CommerceModel.orderPayments(fresh).some(\n (payment) => payment.status === 'pending' || payment.status === 'succeeded',\n )\n if (open) return null\n const next = {\n ...fresh,\n status: 'cancelled' as const,\n timeline: CommerceModel.appendOrderEvent(fresh, 'pos-sale-voided', 'Voided at the register'),\n }\n transaction.set(\n orderRef,\n {\n status: 'cancelled',\n cancelledAtMs: Date.now(),\n timeline: next.timeline,\n ...CommerceModel.orderListFields(next, orderId),\n },\n { merge: true },\n )\n return next\n })\n if (!cancelled) {\n return { ok: false, status: 409, error: 'A payment on this sale changed. Check it and try again.' }\n }\n await releasePosSaleDiscount(hostId, current)\n return { ok: true, order: cancelled, payment: null, completed: false, changed: true }\n}\n\n/** Hands one settled payment back, recording `reversed` in the same commit. */\nasync function reversePayment(\n staff: PosStaff,\n order: PosLiftedOrder,\n payment: CommerceModel.OrderPayment,\n): Promise<PosPaymentOutcome> {\n const hostId = staff.hostId\n if (CommerceModel.isCardPaymentMethod(payment.method)) {\n if (!payment.paymentIntentId) {\n return { ok: false, status: 409, error: 'A card payment on this sale has no charge to refund.' }\n }\n const refund = await posStripe('POST', 'refunds', {\n idempotencyKey: `pos-void:${payment.id}`,\n params: {\n payment_intent: payment.paymentIntentId,\n reverse_transfer: true,\n refund_application_fee: true,\n 'metadata[kind]': 'pos-void',\n 'metadata[orderId]': order.$id,\n },\n })\n if (!refund.ok) {\n return {\n ok: false,\n status: 502,\n error: posStripeErrorMessage(refund.body, 'The card refund failed. The sale is still open.'),\n }\n }\n }\n const cardRef = payment.giftCardId ? giftCardRef(hostId, payment.giftCardId) : null\n const stayRef = payment.reservationId ? reservationRef(hostId, payment.reservationId) : null\n return await applyPosPayment({\n hostId,\n orderId: order.$id,\n paymentId: payment.id,\n prepare: async (transaction) => {\n if (payment.method === 'gift_card' && cardRef) {\n const snapshot = await transaction.get(cardRef)\n return { card: snapshot.exists ? (snapshot.data() as CommerceModel.HostGiftCard) : null, folio: null }\n }\n if (payment.method === 'folio' && stayRef) {\n const snapshot = await transaction.get(stayRef)\n return { card: null, folio: snapshot.exists ? ((snapshot.get('folio') ?? []) as any[]) : null }\n }\n return { card: null, folio: null }\n },\n decide: ({ existing }) => {\n if (!existing) return { kind: 'refuse', status: 404, error: 'Unknown payment' }\n if (existing.status !== 'succeeded') return { kind: 'keep' }\n return {\n kind: 'put',\n payment: { ...existing, status: 'reversed' },\n event: {\n event: 'pos-payment-reversed',\n detail:\n existing.method === 'cash'\n ? `${CommerceModel.describeOrderPayment(existing)} handed back in cash`\n : `${CommerceModel.describeOrderPayment(existing)} returned`,\n },\n }\n },\n write: (transaction, context, reversed) => {\n if (reversed.method === 'gift_card' && cardRef && context.card) {\n transaction.set(\n cardRef,\n { balanceCents: Number(context.card.balanceCents ?? 0) + reversed.amountCents },\n { merge: true },\n )\n }\n if (reversed.method === 'folio' && stayRef && context.folio) {\n transaction.update(stayRef, {\n folio: context.folio.filter((entry) => entry?.paymentId !== reversed.id),\n })\n }\n },\n })\n}\n\n/** A repeat of the same receipt choice inside this window sends nothing more. */\nconst RECEIPT_REPEAT_WINDOW_MS = 2 * 60 * 1000\n\n/**\n * How the customer wants their receipt, from the cashier or the customer\n * display. Kept on the order; an email chosen after the sale is paid is sent\n * at once, and one chosen before is sent when it completes.\n */\nasync function recordReceiptChoice(\n staff: PosStaff,\n orderId: string,\n body: Record<string, any>,\n): Promise<PosPaymentOutcome> {\n const channel = String(body['channel'] ?? '') as CommerceModel.PosReceiptChannel\n if (!['email', 'sms', 'print', 'none'].includes(channel)) {\n return { ok: false, status: 400, error: 'Choose email, text, print or no receipt.' }\n }\n const to =\n channel === 'email'\n ? CommerceModel.posDisplayEmail(body['to'])\n : channel === 'sms'\n ? CommerceModel.posDisplayPhone(body['to'])\n : ''\n if ((channel === 'email' || channel === 'sms') && !to) {\n return {\n ok: false,\n status: 400,\n error: channel === 'email' ? 'Enter a valid email address.' : 'Enter a valid phone number.',\n }\n }\n if (channel === 'sms' && !pluginSmsAvailable()) {\n return { ok: false, status: 409, error: 'Text receipts are not set up for this store.' }\n }\n const marketingOptIn = channel === 'email' && body['marketingOptIn'] === true\n const firestore = firebaseAdmin.app().firestore()\n const orderRef = firestore.collection('hosts').doc(staff.hostId).collection('orders').doc(orderId)\n const order = await firestore.runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(orderRef)\n if (!snapshot.exists) return null\n const fresh = {\n ...(CommerceModel.liftLegacyOrder((snapshot.data() ?? {}) as any) as any),\n $id: orderId,\n } as PosLiftedOrder\n if (fresh.channel !== 'pos') return null\n // The same choice twice in a row (a double tap, or the display and the\n // cashier answering together) is one receipt, not two.\n const previous = fresh.receiptRequest\n if (\n fresh.status === 'paid' &&\n previous &&\n previous.channel === channel &&\n String(previous.to ?? '') === to &&\n Date.now() - Number(previous.atMs ?? 0) < RECEIPT_REPEAT_WINDOW_MS\n ) {\n return { ...fresh, repeated: true } as PosLiftedOrder & { repeated?: boolean }\n }\n const receiptRequest = {\n channel,\n ...(to ? { to } : {}),\n ...(marketingOptIn ? { marketingOptIn: true } : {}),\n atMs: Date.now(),\n }\n transaction.set(\n orderRef,\n {\n receiptRequest,\n ...(channel === 'email' && !fresh.customerEmail\n ? {\n customerEmail: to,\n ...CommerceModel.orderListFields({ ...fresh, customerEmail: to }, orderId),\n }\n : {}),\n // The receipt door texts `customerPhone` (AGL-3610).\n ...(channel === 'sms' ? { customerPhone: to } : {}),\n },\n { merge: true },\n )\n return { ...fresh, receiptRequest } as PosLiftedOrder & { repeated?: boolean }\n })\n if (!order) return { ok: false, status: 404, error: 'Unknown sale' }\n if (order.repeated) return { ok: true, order, payment: null, completed: false, changed: false }\n if (order.status === 'paid' && channel === 'print') {\n // Chosen after the sale completed: printed now on the register's receipt\n // printer, under the sale's own key so it never prints twice (AGL-3609).\n await printPosSaleReceipt(staff.hostId, orderId)\n }\n if (order.status === 'paid' && order.registerId) {\n // The customer has answered (or the cashier for them): the display says\n // thank you and drops the address they typed (AGL-3608).\n await finishPosDisplayReceipt(staff.hostId, order.registerId).catch((error: unknown) =>\n console.error('[pos-payment] display finish failed', error),\n )\n }\n if (order.status === 'paid' && (channel === 'email' || channel === 'sms')) {\n // Chosen after the sale completed: sent now, to where they said.\n const sent = await deliverChosenPosReceipt(\n { hostId: staff.hostId, orderId },\n { channel, to, orderEmail: String(order.customerEmail ?? '') },\n )\n if (channel === 'email') {\n await recordCapturedContact({\n orgId: '',\n hostId: staff.hostId,\n identity: { email: to },\n surface: 'relationship',\n lifecycleFloor: 'customer',\n ...(marketingOptIn ? { marketingConsent: true } : {}),\n interaction: {\n source: 'order',\n refId: orderId,\n summary: `In-store purchase (${CommerceModel.formatReceiptMoney(\n Number(order.totals?.totalCents ?? 0),\n POS_CURRENCY,\n )})`,\n },\n }).catch((error: unknown) => console.error('[pos-payment] contact capture failed', error))\n }\n if (sent !== 'sent') {\n // A failed send is not a repeat: the cashier's retry goes out.\n await orderRef\n .set({ receiptRequest: { atMs: 0 } }, { merge: true })\n .catch((error: unknown) => console.error('[pos-payment] receipt retry reset failed', error))\n }\n if (sent === 'not_configured') {\n return {\n ok: false,\n status: 409,\n error: channel === 'sms' ? 'Text receipts are not set up for this store.' : 'Email is not set up.',\n }\n }\n if (sent !== 'sent') return { ok: false, status: 502, error: 'The receipt could not be sent.' }\n }\n return { ok: true, order, payment: null, completed: false, changed: true }\n}\n"],"names":["consumeRateLimit","firebaseAdmin","getPluginConfig","buildRoute","Route","recordCapturedContact","pluginSmsAvailable","finishPosDisplayReceipt","CommerceModel","posRegisterSettings","authorizePosStaff","posIdempotencyKey","posQueryBody","posRequestBody","applyPosPayment","deliverChosenPosReceipt","posPaymentId","posSaleSummary","readPosSale","releasePosSaleDiscount","posPaymentCashierId","printPosSaleReceipt","POS_CURRENCY","posStripe","posStripeErrorMessage","posStripeTestMode","posTerminalAvailable","cancelPosCardPayment","createCardPresentIntent","refreshPosCardPayment","retryCardPresentPayment","simulatePosReaderTap","startCardKeyedPayment","startCardLinkPayment","startCardPresentPayment","posPaymentHandler","req","res","body","method","status","json","error","hostId","String","gate","staff","action","orderId","giftCardBalance","process","readers","app","firestore","collection","doc","limit","get","docs","map","id","label","registerId","livemode","Boolean","settings","orgId","undefined","terminal","available","testMode","publishableKey","env","NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY","smsReceipts","startsPayment","includes","attemptKey","paymentId","uid","signedInUid","assertion","amountCents","Math","round","Number","tipCents","outcome","order","ok","payment","completed","changed","takeCash","takeGiftCard","takeFolio","cashierId","org","readerId","returnUrl","registerReturnUrl","headers","host","cardNumber","voidPosSale","recordReceiptChoice","sale","clientSecret","paymentIntentId","console","requestHost","origin","subdomain","orgSlug","HOST_PLUGIN","pluginSlug","tenderable","payments","posTenderableCents","totals","totalCents","NOT_OPEN","kind","tenderedCents","askedCents","decide","existing","isFinite","open","min","max","tipProblem","posTipProblem","total","now","Date","atMs","settledAtMs","cashTenderedCents","changeCents","takeFeeCents","posTakeShareCents","posTakeFeeCents","feeCents","giftCardRef","code","giftCardCodeOf","rate","windowMs","allowed","giftCardCodeProblem","snapshot","exists","card","data","availableCents","giftCardAvailableCents","frozen","isGiftCardFrozen","voided","voidedAtMs","last4","slice","cardRef","prepare","transaction","context","giftCardId","write","set","balanceCents","lastUsedAtMs","merge","reservationRef","reservationId","test","stayRef","stayExists","folioAtMs","event","detail","_stay","update","folio","FieldValue","arrayUnion","note","Array","isArray","orderPayments","isCardPaymentMethod","cancelled","current","reversed","reversePayment","orderRef","runTransaction","fresh","liftLegacyOrder","$id","some","next","timeline","appendOrderEvent","cancelledAtMs","orderListFields","refund","idempotencyKey","params","payment_intent","reverse_transfer","refund_application_fee","describeOrderPayment","filter","entry","RECEIPT_REPEAT_WINDOW_MS","channel","to","posDisplayEmail","posDisplayPhone","marketingOptIn","previous","receiptRequest","repeated","customerEmail","customerPhone","catch","sent","orderEmail","identity","email","surface","lifecycleFloor","marketingConsent","interaction","source","refId","summary","formatReceiptMoney"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAChBC,aAAa,EACbC,eAAe,QACV,2BAA0B;AACjC,SAASC,UAAU,EAAEC,KAAK,QAA+B,sBAAqB;AAC9E,OAAOC,2BAA2B,sDAAqD;AACvF,SAASC,kBAAkB,QAAQ,mDAAkD;AACrF,SAASC,uBAAuB,QAAQ,mBAAe;AACvD,YAAYC,mBAAmB,oBAAU;AACzC,SA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nE,KAAK,CAAC,wCAAwCA;QACrF;QACA,IAAIyL,SAAS,QAAQ;YACnB,+DAA+D;YAC/D,MAAMhC,SACH1B,GAAG,CAAC;gBAAEqD,gBAAgB;oBAAEtF,MAAM;gBAAE;YAAE,GAAG;gBAAEoC,OAAO;YAAK,GACnDsD,KAAK,CAAC,CAACxL,QAAmBmE,QAAQnE,KAAK,CAAC,4CAA4CA;QACzF;QACA,IAAIyL,SAAS,kBAAkB;YAC7B,OAAO;gBACL1I,IAAI;gBACJjD,QAAQ;gBACRE,OAAO8K,YAAY,QAAQ,iDAAiD;YAC9E;QACF;QACA,IAAIW,SAAS,QAAQ,OAAO;YAAE1I,IAAI;YAAOjD,QAAQ;YAAKE,OAAO;QAAiC;IAChG;IACA,OAAO;QAAE+C,IAAI;QAAMD;QAAOE,SAAS;QAAMC,WAAW;QAAOC,SAAS;IAAK;AAC3E"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-payment.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 {\n consumeRateLimit,\n firebaseAdmin,\n getPluginConfig,\n} from '@aglyn/tenant-data-admin'\nimport { buildRoute, Route, type PluginApiHandler } from '@aglyn/aglyn/server'\nimport recordCapturedContact from '@aglyn/aglyn/plugin-manager/record-captured-contact'\nimport { pluginSmsAvailable } from '@aglyn/aglyn/plugin-manager/plugin-sms-messaging'\nimport {\n checkoutCreditProvider,\n checkoutCreditProviderForCode,\n normalizeCheckoutCreditAccount,\n normalizeCheckoutCreditCode,\n offeredCheckoutCredits,\n type CheckoutCreditStage,\n} from '@aglyn/aglyn/plugin-manager/plugin-checkout-credits'\nimport { finishPosDisplayReceipt } from './pos-display'\nimport * as CommerceModel from '../model'\nimport { posRegisterSettings } from '../plugin-config'\nimport {\n authorizePosStaff,\n posIdempotencyKey,\n posQueryBody,\n posRequestBody,\n type PosStaff,\n} from './pos-auth'\nimport {\n applyPosPayment,\n deliverChosenPosReceipt,\n posPaymentId,\n posSaleSummary,\n readPosSale,\n releasePosSaleDiscount,\n type PosLiftedOrder,\n type PosPaymentOutcome,\n} from './pos-sale'\nimport { posPaymentCashierId } from './pos-sale-stamp'\nimport { printPosSaleReceipt } from './pos-print'\nimport {\n POS_CURRENCY,\n posStripe,\n posStripeErrorMessage,\n posStripeTestMode,\n posTerminalAvailable,\n} from './pos-stripe'\nimport {\n cancelPosCardPayment,\n createCardPresentIntent,\n refreshPosCardPayment,\n retryCardPresentPayment,\n simulatePosReaderTap,\n startCardKeyedPayment,\n startCardLinkPayment,\n startCardPresentPayment,\n} from './pos-terminal'\n\n/**\n * `POST /api/commerce/pos-payment` (AGL-3607): every tender against an OPEN\n * register sale, one `action` per request.\n *\n * The sale was priced by `pos-order.ts` (`payment: 'open'`); nothing here\n * re-prices it or lets the register name a total. Each payment-starting action\n * needs the register's `Idempotency-Key`, from which the payment's id is\n * derived: pressing a tender twice, or retrying after a lost response, finds\n * the payment the first press started instead of taking the money twice.\n */\nexport const posPaymentHandler: PluginApiHandler = async (req, res) => {\n // `sale` is a read and may be a GET, so a register re-reading its sale does\n // not spend the console's write budget; everything else moves money.\n const body = req.method === 'GET' ? posQueryBody(req) : posRequestBody(req)\n if (\n !(\n req.method === 'POST' ||\n (req.method === 'GET' && (body['action'] === 'sale' || body['action'] === 'context'))\n )\n ) {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(body['hostId'] ?? '')\n const gate = await authorizePosStaff(req, hostId)\n if ('error' in gate) return res.status(gate.status).json({ error: gate.error })\n let staff = gate.staff\n const action = String(body['action'] ?? '')\n const orderId = String(body['orderId'] ?? '')\n try {\n if (action === 'gift-card-balance') {\n return await giftCardBalance(staff, body, res)\n }\n if (action === 'credit-lookup') {\n return await creditLookup(staff, body, res)\n }\n if (action === 'context') {\n // What the register needs to draw its tenders: the site's tip and\n // receipt settings, whether card readers are offered at all, and the\n // key the typed-card form loads Stripe with.\n const readers = posTerminalAvailable()\n ? (\n await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('terminalReaders')\n .limit(50)\n .get()\n ).docs.map((doc: any) => ({\n id: doc.id as string,\n label: String(doc.get('label') ?? 'Card reader'),\n registerId: (doc.get('registerId') as string | undefined) ?? null,\n status: String(doc.get('status') ?? 'offline'),\n livemode: Boolean(doc.get('livemode')),\n }))\n : []\n return res.status(200).json({\n settings: posRegisterSettings(\n await getPluginConfig(staff.orgId || undefined, 'commerce', { hostId }),\n ),\n terminal: { available: posTerminalAvailable(), testMode: posStripeTestMode() },\n readers,\n publishableKey: String(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY ?? ''),\n // A text receipt is offered only when an SMS provider is on (AGL-3610).\n smsReceipts: pluginSmsAvailable(),\n // Store credit other plugins keep — rewards (AGL-3640) — offered here.\n credits: await offeredCheckoutCredits({ hostId, channel: 'pos' }),\n })\n }\n if (!orderId) return res.status(400).json({ error: 'Missing orderId' })\n const startsPayment = [\n 'card-present-sdk',\n 'cash',\n 'gift-card',\n 'credit',\n 'folio',\n 'card-present',\n 'card-keyed',\n 'card-link',\n ].includes(action)\n const attemptKey = posIdempotencyKey(req)\n if (startsPayment && !attemptKey) {\n return res.status(400).json({ error: 'Missing Idempotency-Key' })\n }\n const paymentId = startsPayment\n ? posPaymentId(orderId, attemptKey)\n : String(body['paymentId'] ?? '')\n // The cashier a PIN switched in takes the payment (AGL-3609).\n if (startsPayment && body['cashierAssertion']) {\n staff = {\n ...staff,\n uid: await posPaymentCashierId({\n hostId,\n orderId,\n signedInUid: staff.uid,\n assertion: body['cashierAssertion'],\n }),\n }\n }\n const amountCents = Math.round(Number(body['amountCents'] ?? 0))\n const tipCents = Math.round(Number(body['tipCents'] ?? 0)) || 0\n const settings = posRegisterSettings(\n await getPluginConfig(staff.orgId || undefined, 'commerce', { hostId }),\n )\n let outcome: (PosPaymentOutcome & { clientSecret?: string; paymentIntentId?: string }) | null = null\n switch (action) {\n case 'sale': {\n const order = await readPosSale(hostId, orderId)\n if (!order) return res.status(404).json({ error: 'Unknown sale' })\n outcome = { ok: true, order, payment: null, completed: false, changed: false }\n break\n }\n case 'cash':\n outcome = await takeCash(staff, orderId, paymentId, body, tipCents)\n break\n case 'gift-card':\n outcome = await takeGiftCard(staff, orderId, paymentId, body)\n break\n case 'credit':\n outcome = await takeCredit(staff, orderId, paymentId, body)\n break\n case 'folio':\n outcome = await takeFolio(staff, orderId, paymentId, body)\n break\n case 'card-present':\n outcome = await startCardPresentPayment({\n hostId,\n orderId,\n paymentId,\n amountCents,\n tipCents,\n cashierId: staff.uid,\n org: staff.org,\n readerId: String(body['readerId'] ?? ''),\n settings,\n })\n break\n case 'card-present-sdk':\n // Collected by a native app's Stripe Terminal SDK (Tap to Pay or a\n // Bluetooth reader, AGL-3618) against this server-made intent; it\n // settles exactly like a smart-reader payment.\n outcome = await createCardPresentIntent({\n hostId,\n orderId,\n paymentId,\n amountCents,\n tipCents,\n cashierId: staff.uid,\n org: staff.org,\n })\n break\n case 'card-keyed':\n outcome = await startCardKeyedPayment({\n hostId,\n orderId,\n paymentId,\n amountCents,\n tipCents,\n cashierId: staff.uid,\n org: staff.org,\n })\n break\n case 'card-link':\n outcome = await startCardLinkPayment({\n hostId,\n orderId,\n paymentId,\n amountCents,\n tipCents,\n cashierId: staff.uid,\n org: staff.org,\n returnUrl: await registerReturnUrl(req.headers.host, hostId, staff),\n })\n break\n case 'status':\n outcome = await refreshPosCardPayment({ hostId, orderId, paymentId })\n break\n case 'cancel':\n outcome = await cancelPosCardPayment({ hostId, orderId, paymentId })\n break\n case 'retry':\n outcome = await retryCardPresentPayment({ hostId, orderId, paymentId, settings })\n break\n case 'simulate':\n outcome = await simulatePosReaderTap({\n hostId,\n orderId,\n paymentId,\n cardNumber: String(body['cardNumber'] ?? ''),\n })\n break\n case 'void':\n outcome = await voidPosSale(staff, orderId)\n break\n case 'receipt':\n outcome = await recordReceiptChoice(staff, orderId, body)\n break\n default:\n return res.status(400).json({ error: 'Unknown action' })\n }\n if ('error' in outcome) return res.status(outcome.status).json({ error: outcome.error })\n return res.status(200).json({\n sale: posSaleSummary(outcome.order),\n ...(outcome.payment ? { paymentId: outcome.payment.id } : {}),\n completed: outcome.order.status === 'paid',\n ...(outcome.clientSecret ? { clientSecret: outcome.clientSecret } : {}),\n ...(outcome.paymentIntentId ? { paymentIntentId: outcome.paymentIntentId } : {}),\n })\n } catch (error) {\n console.error('[pos-payment]', action, error)\n return res.status(500).json({ error: 'Payment failed — check the sale before trying again' })\n }\n}\n\n/** Where a QR payment page sends the customer back to: the register. */\nasync function registerReturnUrl(\n requestHost: string | string[] | undefined,\n hostId: string,\n staff: PosStaff,\n): Promise<string> {\n const origin = `https://${String(requestHost ?? '')}`\n const subdomain = (\n await firebaseAdmin.app().firestore().collection('hostIndex').doc(hostId).get()\n ).get('subdomain') as string | undefined\n const orgSlug = staff.org?.['slug'] as string | undefined\n return orgSlug && subdomain\n ? `${origin}${buildRoute(Route.HOST_PLUGIN, { orgSlug, host: subdomain, pluginSlug: 'pos' })}`\n : origin\n}\n\n/** The balance a new tender may take, or a refusal. */\nfunction tenderable(\n order: PosLiftedOrder,\n payments: CommerceModel.OrderPayment[],\n): number {\n return CommerceModel.posTenderableCents(Number(order.totals?.totalCents ?? 0), payments)\n}\n\nconst NOT_OPEN = { kind: 'refuse' as const, status: 409, error: 'This sale is no longer open' }\n\n/**\n * Cash: the amount defaults to whatever is left, the change is what the\n * customer handed over beyond it (and beyond any tip they chose).\n */\nasync function takeCash(\n staff: PosStaff,\n orderId: string,\n paymentId: string,\n body: Record<string, any>,\n tipCents: number,\n): Promise<PosPaymentOutcome> {\n const tenderedCents = Math.round(Number(body['tenderedCents'] ?? 0))\n const askedCents = Math.round(Number(body['amountCents'] ?? 0))\n return await applyPosPayment({\n hostId: staff.hostId,\n orderId,\n paymentId,\n decide: ({ order, payments, existing }) => {\n if (existing) return { kind: 'keep' }\n if (order.status !== 'pending') return NOT_OPEN\n if (!Number.isFinite(tenderedCents) || tenderedCents <= 0) {\n return { kind: 'refuse', status: 400, error: 'Enter the cash received.' }\n }\n const open = tenderable(order, payments)\n if (open <= 0) return { kind: 'refuse', status: 409, error: 'Nothing is left to pay on this sale.' }\n const amountCents =\n askedCents > 0 ? Math.min(askedCents, open) : Math.min(open, Math.max(0, tenderedCents - tipCents))\n if (!(amountCents > 0)) {\n return { kind: 'refuse', status: 400, error: 'The cash received does not cover the tip.' }\n }\n const tipProblem = CommerceModel.posTipProblem(tipCents, amountCents)\n if (tipProblem) return { kind: 'refuse', status: 400, error: tipProblem }\n if (tenderedCents < amountCents + tipCents) {\n return { kind: 'refuse', status: 400, error: 'Cash received is short' }\n }\n const total = Number(order.totals?.totalCents ?? 0)\n const now = Date.now()\n return {\n kind: 'put',\n payment: {\n id: paymentId,\n method: 'cash',\n amountCents,\n ...(tipCents > 0 ? { tipCents } : {}),\n status: 'succeeded',\n atMs: now,\n settledAtMs: now,\n cashTenderedCents: tenderedCents,\n changeCents: tenderedCents - amountCents - tipCents,\n takeFeeCents: CommerceModel.posTakeShareCents({\n takeFeeCents: Number(order.posTakeFeeCents ?? 0),\n totalCents: total,\n amountCents,\n }),\n feeCents: 0,\n cashierId: staff.uid,\n },\n }\n },\n })\n}\n\nfunction giftCardRef(hostId: string, code: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('giftCards')\n .doc(code)\n}\n\n/** A gift card's spendable balance, for the cashier to read to the customer. */\nasync function giftCardBalance(\n staff: PosStaff,\n body: Record<string, any>,\n res: Parameters<PluginApiHandler>[1],\n): Promise<void> {\n const code = CommerceModel.giftCardCodeOf(body['code'])\n const rate = await consumeRateLimit(`pos-gift-balance:${staff.uid}`, {\n limit: 30,\n windowMs: 60_000,\n })\n if (!rate.allowed) {\n return res.status(429).json({ error: 'Too many balance checks. Wait a minute and try again.' })\n }\n if (CommerceModel.giftCardCodeProblem(code)) {\n return res.status(404).json({ error: 'No gift card has that code.' })\n }\n const snapshot = await giftCardRef(staff.hostId, code).get()\n if (!snapshot.exists) return res.status(404).json({ error: 'No gift card has that code.' })\n const card = snapshot.data() as CommerceModel.HostGiftCard\n return res.status(200).json({\n availableCents: CommerceModel.giftCardAvailableCents(card, Date.now()),\n frozen: CommerceModel.isGiftCardFrozen(card),\n voided: Number(card.voidedAtMs) > 0,\n last4: code.slice(-4),\n })\n}\n\n/**\n * A gift card: takes the smaller of what the card can give and what is left\n * to pay, in ONE transaction with the sale. The card's spendable balance\n * honours every live hold an online checkout placed on it (AGL-2449), and a\n * frozen card gives nothing (AGL-3363), so the till and the website can\n * never spend the same dollars.\n */\nasync function takeGiftCard(\n staff: PosStaff,\n orderId: string,\n paymentId: string,\n body: Record<string, any>,\n): Promise<PosPaymentOutcome> {\n const code = CommerceModel.giftCardCodeOf(body['code'])\n if (CommerceModel.giftCardCodeProblem(code)) {\n return { ok: false, status: 404, error: 'No gift card has that code.' }\n }\n const askedCents = Math.round(Number(body['amountCents'] ?? 0))\n const cardRef = giftCardRef(staff.hostId, code)\n return await applyPosPayment({\n hostId: staff.hostId,\n orderId,\n paymentId,\n prepare: async (transaction) => {\n const snapshot = await transaction.get(cardRef)\n return snapshot.exists ? (snapshot.data() as CommerceModel.HostGiftCard) : null\n },\n decide: ({ order, payments, existing, context: card }) => {\n if (existing) return { kind: 'keep' }\n if (order.status !== 'pending') return NOT_OPEN\n if (!card) return { kind: 'refuse', status: 404, error: 'No gift card has that code.' }\n const available = CommerceModel.giftCardAvailableCents(card, Date.now())\n if (available <= 0) {\n return {\n kind: 'refuse',\n status: 409,\n error: CommerceModel.isGiftCardFrozen(card)\n ? 'This gift card is on hold and cannot be used right now.'\n : 'This gift card has no balance left.',\n }\n }\n const open = tenderable(order, payments)\n const amountCents = Math.min(available, open, askedCents > 0 ? askedCents : open)\n if (!(amountCents > 0)) {\n return { kind: 'refuse', status: 409, error: 'Nothing is left to pay on this sale.' }\n }\n const now = Date.now()\n return {\n kind: 'put',\n payment: {\n id: paymentId,\n method: 'gift_card',\n amountCents,\n status: 'succeeded',\n atMs: now,\n settledAtMs: now,\n giftCardId: code,\n last4: code.slice(-4),\n takeFeeCents: CommerceModel.posTakeShareCents({\n takeFeeCents: Number(order.posTakeFeeCents ?? 0),\n totalCents: Number(order.totals?.totalCents ?? 0),\n amountCents,\n }),\n feeCents: 0,\n cashierId: staff.uid,\n },\n }\n },\n write: (transaction, card, payment) => {\n transaction.set(\n cardRef,\n {\n balanceCents: Math.max(0, Number(card?.balanceCents ?? 0) - payment.amountCents),\n lastUsedAtMs: Date.now(),\n },\n { merge: true },\n )\n },\n })\n}\n\n/**\n * Staff search for a store-credit account at the register (AGL-3640): a\n * customer's email or code, answered by the plugin that keeps the account.\n * Only staff reach it — `authorizePosStaff` above — so a provider may look\n * accounts up by email here, which it never does for a shopper.\n */\nasync function creditLookup(staff: PosStaff, body: Record<string, any>, res: any) {\n const entry = checkoutCreditProvider(String(body['providerId'] ?? ''))\n if (!entry?.provider.lookup) return res.status(404).json({ error: 'That kind of credit is not taken here.' })\n const rate = await consumeRateLimit(`pos-credit-lookup:${staff.uid}`, {\n limit: 60,\n windowMs: 60_000,\n })\n if (!rate.allowed) return res.status(429).json({ error: 'Too many lookups. Wait a moment.' })\n if (!(await entry.provider.offered({ hostId: staff.hostId, channel: 'pos' }).catch(() => false))) {\n return res.status(404).json({ error: 'That kind of credit is not taken here.' })\n }\n const found = await entry.provider\n .lookup({ hostId: staff.hostId, query: String(body['query'] ?? '').slice(0, 120) })\n .catch((error: unknown) => {\n console.error('[pos-payment] credit lookup failed', entry.providerId, error)\n return []\n })\n const accounts = found\n .slice(0, 10)\n .map((account) => normalizeCheckoutCreditAccount(account))\n .filter((account) => !('error' in account))\n return res.status(200).json({ providerId: entry.providerId, accounts })\n}\n\n/**\n * Store credit another plugin keeps (AGL-3640) — a rewards balance, a friend's\n * referral credit — by the customer's code, or by the account a staff lookup\n * found. The provider's stage reads the account INSIDE the sale's transaction\n * and its debit writes there, so the credit is taken with the payment or not\n * at all; a retried press finds its own payment and takes nothing more.\n */\nasync function takeCredit(\n staff: PosStaff,\n orderId: string,\n paymentId: string,\n body: Record<string, any>,\n): Promise<PosPaymentOutcome> {\n const code = normalizeCheckoutCreditCode(body['code'])\n const entry = code\n ? checkoutCreditProviderForCode(code)\n : checkoutCreditProvider(String(body['providerId'] ?? ''))\n if (!entry) return { ok: false, status: 404, error: 'That code is not one this store takes.' }\n if (!(await entry.provider.offered({ hostId: staff.hostId, channel: 'pos' }).catch(() => false))) {\n return { ok: false, status: 404, error: 'That kind of credit is not taken here.' }\n }\n const sale = await readPosSale(staff.hostId, orderId)\n if (!sale) return { ok: false, status: 404, error: 'Unknown sale' }\n const account = normalizeCheckoutCreditAccount(\n await entry.provider\n .resolve({\n hostId: staff.hostId,\n ...(code ? { code } : { reference: String(body['reference'] ?? '') }),\n channel: 'pos',\n customerEmail: (sale as { customerEmail?: string | null }).customerEmail ?? null,\n staff: true,\n })\n .catch((error: unknown) => {\n console.error('[pos-payment] credit resolve failed', entry.providerId, error)\n return null\n }),\n )\n if ('error' in account) return { ok: false, status: account.status, error: account.error }\n const askedCents = Math.round(Number(body['amountCents'] ?? 0))\n return await applyPosPayment<CheckoutCreditStage | null>({\n hostId: staff.hostId,\n orderId,\n paymentId,\n prepare: async (transaction) =>\n entry.provider.stage({\n transaction,\n hostId: staff.hostId,\n reference: account.reference,\n orderId,\n nowMs: Date.now(),\n }),\n decide: ({ order, payments, existing, context: stage }) => {\n if (existing) return { kind: 'keep' }\n if (order.status !== 'pending') return NOT_OPEN\n if (!stage) return { kind: 'refuse', status: 404, error: `That ${account.label.toLowerCase()} account no longer exists.` }\n const open = tenderable(order, payments)\n if (open <= 0) return { kind: 'refuse', status: 409, error: 'Nothing is left to pay on this sale.' }\n const amountCents = Math.min(stage.availableCents, open, askedCents > 0 ? askedCents : open)\n if (!(amountCents > 0)) {\n return { kind: 'refuse', status: 409, error: `This ${account.label.toLowerCase()} account has nothing to spend.` }\n }\n const now = Date.now()\n return {\n kind: 'put',\n payment: {\n id: paymentId,\n method: 'credit',\n amountCents,\n status: 'succeeded',\n atMs: now,\n settledAtMs: now,\n creditProviderId: entry.providerId,\n creditReference: account.reference,\n creditLabel: account.label,\n ...(account.last4 ? { last4: account.last4 } : {}),\n takeFeeCents: CommerceModel.posTakeShareCents({\n takeFeeCents: Number(order.posTakeFeeCents ?? 0),\n totalCents: Number(order.totals?.totalCents ?? 0),\n amountCents,\n }),\n feeCents: 0,\n cashierId: staff.uid,\n },\n }\n },\n write: (_transaction, stage, payment) => {\n // The stage writes through the sale's own transaction. Taking less than\n // the payment records would leave the sale paid by money that did not\n // move, so a short debit aborts the whole commit instead.\n const taken = stage ? stage.debit({ cents: payment.amountCents, key: payment.id, orderId, channel: 'pos' }) : 0\n if (taken !== payment.amountCents) {\n throw new Error(`credit debit ${taken} short of payment ${payment.amountCents}`)\n }\n },\n })\n}\n\nfunction reservationRef(hostId: string, reservationId: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('reservations')\n .doc(reservationId)\n}\n\n/** Charged to a checked-in stay's folio, in the same commit as the payment. */\nasync function takeFolio(\n staff: PosStaff,\n orderId: string,\n paymentId: string,\n body: Record<string, any>,\n): Promise<PosPaymentOutcome> {\n const reservationId = String(body['reservationId'] ?? '')\n if (!/^[A-Za-z0-9_-]{1,128}$/.test(reservationId)) {\n return { ok: false, status: 400, error: 'Pick a reservation' }\n }\n const askedCents = Math.round(Number(body['amountCents'] ?? 0))\n const stayRef = reservationRef(staff.hostId, reservationId)\n return await applyPosPayment({\n hostId: staff.hostId,\n orderId,\n paymentId,\n prepare: async (transaction) => (await transaction.get(stayRef)).exists as boolean,\n decide: ({ order, payments, existing, context: stayExists }) => {\n if (existing) return { kind: 'keep' }\n if (order.status !== 'pending') return NOT_OPEN\n if (!stayExists) return { kind: 'refuse', status: 404, error: 'Unknown reservation' }\n const open = tenderable(order, payments)\n const amountCents = Math.min(open, askedCents > 0 ? askedCents : open)\n if (!(amountCents > 0)) {\n return { kind: 'refuse', status: 409, error: 'Nothing is left to pay on this sale.' }\n }\n const now = Date.now()\n return {\n kind: 'put',\n payment: {\n id: paymentId,\n method: 'folio',\n amountCents,\n status: 'succeeded',\n atMs: now,\n settledAtMs: now,\n reservationId,\n folioAtMs: now,\n takeFeeCents: CommerceModel.posTakeShareCents({\n takeFeeCents: Number(order.posTakeFeeCents ?? 0),\n totalCents: Number(order.totals?.totalCents ?? 0),\n amountCents,\n }),\n feeCents: 0,\n cashierId: staff.uid,\n },\n event: { event: 'folio', detail: `Charged to reservation ${reservationId}` },\n }\n },\n write: (transaction, _stay, payment) => {\n // `update`, never a merge-set: a missing stay must not be minted as a\n // stub holding one folio line (AGL-1760). It exists — read above.\n transaction.update(stayRef, {\n folio: firebaseAdmin.firestore.FieldValue.arrayUnion({\n orderId,\n paymentId: payment.id,\n amountCents: payment.amountCents,\n note: 'Register sale',\n atMs: payment.folioAtMs ?? Date.now(),\n }),\n })\n },\n })\n}\n\n/**\n * Abandons an open sale: everything it took is handed back first — cards\n * refunded in full (tip included, fee and transfer reversed), gift cards\n * re-credited, the room charge taken off the folio, cash marked as returned —\n * and only then is the order cancelled. A refund Stripe refuses stops the void\n * with the sale still open and its payment still recorded, never cancelled\n * over money that did not come back.\n */\nexport async function voidPosSale(\n staff: PosStaff,\n orderId: string,\n): Promise<PosPaymentOutcome> {\n const hostId = staff.hostId\n const order = await readPosSale(hostId, orderId)\n if (!order) return { ok: false, status: 404, error: 'Unknown sale' }\n if (order.status === 'cancelled') return { ok: true, order, payment: null, completed: false, changed: false }\n if (order.status !== 'pending' || !Array.isArray(order.payments)) {\n return {\n ok: false,\n status: 409,\n error: 'This sale is already paid. Refund it from the order instead.',\n }\n }\n for (const payment of CommerceModel.orderPayments(order)) {\n if (payment.status === 'pending' && CommerceModel.isCardPaymentMethod(payment.method)) {\n const cancelled = await cancelPosCardPayment({ hostId, orderId, paymentId: payment.id })\n if (!cancelled.ok) return cancelled\n }\n }\n // Re-read after the cancels: one may have completed the sale in the gap.\n const current = await readPosSale(hostId, orderId)\n if (!current) return { ok: false, status: 404, error: 'Unknown sale' }\n if (current.status !== 'pending') {\n return {\n ok: false,\n status: 409,\n error: 'The last card payment went through and the sale is paid. Refund it from the order instead.',\n }\n }\n for (const payment of CommerceModel.orderPayments(current)) {\n if (payment.status !== 'succeeded') continue\n const reversed = await reversePayment(staff, current, payment)\n if (!reversed.ok) return reversed\n }\n const firestore = firebaseAdmin.app().firestore()\n const orderRef = firestore.collection('hosts').doc(hostId).collection('orders').doc(orderId)\n const cancelled = await firestore.runTransaction(async (transaction: any) => {\n const fresh = {\n ...(CommerceModel.liftLegacyOrder(((await transaction.get(orderRef)).data() ?? {}) as any) as any),\n $id: orderId,\n } as PosLiftedOrder\n if (fresh.status !== 'pending') return null\n const open = CommerceModel.orderPayments(fresh).some(\n (payment) => payment.status === 'pending' || payment.status === 'succeeded',\n )\n if (open) return null\n const next = {\n ...fresh,\n status: 'cancelled' as const,\n timeline: CommerceModel.appendOrderEvent(fresh, 'pos-sale-voided', 'Voided at the register'),\n }\n transaction.set(\n orderRef,\n {\n status: 'cancelled',\n cancelledAtMs: Date.now(),\n timeline: next.timeline,\n ...CommerceModel.orderListFields(next, orderId),\n },\n { merge: true },\n )\n return next\n })\n if (!cancelled) {\n return { ok: false, status: 409, error: 'A payment on this sale changed. Check it and try again.' }\n }\n await releasePosSaleDiscount(hostId, current)\n return { ok: true, order: cancelled, payment: null, completed: false, changed: true }\n}\n\n/** Hands one settled payment back, recording `reversed` in the same commit. */\nasync function reversePayment(\n staff: PosStaff,\n order: PosLiftedOrder,\n payment: CommerceModel.OrderPayment,\n): Promise<PosPaymentOutcome> {\n const hostId = staff.hostId\n if (CommerceModel.isCardPaymentMethod(payment.method)) {\n if (!payment.paymentIntentId) {\n return { ok: false, status: 409, error: 'A card payment on this sale has no charge to refund.' }\n }\n const refund = await posStripe('POST', 'refunds', {\n idempotencyKey: `pos-void:${payment.id}`,\n params: {\n payment_intent: payment.paymentIntentId,\n reverse_transfer: true,\n refund_application_fee: true,\n 'metadata[kind]': 'pos-void',\n 'metadata[orderId]': order.$id,\n },\n })\n if (!refund.ok) {\n return {\n ok: false,\n status: 502,\n error: posStripeErrorMessage(refund.body, 'The card refund failed. The sale is still open.'),\n }\n }\n }\n const cardRef = payment.giftCardId ? giftCardRef(hostId, payment.giftCardId) : null\n const stayRef = payment.reservationId ? reservationRef(hostId, payment.reservationId) : null\n // Store credit goes back to the plugin that keeps it (AGL-3640), in the\n // same commit as the reversal. A provider that is gone cannot take it\n // back, so the void stops with the sale still open rather than cancelling\n // over credit that did not come back.\n const creditEntry =\n payment.method === 'credit' && payment.creditProviderId ? checkoutCreditProvider(payment.creditProviderId) : null\n if (payment.method === 'credit' && (!creditEntry || !payment.creditReference)) {\n return {\n ok: false,\n status: 409,\n error: 'The store credit on this sale cannot be handed back right now. The sale is still open.',\n }\n }\n return await applyPosPayment({\n hostId,\n orderId: order.$id,\n paymentId: payment.id,\n prepare: async (transaction) => {\n if (payment.method === 'gift_card' && cardRef) {\n const snapshot = await transaction.get(cardRef)\n return { card: snapshot.exists ? (snapshot.data() as CommerceModel.HostGiftCard) : null, folio: null, credit: null }\n }\n if (payment.method === 'folio' && stayRef) {\n const snapshot = await transaction.get(stayRef)\n return { card: null, folio: snapshot.exists ? ((snapshot.get('folio') ?? []) as any[]) : null, credit: null }\n }\n if (payment.method === 'credit' && creditEntry && payment.creditReference) {\n const credit = await creditEntry.provider.stage({\n transaction,\n hostId,\n reference: payment.creditReference,\n orderId: order.$id,\n nowMs: Date.now(),\n })\n return { card: null, folio: null, credit }\n }\n return { card: null, folio: null, credit: null }\n },\n decide: ({ existing }) => {\n if (!existing) return { kind: 'refuse', status: 404, error: 'Unknown payment' }\n if (existing.status !== 'succeeded') return { kind: 'keep' }\n return {\n kind: 'put',\n payment: { ...existing, status: 'reversed' },\n event: {\n event: 'pos-payment-reversed',\n detail:\n existing.method === 'cash'\n ? `${CommerceModel.describeOrderPayment(existing)} handed back in cash`\n : `${CommerceModel.describeOrderPayment(existing)} returned`,\n },\n }\n },\n write: (transaction, context, reversed) => {\n if (reversed.method === 'gift_card' && cardRef && context.card) {\n transaction.set(\n cardRef,\n { balanceCents: Number(context.card.balanceCents ?? 0) + reversed.amountCents },\n { merge: true },\n )\n }\n if (reversed.method === 'folio' && stayRef && context.folio) {\n transaction.update(stayRef, {\n folio: context.folio.filter((entry) => entry?.paymentId !== reversed.id),\n })\n }\n if (reversed.method === 'credit' && context.credit) {\n context.credit.reverse({ key: reversed.id, orderId: order.$id })\n }\n },\n })\n}\n\n/** A repeat of the same receipt choice inside this window sends nothing more. */\nconst RECEIPT_REPEAT_WINDOW_MS = 2 * 60 * 1000\n\n/**\n * How the customer wants their receipt, from the cashier or the customer\n * display. Kept on the order; an email chosen after the sale is paid is sent\n * at once, and one chosen before is sent when it completes.\n */\nexport async function recordReceiptChoice(\n staff: PosStaff,\n orderId: string,\n body: Record<string, any>,\n): Promise<PosPaymentOutcome> {\n const channel = String(body['channel'] ?? '') as CommerceModel.PosReceiptChannel\n if (!['email', 'sms', 'print', 'none'].includes(channel)) {\n return { ok: false, status: 400, error: 'Choose email, text, print or no receipt.' }\n }\n const to =\n channel === 'email'\n ? CommerceModel.posDisplayEmail(body['to'])\n : channel === 'sms'\n ? CommerceModel.posDisplayPhone(body['to'])\n : ''\n if ((channel === 'email' || channel === 'sms') && !to) {\n return {\n ok: false,\n status: 400,\n error: channel === 'email' ? 'Enter a valid email address.' : 'Enter a valid phone number.',\n }\n }\n if (channel === 'sms' && !pluginSmsAvailable()) {\n return { ok: false, status: 409, error: 'Text receipts are not set up for this store.' }\n }\n const marketingOptIn = channel === 'email' && body['marketingOptIn'] === true\n const firestore = firebaseAdmin.app().firestore()\n const orderRef = firestore.collection('hosts').doc(staff.hostId).collection('orders').doc(orderId)\n const order = await firestore.runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(orderRef)\n if (!snapshot.exists) return null\n const fresh = {\n ...(CommerceModel.liftLegacyOrder((snapshot.data() ?? {}) as any) as any),\n $id: orderId,\n } as PosLiftedOrder\n if (fresh.channel !== 'pos') return null\n // The same choice twice in a row (a double tap, or the display and the\n // cashier answering together) is one receipt, not two.\n const previous = fresh.receiptRequest\n if (\n fresh.status === 'paid' &&\n previous &&\n previous.channel === channel &&\n String(previous.to ?? '') === to &&\n Date.now() - Number(previous.atMs ?? 0) < RECEIPT_REPEAT_WINDOW_MS\n ) {\n return { ...fresh, repeated: true } as PosLiftedOrder & { repeated?: boolean }\n }\n const receiptRequest = {\n channel,\n ...(to ? { to } : {}),\n ...(marketingOptIn ? { marketingOptIn: true } : {}),\n atMs: Date.now(),\n }\n transaction.set(\n orderRef,\n {\n receiptRequest,\n ...(channel === 'email' && !fresh.customerEmail\n ? {\n customerEmail: to,\n ...CommerceModel.orderListFields({ ...fresh, customerEmail: to }, orderId),\n }\n : {}),\n // The receipt door texts `customerPhone` (AGL-3610).\n ...(channel === 'sms' ? { customerPhone: to } : {}),\n },\n { merge: true },\n )\n return { ...fresh, receiptRequest } as PosLiftedOrder & { repeated?: boolean }\n })\n if (!order) return { ok: false, status: 404, error: 'Unknown sale' }\n if (order.repeated) return { ok: true, order, payment: null, completed: false, changed: false }\n if (order.status === 'paid' && channel === 'print') {\n // Chosen after the sale completed: printed now on the register's receipt\n // printer, under the sale's own key so it never prints twice (AGL-3609).\n await printPosSaleReceipt(staff.hostId, orderId)\n }\n // A kiosk's own receipt screen (AGL-3623) is not the register's display:\n // the display may be asking the cashier's customer right now.\n if (order.status === 'paid' && order.registerId && order.posSource !== 'kiosk') {\n // The customer has answered (or the cashier for them): the display says\n // thank you and drops the address they typed (AGL-3608).\n await finishPosDisplayReceipt(staff.hostId, order.registerId).catch((error: unknown) =>\n console.error('[pos-payment] display finish failed', error),\n )\n }\n if (order.status === 'paid' && (channel === 'email' || channel === 'sms')) {\n // Chosen after the sale completed: sent now, to where they said.\n const sent = await deliverChosenPosReceipt(\n { hostId: staff.hostId, orderId },\n { channel, to, orderEmail: String(order.customerEmail ?? '') },\n )\n if (channel === 'email') {\n await recordCapturedContact({\n orgId: '',\n hostId: staff.hostId,\n identity: { email: to },\n surface: 'relationship',\n lifecycleFloor: 'customer',\n ...(marketingOptIn ? { marketingConsent: true } : {}),\n interaction: {\n source: 'order',\n refId: orderId,\n summary: `In-store purchase (${CommerceModel.formatReceiptMoney(\n Number(order.totals?.totalCents ?? 0),\n POS_CURRENCY,\n )})`,\n },\n }).catch((error: unknown) => console.error('[pos-payment] contact capture failed', error))\n }\n if (sent !== 'sent') {\n // A failed send is not a repeat: the cashier's retry goes out.\n await orderRef\n .set({ receiptRequest: { atMs: 0 } }, { merge: true })\n .catch((error: unknown) => console.error('[pos-payment] receipt retry reset failed', error))\n }\n if (sent === 'not_configured') {\n return {\n ok: false,\n status: 409,\n error: channel === 'sms' ? 'Text receipts are not set up for this store.' : 'Email is not set up.',\n }\n }\n if (sent !== 'sent') return { ok: false, status: 502, error: 'The receipt could not be sent.' }\n }\n return { ok: true, order, payment: null, completed: false, changed: true }\n}\n"],"names":["consumeRateLimit","firebaseAdmin","getPluginConfig","buildRoute","Route","recordCapturedContact","pluginSmsAvailable","checkoutCreditProvider","checkoutCreditProviderForCode","normalizeCheckoutCreditAccount","normalizeCheckoutCreditCode","offeredCheckoutCredits","finishPosDisplayReceipt","CommerceModel","posRegisterSettings","authorizePosStaff","posIdempotencyKey","posQueryBody","posRequestBody","applyPosPayment","deliverChosenPosReceipt","posPaymentId","posSaleSummary","readPosSale","releasePosSaleDiscount","posPaymentCashierId","printPosSaleReceipt","POS_CURRENCY","posStripe","posStripeErrorMessage","posStripeTestMode","posTerminalAvailable","cancelPosCardPayment","createCardPresentIntent","refreshPosCardPayment","retryCardPresentPayment","simulatePosReaderTap","startCardKeyedPayment","startCardLinkPayment","startCardPresentPayment","posPaymentHandler","req","res","body","method","status","json","error","hostId","String","gate","staff","action","orderId","giftCardBalance","creditLookup","process","readers","app","firestore","collection","doc","limit","get","docs","map","id","label","registerId","livemode","Boolean","settings","orgId","undefined","terminal","available","testMode","publishableKey","env","NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY","smsReceipts","credits","channel","startsPayment","includes","attemptKey","paymentId","uid","signedInUid","assertion","amountCents","Math","round","Number","tipCents","outcome","order","ok","payment","completed","changed","takeCash","takeGiftCard","takeCredit","takeFolio","cashierId","org","readerId","returnUrl","registerReturnUrl","headers","host","cardNumber","voidPosSale","recordReceiptChoice","sale","clientSecret","paymentIntentId","console","requestHost","origin","subdomain","orgSlug","HOST_PLUGIN","pluginSlug","tenderable","payments","posTenderableCents","totals","totalCents","NOT_OPEN","kind","tenderedCents","askedCents","decide","existing","isFinite","open","min","max","tipProblem","posTipProblem","total","now","Date","atMs","settledAtMs","cashTenderedCents","changeCents","takeFeeCents","posTakeShareCents","posTakeFeeCents","feeCents","giftCardRef","code","giftCardCodeOf","rate","windowMs","allowed","giftCardCodeProblem","snapshot","exists","card","data","availableCents","giftCardAvailableCents","frozen","isGiftCardFrozen","voided","voidedAtMs","last4","slice","cardRef","prepare","transaction","context","giftCardId","write","set","balanceCents","lastUsedAtMs","merge","entry","provider","lookup","offered","catch","found","query","providerId","accounts","account","filter","resolve","reference","customerEmail","stage","nowMs","toLowerCase","creditProviderId","creditReference","creditLabel","_transaction","taken","debit","cents","key","Error","reservationRef","reservationId","test","stayRef","stayExists","folioAtMs","event","detail","_stay","update","folio","FieldValue","arrayUnion","note","Array","isArray","orderPayments","isCardPaymentMethod","cancelled","current","reversed","reversePayment","orderRef","runTransaction","fresh","liftLegacyOrder","$id","some","next","timeline","appendOrderEvent","cancelledAtMs","orderListFields","refund","idempotencyKey","params","payment_intent","reverse_transfer","refund_application_fee","creditEntry","credit","describeOrderPayment","reverse","RECEIPT_REPEAT_WINDOW_MS","to","posDisplayEmail","posDisplayPhone","marketingOptIn","previous","receiptRequest","repeated","customerPhone","posSource","sent","orderEmail","identity","email","surface","lifecycleFloor","marketingConsent","interaction","source","refId","summary","formatReceiptMoney"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAChBC,aAAa,EACbC,eAAe,QACV,2BAA0B;AACjC,SAASC,UAAU,EAAEC,KAAK,QAA+B,sBAAqB;AAC9E,OAAOC,2BAA2B,sDAAqD;AACvF,SAASC,kBAAkB,QAAQ,mDAAkD;AACrF,SACEC,sBAAsB,EACtBC,6BAA6B,EAC7BC,8BAA8B,EAC9BC,2BAA2B,EAC3BC,sBAAsB,QAEjB,sDAAqD;AAC5D,SAASC,uBAAuB,QAAQ,mBAAe;AACvD,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,mBAAmB,QAAQ,sBAAkB;AACtD,SACEC,iBAAiB,EACjBC,iBAAiB,EACjBC,YAAY,EACZC,cAAc,QAET,gBAAY;AACnB,SACEC,eAAe,EACfC,uBAAuB,EACvBC,YAAY,EACZC,cAAc,EACdC,WAAW,EACXC,sBAAsB,QAGjB,gBAAY;AACnB,SAASC,mBAAmB,QAAQ,sBAAkB;AACtD,SAASC,mBAAmB,QAAQ,iBAAa;AACjD,SACEC,YAAY,EACZC,SAAS,EACTC,qBAAqB,EACrBC,iBAAiB,EACjBC,oBAAoB,QACf,kBAAc;AACrB,SACEC,oBAAoB,EACpBC,uBAAuB,EACvBC,qBAAqB,EACrBC,uBAAuB,EACvBC,oBAAoB,EACpBC,qBAAqB,EACrBC,oBAAoB,EACpBC,uBAAuB,QAClB,oBAAgB;AAEvB;;;;;;;;;CASC,GACD,OAAO,MAAMC,oBAAsC,OAAOC,KAAKC;QA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