@aglyn/plugins-commerce 1.14.0 → 1.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/account-subscriptions.d.ts +51 -0
  3. package/src/lib/components/account-subscriptions.js +168 -0
  4. package/src/lib/components/account-subscriptions.js.map +1 -0
  5. package/src/lib/components/account.js +12 -48
  6. package/src/lib/components/account.js.map +1 -1
  7. package/src/lib/components/cart.js +38 -9
  8. package/src/lib/components/cart.js.map +1 -1
  9. package/src/lib/components/commerce-console-page.js +6 -0
  10. package/src/lib/components/commerce-console-page.js.map +1 -1
  11. package/src/lib/components/commerce-console-sections.d.ts +1 -1
  12. package/src/lib/components/commerce-console-sections.js +5 -0
  13. package/src/lib/components/commerce-console-sections.js.map +1 -1
  14. package/src/lib/components/console/paid-media.d.ts +1 -0
  15. package/src/lib/components/console/paid-media.js +15 -4
  16. package/src/lib/components/console/paid-media.js.map +1 -1
  17. package/src/lib/components/console/payments-settings-card.component.js +1 -1
  18. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  19. package/src/lib/components/console/pos/pos-hardware-api.d.ts +10 -1
  20. package/src/lib/components/console/pos/pos-hardware-api.js.map +1 -1
  21. package/src/lib/components/console/pos/pos-hardware-buyer.component.js +2 -2
  22. package/src/lib/components/console/pos/pos-hardware-buyer.component.js.map +1 -1
  23. package/src/lib/components/console/pos/pos-hardware-sale-api.d.ts +2 -0
  24. package/src/lib/components/console/pos/pos-hardware-sale-api.js.map +1 -1
  25. package/src/lib/components/console/pos-cellular-control.component.d.ts +1 -1
  26. package/src/lib/components/console/pos-cellular-control.component.js +5 -5
  27. package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
  28. package/src/lib/components/console/pos-devices-card.component.js +2 -2
  29. package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
  30. package/src/lib/components/console/pos-hardware-card.component.d.ts +5 -0
  31. package/src/lib/components/console/pos-hardware-card.component.js +77 -8
  32. package/src/lib/components/console/pos-hardware-card.component.js.map +1 -1
  33. package/src/lib/components/console/pos-hardware-orders-staff-page.component.js +137 -19
  34. package/src/lib/components/console/pos-hardware-orders-staff-page.component.js.map +1 -1
  35. package/src/lib/components/console/pos-page.component.js +19 -2
  36. package/src/lib/components/console/pos-page.component.js.map +1 -1
  37. package/src/lib/components/console/product-editor-dialog.component.js +21 -2
  38. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  39. package/src/lib/components/console/subscription-detail-dialog.component.d.ts +58 -0
  40. package/src/lib/components/console/subscription-detail-dialog.component.js +201 -0
  41. package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -0
  42. package/src/lib/components/console/subscriptions-card.component.d.ts +60 -0
  43. package/src/lib/components/console/subscriptions-card.component.js +282 -0
  44. package/src/lib/components/console/subscriptions-card.component.js.map +1 -0
  45. package/src/lib/components/hardware-terms-consent.d.ts +22 -0
  46. package/src/lib/components/hardware-terms-consent.js +85 -0
  47. package/src/lib/components/hardware-terms-consent.js.map +1 -0
  48. package/src/lib/components/product-detail.js +32 -8
  49. package/src/lib/components/product-detail.js.map +1 -1
  50. package/src/lib/components/quote-page-body.js +7 -3
  51. package/src/lib/components/quote-page-body.js.map +1 -1
  52. package/src/lib/components/related-products.js +6 -3
  53. package/src/lib/components/related-products.js.map +1 -1
  54. package/src/lib/components/storefront-payment-element.d.ts +7 -1
  55. package/src/lib/components/storefront-payment-element.js +11 -7
  56. package/src/lib/components/storefront-payment-element.js.map +1 -1
  57. package/src/lib/constants/operator-alerts.d.ts +1 -1
  58. package/src/lib/constants/operator-alerts.js +4 -4
  59. package/src/lib/constants/operator-alerts.js.map +1 -1
  60. package/src/lib/model/commerce-orders.d.ts +6 -2
  61. package/src/lib/model/commerce-orders.js.map +1 -1
  62. package/src/lib/model/commerce-payment-methods.d.ts +27 -16
  63. package/src/lib/model/commerce-payment-methods.js +11 -83
  64. package/src/lib/model/commerce-payment-methods.js.map +1 -1
  65. package/src/lib/model/commerce.d.ts +6 -0
  66. package/src/lib/model/commerce.js.map +1 -1
  67. package/src/lib/model/index.d.ts +1 -0
  68. package/src/lib/model/index.js +1 -0
  69. package/src/lib/model/index.js.map +1 -1
  70. package/src/lib/model/paid-media.d.ts +8 -0
  71. package/src/lib/model/paid-media.js +13 -0
  72. package/src/lib/model/paid-media.js.map +1 -1
  73. package/src/lib/model/pos-hardware-in-person.d.ts +23 -2
  74. package/src/lib/model/pos-hardware-in-person.js +52 -20
  75. package/src/lib/model/pos-hardware-in-person.js.map +1 -1
  76. package/src/lib/model/pos-hardware-tax-summary.d.ts +5 -1
  77. package/src/lib/model/pos-hardware-tax-summary.js +2 -1
  78. package/src/lib/model/pos-hardware-tax-summary.js.map +1 -1
  79. package/src/lib/model/pos-hardware-terms.d.ts +37 -2
  80. package/src/lib/model/pos-hardware-terms.js +68 -3
  81. package/src/lib/model/pos-hardware-terms.js.map +1 -1
  82. package/src/lib/model/pos-hardware.d.ts +101 -15
  83. package/src/lib/model/pos-hardware.js +128 -18
  84. package/src/lib/model/pos-hardware.js.map +1 -1
  85. package/src/lib/model/pos-reader-splash.js +2 -2
  86. package/src/lib/model/pos-reader-splash.js.map +1 -1
  87. package/src/lib/model/product-write.d.ts +3 -0
  88. package/src/lib/model/subscription-view.d.ts +90 -0
  89. package/src/lib/model/subscription-view.js +176 -0
  90. package/src/lib/model/subscription-view.js.map +1 -0
  91. package/src/lib/server/billing-webhook.d.ts +27 -6
  92. package/src/lib/server/billing-webhook.js +271 -81
  93. package/src/lib/server/billing-webhook.js.map +1 -1
  94. package/src/lib/server/cancel-order.js +4 -3
  95. package/src/lib/server/cancel-order.js.map +1 -1
  96. package/src/lib/server/cart-checkout.js +105 -23
  97. package/src/lib/server/cart-checkout.js.map +1 -1
  98. package/src/lib/server/cart.js +15 -3
  99. package/src/lib/server/cart.js.map +1 -1
  100. package/src/lib/server/catalog.js +58 -22
  101. package/src/lib/server/catalog.js.map +1 -1
  102. package/src/lib/server/checkout-session-expiry.d.ts +1 -1
  103. package/src/lib/server/checkout-session-expiry.js +19 -5
  104. package/src/lib/server/checkout-session-expiry.js.map +1 -1
  105. package/src/lib/server/checkout-status.js +4 -3
  106. package/src/lib/server/checkout-status.js.map +1 -1
  107. package/src/lib/server/checkout.js +98 -26
  108. package/src/lib/server/checkout.js.map +1 -1
  109. package/src/lib/server/connect.js +42 -11
  110. package/src/lib/server/connect.js.map +1 -1
  111. package/src/lib/server/draft-order.js +36 -7
  112. package/src/lib/server/draft-order.js.map +1 -1
  113. package/src/lib/server/manual-tax-rate.d.ts +11 -3
  114. package/src/lib/server/manual-tax-rate.js +10 -6
  115. package/src/lib/server/manual-tax-rate.js.map +1 -1
  116. package/src/lib/server/membership-account.d.ts +22 -0
  117. package/src/lib/server/membership-account.js +52 -8
  118. package/src/lib/server/membership-account.js.map +1 -1
  119. package/src/lib/server/native-checkout.d.ts +10 -3
  120. package/src/lib/server/native-checkout.js +8 -3
  121. package/src/lib/server/native-checkout.js.map +1 -1
  122. package/src/lib/server/payment-method-domains.d.ts +50 -9
  123. package/src/lib/server/payment-method-domains.js +150 -51
  124. package/src/lib/server/payment-method-domains.js.map +1 -1
  125. package/src/lib/server/payment-methods.js +3 -2
  126. package/src/lib/server/payment-methods.js.map +1 -1
  127. package/src/lib/server/pos-auth.d.ts +3 -3
  128. package/src/lib/server/pos-auth.js +3 -3
  129. package/src/lib/server/pos-auth.js.map +1 -1
  130. package/src/lib/server/pos-cellular-billing.js +1 -1
  131. package/src/lib/server/pos-cellular-billing.js.map +1 -1
  132. package/src/lib/server/pos-cellular-notify.js +1 -1
  133. package/src/lib/server/pos-cellular-notify.js.map +1 -1
  134. package/src/lib/server/pos-cellular.js +1 -1
  135. package/src/lib/server/pos-cellular.js.map +1 -1
  136. package/src/lib/server/pos-hardware-admin.js +86 -13
  137. package/src/lib/server/pos-hardware-admin.js.map +1 -1
  138. package/src/lib/server/pos-hardware-attach.js +5 -5
  139. package/src/lib/server/pos-hardware-attach.js.map +1 -1
  140. package/src/lib/server/pos-hardware-cancel.js +65 -0
  141. package/src/lib/server/pos-hardware-cancel.js.map +1 -1
  142. package/src/lib/server/pos-hardware-closure-notices.js +2 -5
  143. package/src/lib/server/pos-hardware-closure-notices.js.map +1 -1
  144. package/src/lib/server/pos-hardware-closure.js +5 -8
  145. package/src/lib/server/pos-hardware-closure.js.map +1 -1
  146. package/src/lib/server/pos-hardware-in-person.d.ts +2 -1
  147. package/src/lib/server/pos-hardware-in-person.js +72 -17
  148. package/src/lib/server/pos-hardware-in-person.js.map +1 -1
  149. package/src/lib/server/pos-hardware-notify.d.ts +2 -0
  150. package/src/lib/server/pos-hardware-notify.js +30 -5
  151. package/src/lib/server/pos-hardware-notify.js.map +1 -1
  152. package/src/lib/server/pos-hardware-readers.d.ts +25 -0
  153. package/src/lib/server/pos-hardware-readers.js +206 -85
  154. package/src/lib/server/pos-hardware-readers.js.map +1 -1
  155. package/src/lib/server/pos-hardware-returns.d.ts +8 -3
  156. package/src/lib/server/pos-hardware-returns.js +39 -7
  157. package/src/lib/server/pos-hardware-returns.js.map +1 -1
  158. package/src/lib/server/pos-hardware-sale-fields.d.ts +76 -0
  159. package/src/lib/server/pos-hardware-sale-fields.js +114 -1
  160. package/src/lib/server/pos-hardware-sale-fields.js.map +1 -1
  161. package/src/lib/server/pos-hardware-sale.d.ts +2 -0
  162. package/src/lib/server/pos-hardware-sale.js +1 -0
  163. package/src/lib/server/pos-hardware-sale.js.map +1 -1
  164. package/src/lib/server/pos-hardware-tax-return-source.js +7 -4
  165. package/src/lib/server/pos-hardware-tax-return-source.js.map +1 -1
  166. package/src/lib/server/pos-hardware-webhook.js +16 -3
  167. package/src/lib/server/pos-hardware-webhook.js.map +1 -1
  168. package/src/lib/server/pos-hardware.d.ts +14 -3
  169. package/src/lib/server/pos-hardware.js +83 -18
  170. package/src/lib/server/pos-hardware.js.map +1 -1
  171. package/src/lib/server/pos-ops-routes.js +2 -10
  172. package/src/lib/server/pos-ops-routes.js.map +1 -1
  173. package/src/lib/server/pos-order.js +5 -1
  174. package/src/lib/server/pos-order.js.map +1 -1
  175. package/src/lib/server/pos-stripe.d.ts +7 -7
  176. package/src/lib/server/pos-stripe.js +15 -13
  177. package/src/lib/server/pos-stripe.js.map +1 -1
  178. package/src/lib/server/pos-terminal.js +11 -3
  179. package/src/lib/server/pos-terminal.js.map +1 -1
  180. package/src/lib/server/quote-pay.d.ts +23 -1
  181. package/src/lib/server/quote-pay.js +111 -27
  182. package/src/lib/server/quote-pay.js.map +1 -1
  183. package/src/lib/server/quote.d.ts +2 -1
  184. package/src/lib/server/quote.js +12 -11
  185. package/src/lib/server/quote.js.map +1 -1
  186. package/src/lib/server/refund.js +13 -6
  187. package/src/lib/server/refund.js.map +1 -1
  188. package/src/lib/server/related.js +10 -3
  189. package/src/lib/server/related.js.map +1 -1
  190. package/src/lib/server/reserve.js +19 -6
  191. package/src/lib/server/reserve.js.map +1 -1
  192. package/src/lib/server/revenue-source.d.ts +6 -0
  193. package/src/lib/server/revenue-source.js +25 -9
  194. package/src/lib/server/revenue-source.js.map +1 -1
  195. package/src/lib/server/seller-stripe-account.d.ts +45 -0
  196. package/src/lib/server/seller-stripe-account.js +99 -0
  197. package/src/lib/server/seller-stripe-account.js.map +1 -0
  198. package/src/lib/server/storefront-tax-record.js +6 -1
  199. package/src/lib/server/storefront-tax-record.js.map +1 -1
  200. package/src/lib/server/storefront-tax.d.ts +33 -2
  201. package/src/lib/server/storefront-tax.js +39 -3
  202. package/src/lib/server/storefront-tax.js.map +1 -1
  203. package/src/lib/server/stream.d.ts +2 -0
  204. package/src/lib/server/stream.js +22 -2
  205. package/src/lib/server/stream.js.map +1 -1
  206. package/src/lib/server/stripe-refund.d.ts +15 -0
  207. package/src/lib/server/stripe-refund.js +54 -26
  208. package/src/lib/server/stripe-refund.js.map +1 -1
  209. package/src/lib/server/subscription-portal.js +8 -3
  210. package/src/lib/server/subscription-portal.js.map +1 -1
  211. package/src/lib/server/tax-return-source.js +5 -1
  212. package/src/lib/server/tax-return-source.js.map +1 -1
  213. package/src/lib/server.js +2 -2
  214. package/src/lib/server.js.map +1 -1
@@ -26,9 +26,20 @@
26
26
  * refunded share, as it always has.
27
27
  * - the caller's IDEMPOTENCY KEY, so a retried request is the same refund
28
28
  * at Stripe and never a second one.
29
+ *
30
+ * A DIRECT charge (the seller's own Stripe account sold it) is refunded ON
31
+ * that account with the `Stripe-Account` header: the money comes out of the
32
+ * seller's balance, where the sale settled, so there is no transfer to
33
+ * reverse and `reverse_transfer` is never sent. `refund_application_fee` is
34
+ * kept, so Aglyn hands its fee back on the refunded share exactly as it does
35
+ * on a destination charge. A payment intent the seller's account does not
36
+ * know (a sale from before the seller switched, or Aglyn's own hardware) is
37
+ * refunded on the platform as a destination charge, so a caller may pass the
38
+ * site's direct-charge account without first asking which kind the sale was.
29
39
  */ import { _ as _extends } from "@swc/helpers/_/_extends";
30
40
  export async function createStripeRefund(input) {
31
- var _input_secretKey, _input_metadata, _input_fetch, _ref;
41
+ var _input_secretKey, _input_fetch, _ref, _ref1;
42
+ var _refund_error, _refund_error1;
32
43
  const secretKey = (_input_secretKey = input.secretKey) != null ? _input_secretKey : process.env.STRIPE_SECRET_KEY;
33
44
  if (!secretKey) {
34
45
  return {
@@ -38,31 +49,48 @@ export async function createStripeRefund(input) {
38
49
  code: 'not_configured'
39
50
  };
40
51
  }
41
- const params = new URLSearchParams({
42
- payment_intent: input.paymentIntentId,
43
- amount: String(Math.round(input.amountCents)),
44
- reverse_transfer: 'true',
45
- refund_application_fee: 'true'
46
- });
47
- for (const [key, value] of Object.entries((_input_metadata = input.metadata) != null ? _input_metadata : {})){
48
- params.set(`metadata[${key}]`, value);
49
- }
50
52
  const send = (_input_fetch = input.fetch) != null ? _input_fetch : fetch;
51
- const response = await send('https://api.stripe.com/v1/refunds', {
52
- method: 'POST',
53
- headers: _extends({
54
- Authorization: `Bearer ${secretKey}`,
55
- 'Content-Type': 'application/x-www-form-urlencoded'
56
- }, input.idempotencyKey ? {
57
- 'Idempotency-Key': input.idempotencyKey
58
- } : {}),
59
- body: params.toString()
60
- });
61
- const refund = await Promise.resolve().then(()=>response.json()).catch(()=>({}));
53
+ const post = (stripeAccount)=>{
54
+ var _input_metadata;
55
+ const params = new URLSearchParams(_extends({
56
+ payment_intent: input.paymentIntentId,
57
+ amount: String(Math.round(input.amountCents))
58
+ }, stripeAccount ? {} : {
59
+ reverse_transfer: 'true'
60
+ }, {
61
+ refund_application_fee: 'true'
62
+ }));
63
+ for (const [key, value] of Object.entries((_input_metadata = input.metadata) != null ? _input_metadata : {})){
64
+ params.set(`metadata[${key}]`, value);
65
+ }
66
+ return send('https://api.stripe.com/v1/refunds', {
67
+ method: 'POST',
68
+ headers: _extends({
69
+ Authorization: `Bearer ${secretKey}`,
70
+ 'Content-Type': 'application/x-www-form-urlencoded'
71
+ }, input.idempotencyKey ? {
72
+ 'Idempotency-Key': input.idempotencyKey
73
+ } : {}, stripeAccount ? {
74
+ 'Stripe-Account': stripeAccount
75
+ } : {}),
76
+ body: params.toString()
77
+ });
78
+ };
79
+ const stripeAccount = typeof input.stripeAccount === 'string' && input.stripeAccount.trim() ? input.stripeAccount.trim() : null;
80
+ const read = async (sent)=>await Promise.resolve().then(()=>sent.json()).catch(()=>({}));
81
+ let response = await post(stripeAccount);
82
+ let refund = await read(response);
83
+ // Not the seller's payment: a destination sale on the platform. Stripe
84
+ // answers a payment intent another account owns as `resource_missing`, and
85
+ // scopes idempotency keys per account, so the same key is safe there.
86
+ if (stripeAccount && !response.ok && (response.status === 404 || (refund == null ? void 0 : (_refund_error = refund.error) == null ? void 0 : _refund_error.code) === 'resource_missing' && ((_ref = refund == null ? void 0 : (_refund_error1 = refund.error) == null ? void 0 : _refund_error1.param) != null ? _ref : 'payment_intent') === 'payment_intent')) {
87
+ response = await post(null);
88
+ refund = await read(response);
89
+ }
62
90
  if (!response.ok) {
63
- var _ref1, _ref2;
64
- var _refund_error, _refund_error1;
65
- const code = String((_ref1 = refund == null ? void 0 : (_refund_error = refund.error) == null ? void 0 : _refund_error.code) != null ? _ref1 : '');
91
+ var _ref2, _ref3;
92
+ var _refund_error2, _refund_error3;
93
+ const code = String((_ref2 = refund == null ? void 0 : (_refund_error2 = refund.error) == null ? void 0 : _refund_error2.code) != null ? _ref2 : '');
66
94
  if (code === 'charge_disputed' || code === 'refund_disputed_payment') {
67
95
  return {
68
96
  ok: false,
@@ -75,12 +103,12 @@ export async function createStripeRefund(input) {
75
103
  ok: false,
76
104
  status: 502,
77
105
  code,
78
- error: (_ref2 = refund == null ? void 0 : (_refund_error1 = refund.error) == null ? void 0 : _refund_error1.message) != null ? _ref2 : 'Refund failed'
106
+ error: (_ref3 = refund == null ? void 0 : (_refund_error3 = refund.error) == null ? void 0 : _refund_error3.message) != null ? _ref3 : 'Refund failed'
79
107
  };
80
108
  }
81
109
  return {
82
110
  ok: true,
83
- refundId: String((_ref = refund == null ? void 0 : refund.id) != null ? _ref : '')
111
+ refundId: String((_ref1 = refund == null ? void 0 : refund.id) != null ? _ref1 : '')
84
112
  };
85
113
  }
86
114
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/stripe-refund.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * ONE STRIPE REFUND, the way every commerce refund sends one (AGL-3609).\n *\n * Shared by the order dialog's refund (`refund.ts`) and a return at the\n * register (`pos-return.ts`), so both take the money back the same way:\n *\n * - `reverse_transfer`: a destination charge's money sits in the\n * merchant's connected account, so the refund pulls it back from there\n * rather than out of the platform's balance.\n * - `refund_application_fee`: the platform hands its fee back on the\n * refunded share, as it always has.\n * - the caller's IDEMPOTENCY KEY, so a retried request is the same refund\n * at Stripe and never a second one.\n */\nexport type StripeRefundResult =\n | { ok: true; refundId: string }\n | { ok: false; status: number; error: string; code: string }\n\nexport async function createStripeRefund(input: {\n paymentIntentId: string\n amountCents: number\n idempotencyKey?: string | null\n metadata?: Record<string, string>\n fetch?: typeof fetch\n secretKey?: string\n}): Promise<StripeRefundResult> {\n const secretKey = input.secretKey ?? process.env.STRIPE_SECRET_KEY\n if (!secretKey) {\n return { ok: false, status: 501, error: 'Payments are not configured.', code: 'not_configured' }\n }\n const params = new URLSearchParams({\n payment_intent: input.paymentIntentId,\n amount: String(Math.round(input.amountCents)),\n reverse_transfer: 'true',\n refund_application_fee: 'true',\n })\n for (const [key, value] of Object.entries(input.metadata ?? {})) {\n params.set(`metadata[${key}]`, value)\n }\n const send = input.fetch ?? fetch\n const response = await send('https://api.stripe.com/v1/refunds', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${secretKey}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...(input.idempotencyKey ? { 'Idempotency-Key': input.idempotencyKey } : {}),\n },\n body: params.toString(),\n })\n const refund = (await Promise.resolve()\n .then(() => response.json())\n .catch(() => ({}))) as {\n id?: string\n error?: { code?: string; message?: string }\n }\n if (!response.ok) {\n const code = String(refund?.error?.code ?? '')\n if (code === 'charge_disputed' || code === 'refund_disputed_payment') {\n return {\n ok: false,\n status: 409,\n code,\n error:\n 'Stripe refused this refund because the charge is disputed. ' +\n 'Respond to the dispute or accept it in the Stripe dashboard; ' +\n 'refund any remainder once it settles.',\n }\n }\n return { ok: false, status: 502, code, error: refund?.error?.message ?? 'Refund failed' }\n }\n return { ok: true, refundId: String(refund?.id ?? '') }\n}\n"],"names":["createStripeRefund","input","secretKey","process","env","STRIPE_SECRET_KEY","ok","status","error","code","params","URLSearchParams","payment_intent","paymentIntentId","amount","String","Math","round","amountCents","reverse_transfer","refund_application_fee","key","value","Object","entries","metadata","set","send","fetch","response","method","headers","Authorization","idempotencyKey","body","toString","refund","Promise","resolve","then","json","catch","message","refundId","id"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;CAaC;AAKD,OAAO,eAAeA,mBAAmBC,KAOxC;QACmBA,kBAUwBA,iBAG7BA;IAbb,MAAMC,aAAYD,mBAAAA,MAAMC,SAAS,YAAfD,mBAAmBE,QAAQC,GAAG,CAACC,iBAAiB;IAClE,IAAI,CAACH,WAAW;QACd,OAAO;YAAEI,IAAI;YAAOC,QAAQ;YAAKC,OAAO;YAAgCC,MAAM;QAAiB;IACjG;IACA,MAAMC,SAAS,IAAIC,gBAAgB;QACjCC,gBAAgBX,MAAMY,eAAe;QACrCC,QAAQC,OAAOC,KAAKC,KAAK,CAAChB,MAAMiB,WAAW;QAC3CC,kBAAkB;QAClBC,wBAAwB;IAC1B;IACA,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAOC,OAAO,EAACvB,kBAAAA,MAAMwB,QAAQ,YAAdxB,kBAAkB,CAAC,GAAI;QAC/DS,OAAOgB,GAAG,CAAC,CAAC,SAAS,EAAEL,IAAI,CAAC,CAAC,EAAEC;IACjC;IACA,MAAMK,QAAO1B,eAAAA,MAAM2B,KAAK,YAAX3B,eAAe2B;IAC5B,MAAMC,WAAW,MAAMF,KAAK,qCAAqC;QAC/DG,QAAQ;QACRC,SAAS;YACPC,eAAe,CAAC,OAAO,EAAE9B,WAAW;YACpC,gBAAgB;WACZD,MAAMgC,cAAc,GAAG;YAAE,mBAAmBhC,MAAMgC,cAAc;QAAC,IAAI,CAAC;QAE5EC,MAAMxB,OAAOyB,QAAQ;IACvB;IACA,MAAMC,SAAU,MAAMC,QAAQC,OAAO,GAClCC,IAAI,CAAC,IAAMV,SAASW,IAAI,IACxBC,KAAK,CAAC,IAAO,CAAA,CAAC,CAAA;IAIjB,IAAI,CAACZ,SAASvB,EAAE,EAAE;;YACI8B,eAY0BA;QAZ9C,MAAM3B,OAAOM,gBAAOqB,2BAAAA,gBAAAA,OAAQ5B,KAAK,qBAAb4B,cAAe3B,IAAI,oBAAI;QAC3C,IAAIA,SAAS,qBAAqBA,SAAS,2BAA2B;YACpE,OAAO;gBACLH,IAAI;gBACJC,QAAQ;gBACRE;gBACAD,OACE,gEACA,kEACA;YACJ;QACF;QACA,OAAO;YAAEF,IAAI;YAAOC,QAAQ;YAAKE;YAAMD,KAAK,WAAE4B,2BAAAA,iBAAAA,OAAQ5B,KAAK,qBAAb4B,eAAeM,OAAO,oBAAI;QAAgB;IAC1F;IACA,OAAO;QAAEpC,IAAI;QAAMqC,UAAU5B,eAAOqB,0BAAAA,OAAQQ,EAAE,mBAAI;IAAI;AACxD"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/stripe-refund.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * ONE STRIPE REFUND, the way every commerce refund sends one (AGL-3609).\n *\n * Shared by the order dialog's refund (`refund.ts`) and a return at the\n * register (`pos-return.ts`), so both take the money back the same way:\n *\n * - `reverse_transfer`: a destination charge's money sits in the\n * merchant's connected account, so the refund pulls it back from there\n * rather than out of the platform's balance.\n * - `refund_application_fee`: the platform hands its fee back on the\n * refunded share, as it always has.\n * - the caller's IDEMPOTENCY KEY, so a retried request is the same refund\n * at Stripe and never a second one.\n *\n * A DIRECT charge (the seller's own Stripe account sold it) is refunded ON\n * that account with the `Stripe-Account` header: the money comes out of the\n * seller's balance, where the sale settled, so there is no transfer to\n * reverse and `reverse_transfer` is never sent. `refund_application_fee` is\n * kept, so Aglyn hands its fee back on the refunded share exactly as it does\n * on a destination charge. A payment intent the seller's account does not\n * know (a sale from before the seller switched, or Aglyn's own hardware) is\n * refunded on the platform as a destination charge, so a caller may pass the\n * site's direct-charge account without first asking which kind the sale was.\n */\nexport type StripeRefundResult =\n | { ok: true; refundId: string }\n | { ok: false; status: number; error: string; code: string }\n\nexport async function createStripeRefund(input: {\n paymentIntentId: string\n amountCents: number\n idempotencyKey?: string | null\n metadata?: Record<string, string>\n /**\n * The seller's connected account when the sale was (or may have been) a\n * DIRECT charge. Absent for a destination sale.\n */\n stripeAccount?: string | null\n fetch?: typeof fetch\n secretKey?: string\n}): Promise<StripeRefundResult> {\n const secretKey = input.secretKey ?? process.env.STRIPE_SECRET_KEY\n if (!secretKey) {\n return { ok: false, status: 501, error: 'Payments are not configured.', code: 'not_configured' }\n }\n const send = input.fetch ?? fetch\n const post = (stripeAccount: string | null) => {\n const params = new URLSearchParams({\n payment_intent: input.paymentIntentId,\n amount: String(Math.round(input.amountCents)),\n ...(stripeAccount ? {} : { reverse_transfer: 'true' }),\n refund_application_fee: 'true',\n })\n for (const [key, value] of Object.entries(input.metadata ?? {})) {\n params.set(`metadata[${key}]`, value)\n }\n return send('https://api.stripe.com/v1/refunds', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${secretKey}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...(input.idempotencyKey ? { 'Idempotency-Key': input.idempotencyKey } : {}),\n ...(stripeAccount ? { 'Stripe-Account': stripeAccount } : {}),\n },\n body: params.toString(),\n })\n }\n const stripeAccount =\n typeof input.stripeAccount === 'string' && input.stripeAccount.trim()\n ? input.stripeAccount.trim()\n : null\n type RefundBody = {\n id?: string\n error?: { code?: string; message?: string; param?: string }\n }\n const read = async (sent: Response): Promise<RefundBody> =>\n (await Promise.resolve()\n .then(() => sent.json())\n .catch(() => ({}))) as RefundBody\n let response = await post(stripeAccount)\n let refund = await read(response)\n // Not the seller's payment: a destination sale on the platform. Stripe\n // answers a payment intent another account owns as `resource_missing`, and\n // scopes idempotency keys per account, so the same key is safe there.\n if (\n stripeAccount &&\n !response.ok &&\n (response.status === 404 ||\n (refund?.error?.code === 'resource_missing' &&\n (refund?.error?.param ?? 'payment_intent') === 'payment_intent'))\n ) {\n response = await post(null)\n refund = await read(response)\n }\n if (!response.ok) {\n const code = String(refund?.error?.code ?? '')\n if (code === 'charge_disputed' || code === 'refund_disputed_payment') {\n return {\n ok: false,\n status: 409,\n code,\n error:\n 'Stripe refused this refund because the charge is disputed. ' +\n 'Respond to the dispute or accept it in the Stripe dashboard; ' +\n 'refund any remainder once it settles.',\n }\n }\n return { ok: false, status: 502, code, error: refund?.error?.message ?? 'Refund failed' }\n }\n return { ok: true, refundId: String(refund?.id ?? '') }\n}\n"],"names":["createStripeRefund","input","refund","secretKey","process","env","STRIPE_SECRET_KEY","ok","status","error","code","send","fetch","post","stripeAccount","params","URLSearchParams","payment_intent","paymentIntentId","amount","String","Math","round","amountCents","reverse_transfer","refund_application_fee","key","value","Object","entries","metadata","set","method","headers","Authorization","idempotencyKey","body","toString","trim","read","sent","Promise","resolve","then","json","catch","response","param","message","refundId","id"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;CAuBC;AAKD,OAAO,eAAeA,mBAAmBC,KAYxC;QACmBA,kBAILA;QA2CRC,eACEA;IAhDP,MAAMC,aAAYF,mBAAAA,MAAME,SAAS,YAAfF,mBAAmBG,QAAQC,GAAG,CAACC,iBAAiB;IAClE,IAAI,CAACH,WAAW;QACd,OAAO;YAAEI,IAAI;YAAOC,QAAQ;YAAKC,OAAO;YAAgCC,MAAM;QAAiB;IACjG;IACA,MAAMC,QAAOV,eAAAA,MAAMW,KAAK,YAAXX,eAAeW;IAC5B,MAAMC,OAAO,CAACC;YAO8Bb;QAN1C,MAAMc,SAAS,IAAIC,g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AK,mBAAI,sBAAsB,gBAAgB,GACnE;QACAD,WAAW,MAAMjC,KAAK;QACtBX,SAAS,MAAMqC,KAAKO;IACtB;IACA,IAAI,CAACA,SAASvC,EAAE,EAAE;;YACIL,gBAY0BA;QAZ9C,MAAMQ,OAAOU,gBAAOlB,2BAAAA,iBAAAA,OAAQO,KAAK,qBAAbP,eAAeQ,IAAI,oBAAI;QAC3C,IAAIA,SAAS,qBAAqBA,SAAS,2BAA2B;YACpE,OAAO;gBACLH,IAAI;gBACJC,QAAQ;gBACRE;gBACAD,OACE,gEACA,kEACA;YACJ;QACF;QACA,OAAO;YAAEF,IAAI;YAAOC,QAAQ;YAAKE;YAAMD,KAAK,WAAEP,2BAAAA,iBAAAA,OAAQO,KAAK,qBAAbP,eAAe8C,OAAO,oBAAI;QAAgB;IAC1F;IACA,OAAO;QAAEzC,IAAI;QAAM0C,UAAU7B,gBAAOlB,0BAAAA,OAAQgD,EAAE,oBAAI;IAAI;AACxD"}
@@ -13,7 +13,8 @@
13
13
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
- */ import { readSiteReturnHost, siteReturnUrl } from "@aglyn/aglyn/app-utils/site-return-url";
16
+ */ import { directSellerAccountForHost, fetchOnSellerThenPlatform } from "./seller-stripe-account.js";
17
+ import { readSiteReturnHost, siteReturnUrl } from "@aglyn/aglyn/app-utils/site-return-url";
17
18
  import { firebaseAdmin } from "@aglyn/tenant-data-admin";
18
19
  import { requireActiveMember } from "./membership.js";
19
20
  /**
@@ -53,6 +54,10 @@ import { requireActiveMember } from "./membership.js";
53
54
  });
54
55
  const subscriptions = await hostRef.collection('subscriptions').where('customerEmail', '==', email).limit(1).get();
55
56
  const customerId = (_subscriptions_docs_ = subscriptions.docs[0]) == null ? void 0 : _subscriptions_docs_.get('stripeCustomerId');
57
+ // A direct-charge subscription's customer lives on the seller's account,
58
+ // so the portal session is opened there; the seller's own portal
59
+ // settings in their Stripe Dashboard apply.
60
+ const sellerAccount = await directSellerAccountForHost(hostId);
56
61
  if (!customerId) {
57
62
  return res.status(404).json({
58
63
  error: 'No subscription found'
@@ -67,7 +72,7 @@ import { requireActiveMember } from "./membership.js";
67
72
  site: await readSiteReturnHost(hostRef),
68
73
  requestHost: String((_req_headers_host = req.headers.host) != null ? _req_headers_host : '')
69
74
  });
70
- const response = await fetch('https://api.stripe.com/v1/billing_portal/sessions', {
75
+ const response = await fetchOnSellerThenPlatform('https://api.stripe.com/v1/billing_portal/sessions', {
71
76
  method: 'POST',
72
77
  headers: {
73
78
  Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
@@ -77,7 +82,7 @@ import { requireActiveMember } from "./membership.js";
77
82
  customer: String(customerId),
78
83
  return_url: returnUrl
79
84
  }).toString()
80
- });
85
+ }, sellerAccount);
81
86
  const session = await response.json();
82
87
  if (!response.ok || !session.url) {
83
88
  console.error('Portal error', session == null ? void 0 : session.error);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/subscription-portal.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 { readSiteReturnHost, siteReturnUrl } from '@aglyn/aglyn/app-utils/site-return-url'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { requireActiveMember } from './membership'\n\n/**\n * Subscriber self-service (AGL-303): opens the Stripe Billing Portal for\n * the signed-in member's storefront subscription (cancel, switch\n * payment method). Member-gated; the portal customer is matched by the\n * member's email through the recorded subscription doc.\n */\nexport const subscriptionPortalHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res.status(501).json({ error: 'Billing is not configured.' })\n }\n const hostId = String(req.body?.hostId ?? '')\n if (!hostId) return res.status(400).json({ error: 'Missing hostId' })\n\n try {\n // Suspension gate (AGL-550): suspended members (AGL-546) cannot\n // open the billing portal — 403'd with the session cookie cleared.\n const auth = await requireActiveMember(req, res, hostId)\n if (!auth) return\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const email = String(auth.member.get('email') ?? '')\n if (!email) return res.status(401).json({ error: 'Not signed in' })\n const subscriptions = await hostRef\n .collection('subscriptions')\n .where('customerEmail', '==', email)\n .limit(1)\n .get()\n const customerId = subscriptions.docs[0]?.get('stripeCustomerId')\n if (!customerId) {\n return res.status(404).json({ error: 'No subscription found' })\n }\n // The site's own page, never a header's say-so (AGL-3363).\n const returnUrl = siteReturnUrl({\n candidates: [String(req.headers.referer ?? ''), `https://${req.headers.host}`],\n site: await readSiteReturnHost(hostRef),\n requestHost: String(req.headers.host ?? ''),\n })\n const response = await fetch(\n 'https://api.stripe.com/v1/billing_portal/sessions',\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n customer: String(customerId),\n return_url: returnUrl,\n }).toString(),\n },\n )\n const session = await response.json()\n if (!response.ok || !session.url) {\n console.error('Portal error', session?.error)\n return res.status(502).json({ error: 'Portal unavailable' })\n }\n return res.status(200).json({ url: session.url })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Portal unavailable' })\n }\n}\n"],"names":["readSiteReturnHost","siteReturnUrl","firebaseAdmin","requireActiveMember","subscriptionPortalHandler","req","res","method","status","json","error","process","env","STRIPE_SECRET_KEY","hostId","String","body","auth","subscriptions","firestore","app","hostRef","collection","doc","email","member","get","where","limit","customerId","docs","returnUrl","candidates","headers","referer","host","site","requestHost","response","fetch","Authorization","URLSearchParams","customer","return_url","toString","session","ok","url","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,EAAEC,aAAa,QAAQ,yCAAwC;AAE1F,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,mBAAmB,QAAQ,kBAAc;AAElD;;;;;CAKC,GACD,OAAO,MAAMC,4BAA8C,OAAOC,KAAKC;;QAO/CD;IANtB,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,IAAI,CAACC,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QAClC,OAAOP,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA6B;IACpE;IACA,MAAMI,SAASC,gBAAOV,YAAAA,IAAIW,IAAI,qBAARX,UAAUS,MAAM,mBAAI;IAC1C,IAAI,CAACA,QAAQ,OAAOR,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;QAAEC,OAAO;IAAiB;IAEnE,IAAI;YAOmBO,kBAaCZ,sBAEAA;YARHa;QAbnB,gEAAgE;QAChE,mEAAmE;QACnE,MAAMD,OAAO,MAAMd,oBAAoBE,KAAKC,KAAKQ;QACjD,IAAI,CAACG,MAAM;QACX,MAAME,YAAYjB,cAAckB,GAAG,GAAGD,SAAS;QAC/C,MAAME,UAAUF,UAAUG,UAAU,CAAC,SAASC,GAAG,CAACT;QAClD,MAAMU,QAAQT,QAAOE,mBAAAA,KAAKQ,MAAM,CAACC,GAAG,CAAC,oBAAhBT,mBAA4B;QACjD,IAAI,CAACO,OAAO,OAAOlB,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAgB;QACjE,MAAMQ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C,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/subscription-portal.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 { directSellerAccountForHost, fetchOnSellerThenPlatform } from './seller-stripe-account'\nimport { readSiteReturnHost, siteReturnUrl } from '@aglyn/aglyn/app-utils/site-return-url'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { requireActiveMember } from './membership'\n\n/**\n * Subscriber self-service (AGL-303): opens the Stripe Billing Portal for\n * the signed-in member's storefront subscription (cancel, switch\n * payment method). Member-gated; the portal customer is matched by the\n * member's email through the recorded subscription doc.\n */\nexport const subscriptionPortalHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res.status(501).json({ error: 'Billing is not configured.' })\n }\n const hostId = String(req.body?.hostId ?? '')\n if (!hostId) return res.status(400).json({ error: 'Missing hostId' })\n\n try {\n // Suspension gate (AGL-550): suspended members (AGL-546) cannot\n // open the billing portal — 403'd with the session cookie cleared.\n const auth = await requireActiveMember(req, res, hostId)\n if (!auth) return\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const email = String(auth.member.get('email') ?? '')\n if (!email) return res.status(401).json({ error: 'Not signed in' })\n const subscriptions = await hostRef\n .collection('subscriptions')\n .where('customerEmail', '==', email)\n .limit(1)\n .get()\n const customerId = subscriptions.docs[0]?.get('stripeCustomerId')\n // A direct-charge subscription's customer lives on the seller's account,\n // so the portal session is opened there; the seller's own portal\n // settings in their Stripe Dashboard apply.\n const sellerAccount = await directSellerAccountForHost(hostId)\n if (!customerId) {\n return res.status(404).json({ error: 'No subscription found' })\n }\n // The site's own page, never a header's say-so (AGL-3363).\n const returnUrl = siteReturnUrl({\n candidates: [String(req.headers.referer ?? ''), `https://${req.headers.host}`],\n site: await readSiteReturnHost(hostRef),\n requestHost: String(req.headers.host ?? ''),\n })\n const response = await fetchOnSellerThenPlatform(\n 'https://api.stripe.com/v1/billing_portal/sessions',\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n customer: String(customerId),\n return_url: returnUrl,\n }).toString(),\n },\n sellerAccount,\n )\n const session = await response.json()\n if (!response.ok || !session.url) {\n console.error('Portal error', session?.error)\n return res.status(502).json({ error: 'Portal unavailable' })\n }\n return res.status(200).json({ url: session.url })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Portal unavailable' })\n }\n}\n"],"names":["directSellerAccountForHost","fetchOnSellerThenPlatform","readSiteReturnHost","siteReturnUrl","firebaseAdmin","requireActiveMember","subscriptionPortalHandler","req","res","method","status","json","error","process","env","STRIPE_SECRET_KEY","hostId","String","body","auth","subscriptions","firestore","app","hostRef","collection","doc","email","member","get","where","limit","customerId","docs","sellerAccount","returnUrl","candidates","headers","referer","host","site","requestHost","response","Authorization","URLSearchParams","customer","return_url","toString","session","ok","url","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,0BAA0B,EAAEC,yBAAyB,QAAQ,6BAAyB;AAC/F,SAASC,kBAAkB,EAAEC,aAAa,QAAQ,yCAAwC;AAE1F,SA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wnStoreOrders, resolveOwnStores } from ".
588
588
  // (AGL-4038): the hardware section counts them, so their part of the
589
589
  // register sale's storefront row comes out here (`posHardwareSales`
590
590
  // `source, paidAtMs`).
591
- firestore.collection(POS_HARDWARE_SALES_COLLECTION).where('source', '==', 'in_person').where('paidAtMs', '>=', request.start.getTime() - IN_PERSON_ROW_MARGIN_MS).where('paidAtMs', '<', request.end.getTime() + IN_PERSON_ROW_MARGIN_MS).limit(request.rowCap).get()
591
+ firestore.collection(POS_HARDWARE_SALES_COLLECTION)// In person or online from its own store (AGL-4038): the same index.
592
+ .where('source', 'in', [
593
+ 'in_person',
594
+ 'storefront'
595
+ ]).where('paidAtMs', '>=', request.start.getTime() - IN_PERSON_ROW_MARGIN_MS).where('paidAtMs', '<', request.end.getTime() + IN_PERSON_ROW_MARGIN_MS).limit(request.rowCap).get()
592
596
  ]);
593
597
  const rows = storefrontRowsWithoutInPersonHardware(inPeriod.docs.slice(0, request.rowCap).map((doc)=>_extends({
594
598
  id: doc.id
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/tax-return-source.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Storefront sales on the operator's sales tax return (AGL-1904, AGL-3080).\n *\n * The operator's return sums its own invoices; this is the storefront's half\n * of it, answered through the platform's tax return source contract\n * (`@aglyn/aglyn/plugin-manager/plugin-tax-return-sources`). It reads\n * `storefrontTaxCollected` — a SEPARATE collection from the operator's own\n * invoices, queried and reported separately, because a storefront row's\n * money is mostly the merchant's while an invoice row's is the operator's.\n * Summing the two would put other companies' receipts into the return's\n * total sales, which is why they never meet in one query and never share a\n * figure.\n *\n * What it answers, all worded for the filing jurisdiction the platform\n * resolved:\n *\n * - **The three liability buckets**, never summed — see\n * `model/storefront-tax-summary.ts`.\n * - **A blocking finding for the platform-liable tax** in the filing\n * jurisdiction. Every storefront checkout is created on the platform's\n * own account, so a `mode: 'stripe'` store's shopper is charged tax Stripe\n * computes against the PLATFORM's registrations — measured, not inferred.\n * That money is in the platform's balance and is NOT in the filing\n * figures, which sum the operator's own sales only. Filing those without\n * deciding what to do with this figure is exactly the shortfall an\n * auditor finds. It states the mechanics and asks for a decision; it does\n * NOT assert a marketplace-facilitator position — that attaches by\n * operation of law and belongs to counsel, not to this report.\n * - **Two lines beneath the filing figures** — the platform-liable tax and\n * the merchant's own rate, stated side by side and never folded into a\n * form item, because this report does not decide how storefront receipts\n * are reported and adding them to one would be deciding it silently.\n * - **Facilitated sales by buyer state** — the economic-nexus question\n * (AGL-1956), with the three buckets SUMMED per jurisdiction on purpose:\n * a threshold counts the sale whoever remits it. Who remits is still\n * carried per row.\n *\n * Truncation and rows no period can reach are reported, and the platform\n * raises each as a blocking finding of its own.\n */\n\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport {\n asRowDate,\n centsToDollars,\n} from '@aglyn/aglyn/app-utils/tax-jurisdiction-figures'\nimport type {\n TaxReturnExportBlock,\n TaxReturnFiling,\n TaxReturnFilingLine,\n TaxReturnFinding,\n TaxReturnSectionTable,\n TaxReturnSource,\n TaxReturnSourceAnswer,\n TaxReturnSourceRequest,\n} from '@aglyn/aglyn/plugin-manager/plugin-tax-return-sources'\nimport {\n storefrontTaxSummary,\n type StorefrontTaxReturnRowInput,\n type StorefrontTaxSummary,\n} from '../model/storefront-tax-summary'\nimport { readPosHardwareTaxReturn } from './pos-hardware-tax-return-source'\nimport { POS_HARDWARE_SALES_COLLECTION } from '../model/pos-hardware'\nimport {\n posHardwareStorefrontParts,\n storefrontRowsWithoutInPersonHardware,\n} from '../model/pos-hardware-tax-summary'\nimport { statedTaxableBase } from '../model/own-store-tax-summary'\nimport {\n ownStoreTaxReturnAnswer,\n readOwnStoreOrders,\n resolveOwnStores,\n type OwnStores,\n} from './own-store-tax-return-source'\n\n/**\n * How far either side of the period an in-person hardware record is read,\n * to meet the storefront row its register sale filed: the two are written\n * seconds apart, so a week is more than enough for either edge.\n */\nconst IN_PERSON_ROW_MARGIN_MS = 7 * 24 * 60 * 60 * 1000\n\n/** One row of the storefront listing, as the working papers carry it. */\nexport interface StorefrontTaxRow {\n id: string\n hostId: string | null\n orgId: string | null\n paidAt: string | null\n taxMode: string | null\n taxLiability: string | null\n grossCents: number\n taxCents: number\n taxableSalesCents: number\n state: string | null\n country: string | null\n}\n\n/** A liability bucket, ready to print. */\nexport interface StorefrontTaxBucketRow {\n id: 'aglynLiable' | 'merchantManual' | 'connectedAccountLiable'\n label: string\n /** Who owes it — the sentence that decides whether it is on this return. */\n liability: string\n transactionCount: number\n grossDollars: string\n taxableSalesDollars: string\n taxCollectedDollars: string\n /** True when this row is money in the platform's balance under its registration. */\n platformLiable: boolean\n}\n\n/** One state's facilitated storefront sales, for the nexus question. */\nexport interface StorefrontFacilitatedJurisdictionRow {\n jurisdiction: string\n /** True for the one jurisdiction this deployment files a return in. */\n isFilingJurisdiction: boolean\n transactionCount: number\n totalSalesDollars: string\n taxCollectedDollars: string\n /** The part of `taxCollectedDollars` the platform holds and must remit. */\n platformLiableTaxDollars: string\n /** True when NO tax was collected on any sale into this state. */\n untaxed: boolean\n}\n\n/**\n * Storefront tax in the FILING jurisdiction that Stripe computed against the\n * platform's own registrations.\n *\n * The one figure that decides whether a period can be filed from the filing\n * lines alone. Deliberately excludes `merchantManual` — a merchant's own\n * configured rate never touched those registrations. Read against the\n * configured jurisdiction rather than Texas, because a hard-coded key answers\n * `0.00` everywhere else — and a zero here reads as \"nothing to decide\" on\n * the one finding that blocks filing.\n */\nexport function storefrontPlatformLiableCents(\n summary: StorefrontTaxSummary | null | undefined,\n filing: TaxReturnFiling,\n): number {\n const figures = summary?.aglynLiable?.byJurisdiction?.[filing.code]\n const cents = Number(figures?.taxCollectedCents ?? 0)\n return Number.isFinite(cents) ? cents : 0\n}\n\n/** The merchant's own configured tax in the filing jurisdiction. */\nfunction merchantManualCents(\n summary: StorefrontTaxSummary | null | undefined,\n filing: TaxReturnFiling,\n): number {\n return Number(\n summary?.merchantManual?.byJurisdiction?.[filing.code]?.taxCollectedCents ?? 0,\n )\n}\n\n/** The storefront's findings. The platform raises the non-zero ones. */\nexport function storefrontTaxFindings(\n summary: StorefrontTaxSummary,\n filing: TaxReturnFiling,\n): TaxReturnFinding[] {\n const brand = PLATFORM_BRAND_NAME\n return [\n {\n // BLOCKING on purpose — see the module note.\n id: 'storefrontAglynLiableTax',\n severity: 'blocking',\n count: storefrontPlatformLiableCents(summary, filing),\n label: `${filing.label} storefront tax collected under ${brand}’s registration`,\n detail:\n 'Cents. Charged to shoppers on merchants’ storefront sales, computed ' +\n 'by Stripe Tax against THE PLATFORM’s registrations (the session is ' +\n 'created on the platform account), and settled into the platform’s ' +\n `balance. It is NOT included in ${filing.figuresName} below. Decide ` +\n 'with counsel how it is reported before filing — do not file as if ' +\n 'it were zero.',\n },\n {\n id: 'storefrontUnclassified',\n severity: 'blocking',\n count: Number(summary?.attention?.rowsUnclassified ?? 0),\n label: 'Storefront rows with an unrecognised tax mode',\n detail:\n 'Not counted in any storefront bucket, so they are in no figure at ' +\n 'all. Classify them before filing.',\n },\n {\n id: 'storefrontMissingTaxableBase',\n severity: 'review',\n count: Number(summary?.attention?.rowsMissingTaxableBase ?? 0),\n label: 'Storefront rows with tax but no stated base',\n detail:\n 'Tax was collected but Stripe’s taxable_amount could not be read, so ' +\n 'the storefront taxable-sales figure understates the base. Re-read ' +\n 'the session in Stripe with the tax breakdown expanded.',\n },\n ]\n}\n\n/**\n * The two lines beneath the filing figures: the platform-liable tax and the\n * merchant's own rate, separately, and outside every form item.\n */\nexport function storefrontFilingLines(\n summary: StorefrontTaxSummary,\n filing: TaxReturnFiling,\n): TaxReturnFilingLine[] {\n const brand = PLATFORM_BRAND_NAME\n const platformLiable = centsToDollars(storefrontPlatformLiableCents(summary, filing))\n const merchant = centsToDollars(merchantManualCents(summary, filing))\n if (filing.form === 'tx-webfile') {\n return [\n {\n item: '—',\n label: `${filing.label} storefront tax under ${brand}’s registration (NOT in ${filing.figuresName})`,\n dollars: platformLiable,\n note:\n `Collected from shoppers on merchants’ sales and held in ${brand}’s ` +\n 'balance. Excluded from every item above. Its treatment on the ' +\n 'return is a question for counsel — see AGL-1904.',\n },\n {\n item: '—',\n label: `${filing.label} storefront tax under the MERCHANT’s own rate (not ${brand}’s)`,\n dollars: merchant,\n note:\n `A manual-mode store’s own configured rate. ${brand}’s registrations ` +\n 'played no part in computing it. Shown so it is visibly NOT the line ' +\n 'above — the two must never be added together.',\n },\n ]\n }\n return [\n {\n item: '—',\n label: `${filing.code} storefront tax under the platform’s registration (NOT in the figures above)`,\n dollars: platformLiable,\n note:\n 'Collected from shoppers on merchants’ sales and held in the ' +\n 'platform’s balance. Excluded from every figure above. Its treatment ' +\n 'on the return is a question for the operator’s own counsel.',\n },\n {\n item: '—',\n label: `${filing.code} storefront tax under the MERCHANT’s own rate`,\n dollars: merchant,\n note:\n 'A manual-mode store’s own configured rate. The platform’s ' +\n 'registrations played no part in computing it. Shown so it is ' +\n 'visibly NOT the line above — the two must never be added together.',\n },\n ]\n}\n\n/** The three liability buckets, in the order a reader decides them. */\nexport function storefrontBucketRows(\n summary: StorefrontTaxSummary,\n): StorefrontTaxBucketRow[] {\n const brand = PLATFORM_BRAND_NAME\n const buckets: Array<{\n id: StorefrontTaxBucketRow['id']\n label: string\n liability: string\n platformLiable: boolean\n }> = [\n {\n id: 'aglynLiable',\n label: `Computed against ${brand}’s registrations`,\n liability: `In ${brand}’s balance. Stripe Tax computed it on ${brand}’s platform account.`,\n platformLiable: true,\n },\n {\n id: 'merchantManual',\n label: 'Merchant’s own configured rate',\n liability: `The merchant’s. It never touched an ${brand} registration and is not ${brand}’s to remit.`,\n platformLiable: false,\n },\n {\n id: 'connectedAccountLiable',\n label: 'Stripe Tax named the connected account liable',\n liability: 'The connected account’s. Empty today.',\n platformLiable: false,\n },\n ]\n return buckets.map((bucket) => {\n const figures = summary?.[bucket.id]\n return {\n id: bucket.id,\n label: bucket.label,\n liability: bucket.liability,\n transactionCount: Number(figures?.transactionCount ?? 0),\n grossDollars: centsToDollars(figures?.grossCents),\n taxableSalesDollars: centsToDollars(figures?.taxableSalesCents),\n taxCollectedDollars: centsToDollars(figures?.taxCollectedCents),\n platformLiable: bucket.platformLiable,\n }\n })\n}\n\n/**\n * FACILITATED SALES BY STATE — the economic-nexus question (AGL-1956).\n *\n * The question a state asks a marketplace facilitator is \"how much did you\n * facilitate INTO this state, and in how many transactions\" — not \"how much\n * tax did you collect there\". A state the operator is not registered in\n * collects nothing by definition, which is exactly why collection cannot be\n * the measure: the states worth watching are the ones showing $0 tax and a\n * rising sales figure.\n *\n * So this SUMS the three liability buckets per jurisdiction. The rule that\n * the operator's own invoices and storefront rows are never summed still\n * holds — nothing here touches the operator's own sales; within the\n * storefront collection the buckets differ only in WHO REMITS, and a nexus\n * threshold counts the sale whoever remits it. Who remits is still carried\n * per row, because \"do we have nexus here\" and \"what do we owe here\" are\n * answered off the same rows and must not blur.\n *\n * ⚠️ A LOWER BOUND, deliberately rather than silently: `storefront-tax-record.ts`\n * files no row at all for a sale whose `taxMode` resolves to `none`, so a\n * wholly untaxed storefront sale is invisible here — the population nexus\n * detection most needs. Closing it is a write-side change recorded on\n * AGL-1956. The filing jurisdiction does not depend on any of this: a filer\n * registered where it is established has no in-state threshold left to cross.\n */\nexport function storefrontFacilitatedJurisdictionRows(\n summary: StorefrontTaxSummary | null | undefined,\n filing: TaxReturnFiling,\n): StorefrontFacilitatedJurisdictionRow[] {\n if (!summary) return []\n const totals = new Map<\n string,\n { count: number; salesCents: number; taxCents: number; platformCents: number }\n >()\n const buckets: Array<[StorefrontTaxBucketRow['id'], boolean]> = [\n ['aglynLiable', true],\n ['merchantManual', false],\n ['connectedAccountLiable', false],\n ]\n for (const [id, platformLiable] of buckets) {\n const byJurisdiction = summary[id]?.byJurisdiction ?? {}\n for (const [jurisdiction, figures] of Object.entries(byJurisdiction)) {\n const entry = totals.get(jurisdiction) ?? {\n count: 0,\n salesCents: 0,\n taxCents: 0,\n platformCents: 0,\n }\n const taxCents = Number(figures?.taxCollectedCents ?? 0)\n entry.count += Number(figures?.transactionCount ?? 0)\n entry.salesCents += Number(figures?.totalSalesCents ?? 0)\n entry.taxCents += taxCents\n if (platformLiable) entry.platformCents += taxCents\n totals.set(jurisdiction, entry)\n }\n }\n return [...totals.entries()]\n .map(([jurisdiction, entry]) => ({\n jurisdiction,\n isFilingJurisdiction: jurisdiction === filing.code,\n transactionCount: entry.count,\n totalSalesDollars: centsToDollars(entry.salesCents),\n taxCollectedDollars: centsToDollars(entry.taxCents),\n platformLiableTaxDollars: centsToDollars(entry.platformCents),\n untaxed: entry.taxCents === 0,\n }))\n .sort(\n (a, b) =>\n // The filing jurisdiction first — it is the one obligation that does\n // not wait on a threshold — then by the figure a threshold is\n // actually measured against.\n Number(b.isFilingJurisdiction) - Number(a.isFilingJurisdiction) ||\n Number(b.totalSalesDollars) - Number(a.totalSalesDollars) ||\n a.jurisdiction.localeCompare(b.jurisdiction),\n )\n}\n\n/** The storefront's two tables on the return's screen. */\nfunction storefrontTables(\n summary: StorefrontTaxSummary,\n filing: TaxReturnFiling,\n): TaxReturnSectionTable[] {\n const brand = PLATFORM_BRAND_NAME\n return [\n {\n // Split by who owes it, never summed — one \"storefront tax\" total would\n // merge two facts into a number that is true of neither.\n columns: [\n { label: 'Bucket' },\n { label: 'Sales', numeric: true },\n { label: 'Gross', numeric: true, money: true },\n { label: 'Taxable sales', numeric: true, money: true },\n { label: 'Tax collected', numeric: true, money: true },\n ],\n rows: storefrontBucketRows(summary).map((row) => ({\n key: row.id,\n cells: [\n {\n text: row.label,\n caption: row.liability,\n ...(row.platformLiable\n ? { tag: { label: `${brand} holds this`, tone: 'attention' as const } }\n : {}),\n },\n { text: String(row.transactionCount) },\n { text: `$${row.grossDollars}` },\n { text: `$${row.taxableSalesDollars}` },\n { text: `$${row.taxCollectedDollars}`, strong: row.platformLiable },\n ],\n })),\n empty: 'This period’s response carries no storefront figures.',\n },\n {\n heading: 'Facilitated sales by buyer state',\n description:\n `What ${brand} facilitated into each state, whoever remits the ` +\n 'tax — the figure an economic-nexus threshold is measured ' +\n `against. ${filing.code} needs no threshold: the filer is ` +\n 'established there, so the obligation is unconditional. A ' +\n 'region showing sales and no tax is the one to watch.',\n columns: [\n { label: 'Buyer state' },\n { label: 'Sales', numeric: true },\n { label: 'Total sales', numeric: true, money: true },\n { label: 'Tax collected', numeric: true, money: true },\n { label: `Of which ${brand} owes`, numeric: true, money: true },\n ],\n rows: storefrontFacilitatedJurisdictionRows(summary, filing).map((row) => ({\n key: row.jurisdiction,\n cells: [\n {\n text: row.jurisdiction === 'unknown' ? 'Not stated' : row.jurisdiction,\n ...(row.isFilingJurisdiction\n ? { tag: { label: 'Registered', tone: 'attention' as const } }\n : row.untaxed\n ? { tag: { label: 'No tax collected', tone: 'neutral' as const } }\n : {}),\n },\n { text: String(row.transactionCount) },\n { text: `$${row.totalSalesDollars}` },\n { text: `$${row.taxCollectedDollars}` },\n {\n text: `$${row.platformLiableTaxDollars}`,\n strong: Number(row.platformLiableTaxDollars) > 0,\n },\n ],\n })),\n empty: 'No storefront sales recorded in this period.',\n footnote:\n 'A LOWER BOUND. A storefront sale that collected no tax at ' +\n 'all files no row, so it is missing here — which is exactly ' +\n 'the population a nexus check wants. Recorded on AGL-1956.',\n },\n ]\n}\n\n/**\n * The storefront's blocks of the working-papers export: the nexus figures\n * beside the operator's own sales by jurisdiction — a different taxpayer's\n * money and never summed with them — and the liability buckets after the\n * working papers.\n */\nfunction storefrontExports(\n summary: StorefrontTaxSummary,\n filing: TaxReturnFiling,\n): TaxReturnExportBlock[] {\n const brand = PLATFORM_BRAND_NAME\n const facilitated = storefrontFacilitatedJurisdictionRows(summary, filing)\n return [\n {\n placement: 'jurisdictions',\n rows: [\n ['Facilitated sales by buyer state (merchants’ storefronts)'],\n [\n 'Buyer state',\n 'Sales',\n 'Total sales (USD)',\n 'Tax collected (USD)',\n `Of which ${brand} owes (USD)`,\n ],\n ...(facilitated.length\n ? facilitated.map((row) => [\n row.jurisdiction,\n String(row.transactionCount),\n row.totalSalesDollars,\n row.taxCollectedDollars,\n row.platformLiableTaxDollars,\n ])\n : [['—', '0', '0.00', '0.00', '0.00']]),\n [\n 'LOWER BOUND — a storefront sale that collected no tax files no row, ' +\n `so it is absent here. ${filing.code} needs no threshold: the filer ` +\n 'is established there.',\n ],\n ],\n },\n {\n placement: 'sections',\n rows: [\n [\n 'Storefront commerce tax by liability (AGL-1904) — NOT in ' +\n (filing.form === 'tx-webfile' ? 'the Webfile figures' : 'the breakdown above'),\n ],\n [\n 'Bucket',\n 'Who owes it',\n 'Transactions',\n 'Gross (USD)',\n 'Taxable sales (USD)',\n 'Tax collected (USD)',\n ],\n ...storefrontBucketRows(summary).map((row) => [\n row.label,\n row.liability,\n String(row.transactionCount),\n row.grossDollars,\n row.taxableSalesDollars,\n row.taxCollectedDollars,\n ]),\n ],\n },\n ]\n}\n\n/** One storefront row as the working papers carry it. */\nfunction projectRow(row: StorefrontTaxReturnRowInput): StorefrontTaxRow {\n return {\n id: row.id,\n hostId: typeof row.hostId === 'string' ? row.hostId : null,\n orgId: row.orgId ?? null,\n paidAt: asRowDate(row.paidAt)?.toISOString() ?? null,\n taxMode: typeof row.taxMode === 'string' ? row.taxMode : null,\n taxLiability: typeof row.taxLiability === 'string' ? row.taxLiability : null,\n grossCents: Number(row.grossCents ?? 0),\n taxCents: Number(row.taxCents ?? 0),\n taxableSalesCents: (Array.isArray(row.taxLines) ? row.taxLines : [])\n .map((line) => Number(line?.taxableAmountCents ?? 0))\n .reduce((sum, base) => sum + (Number.isFinite(base) ? base : 0), 0),\n state: typeof row.customerAddress?.state === 'string' ? row.customerAddress.state : null,\n country:\n typeof row.customerAddress?.country === 'string' ? row.customerAddress.country : null,\n }\n}\n\n/**\n * The storefront's answer for one period, from rows already read. Pure, so\n * the section a preparer reads can be proved from fixtures.\n */\nexport function storefrontTaxReturnAnswer(\n read: {\n rows: readonly StorefrontTaxReturnRowInput[]\n truncated: boolean\n undatedRows: number\n /** Rows of the operator's own stores, which their own card folds in instead (AGL-4038). */\n ownStoreRows?: number\n },\n request: TaxReturnSourceRequest,\n): TaxReturnSourceAnswer {\n const brand = PLATFORM_BRAND_NAME\n const { filing } = request\n const summary = storefrontTaxSummary(read.rows, request)\n return {\n id: 'storefront',\n name: 'Storefront',\n title: 'Storefront commerce tax — merchants’ sales',\n help:\n 'Tax charged to shoppers on merchants’ storefronts, split by who owes it. None of it is in the filing figures above.',\n intro:\n `None of this is in the ${\n filing.form === 'tx-webfile' ? 'Webfile' : 'breakdown'\n } figures above, which sum ` +\n `${brand}’s OWN sales only. The first row is the one that ` +\n `needs a decision: those sessions are created on ${brand}’s ` +\n `platform account, so Stripe computed that tax against ` +\n `${brand}’s registrations and it settled into ${brand}’s balance.`,\n truncated: read.truncated,\n undatedRows: read.undatedRows,\n findings: storefrontTaxFindings(summary, filing),\n filingLines: storefrontFilingLines(summary, filing),\n tables: storefrontTables(summary, filing),\n figures: read.ownStoreRows\n ? [\n {\n label: `Rows of ${brand}’s own stores`,\n value: String(read.ownStoreRows),\n note: `${brand}’s own sales, not a merchant’s: on the own stores card and folded into the filing figures, never here.`,\n },\n ]\n : [],\n exports: storefrontExports(summary, filing),\n summary,\n rows: read.rows.map(projectRow),\n }\n}\n\n/**\n * Commerce's source, registered on the console's API surface: the staff\n * return awaits that surface before it asks. It answers three sections, one\n * per kind of sale commerce records apart:\n *\n * - the storefront's FACILITATED sales — merchants' money (below);\n * - the POS hardware shop's, the operator's own\n * (`pos-hardware-tax-return-source.ts`, AGL-4038);\n * - the operator's own stores', its own too (`own-store-tax-return-source.ts`,\n * AGL-4038).\n *\n * The operator's own stores are resolved FIRST, because each of the others\n * leaves their sales to the third: the storefront drops their tax rows (and\n * hands their stated bases over), and the hardware section folds in no\n * reader sold at their registers. So every sale is counted once. Any read\n * failing refuses all three, so a half-read commerce never reads as a\n * complete one.\n */\nexport const commerceTaxReturnSource: TaxReturnSource = {\n async read(request) {\n const own = await resolveOwnStores()\n const ownHostIds = new Set(own.stores.map((store) => store.hostId))\n const [storefrontRead, hardware, ownOrders] = await Promise.all([\n readStorefrontTaxRows(request),\n readPosHardwareTaxReturn(request, { ownHostIds }),\n readOwnStoreOrders(request, own.stores),\n ])\n const isOwn = (row: StorefrontTaxReturnRowInput) => isOwnStoreRow(row, own)\n const ownRows = storefrontRead.rows.filter(isOwn)\n const storefront = storefrontTaxReturnAnswer(\n { ...storefrontRead, rows: storefrontRead.rows.filter((row) => !isOwn(row)), ownStoreRows: ownRows.length },\n request,\n )\n // The base Stripe stated on an own store's online sale, by its order id\n // (an online order is keyed by its Checkout Session, as its row is).\n const statedBases = new Map<string, number>()\n for (const row of ownRows) {\n const base = statedTaxableBase(Array.isArray(row.taxLines) ? row.taxLines : [])\n if (base !== null) statedBases.set(row.id, base)\n }\n const ownStores = ownStoreTaxReturnAnswer({ own, read: ownOrders, statedBases }, request)\n return [storefront, hardware, ownStores]\n },\n}\n\n/** Whether a storefront tax row is one of the operator's own stores' (AGL-4038). */\nexport function isOwnStoreRow(\n row: Pick<StorefrontTaxReturnRowInput, 'hostId' | 'orgId'>,\n own: OwnStores,\n): boolean {\n if (typeof row.hostId === 'string' && own.stores.some((store) => store.hostId === row.hostId)) return true\n return Boolean(own.orgId) && row.orgId === own.orgId\n}\n\n/**\n * The storefront's section.\n *\n * Two queries, and the second is the honesty check: the period query ranges\n * on `paidAt`, and a Firestore range query CANNOT match a document whose\n * field is null — so a row that failed to date itself would be invisible to\n * every period. The equality probe counts those rows, over all of them, and\n * the platform blocks the return on any.\n */\nexport async function readStorefrontTaxReturn(\n request: TaxReturnSourceRequest,\n): Promise<TaxReturnSourceAnswer> {\n return storefrontTaxReturnAnswer(await readStorefrontTaxRows(request), request)\n}\n\n/** The storefront's rows for the period, before any is set aside. See {@link readStorefrontTaxReturn}. */\nexport async function readStorefrontTaxRows(request: TaxReturnSourceRequest): Promise<{\n rows: StorefrontTaxReturnRowInput[]\n truncated: boolean\n undatedRows: number\n}> {\n const firestore = firebaseAdmin.app().firestore()\n const collection = firestore.collection('storefrontTaxCollected')\n const [inPeriod, undated, inPerson] = await Promise.all([\n collection\n .where('paidAt', '>=', request.start)\n .where('paidAt', '<', request.end)\n .limit(request.rowCap + 1)\n .get(),\n collection.where('paidAt', '==', null).count().get(),\n // The platform's own in-person hardware sales around the period\n // (AGL-4038): the hardware section counts them, so their part of the\n // register sale's storefront row comes out here (`posHardwareSales`\n // `source, paidAtMs`).\n firestore\n .collection(POS_HARDWARE_SALES_COLLECTION)\n .where('source', '==', 'in_person')\n .where('paidAtMs', '>=', request.start.getTime() - IN_PERSON_ROW_MARGIN_MS)\n .where('paidAtMs', '<', request.end.getTime() + IN_PERSON_ROW_MARGIN_MS)\n .limit(request.rowCap)\n .get(),\n ])\n const rows: StorefrontTaxReturnRowInput[] = storefrontRowsWithoutInPersonHardware(\n inPeriod.docs.slice(0, request.rowCap).map((doc) => ({\n id: doc.id,\n ...(doc.data() as Omit<StorefrontTaxReturnRowInput, 'id'>),\n })),\n posHardwareStorefrontParts(inPerson.docs.map((doc) => doc.data())),\n )\n return {\n rows,\n truncated: inPeriod.size > request.rowCap,\n undatedRows: Number(undated.data().count ?? 0),\n }\n}\n"],"names":["firebaseAdmin","PLATFORM_BRAND_NAME","asRowDate","centsToDollars","storefrontTaxSummary","readPosHardwareTaxReturn","POS_HARDWARE_SALES_COLLECTION","posHardwareStorefrontParts","storefrontRowsWithoutInPersonHardware","statedTaxableBase","ownStoreTaxReturnAnswer","readOwnStoreOrders","resolveOwnStores","IN_PERSON_ROW_MARGIN_MS","storefrontPlatformLiableCents","summary","filing","figures","aglynLiable","byJurisdiction","code","cents","Number","taxCollectedCents","isFinite","merchantManualCents","merchantManual","storefrontTaxFindings","brand","id","severity","count","label","detail","figuresName","attention","rowsUnclassified","rowsMissingTaxableBase","storefrontFilingLines","platformLiable","merchant","form","item","dollars","note","storefrontBucketRows","buckets","liability","map","bucket","transactionCount","grossDollars","grossCents","taxableSalesDollars","taxableSalesCents","taxCollectedDollars","storefrontFacilitatedJurisdictionRows","totals","Map","jurisdiction","Object","entries","entry","get","salesCents","taxCents","platformCents","totalSalesCents","set","isFilingJurisdiction","totalSalesDollars","platformLiableTaxDollars","untaxed","sort","a","b","localeCompare","storefrontTables","columns","numeric","money","rows","row","key","cells","text","caption","tag","tone","String","strong","empty","heading","description","footnote","storefrontExports","facilitated","placement","length","projectRow","hostId","orgId","paidAt","toISOString","taxMode","taxLiability","Array","isArray","taxLines","line","taxableAmountCents","reduce","sum","base","state","customerAddress","country","storefrontTaxReturnAnswer","read","request","name","title","help","intro","truncated","undatedRows","findings","filingLines","tables","ownStoreRows","value","exports","commerceTaxReturnSource","own","ownHostIds","Set","stores","store","storefrontRead","hardware","ownOrders","Promise","all","readStorefrontTaxRows","isOwn","isOwnStoreRow","ownRows","filter","storefront","statedBases","ownStores","some","Boolean","readStorefrontTaxReturn","undated","firestore","app","collection","inPeriod","inPerson","where","start","end","limit","rowCap","getTime","docs","slice","doc","data","size"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuCC,GAED,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SACEC,SAAS,EACTC,cAAc,QACT,kDAAiD;AAWxD,SACEC,oBAAoB,QAGf,qCAAiC;AACxC,SAASC,wBAAwB,QAAQ,sC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0J,KAAK,CAAC,UAAU,MAAM,aACtBA,KAAK,CAAC,YAAY,MAAMzC,QAAQ0C,KAAK,CAACI,OAAO,KAAKxJ,yBAClDmJ,KAAK,CAAC,YAAY,KAAKzC,QAAQ2C,GAAG,CAACG,OAAO,KAAKxJ,yBAC/CsJ,KAAK,CAAC5C,QAAQ6C,MAAM,EACpBrG,GAAG;KACP;IACD,MAAMkB,OAAsCzE,sCAC1CsJ,SAASQ,IAAI,CAACC,KAAK,CAAC,GAAGhD,QAAQ6C,MAAM,EAAEpH,GAAG,CAAC,CAACwH,MAAS;YACnD3I,IAAI2I,IAAI3I,EAAE;WACN2I,IAAIC,IAAI,MAEdlK,2BAA2BwJ,SAASO,IAAI,CAACtH,GAAG,CAAC,CAACwH,MAAQA,IAAIC,IAAI;IAEhE,OAAO;QACLxF;QACA2C,WAAWkC,SAASY,IAAI,GAAGnD,QAAQ6C,MAAM;QACzCvC,aAAavG,QAAOoI,sBAAAA,QAAQe,IAAI,GAAG1I,KAAK,YAApB2H,sBAAwB;IAC9C;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/tax-return-source.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Storefront sales on the operator's sales tax return (AGL-1904, AGL-3080).\n *\n * The operator's return sums its own invoices; this is the storefront's half\n * of it, answered through the platform's tax return source contract\n * (`@aglyn/aglyn/plugin-manager/plugin-tax-return-sources`). It reads\n * `storefrontTaxCollected` — a SEPARATE collection from the operator's own\n * invoices, queried and reported separately, because a storefront row's\n * money is mostly the merchant's while an invoice row's is the operator's.\n * Summing the two would put other companies' receipts into the return's\n * total sales, which is why they never meet in one query and never share a\n * figure.\n *\n * What it answers, all worded for the filing jurisdiction the platform\n * resolved:\n *\n * - **The three liability buckets**, never summed — see\n * `model/storefront-tax-summary.ts`.\n * - **A blocking finding for the platform-liable tax** in the filing\n * jurisdiction. Every storefront checkout is created on the platform's\n * own account, so a `mode: 'stripe'` store's shopper is charged tax Stripe\n * computes against the PLATFORM's registrations — measured, not inferred.\n * That money is in the platform's balance and is NOT in the filing\n * figures, which sum the operator's own sales only. Filing those without\n * deciding what to do with this figure is exactly the shortfall an\n * auditor finds. It states the mechanics and asks for a decision; it does\n * NOT assert a marketplace-facilitator position — that attaches by\n * operation of law and belongs to counsel, not to this report.\n * - **Two lines beneath the filing figures** — the platform-liable tax and\n * the merchant's own rate, stated side by side and never folded into a\n * form item, because this report does not decide how storefront receipts\n * are reported and adding them to one would be deciding it silently.\n * - **Facilitated sales by buyer state** — the economic-nexus question\n * (AGL-1956), with the three buckets SUMMED per jurisdiction on purpose:\n * a threshold counts the sale whoever remits it. Who remits is still\n * carried per row.\n *\n * Truncation and rows no period can reach are reported, and the platform\n * raises each as a blocking finding of its own.\n */\n\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport {\n asRowDate,\n centsToDollars,\n} from '@aglyn/aglyn/app-utils/tax-jurisdiction-figures'\nimport type {\n TaxReturnExportBlock,\n TaxReturnFiling,\n TaxReturnFilingLine,\n TaxReturnFinding,\n TaxReturnSectionTable,\n TaxReturnSource,\n TaxReturnSourceAnswer,\n TaxReturnSourceRequest,\n} from '@aglyn/aglyn/plugin-manager/plugin-tax-return-sources'\nimport {\n storefrontTaxSummary,\n type StorefrontTaxReturnRowInput,\n type StorefrontTaxSummary,\n} from '../model/storefront-tax-summary'\nimport { readPosHardwareTaxReturn } from './pos-hardware-tax-return-source'\nimport { POS_HARDWARE_SALES_COLLECTION } from '../model/pos-hardware'\nimport {\n posHardwareStorefrontParts,\n storefrontRowsWithoutInPersonHardware,\n} from '../model/pos-hardware-tax-summary'\nimport { statedTaxableBase } from '../model/own-store-tax-summary'\nimport {\n ownStoreTaxReturnAnswer,\n readOwnStoreOrders,\n resolveOwnStores,\n type OwnStores,\n} from './own-store-tax-return-source'\n\n/**\n * How far either side of the period an in-person hardware record is read,\n * to meet the storefront row its register sale filed: the two are written\n * seconds apart, so a week is more than enough for either edge.\n */\nconst IN_PERSON_ROW_MARGIN_MS = 7 * 24 * 60 * 60 * 1000\n\n/** One row of the storefront listing, as the working papers carry it. */\nexport interface StorefrontTaxRow {\n id: string\n hostId: string | null\n orgId: string | null\n paidAt: string | null\n taxMode: string | null\n taxLiability: string | null\n grossCents: number\n taxCents: number\n taxableSalesCents: number\n state: string | null\n country: string | null\n}\n\n/** A liability bucket, ready to print. */\nexport interface StorefrontTaxBucketRow {\n id: 'aglynLiable' | 'merchantManual' | 'connectedAccountLiable'\n label: string\n /** Who owes it — the sentence that decides whether it is on this return. */\n liability: string\n transactionCount: number\n grossDollars: string\n taxableSalesDollars: string\n taxCollectedDollars: string\n /** True when this row is money in the platform's balance under its registration. */\n platformLiable: boolean\n}\n\n/** One state's facilitated storefront sales, for the nexus question. */\nexport interface StorefrontFacilitatedJurisdictionRow {\n jurisdiction: string\n /** True for the one jurisdiction this deployment files a return in. */\n isFilingJurisdiction: boolean\n transactionCount: number\n totalSalesDollars: string\n taxCollectedDollars: string\n /** The part of `taxCollectedDollars` the platform holds and must remit. */\n platformLiableTaxDollars: string\n /** True when NO tax was collected on any sale into this state. */\n untaxed: boolean\n}\n\n/**\n * Storefront tax in the FILING jurisdiction that Stripe computed against the\n * platform's own registrations.\n *\n * The one figure that decides whether a period can be filed from the filing\n * lines alone. Deliberately excludes `merchantManual` — a merchant's own\n * configured rate never touched those registrations. Read against the\n * configured jurisdiction rather than Texas, because a hard-coded key answers\n * `0.00` everywhere else — and a zero here reads as \"nothing to decide\" on\n * the one finding that blocks filing.\n */\nexport function storefrontPlatformLiableCents(\n summary: StorefrontTaxSummary | null | undefined,\n filing: TaxReturnFiling,\n): number {\n const figures = summary?.aglynLiable?.byJurisdiction?.[filing.code]\n const cents = Number(figures?.taxCollectedCents ?? 0)\n return Number.isFinite(cents) ? cents : 0\n}\n\n/** The merchant's own configured tax in the filing jurisdiction. */\nfunction merchantManualCents(\n summary: StorefrontTaxSummary | null | undefined,\n filing: TaxReturnFiling,\n): number {\n return Number(\n summary?.merchantManual?.byJurisdiction?.[filing.code]?.taxCollectedCents ?? 0,\n )\n}\n\n/** The storefront's findings. The platform raises the non-zero ones. */\nexport function storefrontTaxFindings(\n summary: StorefrontTaxSummary,\n filing: TaxReturnFiling,\n): TaxReturnFinding[] {\n const brand = PLATFORM_BRAND_NAME\n return [\n {\n // BLOCKING on purpose — see the module note.\n id: 'storefrontAglynLiableTax',\n severity: 'blocking',\n count: storefrontPlatformLiableCents(summary, filing),\n label: `${filing.label} storefront tax collected under ${brand}’s registration`,\n detail:\n 'Cents. Charged to shoppers on merchants’ storefront sales, computed ' +\n 'by Stripe Tax against THE PLATFORM’s registrations (the session is ' +\n 'created on the platform account), and settled into the platform’s ' +\n `balance. It is NOT included in ${filing.figuresName} below. Decide ` +\n 'with counsel how it is reported before filing — do not file as if ' +\n 'it were zero.',\n },\n {\n id: 'storefrontUnclassified',\n severity: 'blocking',\n count: Number(summary?.attention?.rowsUnclassified ?? 0),\n label: 'Storefront rows with an unrecognised tax mode',\n detail:\n 'Not counted in any storefront bucket, so they are in no figure at ' +\n 'all. Classify them before filing.',\n },\n {\n id: 'storefrontMissingTaxableBase',\n severity: 'review',\n count: Number(summary?.attention?.rowsMissingTaxableBase ?? 0),\n label: 'Storefront rows with tax but no stated base',\n detail:\n 'Tax was collected but Stripe’s taxable_amount could not be read, so ' +\n 'the storefront taxable-sales figure understates the base. Re-read ' +\n 'the session in Stripe with the tax breakdown expanded.',\n },\n ]\n}\n\n/**\n * The two lines beneath the filing figures: the platform-liable tax and the\n * merchant's own rate, separately, and outside every form item.\n */\nexport function storefrontFilingLines(\n summary: StorefrontTaxSummary,\n filing: TaxReturnFiling,\n): TaxReturnFilingLine[] {\n const brand = PLATFORM_BRAND_NAME\n const platformLiable = centsToDollars(storefrontPlatformLiableCents(summary, filing))\n const merchant = centsToDollars(merchantManualCents(summary, filing))\n if (filing.form === 'tx-webfile') {\n return [\n {\n item: '—',\n label: `${filing.label} storefront tax under ${brand}’s registration (NOT in ${filing.figuresName})`,\n dollars: platformLiable,\n note:\n `Collected from shoppers on merchants’ sales and held in ${brand}’s ` +\n 'balance. Excluded from every item above. Its treatment on the ' +\n 'return is a question for counsel — see AGL-1904.',\n },\n {\n item: '—',\n label: `${filing.label} storefront tax under the MERCHANT’s own rate (not ${brand}’s)`,\n dollars: merchant,\n note:\n `A manual-mode store’s own configured rate. ${brand}’s registrations ` +\n 'played no part in computing it. Shown so it is visibly NOT the line ' +\n 'above — the two must never be added together.',\n },\n ]\n }\n return [\n {\n item: '—',\n label: `${filing.code} storefront tax under the platform’s registration (NOT in the figures above)`,\n dollars: platformLiable,\n note:\n 'Collected from shoppers on merchants’ sales and held in the ' +\n 'platform’s balance. Excluded from every figure above. Its treatment ' +\n 'on the return is a question for the operator’s own counsel.',\n },\n {\n item: '—',\n label: `${filing.code} storefront tax under the MERCHANT’s own rate`,\n dollars: merchant,\n note:\n 'A manual-mode store’s own configured rate. The platform’s ' +\n 'registrations played no part in computing it. Shown so it is ' +\n 'visibly NOT the line above — the two must never be added together.',\n },\n ]\n}\n\n/** The three liability buckets, in the order a reader decides them. */\nexport function storefrontBucketRows(\n summary: StorefrontTaxSummary,\n): StorefrontTaxBucketRow[] {\n const brand = PLATFORM_BRAND_NAME\n const buckets: Array<{\n id: StorefrontTaxBucketRow['id']\n label: string\n liability: string\n platformLiable: boolean\n }> = [\n {\n id: 'aglynLiable',\n label: `Computed against ${brand}’s registrations`,\n liability: `In ${brand}’s balance. Stripe Tax computed it on ${brand}’s platform account.`,\n platformLiable: true,\n },\n {\n id: 'merchantManual',\n label: 'Merchant’s own configured rate',\n liability: `The merchant’s. It never touched an ${brand} registration and is not ${brand}’s to remit.`,\n platformLiable: false,\n },\n {\n id: 'connectedAccountLiable',\n label: 'Stripe Tax named the connected account liable',\n liability: 'The connected account’s. Empty today.',\n platformLiable: false,\n },\n ]\n return buckets.map((bucket) => {\n const figures = summary?.[bucket.id]\n return {\n id: bucket.id,\n label: bucket.label,\n liability: bucket.liability,\n transactionCount: Number(figures?.transactionCount ?? 0),\n grossDollars: centsToDollars(figures?.grossCents),\n taxableSalesDollars: centsToDollars(figures?.taxableSalesCents),\n taxCollectedDollars: centsToDollars(figures?.taxCollectedCents),\n platformLiable: bucket.platformLiable,\n }\n })\n}\n\n/**\n * FACILITATED SALES BY STATE — the economic-nexus question (AGL-1956).\n *\n * The question a state asks a marketplace facilitator is \"how much did you\n * facilitate INTO this state, and in how many transactions\" — not \"how much\n * tax did you collect there\". A state the operator is not registered in\n * collects nothing by definition, which is exactly why collection cannot be\n * the measure: the states worth watching are the ones showing $0 tax and a\n * rising sales figure.\n *\n * So this SUMS the three liability buckets per jurisdiction. The rule that\n * the operator's own invoices and storefront rows are never summed still\n * holds — nothing here touches the operator's own sales; within the\n * storefront collection the buckets differ only in WHO REMITS, and a nexus\n * threshold counts the sale whoever remits it. Who remits is still carried\n * per row, because \"do we have nexus here\" and \"what do we owe here\" are\n * answered off the same rows and must not blur.\n *\n * ⚠️ A LOWER BOUND, deliberately rather than silently: `storefront-tax-record.ts`\n * files no row at all for a sale whose `taxMode` resolves to `none`, so a\n * wholly untaxed storefront sale is invisible here — the population nexus\n * detection most needs. Closing it is a write-side change recorded on\n * AGL-1956. The filing jurisdiction does not depend on any of this: a filer\n * registered where it is established has no in-state threshold left to cross.\n */\nexport function storefrontFacilitatedJurisdictionRows(\n summary: StorefrontTaxSummary | null | undefined,\n filing: TaxReturnFiling,\n): StorefrontFacilitatedJurisdictionRow[] {\n if (!summary) return []\n const totals = new Map<\n string,\n { count: number; salesCents: number; taxCents: number; platformCents: number }\n >()\n const buckets: Array<[StorefrontTaxBucketRow['id'], boolean]> = [\n ['aglynLiable', true],\n ['merchantManual', false],\n ['connectedAccountLiable', false],\n ]\n for (const [id, platformLiable] of buckets) {\n const byJurisdiction = summary[id]?.byJurisdiction ?? {}\n for (const [jurisdiction, figures] of Object.entries(byJurisdiction)) {\n const entry = totals.get(jurisdiction) ?? {\n count: 0,\n salesCents: 0,\n taxCents: 0,\n platformCents: 0,\n }\n const taxCents = Number(figures?.taxCollectedCents ?? 0)\n entry.count += Number(figures?.transactionCount ?? 0)\n entry.salesCents += Number(figures?.totalSalesCents ?? 0)\n entry.taxCents += taxCents\n if (platformLiable) entry.platformCents += taxCents\n totals.set(jurisdiction, entry)\n }\n }\n return [...totals.entries()]\n .map(([jurisdiction, entry]) => ({\n jurisdiction,\n isFilingJurisdiction: jurisdiction === filing.code,\n transactionCount: entry.count,\n totalSalesDollars: centsToDollars(entry.salesCents),\n taxCollectedDollars: centsToDollars(entry.taxCents),\n platformLiableTaxDollars: centsToDollars(entry.platformCents),\n untaxed: entry.taxCents === 0,\n }))\n .sort(\n (a, b) =>\n // The filing jurisdiction first — it is the one obligation that does\n // not wait on a threshold — then by the figure a threshold is\n // actually measured against.\n Number(b.isFilingJurisdiction) - Number(a.isFilingJurisdiction) ||\n Number(b.totalSalesDollars) - Number(a.totalSalesDollars) ||\n a.jurisdiction.localeCompare(b.jurisdiction),\n )\n}\n\n/** The storefront's two tables on the return's screen. */\nfunction storefrontTables(\n summary: StorefrontTaxSummary,\n filing: TaxReturnFiling,\n): TaxReturnSectionTable[] {\n const brand = PLATFORM_BRAND_NAME\n return [\n {\n // Split by who owes it, never summed — one \"storefront tax\" total would\n // merge two facts into a number that is true of neither.\n columns: [\n { label: 'Bucket' },\n { label: 'Sales', numeric: true },\n { label: 'Gross', numeric: true, money: true },\n { label: 'Taxable sales', numeric: true, money: true },\n { label: 'Tax collected', numeric: true, money: true },\n ],\n rows: storefrontBucketRows(summary).map((row) => ({\n key: row.id,\n cells: [\n {\n text: row.label,\n caption: row.liability,\n ...(row.platformLiable\n ? { tag: { label: `${brand} holds this`, tone: 'attention' as const } }\n : {}),\n },\n { text: String(row.transactionCount) },\n { text: `$${row.grossDollars}` },\n { text: `$${row.taxableSalesDollars}` },\n { text: `$${row.taxCollectedDollars}`, strong: row.platformLiable },\n ],\n })),\n empty: 'This period’s response carries no storefront figures.',\n },\n {\n heading: 'Facilitated sales by buyer state',\n description:\n `What ${brand} facilitated into each state, whoever remits the ` +\n 'tax — the figure an economic-nexus threshold is measured ' +\n `against. ${filing.code} needs no threshold: the filer is ` +\n 'established there, so the obligation is unconditional. A ' +\n 'region showing sales and no tax is the one to watch.',\n columns: [\n { label: 'Buyer state' },\n { label: 'Sales', numeric: true },\n { label: 'Total sales', numeric: true, money: true },\n { label: 'Tax collected', numeric: true, money: true },\n { label: `Of which ${brand} owes`, numeric: true, money: true },\n ],\n rows: storefrontFacilitatedJurisdictionRows(summary, filing).map((row) => ({\n key: row.jurisdiction,\n cells: [\n {\n text: row.jurisdiction === 'unknown' ? 'Not stated' : row.jurisdiction,\n ...(row.isFilingJurisdiction\n ? { tag: { label: 'Registered', tone: 'attention' as const } }\n : row.untaxed\n ? { tag: { label: 'No tax collected', tone: 'neutral' as const } }\n : {}),\n },\n { text: String(row.transactionCount) },\n { text: `$${row.totalSalesDollars}` },\n { text: `$${row.taxCollectedDollars}` },\n {\n text: `$${row.platformLiableTaxDollars}`,\n strong: Number(row.platformLiableTaxDollars) > 0,\n },\n ],\n })),\n empty: 'No storefront sales recorded in this period.',\n footnote:\n 'A LOWER BOUND. A storefront sale that collected no tax at ' +\n 'all files no row, so it is missing here — which is exactly ' +\n 'the population a nexus check wants. Recorded on AGL-1956.',\n },\n ]\n}\n\n/**\n * The storefront's blocks of the working-papers export: the nexus figures\n * beside the operator's own sales by jurisdiction — a different taxpayer's\n * money and never summed with them — and the liability buckets after the\n * working papers.\n */\nfunction storefrontExports(\n summary: StorefrontTaxSummary,\n filing: TaxReturnFiling,\n): TaxReturnExportBlock[] {\n const brand = PLATFORM_BRAND_NAME\n const facilitated = storefrontFacilitatedJurisdictionRows(summary, filing)\n return [\n {\n placement: 'jurisdictions',\n rows: [\n ['Facilitated sales by buyer state (merchants’ storefronts)'],\n [\n 'Buyer state',\n 'Sales',\n 'Total sales (USD)',\n 'Tax collected (USD)',\n `Of which ${brand} owes (USD)`,\n ],\n ...(facilitated.length\n ? facilitated.map((row) => [\n row.jurisdiction,\n String(row.transactionCount),\n row.totalSalesDollars,\n row.taxCollectedDollars,\n row.platformLiableTaxDollars,\n ])\n : [['—', '0', '0.00', '0.00', '0.00']]),\n [\n 'LOWER BOUND — a storefront sale that collected no tax files no row, ' +\n `so it is absent here. ${filing.code} needs no threshold: the filer ` +\n 'is established there.',\n ],\n ],\n },\n {\n placement: 'sections',\n rows: [\n [\n 'Storefront commerce tax by liability (AGL-1904) — NOT in ' +\n (filing.form === 'tx-webfile' ? 'the Webfile figures' : 'the breakdown above'),\n ],\n [\n 'Bucket',\n 'Who owes it',\n 'Transactions',\n 'Gross (USD)',\n 'Taxable sales (USD)',\n 'Tax collected (USD)',\n ],\n ...storefrontBucketRows(summary).map((row) => [\n row.label,\n row.liability,\n String(row.transactionCount),\n row.grossDollars,\n row.taxableSalesDollars,\n row.taxCollectedDollars,\n ]),\n ],\n },\n ]\n}\n\n/** One storefront row as the working papers carry it. */\nfunction projectRow(row: StorefrontTaxReturnRowInput): StorefrontTaxRow {\n return {\n id: row.id,\n hostId: typeof row.hostId === 'string' ? row.hostId : null,\n orgId: row.orgId ?? null,\n paidAt: asRowDate(row.paidAt)?.toISOString() ?? null,\n taxMode: typeof row.taxMode === 'string' ? row.taxMode : null,\n taxLiability: typeof row.taxLiability === 'string' ? row.taxLiability : null,\n grossCents: Number(row.grossCents ?? 0),\n taxCents: Number(row.taxCents ?? 0),\n taxableSalesCents: (Array.isArray(row.taxLines) ? row.taxLines : [])\n .map((line) => Number(line?.taxableAmountCents ?? 0))\n .reduce((sum, base) => sum + (Number.isFinite(base) ? base : 0), 0),\n state: typeof row.customerAddress?.state === 'string' ? row.customerAddress.state : null,\n country:\n typeof row.customerAddress?.country === 'string' ? row.customerAddress.country : null,\n }\n}\n\n/**\n * The storefront's answer for one period, from rows already read. Pure, so\n * the section a preparer reads can be proved from fixtures.\n */\nexport function storefrontTaxReturnAnswer(\n read: {\n rows: readonly StorefrontTaxReturnRowInput[]\n truncated: boolean\n undatedRows: number\n /** Rows of the operator's own stores, which their own card folds in instead (AGL-4038). */\n ownStoreRows?: number\n },\n request: TaxReturnSourceRequest,\n): TaxReturnSourceAnswer {\n const brand = PLATFORM_BRAND_NAME\n const { filing } = request\n const summary = storefrontTaxSummary(read.rows, request)\n return {\n id: 'storefront',\n name: 'Storefront',\n title: 'Storefront commerce tax — merchants’ sales',\n help:\n 'Tax charged to shoppers on merchants’ storefronts, split by who owes it. None of it is in the filing figures above.',\n intro:\n `None of this is in the ${\n filing.form === 'tx-webfile' ? 'Webfile' : 'breakdown'\n } figures above, which sum ` +\n `${brand}’s OWN sales only. The first row is the one that ` +\n `needs a decision: those sessions are created on ${brand}’s ` +\n `platform account, so Stripe computed that tax against ` +\n `${brand}’s registrations and it settled into ${brand}’s balance.`,\n truncated: read.truncated,\n undatedRows: read.undatedRows,\n findings: storefrontTaxFindings(summary, filing),\n filingLines: storefrontFilingLines(summary, filing),\n tables: storefrontTables(summary, filing),\n figures: read.ownStoreRows\n ? [\n {\n label: `Rows of ${brand}’s own stores`,\n value: String(read.ownStoreRows),\n note: `${brand}’s own sales, not a merchant’s: on the own stores card and folded into the filing figures, never here.`,\n },\n ]\n : [],\n exports: storefrontExports(summary, filing),\n summary,\n rows: read.rows.map(projectRow),\n }\n}\n\n/**\n * Commerce's source, registered on the console's API surface: the staff\n * return awaits that surface before it asks. It answers three sections, one\n * per kind of sale commerce records apart:\n *\n * - the storefront's FACILITATED sales — merchants' money (below);\n * - the POS hardware shop's, the operator's own\n * (`pos-hardware-tax-return-source.ts`, AGL-4038);\n * - the operator's own stores', its own too (`own-store-tax-return-source.ts`,\n * AGL-4038).\n *\n * The operator's own stores are resolved FIRST, because each of the others\n * leaves their sales to the third: the storefront drops their tax rows (and\n * hands their stated bases over), and the hardware section folds in no\n * reader sold at their registers. So every sale is counted once. Any read\n * failing refuses all three, so a half-read commerce never reads as a\n * complete one.\n */\nexport const commerceTaxReturnSource: TaxReturnSource = {\n async read(request) {\n const own = await resolveOwnStores()\n const ownHostIds = new Set(own.stores.map((store) => store.hostId))\n const [storefrontRead, hardware, ownOrders] = await Promise.all([\n readStorefrontTaxRows(request),\n readPosHardwareTaxReturn(request, { ownHostIds }),\n readOwnStoreOrders(request, own.stores),\n ])\n const isOwn = (row: StorefrontTaxReturnRowInput) => isOwnStoreRow(row, own)\n const ownRows = storefrontRead.rows.filter(isOwn)\n const storefront = storefrontTaxReturnAnswer(\n { ...storefrontRead, rows: storefrontRead.rows.filter((row) => !isOwn(row)), ownStoreRows: ownRows.length },\n request,\n )\n // The base Stripe stated on an own store's online sale, by its order id\n // (an online order is keyed by its Checkout Session, as its row is).\n const statedBases = new Map<string, number>()\n for (const row of ownRows) {\n const base = statedTaxableBase(Array.isArray(row.taxLines) ? row.taxLines : [])\n if (base !== null) statedBases.set(row.id, base)\n }\n const ownStores = ownStoreTaxReturnAnswer({ own, read: ownOrders, statedBases }, request)\n return [storefront, hardware, ownStores]\n },\n}\n\n/** Whether a storefront tax row is one of the operator's own stores' (AGL-4038). */\nexport function isOwnStoreRow(\n row: Pick<StorefrontTaxReturnRowInput, 'hostId' | 'orgId'>,\n own: OwnStores,\n): boolean {\n if (typeof row.hostId === 'string' && own.stores.some((store) => store.hostId === row.hostId)) return true\n return Boolean(own.orgId) && row.orgId === own.orgId\n}\n\n/**\n * The storefront's section.\n *\n * Two queries, and the second is the honesty check: the period query ranges\n * on `paidAt`, and a Firestore range query CANNOT match a document whose\n * field is null — so a row that failed to date itself would be invisible to\n * every period. The equality probe counts those rows, over all of them, and\n * the platform blocks the return on any.\n */\nexport async function readStorefrontTaxReturn(\n request: TaxReturnSourceRequest,\n): Promise<TaxReturnSourceAnswer> {\n return storefrontTaxReturnAnswer(await readStorefrontTaxRows(request), request)\n}\n\n/** The storefront's rows for the period, before any is set aside. See {@link readStorefrontTaxReturn}. */\nexport async function readStorefrontTaxRows(request: TaxReturnSourceRequest): Promise<{\n rows: StorefrontTaxReturnRowInput[]\n truncated: boolean\n undatedRows: number\n}> {\n const firestore = firebaseAdmin.app().firestore()\n const collection = firestore.collection('storefrontTaxCollected')\n const [inPeriod, undated, inPerson] = await Promise.all([\n collection\n .where('paidAt', '>=', request.start)\n .where('paidAt', '<', request.end)\n .limit(request.rowCap + 1)\n .get(),\n collection.where('paidAt', '==', null).count().get(),\n // The platform's own in-person hardware sales around the period\n // (AGL-4038): the hardware section counts them, so their part of the\n // register sale's storefront row comes out here (`posHardwareSales`\n // `source, paidAtMs`).\n firestore\n .collection(POS_HARDWARE_SALES_COLLECTION)\n // In person or online from its own store (AGL-4038): the same index.\n .where('source', 'in', ['in_person', 'storefront'])\n .where('paidAtMs', '>=', request.start.getTime() - IN_PERSON_ROW_MARGIN_MS)\n .where('paidAtMs', '<', request.end.getTime() + IN_PERSON_ROW_MARGIN_MS)\n .limit(request.rowCap)\n .get(),\n ])\n const rows: StorefrontTaxReturnRowInput[] = storefrontRowsWithoutInPersonHardware(\n inPeriod.docs.slice(0, request.rowCap).map((doc) => ({\n id: doc.id,\n ...(doc.data() as Omit<StorefrontTaxReturnRowInput, 'id'>),\n })),\n posHardwareStorefrontParts(inPerson.docs.map((doc) => doc.data())),\n )\n return {\n rows,\n truncated: inPeriod.size > request.rowCap,\n undatedRows: Number(undated.data().count ?? 0),\n }\n}\n"],"names":["firebaseAdmin","PLATFORM_BRAND_NAME","asRowDate","centsToDollars","storefrontTaxSummary","readPosHardwareTaxReturn","POS_HARDWARE_SALES_COLLECTION","posHardwareStorefrontParts","storefrontRowsWithoutInPersonHardware","statedTaxableBase","ownStoreTaxReturnAnswer","readOwnStoreOrders","resolveOwnStores","IN_PERSON_ROW_MARGIN_MS","storefrontPlatformLiableCents","summary","filing","figures","aglynLiable","byJurisdiction","code","cents","Number","taxCollectedCents","isFinite","merchantManualCents","merchantManual","storefrontTaxFindings","brand","id","severity","count","label","detail","figuresName","attention","rowsUnclassified","rowsMissingTaxableBase","storefrontFilingLines","platformLiable","merchant","form","item","dollars","note","storefrontBucketRows","buckets","liability","map","bucket","transactionCount","grossDollars","grossCents","taxableSalesDollars","taxableSalesCents","taxCollectedDollars","storefrontFacilitatedJurisdictionRows","totals","Map","jurisdiction","Object","entries","entry","get","salesCents","taxCents","platformCents","totalSalesCents","set","isFilingJurisdiction","totalSalesDollars","platformLiableTaxDollars","untaxed","sort","a","b","localeCompare","storefrontTables","columns","numeric","money","rows","row","key","cells","text","caption","tag","tone","String","strong","empty","heading","description","footnote","storefrontExports","facilitated","placement","length","projectRow","hostId","orgId","paidAt","toISOString","taxMode","taxLiability","Array","isArray","taxLines","line","taxableAmountCents","reduce","sum","base","state","customerAddress","country","storefrontTaxReturnAnswer","read","request","name","title","help","intro","truncated","undatedRows","findings","filingLines","tables","ownStoreRows","value","exports","commerceTaxReturnSource","own","ownHostIds","Set","stores","store","storefrontRead","hardware","ownOrders","Promise","all","readStorefrontTaxRows","isOwn","isOwnStoreRow","ownRows","filter","storefront","statedBases","ownStores","some","Boolean","readStorefrontTaxReturn","undated","firestore","app","collection","inPeriod","inPerson","where","start","end","limit","rowCap","getTime","docs","slice","doc","data","size"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuCC,GAED,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SACEC,SAAS,EACTC,cAAc,QACT,kDAAiD;AAWxD,SACEC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AAoE;QACpE,uBAAuB;QACvB4F,UACGE,UAAU,CAACvJ,8BACZ,qEAAqE;SACpE0J,KAAK,CAAC,UAAU,MAAM;YAAC;YAAa;SAAa,EACjDA,KAAK,CAAC,YAAY,MAAMzC,QAAQ0C,KAAK,CAACI,OAAO,KAAKxJ,yBAClDmJ,KAAK,CAAC,YAAY,KAAKzC,QAAQ2C,GAAG,CAACG,OAAO,KAAKxJ,yBAC/CsJ,KAAK,CAAC5C,QAAQ6C,MAAM,EACpBrG,GAAG;KACP;IACD,MAAMkB,OAAsCzE,sCAC1CsJ,SAASQ,IAAI,CAACC,KAAK,CAAC,GAAGhD,QAAQ6C,MAAM,EAAEpH,GAAG,CAAC,CAACwH,MAAS;YACnD3I,IAAI2I,IAAI3I,EAAE;WACN2I,IAAIC,IAAI,MAEdlK,2BAA2BwJ,SAASO,IAAI,CAACtH,GAAG,CAAC,CAACwH,MAAQA,IAAIC,IAAI;IAEhE,OAAO;QACLxF;QACA2C,WAAWkC,SAASY,IAAI,GAAGnD,QAAQ6C,MAAM;QACzCvC,aAAavG,QAAOoI,sBAAAA,QAAQe,IAAI,GAAG1I,KAAK,YAApB2H,sBAAwB;IAC9C;AACF"}
package/src/lib/server.js CHANGED
@@ -267,7 +267,7 @@ registerPluginJob({
267
267
  }
268
268
  });
269
269
  /**
270
- * The monthly 4G charge for Stripe Reader S710s (AGL-4038): each workspace
270
+ * The monthly 4G charge for S710 readers (AGL-4038): each workspace
271
271
  * whose readers had 4G in the month just ended is charged once, through
272
272
  * core's usage-invoice charge. Every six hours, so the charge goes out early
273
273
  * on the 1st and one that could not reach Stripe is tried again the same
@@ -278,7 +278,7 @@ registerPluginJob({
278
278
  pluginId: BUNDLE_ID,
279
279
  name: 'pos-cellular-billing',
280
280
  intervalMinutes: 6 * 60,
281
- description: 'Charge each workspace for 4G on its Stripe Reader S710s for the month just ended, once (AGL-4038).',
281
+ description: 'Charge each workspace for 4G on its S710 readers for the month just ended, once (AGL-4038).',
282
282
  lockdown: {
283
283
  scope: 'per-host'
284
284
  },