@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.
- package/package.json +13 -13
- package/src/lib/components/account-subscriptions.d.ts +51 -0
- package/src/lib/components/account-subscriptions.js +168 -0
- package/src/lib/components/account-subscriptions.js.map +1 -0
- package/src/lib/components/account.js +12 -48
- package/src/lib/components/account.js.map +1 -1
- package/src/lib/components/cart.js +38 -9
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/commerce-console-page.js +6 -0
- package/src/lib/components/commerce-console-page.js.map +1 -1
- package/src/lib/components/commerce-console-sections.d.ts +1 -1
- package/src/lib/components/commerce-console-sections.js +5 -0
- package/src/lib/components/commerce-console-sections.js.map +1 -1
- package/src/lib/components/console/paid-media.d.ts +1 -0
- package/src/lib/components/console/paid-media.js +15 -4
- package/src/lib/components/console/paid-media.js.map +1 -1
- package/src/lib/components/console/payments-settings-card.component.js +1 -1
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-api.d.ts +10 -1
- package/src/lib/components/console/pos/pos-hardware-api.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-buyer.component.js +2 -2
- package/src/lib/components/console/pos/pos-hardware-buyer.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-sale-api.d.ts +2 -0
- package/src/lib/components/console/pos/pos-hardware-sale-api.js.map +1 -1
- package/src/lib/components/console/pos-cellular-control.component.d.ts +1 -1
- package/src/lib/components/console/pos-cellular-control.component.js +5 -5
- package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
- package/src/lib/components/console/pos-devices-card.component.js +2 -2
- package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
- package/src/lib/components/console/pos-hardware-card.component.d.ts +5 -0
- package/src/lib/components/console/pos-hardware-card.component.js +77 -8
- package/src/lib/components/console/pos-hardware-card.component.js.map +1 -1
- package/src/lib/components/console/pos-hardware-orders-staff-page.component.js +137 -19
- package/src/lib/components/console/pos-hardware-orders-staff-page.component.js.map +1 -1
- package/src/lib/components/console/pos-page.component.js +19 -2
- package/src/lib/components/console/pos-page.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +21 -2
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/subscription-detail-dialog.component.d.ts +58 -0
- package/src/lib/components/console/subscription-detail-dialog.component.js +201 -0
- package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -0
- package/src/lib/components/console/subscriptions-card.component.d.ts +60 -0
- package/src/lib/components/console/subscriptions-card.component.js +282 -0
- package/src/lib/components/console/subscriptions-card.component.js.map +1 -0
- package/src/lib/components/hardware-terms-consent.d.ts +22 -0
- package/src/lib/components/hardware-terms-consent.js +85 -0
- package/src/lib/components/hardware-terms-consent.js.map +1 -0
- package/src/lib/components/product-detail.js +32 -8
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/quote-page-body.js +7 -3
- package/src/lib/components/quote-page-body.js.map +1 -1
- package/src/lib/components/related-products.js +6 -3
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/components/storefront-payment-element.d.ts +7 -1
- package/src/lib/components/storefront-payment-element.js +11 -7
- package/src/lib/components/storefront-payment-element.js.map +1 -1
- package/src/lib/constants/operator-alerts.d.ts +1 -1
- package/src/lib/constants/operator-alerts.js +4 -4
- package/src/lib/constants/operator-alerts.js.map +1 -1
- package/src/lib/model/commerce-orders.d.ts +6 -2
- package/src/lib/model/commerce-orders.js.map +1 -1
- package/src/lib/model/commerce-payment-methods.d.ts +27 -16
- package/src/lib/model/commerce-payment-methods.js +11 -83
- package/src/lib/model/commerce-payment-methods.js.map +1 -1
- package/src/lib/model/commerce.d.ts +6 -0
- package/src/lib/model/commerce.js.map +1 -1
- package/src/lib/model/index.d.ts +1 -0
- package/src/lib/model/index.js +1 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/model/paid-media.d.ts +8 -0
- package/src/lib/model/paid-media.js +13 -0
- package/src/lib/model/paid-media.js.map +1 -1
- package/src/lib/model/pos-hardware-in-person.d.ts +23 -2
- package/src/lib/model/pos-hardware-in-person.js +52 -20
- package/src/lib/model/pos-hardware-in-person.js.map +1 -1
- package/src/lib/model/pos-hardware-tax-summary.d.ts +5 -1
- package/src/lib/model/pos-hardware-tax-summary.js +2 -1
- package/src/lib/model/pos-hardware-tax-summary.js.map +1 -1
- package/src/lib/model/pos-hardware-terms.d.ts +37 -2
- package/src/lib/model/pos-hardware-terms.js +68 -3
- package/src/lib/model/pos-hardware-terms.js.map +1 -1
- package/src/lib/model/pos-hardware.d.ts +101 -15
- package/src/lib/model/pos-hardware.js +128 -18
- package/src/lib/model/pos-hardware.js.map +1 -1
- package/src/lib/model/pos-reader-splash.js +2 -2
- package/src/lib/model/pos-reader-splash.js.map +1 -1
- package/src/lib/model/product-write.d.ts +3 -0
- package/src/lib/model/subscription-view.d.ts +90 -0
- package/src/lib/model/subscription-view.js +176 -0
- package/src/lib/model/subscription-view.js.map +1 -0
- package/src/lib/server/billing-webhook.d.ts +27 -6
- package/src/lib/server/billing-webhook.js +271 -81
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/cancel-order.js +4 -3
- package/src/lib/server/cancel-order.js.map +1 -1
- package/src/lib/server/cart-checkout.js +105 -23
- package/src/lib/server/cart-checkout.js.map +1 -1
- package/src/lib/server/cart.js +15 -3
- package/src/lib/server/cart.js.map +1 -1
- package/src/lib/server/catalog.js +58 -22
- package/src/lib/server/catalog.js.map +1 -1
- package/src/lib/server/checkout-session-expiry.d.ts +1 -1
- package/src/lib/server/checkout-session-expiry.js +19 -5
- package/src/lib/server/checkout-session-expiry.js.map +1 -1
- package/src/lib/server/checkout-status.js +4 -3
- package/src/lib/server/checkout-status.js.map +1 -1
- package/src/lib/server/checkout.js +98 -26
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/connect.js +42 -11
- package/src/lib/server/connect.js.map +1 -1
- package/src/lib/server/draft-order.js +36 -7
- package/src/lib/server/draft-order.js.map +1 -1
- package/src/lib/server/manual-tax-rate.d.ts +11 -3
- package/src/lib/server/manual-tax-rate.js +10 -6
- package/src/lib/server/manual-tax-rate.js.map +1 -1
- package/src/lib/server/membership-account.d.ts +22 -0
- package/src/lib/server/membership-account.js +52 -8
- package/src/lib/server/membership-account.js.map +1 -1
- package/src/lib/server/native-checkout.d.ts +10 -3
- package/src/lib/server/native-checkout.js +8 -3
- package/src/lib/server/native-checkout.js.map +1 -1
- package/src/lib/server/payment-method-domains.d.ts +50 -9
- package/src/lib/server/payment-method-domains.js +150 -51
- package/src/lib/server/payment-method-domains.js.map +1 -1
- package/src/lib/server/payment-methods.js +3 -2
- package/src/lib/server/payment-methods.js.map +1 -1
- package/src/lib/server/pos-auth.d.ts +3 -3
- package/src/lib/server/pos-auth.js +3 -3
- package/src/lib/server/pos-auth.js.map +1 -1
- package/src/lib/server/pos-cellular-billing.js +1 -1
- package/src/lib/server/pos-cellular-billing.js.map +1 -1
- package/src/lib/server/pos-cellular-notify.js +1 -1
- package/src/lib/server/pos-cellular-notify.js.map +1 -1
- package/src/lib/server/pos-cellular.js +1 -1
- package/src/lib/server/pos-cellular.js.map +1 -1
- package/src/lib/server/pos-hardware-admin.js +86 -13
- package/src/lib/server/pos-hardware-admin.js.map +1 -1
- package/src/lib/server/pos-hardware-attach.js +5 -5
- package/src/lib/server/pos-hardware-attach.js.map +1 -1
- package/src/lib/server/pos-hardware-cancel.js +65 -0
- package/src/lib/server/pos-hardware-cancel.js.map +1 -1
- package/src/lib/server/pos-hardware-closure-notices.js +2 -5
- package/src/lib/server/pos-hardware-closure-notices.js.map +1 -1
- package/src/lib/server/pos-hardware-closure.js +5 -8
- package/src/lib/server/pos-hardware-closure.js.map +1 -1
- package/src/lib/server/pos-hardware-in-person.d.ts +2 -1
- package/src/lib/server/pos-hardware-in-person.js +72 -17
- package/src/lib/server/pos-hardware-in-person.js.map +1 -1
- package/src/lib/server/pos-hardware-notify.d.ts +2 -0
- package/src/lib/server/pos-hardware-notify.js +30 -5
- package/src/lib/server/pos-hardware-notify.js.map +1 -1
- package/src/lib/server/pos-hardware-readers.d.ts +25 -0
- package/src/lib/server/pos-hardware-readers.js +206 -85
- package/src/lib/server/pos-hardware-readers.js.map +1 -1
- package/src/lib/server/pos-hardware-returns.d.ts +8 -3
- package/src/lib/server/pos-hardware-returns.js +39 -7
- package/src/lib/server/pos-hardware-returns.js.map +1 -1
- package/src/lib/server/pos-hardware-sale-fields.d.ts +76 -0
- package/src/lib/server/pos-hardware-sale-fields.js +114 -1
- package/src/lib/server/pos-hardware-sale-fields.js.map +1 -1
- package/src/lib/server/pos-hardware-sale.d.ts +2 -0
- package/src/lib/server/pos-hardware-sale.js +1 -0
- package/src/lib/server/pos-hardware-sale.js.map +1 -1
- package/src/lib/server/pos-hardware-tax-return-source.js +7 -4
- package/src/lib/server/pos-hardware-tax-return-source.js.map +1 -1
- package/src/lib/server/pos-hardware-webhook.js +16 -3
- package/src/lib/server/pos-hardware-webhook.js.map +1 -1
- package/src/lib/server/pos-hardware.d.ts +14 -3
- package/src/lib/server/pos-hardware.js +83 -18
- package/src/lib/server/pos-hardware.js.map +1 -1
- package/src/lib/server/pos-ops-routes.js +2 -10
- package/src/lib/server/pos-ops-routes.js.map +1 -1
- package/src/lib/server/pos-order.js +5 -1
- package/src/lib/server/pos-order.js.map +1 -1
- package/src/lib/server/pos-stripe.d.ts +7 -7
- package/src/lib/server/pos-stripe.js +15 -13
- package/src/lib/server/pos-stripe.js.map +1 -1
- package/src/lib/server/pos-terminal.js +11 -3
- package/src/lib/server/pos-terminal.js.map +1 -1
- package/src/lib/server/quote-pay.d.ts +23 -1
- package/src/lib/server/quote-pay.js +111 -27
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/quote.d.ts +2 -1
- package/src/lib/server/quote.js +12 -11
- package/src/lib/server/quote.js.map +1 -1
- package/src/lib/server/refund.js +13 -6
- package/src/lib/server/refund.js.map +1 -1
- package/src/lib/server/related.js +10 -3
- package/src/lib/server/related.js.map +1 -1
- package/src/lib/server/reserve.js +19 -6
- package/src/lib/server/reserve.js.map +1 -1
- package/src/lib/server/revenue-source.d.ts +6 -0
- package/src/lib/server/revenue-source.js +25 -9
- package/src/lib/server/revenue-source.js.map +1 -1
- package/src/lib/server/seller-stripe-account.d.ts +45 -0
- package/src/lib/server/seller-stripe-account.js +99 -0
- package/src/lib/server/seller-stripe-account.js.map +1 -0
- package/src/lib/server/storefront-tax-record.js +6 -1
- package/src/lib/server/storefront-tax-record.js.map +1 -1
- package/src/lib/server/storefront-tax.d.ts +33 -2
- package/src/lib/server/storefront-tax.js +39 -3
- package/src/lib/server/storefront-tax.js.map +1 -1
- package/src/lib/server/stream.d.ts +2 -0
- package/src/lib/server/stream.js +22 -2
- package/src/lib/server/stream.js.map +1 -1
- package/src/lib/server/stripe-refund.d.ts +15 -0
- package/src/lib/server/stripe-refund.js +54 -26
- package/src/lib/server/stripe-refund.js.map +1 -1
- package/src/lib/server/subscription-portal.js +8 -3
- package/src/lib/server/subscription-portal.js.map +1 -1
- package/src/lib/server/tax-return-source.js +5 -1
- package/src/lib/server/tax-return-source.js.map +1 -1
- package/src/lib/server.js +2 -2
- package/src/lib/server.js.map +1 -1
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
1
2
|
/**
|
|
2
3
|
* @license
|
|
3
4
|
* Copyright 2026 Aglyn LLC
|
|
@@ -13,7 +14,8 @@
|
|
|
13
14
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
15
|
* See the License for the specific language governing permissions and
|
|
15
16
|
* limitations under the License.
|
|
16
|
-
*/ import { isPosHardwareSkuId, parsePosHardwareInPersonConfig } from "../model/pos-hardware.js";
|
|
17
|
+
*/ import { isPosHardwareSkuId, parsePosHardwareInPersonConfig, POS_HARDWARE_MAX_PER_LINE, POS_HARDWARE_MAX_UNITS } from "../model/pos-hardware.js";
|
|
18
|
+
import { POS_HARDWARE_TERMS_REQUIRED, posHardwareTermsConfirmed, posHardwareTermsFromMetadata } from "../model/pos-hardware-terms.js";
|
|
17
19
|
/*==========================================
|
|
18
20
|
* THE MARK A REGISTER SALE OF HARDWARE CARRIES (AGL-4038).
|
|
19
21
|
*
|
|
@@ -40,5 +42,116 @@
|
|
|
40
42
|
hardwareSalePending: true
|
|
41
43
|
} : {};
|
|
42
44
|
}
|
|
45
|
+
/**
|
|
46
|
+
* Reads a checkout's lines for hardware on the platform's own store. Answers
|
|
47
|
+
* `hardware: false` for every other store, from the environment alone.
|
|
48
|
+
*/ export function sellerStoreHardwareCheckout(input, env = process.env) {
|
|
49
|
+
const config = parsePosHardwareInPersonConfig(env);
|
|
50
|
+
const none = {
|
|
51
|
+
hardware: false,
|
|
52
|
+
skus: input.lines.map(()=>null),
|
|
53
|
+
refusal: null
|
|
54
|
+
};
|
|
55
|
+
if (!config || config.sellerHostId !== input.hostId || config.sellerOrgId !== input.orgId) return none;
|
|
56
|
+
const skus = input.lines.map((line)=>{
|
|
57
|
+
var _input_products_get;
|
|
58
|
+
const sku = (_input_products_get = input.products.get(line.productId)) == null ? void 0 : _input_products_get.hardwareSku;
|
|
59
|
+
return isPosHardwareSkuId(sku) ? sku : null;
|
|
60
|
+
});
|
|
61
|
+
if (!skus.some(Boolean)) return none;
|
|
62
|
+
if (input.subscription) {
|
|
63
|
+
return {
|
|
64
|
+
hardware: true,
|
|
65
|
+
skus,
|
|
66
|
+
refusal: {
|
|
67
|
+
status: 400,
|
|
68
|
+
error: 'Card reader hardware is bought once, not by subscription.'
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
const perItem = new Map();
|
|
73
|
+
input.lines.forEach((line, index)=>{
|
|
74
|
+
var _perItem_get;
|
|
75
|
+
const sku = skus[index];
|
|
76
|
+
if (sku) perItem.set(sku, ((_perItem_get = perItem.get(sku)) != null ? _perItem_get : 0) + Math.max(0, Math.round(Number(line.quantity) || 0)));
|
|
77
|
+
});
|
|
78
|
+
const units = [
|
|
79
|
+
...perItem.values()
|
|
80
|
+
].reduce((sum, quantity)=>sum + quantity, 0);
|
|
81
|
+
if ([
|
|
82
|
+
...perItem.values()
|
|
83
|
+
].some((quantity)=>quantity > POS_HARDWARE_MAX_PER_LINE) || units > POS_HARDWARE_MAX_UNITS) {
|
|
84
|
+
return {
|
|
85
|
+
hardware: true,
|
|
86
|
+
skus,
|
|
87
|
+
refusal: {
|
|
88
|
+
status: 400,
|
|
89
|
+
error: `One order holds at most ${POS_HARDWARE_MAX_PER_LINE} of each card reader or accessory, and ${POS_HARDWARE_MAX_UNITS} in all.`
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
if (!posHardwareTermsConfirmed(input.hardwareTerms)) {
|
|
94
|
+
return {
|
|
95
|
+
hardware: true,
|
|
96
|
+
skus,
|
|
97
|
+
refusal: {
|
|
98
|
+
status: 400,
|
|
99
|
+
error: POS_HARDWARE_TERMS_REQUIRED,
|
|
100
|
+
needsHardwareTerms: true
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
hardware: true,
|
|
106
|
+
skus,
|
|
107
|
+
refusal: null
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* The hardware fields a paid online order on the seller store is written
|
|
112
|
+
* with: the mark, and the terms of sale the buyer ticked at checkout, dated
|
|
113
|
+
* when the session was made. Nothing for any other order.
|
|
114
|
+
*/ export function storefrontHardwareSaleFields(input, env = process.env) {
|
|
115
|
+
const mark = posHardwareSaleFields(input, env);
|
|
116
|
+
if (!mark.hardwareSalePending) return {};
|
|
117
|
+
const createdMs = Number(input.createdSeconds) > 0 ? Number(input.createdSeconds) * 1000 : Date.now();
|
|
118
|
+
const acceptance = posHardwareTermsFromMetadata(input.metadata, createdMs);
|
|
119
|
+
return _extends({}, mark, acceptance ? {
|
|
120
|
+
hardwareTermsAcceptance: acceptance
|
|
121
|
+
} : {});
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* {@link storefrontHardwareSaleFields} for the webhook that writes a paid
|
|
125
|
+
* online order: the store's workspace is asked for (`orgIdOf`) only when
|
|
126
|
+
* the store is the configured seller, so every other store's order costs
|
|
127
|
+
* nothing more. Never throws: an unreadable workspace leaves the order
|
|
128
|
+
* unmarked, as any other store's.
|
|
129
|
+
*/ export async function sellerStoreOrderHardwareFields(input, env = process.env) {
|
|
130
|
+
var _parsePosHardwareInPersonConfig;
|
|
131
|
+
if (((_parsePosHardwareInPersonConfig = parsePosHardwareInPersonConfig(env)) == null ? void 0 : _parsePosHardwareInPersonConfig.sellerHostId) !== input.hostId) return {};
|
|
132
|
+
const orgId = await input.orgIdOf().catch(()=>null);
|
|
133
|
+
return storefrontHardwareSaleFields({
|
|
134
|
+
hostId: input.hostId,
|
|
135
|
+
orgId,
|
|
136
|
+
lineItems: input.lineItems,
|
|
137
|
+
products: input.products,
|
|
138
|
+
metadata: input.metadata,
|
|
139
|
+
createdSeconds: input.createdSeconds
|
|
140
|
+
}, env);
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Records the hardware order of a paid sale on the platform's own store —
|
|
144
|
+
* a register sale or an online order — once, through the one recorder. Every
|
|
145
|
+
* other store's sale is answered from the environment alone, without loading
|
|
146
|
+
* it. Never throws: a sale this misses stays marked, and the sweep records it.
|
|
147
|
+
*/ export async function recordSellerStoreSaleHardware(event, env = process.env) {
|
|
148
|
+
var _parsePosHardwareInPersonConfig;
|
|
149
|
+
if (((_parsePosHardwareInPersonConfig = parsePosHardwareInPersonConfig(env)) == null ? void 0 : _parsePosHardwareInPersonConfig.sellerHostId) !== event.hostId) return;
|
|
150
|
+
try {
|
|
151
|
+
await (await import("./pos-hardware-in-person.js")).recordCompletedSaleHardware(event);
|
|
152
|
+
} catch (error) {
|
|
153
|
+
console.error('[pos-hardware-in-person] recorder not loaded', event.orderId, error);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
43
156
|
|
|
44
157
|
//# sourceMappingURL=pos-hardware-sale-fields.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-sale-fields.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 { isPosHardwareSkuId, parsePosHardwareInPersonConfig } from '../model/pos-hardware'\n\n/*==========================================\n * THE MARK A REGISTER SALE OF HARDWARE CARRIES (AGL-4038).\n *\n * Every path that writes a register sale — an open sale, a payment link, a\n * cash or room sale, the kiosk's cart, an offline sale synced later — spreads\n * these fields into the order it writes. On the platform's own store, a sale\n * with a line whose product is a hardware item says `hardwareSalePending`\n * from the moment it exists, and the hardware order is recorded when it is\n * paid. The completion listener clears the mark; one it missed is found by\n * the mark and recorded on the next sweep, so a sale is never lost because a\n * listener failed after the money was taken.\n *\n * Read on every sale of every store, so it costs nothing anywhere but the\n * seller: the environment is read first, and the products are the ones the\n * sale already loaded.\n *=========================================*/\n\nexport function posHardwareSaleFields(\n input: {\n hostId: string\n orgId: string | null | undefined\n lineItems: ReadonlyArray<{ productId: string }>\n products: ReadonlyMap<string, { hardwareSku?: unknown } | null | undefined>\n },\n env: Record<string, string | undefined> = process.env,\n): { hardwareSalePending?: true } {\n const config = parsePosHardwareInPersonConfig(env)\n if (!config || config.sellerHostId !== input.hostId || config.sellerOrgId !== input.orgId) return {}\n const sellsHardware = input.lineItems.some((line) =>\n isPosHardwareSkuId(input.products.get(line.productId)?.hardwareSku),\n )\n return sellsHardware ? { hardwareSalePending: true } : {}\n}\n"],"names":["isPosHardwareSkuId","parsePosHardwareInPersonConfig","posHardwareSaleFields","input","env","process","config","sellerHostId","hostId","sellerOrgId","orgId","sellsHardware","lineItems","some","line","products","get","productId","hardwareSku","hardwareSalePending"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,EAAEC,8BAA8B,QAAQ,2BAAuB;AAE1F;;;;;;;;;;;;;;;2CAe2C,GAE3C,OAAO,SAASC,sBACdC,KAKC,EACDC,MAA0CC,QAAQD,GAAG;IAErD,MAAME,SAASL,+BAA+BG;IAC9C,IAAI,CAACE,UAAUA,OAAOC,YAAY,KAAKJ,MAAMK,MAAM,IAAIF,OAAOG,WAAW,KAAKN,MAAMO,KAAK,EAAE,OAAO,CAAC;IACnG,MAAMC,gBAAgBR,MAAMS,SAAS,CAACC,IAAI,CAAC,CAACC;YACvBX;eAAnBH,oBAAmBG,sBAAAA,MAAMY,QAAQ,CAACC,GAAG,CAACF,KAAKG,SAAS,sBAAjCd,oBAAoCe,WAAW;;IAEpE,OAAOP,gBAAgB;QAAEQ,qBAAqB;IAAK,IAAI,CAAC;AAC1D"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-sale-fields.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n isPosHardwareSkuId,\n parsePosHardwareInPersonConfig,\n POS_HARDWARE_MAX_PER_LINE,\n POS_HARDWARE_MAX_UNITS,\n type PosHardwareSkuId,\n} from '../model/pos-hardware'\nimport {\n POS_HARDWARE_TERMS_REQUIRED,\n posHardwareTermsConfirmed,\n posHardwareTermsFromMetadata,\n type PosHardwareTermsAcceptance,\n} from '../model/pos-hardware-terms'\n\n/*==========================================\n * THE MARK A REGISTER SALE OF HARDWARE CARRIES (AGL-4038).\n *\n * Every path that writes a register sale — an open sale, a payment link, a\n * cash or room sale, the kiosk's cart, an offline sale synced later — spreads\n * these fields into the order it writes. On the platform's own store, a sale\n * with a line whose product is a hardware item says `hardwareSalePending`\n * from the moment it exists, and the hardware order is recorded when it is\n * paid. The completion listener clears the mark; one it missed is found by\n * the mark and recorded on the next sweep, so a sale is never lost because a\n * listener failed after the money was taken.\n *\n * Read on every sale of every store, so it costs nothing anywhere but the\n * seller: the environment is read first, and the products are the ones the\n * sale already loaded.\n *=========================================*/\n\nexport function posHardwareSaleFields(\n input: {\n hostId: string\n orgId: string | null | undefined\n lineItems: ReadonlyArray<{ productId: string }>\n products: ReadonlyMap<string, { hardwareSku?: unknown } | null | undefined>\n },\n env: Record<string, string | undefined> = process.env,\n): { hardwareSalePending?: true } {\n const config = parsePosHardwareInPersonConfig(env)\n if (!config || config.sellerHostId !== input.hostId || config.sellerOrgId !== input.orgId) return {}\n const sellsHardware = input.lineItems.some((line) =>\n isPosHardwareSkuId(input.products.get(line.productId)?.hardwareSku),\n )\n return sellsHardware ? { hardwareSalePending: true } : {}\n}\n\n/*==========================================\n * THE PLATFORM'S OWN ONLINE STORE SELLS HARDWARE TOO (AGL-4038).\n *\n * A product on the seller store that names a hardware item sells online\n * through the store's ordinary product page, cart and checkout, and the order\n * becomes a hardware order exactly as a register sale does: marked when it is\n * written ({@link posHardwareSaleFields}, `hardwareSalePending`), recorded\n * by the same recorder the register's completion listener runs\n * ({@link recordSellerStoreSaleHardware}), and found again by the same sweep.\n *\n * At checkout, before anything is held or charged\n * ({@link sellerStoreHardwareCheckout}):\n * - each hardware line carries the tangible goods tax code;\n * - the buyer must have ticked the terms of sale and business use, or the\n * checkout is refused with one plain sentence and `needsHardwareTerms`;\n * - the online order limits of the terms of sale hold: at most\n * {@link POS_HARDWARE_MAX_PER_LINE} of an item and\n * {@link POS_HARDWARE_MAX_UNITS} items of hardware in one order.\n * Every other store, and every other line, is untouched.\n *=========================================*/\n\n/** What a checkout on any store is told about the hardware in it. */\nexport interface SellerStoreHardwareCheckout {\n /** Whether any line is hardware on the platform's own store. */\n hardware: boolean\n /** The hardware item of each line, by its index in the lines given; null for any other line. */\n skus: Array<PosHardwareSkuId | null>\n /** Why the checkout is refused, before anything is held or charged; null when it is not. */\n refusal: { status: number; error: string; needsHardwareTerms?: true } | null\n}\n\n/**\n * Reads a checkout's lines for hardware on the platform's own store. Answers\n * `hardware: false` for every other store, from the environment alone.\n */\nexport function sellerStoreHardwareCheckout(\n input: {\n hostId: string\n orgId: string | null | undefined\n lines: ReadonlyArray<{ productId: string; quantity: number }>\n products: ReadonlyMap<string, { hardwareSku?: unknown } | null | undefined>\n /** The request's `hardwareTerms`: both boxes ticked, or not. */\n hardwareTerms: unknown\n /** A recurring checkout: hardware is bought once. */\n subscription?: boolean\n },\n env: Record<string, string | undefined> = process.env,\n): SellerStoreHardwareCheckout {\n const config = parsePosHardwareInPersonConfig(env)\n const none: SellerStoreHardwareCheckout = { hardware: false, skus: input.lines.map(() => null), refusal: null }\n if (!config || config.sellerHostId !== input.hostId || config.sellerOrgId !== input.orgId) return none\n const skus = input.lines.map((line) => {\n const sku = input.products.get(line.productId)?.hardwareSku\n return isPosHardwareSkuId(sku) ? sku : null\n })\n if (!skus.some(Boolean)) return none\n if (input.subscription) {\n return { hardware: true, skus, refusal: { status: 400, error: 'Card reader hardware is bought once, not by subscription.' } }\n }\n const perItem = new Map<string, number>()\n input.lines.forEach((line, index) => {\n const sku = skus[index]\n if (sku) perItem.set(sku, (perItem.get(sku) ?? 0) + Math.max(0, Math.round(Number(line.quantity) || 0)))\n })\n const units = [...perItem.values()].reduce((sum, quantity) => sum + quantity, 0)\n if ([...perItem.values()].some((quantity) => quantity > POS_HARDWARE_MAX_PER_LINE) || units > POS_HARDWARE_MAX_UNITS) {\n return {\n hardware: true,\n skus,\n refusal: {\n status: 400,\n error: `One order holds at most ${POS_HARDWARE_MAX_PER_LINE} of each card reader or accessory, and ${POS_HARDWARE_MAX_UNITS} in all.`,\n },\n }\n }\n if (!posHardwareTermsConfirmed(input.hardwareTerms)) {\n return { hardware: true, skus, refusal: { status: 400, error: POS_HARDWARE_TERMS_REQUIRED, needsHardwareTerms: true } }\n }\n return { hardware: true, skus, refusal: null }\n}\n\n/**\n * The hardware fields a paid online order on the seller store is written\n * with: the mark, and the terms of sale the buyer ticked at checkout, dated\n * when the session was made. Nothing for any other order.\n */\nexport function storefrontHardwareSaleFields(\n input: {\n hostId: string\n orgId: string | null | undefined\n lineItems: ReadonlyArray<{ productId: string }>\n products: ReadonlyMap<string, { hardwareSku?: unknown } | null | undefined>\n /** The paid Checkout Session's metadata and creation time (Stripe's seconds). */\n metadata: unknown\n createdSeconds: unknown\n },\n env: Record<string, string | undefined> = process.env,\n): { hardwareSalePending?: true; hardwareTermsAcceptance?: PosHardwareTermsAcceptance } {\n const mark = posHardwareSaleFields(input, env)\n if (!mark.hardwareSalePending) return {}\n const createdMs = Number(input.createdSeconds) > 0 ? Number(input.createdSeconds) * 1000 : Date.now()\n const acceptance = posHardwareTermsFromMetadata(input.metadata, createdMs)\n return { ...mark, ...(acceptance ? { hardwareTermsAcceptance: acceptance } : {}) }\n}\n\n/**\n * {@link storefrontHardwareSaleFields} for the webhook that writes a paid\n * online order: the store's workspace is asked for (`orgIdOf`) only when\n * the store is the configured seller, so every other store's order costs\n * nothing more. Never throws: an unreadable workspace leaves the order\n * unmarked, as any other store's.\n */\nexport async function sellerStoreOrderHardwareFields(\n input: Omit<Parameters<typeof storefrontHardwareSaleFields>[0], 'orgId'> & {\n orgIdOf: () => Promise<string | null | undefined>\n },\n env: Record<string, string | undefined> = process.env,\n): Promise<ReturnType<typeof storefrontHardwareSaleFields>> {\n if (parsePosHardwareInPersonConfig(env)?.sellerHostId !== input.hostId) return {}\n const orgId = await input.orgIdOf().catch(() => null)\n return storefrontHardwareSaleFields(\n {\n hostId: input.hostId,\n orgId,\n lineItems: input.lineItems,\n products: input.products,\n metadata: input.metadata,\n createdSeconds: input.createdSeconds,\n },\n env,\n )\n}\n\n/**\n * Records the hardware order of a paid sale on the platform's own store —\n * a register sale or an online order — once, through the one recorder. Every\n * other store's sale is answered from the environment alone, without loading\n * it. Never throws: a sale this misses stays marked, and the sweep records it.\n */\nexport async function recordSellerStoreSaleHardware(\n event: { hostId: string; orderId: string; offline?: boolean },\n env: Record<string, string | undefined> = process.env,\n): Promise<void> {\n if (parsePosHardwareInPersonConfig(env)?.sellerHostId !== event.hostId) return\n try {\n await (await import('./pos-hardware-in-person')).recordCompletedSaleHardware(event)\n } catch (error) {\n console.error('[pos-hardware-in-person] recorder not loaded', event.orderId, error)\n }\n}\n"],"names":["isPosHardwareSkuId","parsePosHardwareInPersonConfig","POS_HARDWARE_MAX_PER_LINE","POS_HARDWARE_MAX_UNITS","POS_HARDWARE_TERMS_REQUIRED","posHardwareTermsConfirmed","posHardwareTermsFromMetadata","posHardwareSaleFields","input","env","process","config","sellerHostId","hostId","sellerOrgId","orgId","sellsHardware","lineItems","some","line","products","get","productId","hardwareSku","hardwareSalePending","sellerStoreHardwareCheckout","none","hardware","skus","lines","map","refusal","sku","Boolean","subscription","status","error","perItem","Map","forEach","index","set","Math","max","round","Number","quantity","units","values","reduce","sum","hardwareTerms","needsHardwareTerms","storefrontHardwareSaleFields","mark","createdMs","createdSeconds","Date","now","acceptance","metadata","hardwareTermsAcceptance","sellerStoreOrderHardwareFields","orgIdOf","catch","recordSellerStoreSaleHardware","event","recordCompletedSaleHardware","console","orderId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,kBAAkB,EAClBC,8BAA8B,EAC9BC,yBAAyB,EAC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,KAAKC,GAAG;IACnG,MAAMC,aAAarD,6BAA6BE,MAAMoD,QAAQ,EAAEL;IAChE,OAAO,aAAKD,MAAUK,aAAa;QAAEE,yBAAyBF;IAAW,IAAI,CAAC;AAChF;AAEA;;;;;;CAMC,GACD,OAAO,eAAeG,+BACpBtD,KAEC,EACDC,MAA0CC,QAAQD,GAAG;QAEjDR;IAAJ,IAAIA,EAAAA,kCAAAA,+BAA+BQ,yBAA/BR,gCAAqCW,YAAY,MAAKJ,MAAMK,MAAM,EAAE,OAAO,CAAC;IAChF,MAAME,QAAQ,MAAMP,MAAMuD,OAAO,GAAGC,KAAK,CAAC,IAAM;IAChD,OAAOX,6BACL;QACExC,QAAQL,MAAMK,MAAM;QACpBE;QACAE,WAAWT,MAAMS,SAAS;QAC1BG,UAAUZ,MAAMY,QAAQ;QACxBwC,UAAUpD,MAAMoD,QAAQ;QACxBJ,gBAAgBhD,MAAMgD,cAAc;IACtC,GACA/C;AAEJ;AAEA;;;;;CAKC,GACD,OAAO,eAAewD,8BACpBC,KAA6D,EAC7DzD,MAA0CC,QAAQD,GAAG;QAEjDR;IAAJ,IAAIA,EAAAA,kCAAAA,+BAA+BQ,yBAA/BR,gCAAqCW,YAAY,MAAKsD,MAAMrD,MAAM,EAAE;IACxE,IAAI;QACF,MAAM,AAAC,CAAA,MAAM,MAAM,CAAC,8BAA0B,EAAGsD,2BAA2B,CAACD;IAC/E,EAAE,OAAO9B,OAAO;QACdgC,QAAQhC,KAAK,CAAC,gDAAgD8B,MAAMG,OAAO,EAAEjC;IAC/E;AACF"}
|
|
@@ -30,6 +30,8 @@ export declare function toAttachView(id: string, order: PosHardwareOrder): {
|
|
|
30
30
|
registerOrderId: string;
|
|
31
31
|
registerNumber: number;
|
|
32
32
|
kiosk: boolean;
|
|
33
|
+
/** Bought from the store's own product pages or cart (AGL-4038), not at the register. */
|
|
34
|
+
online: boolean;
|
|
33
35
|
offline: boolean;
|
|
34
36
|
lines: {
|
|
35
37
|
sku: import("../model/pos-hardware").PosHardwareSkuId;
|
|
@@ -328,6 +328,7 @@ const LOOKUP_WINDOW_MS = 10 * 60 * 1000;
|
|
|
328
328
|
registerOrderId: (_ref = (_order_posSale = order.posSale) == null ? void 0 : _order_posSale.orderId) != null ? _ref : null,
|
|
329
329
|
registerNumber: (_ref1 = (_order_posSale1 = order.posSale) == null ? void 0 : _order_posSale1.number) != null ? _ref1 : null,
|
|
330
330
|
kiosk: ((_order_posSale2 = order.posSale) == null ? void 0 : _order_posSale2.kiosk) === true,
|
|
331
|
+
/** Bought from the store's own product pages or cart (AGL-4038), not at the register. */ online: order.source === 'storefront',
|
|
331
332
|
offline: ((_order_posSale3 = order.posSale) == null ? void 0 : _order_posSale3.offline) === true,
|
|
332
333
|
lines: ((_order_lines = order.lines) != null ? _order_lines : []).map((line)=>({
|
|
333
334
|
sku: line.sku,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-sale.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { consumeRateLimit, firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { addAdminAudit } from '@aglyn/tenant-data-admin/server/admin-audit-write'\nimport { maskEmailAddress } from '@aglyn/tenant-data-admin/server/admin-audit'\nimport { POS_HARDWARE_SKUS, type PosHardwareOrder } from '../model/pos-hardware'\nimport type { PosPermission } from '../model/plugin-permissions'\nimport { authorizePosStaff, posIdempotencyKey, posRequestBody, type PosStaff } from './pos-auth'\nimport { isPosHardwareSellerStore, posHardwareInPersonConfig, posHardwareOrderNumber } from './pos-hardware'\n\n/** How many lookups one register user makes in ten minutes. */\nexport const BUYER_LOOKUPS_PER_WINDOW = 30\nconst LOOKUP_WINDOW_MS = 10 * 60 * 1000\n\n/*==========================================\n * `POST /api/commerce/pos-hardware-sale` (AGL-4038): selling a card reader in\n * person, at the platform's own store's register, to someone who is not a\n * member of it.\n *\n * status whether this store is the platform's hardware seller, and the\n * hardware items a product of it may be — the product editor's\n * \"Point of sale hardware\" choice is shown only where it is.\n * pending the \"To attach\" list: sales of hardware nobody has said whose\n * they are yet (a kiosk or offline sale, a buyer with no account\n * or no workspace yet), newest first. Records any paid sale still\n * waiting to be recorded first (`sweepInPersonPosHardwareSales`).\n * find look the buyer up across the platform by exact email, a\n * person's name or a workspace's name (`pos-hardware-buyer-lookup.ts`):\n * the least that picks the right person, their address in full.\n * Rate-limited per register user and written to the platform's\n * audit log (the address masked there), every time.\n * attach say whose a sale is — by the register sale or the To attach\n * entry — as an account and workspace (and store), an account\n * with no workspace yet, or the address of someone with no\n * account, who is invited to sign up (`pos-hardware-attach.ts`).\n * Idempotency-Key required; audited.\n * detach put an attached sale back on the To attach list. Audited.\n * serials the serial numbers of the sale's readers, scanned or typed at\n * the sale, so the order sets itself up when the buyer registers\n * them (`pos-hardware-readers.ts`).\n * terms the terms of sale the buyer accepts before paying (Terms\n * 4.26–4.32 in short, with the link), and `terms-status` whether\n * they have, for the register waiting on its display.\n * accept-terms the buyer accepted on the register tablet handed to them;\n * `terms-on-display` notes who is putting them on the customer\n * display, before the register shows them there (`pos-hardware-terms.ts`).\n * register-at-booth register a reader to the buyer's chosen store by the\n * code it shows, while they are there, with the store's address\n * when it has no reader Location yet (`address`; refused with\n * `reason: 'needs-address'` without one). Idempotency-Key\n * required; audited.\n *\n * `status` is asked of whoever works the register; everything else needs\n * \"Sell at the register\" (`posSell`) on the seller store, since it is part\n * of ringing a sale there, and answers 404 on any other store.\n *\n * Gated like the register (`authorizePosStaff`, on a plan with POS). Every\n * answer is about THIS store: on any store but the configured seller it says\n * `seller: false` and nothing else, so no other workspace learns the\n * platform's configuration or is shown a control it cannot use.\n *=========================================*/\n\nexport const posHardwareSaleHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = posRequestBody(req)\n const hostId = String(body['hostId'] ?? '')\n const action = String(body['action'] ?? '')\n const permission: PosPermission | undefined = action === 'status' ? undefined : 'posSell'\n const gate = await authorizePosStaff(req, hostId, permission)\n if ('error' in gate) return res.status(gate.status).json({ error: gate.error })\n const staff = gate.staff\n const config = posHardwareInPersonConfig()\n const seller = isPosHardwareSellerStore(config, staff.hostId, staff.orgId)\n try {\n if (action === 'status') {\n if (!seller) return res.status(200).json({ seller: false })\n return res.status(200).json({\n seller: true,\n items: POS_HARDWARE_SKUS.map((sku) => ({ sku: sku.id, name: sku.displayName, kind: sku.kind })),\n })\n }\n if (!seller) return res.status(404).json({ error: 'Card reader sales are not available on this store.' })\n const inPerson = await import('./pos-hardware-in-person')\n switch (action) {\n case 'pending': {\n await inPerson.sweepInPersonPosHardwareSales(config)\n const pending = await inPerson.pendingInPersonPosHardwareOrders(config)\n return res.status(200).json({ orders: pending.map(({ id, order }) => toAttachView(id, order)) })\n }\n case 'find': {\n const query = String(body['query'] ?? '').trim().slice(0, 120)\n if (query.length < 2) return res.status(400).json({ error: 'Type at least two letters, or an email address.' })\n const rate = await consumeRateLimit(`pos-hardware-lookup:${staff.uid}`, {\n limit: BUYER_LOOKUPS_PER_WINDOW,\n windowMs: LOOKUP_WINDOW_MS,\n })\n if (!rate.allowed) return res.status(429).json({ error: 'Too many lookups. Try again in a few minutes.' })\n const found = await (await import('./pos-hardware-buyer-lookup')).findHardwareBuyers(query)\n await audit(staff, 'pos-hardware-buyer-lookup', {\n // The audit log keeps an address masked; a name as typed. The\n // register itself is answered in full.\n query: found.kind === 'email' ? maskEmailAddress(query) : query,\n kind: found.kind,\n matched: [\n ...found.people.map((person) => person.uid),\n ...found.workspaces.map((workspace) => `org:${workspace.orgId}`),\n ],\n })\n return res.status(200).json(found)\n }\n case 'terms':\n case 'terms-status':\n case 'terms-on-display':\n case 'accept-terms': {\n const terms = await import('./pos-hardware-terms')\n const registerOrderId = String(body['registerOrderId'] ?? '')\n try {\n if (action === 'terms') return res.status(200).json(terms.posHardwareTermsView())\n if (action === 'terms-status') {\n return res.status(200).json(await terms.posHardwareTermsStatus(config, registerOrderId))\n }\n if (action === 'terms-on-display') {\n await terms.requestPosHardwareTermsOnDisplay({ config, registerOrderId, uid: staff.uid })\n return res.status(200).json({ ok: true })\n }\n const device = terms.posHardwareTermsDevice(req.headers as Record<string, unknown>)\n const acceptance = await terms.recordPosHardwareTermsAcceptance({\n config,\n registerOrderId,\n method: 'tablet',\n staffUid: staff.uid,\n ...device,\n })\n await audit(staff, 'pos-hardware-terms-accepted', { method: acceptance.method, version: acceptance.version, registerOrderId }, null)\n return res.status(200).json({ ok: true, acceptance })\n } catch (error) {\n if (error instanceof terms.PosHardwareTermsRefusal) {\n return res.status(error.status).json({ error: error.message })\n }\n throw error\n }\n }\n case 'serials':\n case 'register-at-booth': {\n const readers = await import('./pos-hardware-readers')\n try {\n if (action === 'serials') {\n const saved = await readers.recordPosHardwareSerials({\n config,\n registerOrderId: typeof body['registerOrderId'] === 'string' ? body['registerOrderId'] : null,\n orderId: typeof body['orderId'] === 'string' ? body['orderId'] : null,\n serials: body['serials'],\n })\n return res.status(200).json({ ok: true, serials: saved.serials, recorded: saved.recorded })\n }\n if (!posIdempotencyKey(req)) return res.status(400).json({ error: 'Missing Idempotency-Key' })\n const registerOrderId = typeof body['registerOrderId'] === 'string' ? body['registerOrderId'] : ''\n const orderId = registerOrderId\n ? (await import('./pos-hardware')).posHardwareInPersonOrderId(config.sellerHostId, registerOrderId)\n : String(body['orderId'] ?? '')\n const { order, readerId, storeAddress } = await readers.registerPosHardwareAtBooth({\n config,\n orderId,\n registrationCode: body['registrationCode'],\n label: body['label'],\n address: body['address'],\n uid: staff.uid,\n })\n await audit(\n staff,\n 'pos-hardware-register-at-booth',\n {\n readerId,\n hostId: order.hostId,\n orgId: order.orgId,\n // That the buyer's store address was typed here, and where:\n // the store's reader Location was made from it. The street\n // stays with the store, never in the audit log.\n ...(storeAddress\n ? {\n storeAddressEntered: {\n city: storeAddress.city,\n state: storeAddress.state ?? null,\n country: storeAddress.country,\n },\n }\n : {}),\n },\n orderId,\n )\n return res.status(200).json({\n ok: true,\n readerId,\n storeAddressSaved: Boolean(storeAddress),\n order: toAttachView(orderId, order),\n })\n } catch (error) {\n if (error instanceof readers.PosHardwareReaderRefusal) {\n return res\n .status(error.status)\n .json({ error: error.message, ...(error.reason ? { reason: error.reason } : {}) })\n }\n throw error\n }\n }\n case 'attach':\n case 'detach': {\n if (!posIdempotencyKey(req)) return res.status(400).json({ error: 'Missing Idempotency-Key' })\n const attach = await import('./pos-hardware-attach')\n try {\n if (action === 'detach') {\n const orderId = String(body['orderId'] ?? '')\n const { order } = await attach.detachPosHardwareSale({ config, orderId })\n await audit(staff, 'pos-hardware-sale-detach', { orderId }, orderId)\n return res.status(200).json({ ok: true, order: toAttachView(orderId, order) })\n }\n const buyer = await attach.checkHardwareBuyer((body['buyer'] ?? {}) as Record<string, unknown>)\n const outcome = await attach.attachPosHardwareSale({\n config,\n buyer,\n attachedBy: staff.uid,\n registerOrderId: typeof body['registerOrderId'] === 'string' ? body['registerOrderId'] : null,\n orderId: typeof body['orderId'] === 'string' ? body['orderId'] : null,\n })\n const target = outcome.outcome === 'waiting' ? null : outcome.orderId\n await audit(\n staff,\n 'pos-hardware-sale-attach',\n {\n outcome: outcome.outcome,\n uid: buyer.uid,\n orgId: buyer.orgId,\n hostId: buyer.hostId,\n email: buyer.uid ? null : maskEmailAddress(buyer.email),\n ...(outcome.outcome === 'waiting' ? { registerOrderId: outcome.registerOrderId } : {}),\n },\n target,\n )\n return res.status(200).json(\n outcome.outcome === 'waiting'\n ? { outcome: 'waiting' }\n : { outcome: outcome.outcome, order: toAttachView(outcome.orderId, outcome.order) },\n )\n } catch (error) {\n if (error instanceof attach.PosHardwareAttachRefusal) {\n return res.status(error.status).json({ error: error.message })\n }\n throw error\n }\n }\n default:\n return res.status(400).json({ error: 'Unknown action' })\n }\n } catch (error) {\n console.error('[pos-hardware-sale]', action, error)\n return res.status(500).json({ error: 'The card reader sale could not answer' })\n }\n}\n\n/**\n * A sale on the To attach list, as the register shows it: what was sold and\n * when, the register order it came from, and what is known of the buyer —\n * the receipt address, or the address or account a register user gave.\n */\nexport function toAttachView(id: string, order: PosHardwareOrder) {\n return {\n id,\n number: posHardwareOrderNumber(id),\n registerOrderId: order.posSale?.orderId ?? null,\n registerNumber: order.posSale?.number ?? null,\n kiosk: order.posSale?.kiosk === true,\n offline: order.posSale?.offline === true,\n lines: (order.lines ?? []).map((line) => ({ sku: line.sku, name: line.name, quantity: line.quantity })),\n totalCents: order.totalCents ?? 0,\n createdAtMs: order.createdAtMs ?? 0,\n // The buyer's address in full, as the lookup shows it (AGL-4038): the\n // account's, a receipt's, or one typed for a buyer with no account.\n contactEmail: order.contactEmail ?? null,\n attached: order.attachment?.state === 'attached',\n /** Attached with the buyer's store chosen: a reader can be registered to it here. */\n storeChosen: order.attachment?.state === 'attached' && Boolean(order.hostId),\n /** Readers on the sale, and how many have a serial or are set up. */\n readers: (order.units ?? []).length,\n serialsTaken: (order.units ?? []).filter((unit) => unit.serialNumber).length,\n readersSetUp: (order.units ?? []).filter((unit) => unit.readerId).length,\n /** A buyer with an account and no workspace yet. */\n awaitingWorkspace: Boolean(order.attachment?.uid),\n /** A buyer with no account yet, invited to sign up. */\n invited: Boolean(order.attachment?.email && !order.attachment?.uid),\n }\n}\n\nexport type ToAttachView = ReturnType<typeof toAttachView>\n\n/**\n * One row of the platform's audit log for a lookup or an attachment: who on\n * the selling store did it, and what — never the buyer's full address.\n */\nasync function audit(\n staff: PosStaff,\n action: string,\n after: Record<string, unknown>,\n orderId: string | null = null,\n): Promise<void> {\n const firestore = firebaseAdmin.app().firestore()\n await addAdminAudit(firestore, {\n action,\n actorUid: staff.uid,\n actorEmail: null,\n scope: 'posHardwareSale',\n target: orderId ? `posHardwareSales/${orderId}` : `hosts/${staff.hostId}`,\n orgId: staff.orgId,\n before: null,\n after,\n at: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n })\n}\n"],"names":["consumeRateLimit","firebaseAdmin","addAdminAudit","maskEmailAddress","POS_HARDWARE_SKUS","authorizePosStaff","posIdempotencyKey","posRequestBody","isPosHardwareSellerStore","posHardwareInPersonConfig","posHardwareOrderNumber","BUYER_LOOKUPS_PER_WINDOW","LOOKUP_WINDOW_MS","posHardwareSaleHandler","req","res","body","method","status","json","error","hostId","String","action","permission","undefined","gate","staff","config","seller","orgId","items","map","sku","id","name","displayName","kind","inPerson","sweepInPersonPosHardwareSales","pending","pendingInPersonPosHardwareOrders","orders","order","toAttachView","query","trim","slice","length","rate","uid","limit","windowMs","allowed","found","findHardwareBuyers","audit","matched","people","person","workspaces","workspace","terms","registerOrderId","posHardwareTermsView","posHardwareTermsStatus","requestPosHardwareTermsOnDisplay","ok","device","posHardwareTermsDevice","headers","acceptance","recordPosHardwareTermsAcceptance","staffUid","version","PosHardwareTermsRefusal","message","readers","storeAddress","saved","recordPosHardwareSerials","orderId","serials","recorded","posHardwareInPersonOrderId","sellerHostId","readerId","registerPosHardwareAtBooth","registrationCode","label","address","storeAddressEntered","city","state","country","storeAddressSaved","Boolean","PosHardwareReaderRefusal","reason","attach","detachPosHardwareSale","buyer","checkHardwareBuyer","outcome","attachPosHardwareSale","attachedBy","target","email","PosHardwareAttachRefusal","console","number","posSale","registerNumber","kiosk","offline","lines","line","quantity","totalCents","createdAtMs","contactEmail","attached","attachment","storeChosen","units","serialsTaken","filter","unit","serialNumber","readersSetUp","awaitingWorkspace","invited","after","firestore","app","actorUid","actorEmail","scope","before","at","FieldValue","serverTimestamp"],"mappings":"AAAA;;;;;;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B,KAAe,EACfJ,MAAc,EACd6G,KAA8B,EAC9BnD,UAAyB,IAAI;IAE7B,MAAMoD,YAAYpI,cAAcqI,GAAG,GAAGD,SAAS;IAC/C,MAAMnI,cAAcmI,WAAW;QAC7B9G;QACAgH,UAAU5G,MAAMuB,GAAG;QACnBsF,YAAY;QACZC,OAAO;QACP/B,QAAQzB,UAAU,CAAC,iBAAiB,EAAEA,SAAS,GAAG,CAAC,MAAM,EAAEtD,MAAMN,MAAM,EAAE;QACzES,OAAOH,MAAMG,KAAK;QAClB4G,QAAQ;QACRN;QACAO,IAAI1I,cAAcoI,SAAS,CAACO,UAAU,CAACC,eAAe;IACxD;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-sale.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { consumeRateLimit, firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { addAdminAudit } from '@aglyn/tenant-data-admin/server/admin-audit-write'\nimport { maskEmailAddress } from '@aglyn/tenant-data-admin/server/admin-audit'\nimport { POS_HARDWARE_SKUS, type PosHardwareOrder } from '../model/pos-hardware'\nimport type { PosPermission } from '../model/plugin-permissions'\nimport { authorizePosStaff, posIdempotencyKey, posRequestBody, type PosStaff } from './pos-auth'\nimport { isPosHardwareSellerStore, posHardwareInPersonConfig, posHardwareOrderNumber } from './pos-hardware'\n\n/** How many lookups one register user makes in ten minutes. */\nexport const BUYER_LOOKUPS_PER_WINDOW = 30\nconst LOOKUP_WINDOW_MS = 10 * 60 * 1000\n\n/*==========================================\n * `POST /api/commerce/pos-hardware-sale` (AGL-4038): selling a card reader in\n * person, at the platform's own store's register, to someone who is not a\n * member of it.\n *\n * status whether this store is the platform's hardware seller, and the\n * hardware items a product of it may be — the product editor's\n * \"Point of sale hardware\" choice is shown only where it is.\n * pending the \"To attach\" list: sales of hardware nobody has said whose\n * they are yet (a kiosk or offline sale, a buyer with no account\n * or no workspace yet), newest first. Records any paid sale still\n * waiting to be recorded first (`sweepInPersonPosHardwareSales`).\n * find look the buyer up across the platform by exact email, a\n * person's name or a workspace's name (`pos-hardware-buyer-lookup.ts`):\n * the least that picks the right person, their address in full.\n * Rate-limited per register user and written to the platform's\n * audit log (the address masked there), every time.\n * attach say whose a sale is — by the register sale or the To attach\n * entry — as an account and workspace (and store), an account\n * with no workspace yet, or the address of someone with no\n * account, who is invited to sign up (`pos-hardware-attach.ts`).\n * Idempotency-Key required; audited.\n * detach put an attached sale back on the To attach list. Audited.\n * serials the serial numbers of the sale's readers, scanned or typed at\n * the sale, so the order sets itself up when the buyer registers\n * them (`pos-hardware-readers.ts`).\n * terms the terms of sale the buyer accepts before paying (Terms\n * 4.26–4.32 in short, with the link), and `terms-status` whether\n * they have, for the register waiting on its display.\n * accept-terms the buyer accepted on the register tablet handed to them;\n * `terms-on-display` notes who is putting them on the customer\n * display, before the register shows them there (`pos-hardware-terms.ts`).\n * register-at-booth register a reader to the buyer's chosen store by the\n * code it shows, while they are there, with the store's address\n * when it has no reader Location yet (`address`; refused with\n * `reason: 'needs-address'` without one). Idempotency-Key\n * required; audited.\n *\n * `status` is asked of whoever works the register; everything else needs\n * \"Sell at the register\" (`posSell`) on the seller store, since it is part\n * of ringing a sale there, and answers 404 on any other store.\n *\n * Gated like the register (`authorizePosStaff`, on a plan with POS). Every\n * answer is about THIS store: on any store but the configured seller it says\n * `seller: false` and nothing else, so no other workspace learns the\n * platform's configuration or is shown a control it cannot use.\n *=========================================*/\n\nexport const posHardwareSaleHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = posRequestBody(req)\n const hostId = String(body['hostId'] ?? '')\n const action = String(body['action'] ?? '')\n const permission: PosPermission | undefined = action === 'status' ? undefined : 'posSell'\n const gate = await authorizePosStaff(req, hostId, permission)\n if ('error' in gate) return res.status(gate.status).json({ error: gate.error })\n const staff = gate.staff\n const config = posHardwareInPersonConfig()\n const seller = isPosHardwareSellerStore(config, staff.hostId, staff.orgId)\n try {\n if (action === 'status') {\n if (!seller) return res.status(200).json({ seller: false })\n return res.status(200).json({\n seller: true,\n items: POS_HARDWARE_SKUS.map((sku) => ({ sku: sku.id, name: sku.displayName, kind: sku.kind })),\n })\n }\n if (!seller) return res.status(404).json({ error: 'Card reader sales are not available on this store.' })\n const inPerson = await import('./pos-hardware-in-person')\n switch (action) {\n case 'pending': {\n await inPerson.sweepInPersonPosHardwareSales(config)\n const pending = await inPerson.pendingInPersonPosHardwareOrders(config)\n return res.status(200).json({ orders: pending.map(({ id, order }) => toAttachView(id, order)) })\n }\n case 'find': {\n const query = String(body['query'] ?? '').trim().slice(0, 120)\n if (query.length < 2) return res.status(400).json({ error: 'Type at least two letters, or an email address.' })\n const rate = await consumeRateLimit(`pos-hardware-lookup:${staff.uid}`, {\n limit: BUYER_LOOKUPS_PER_WINDOW,\n windowMs: LOOKUP_WINDOW_MS,\n })\n if (!rate.allowed) return res.status(429).json({ error: 'Too many lookups. Try again in a few minutes.' })\n const found = await (await import('./pos-hardware-buyer-lookup')).findHardwareBuyers(query)\n await audit(staff, 'pos-hardware-buyer-lookup', {\n // The audit log keeps an address masked; a name as typed. The\n // register itself is answered in full.\n query: found.kind === 'email' ? maskEmailAddress(query) : query,\n kind: found.kind,\n matched: [\n ...found.people.map((person) => person.uid),\n ...found.workspaces.map((workspace) => `org:${workspace.orgId}`),\n ],\n })\n return res.status(200).json(found)\n }\n case 'terms':\n case 'terms-status':\n case 'terms-on-display':\n case 'accept-terms': {\n const terms = await import('./pos-hardware-terms')\n const registerOrderId = String(body['registerOrderId'] ?? '')\n try {\n if (action === 'terms') return res.status(200).json(terms.posHardwareTermsView())\n if (action === 'terms-status') {\n return res.status(200).json(await terms.posHardwareTermsStatus(config, registerOrderId))\n }\n if (action === 'terms-on-display') {\n await terms.requestPosHardwareTermsOnDisplay({ config, registerOrderId, uid: staff.uid })\n return res.status(200).json({ ok: true })\n }\n const device = terms.posHardwareTermsDevice(req.headers as Record<string, unknown>)\n const acceptance = await terms.recordPosHardwareTermsAcceptance({\n config,\n registerOrderId,\n method: 'tablet',\n staffUid: staff.uid,\n ...device,\n })\n await audit(staff, 'pos-hardware-terms-accepted', { method: acceptance.method, version: acceptance.version, registerOrderId }, null)\n return res.status(200).json({ ok: true, acceptance })\n } catch (error) {\n if (error instanceof terms.PosHardwareTermsRefusal) {\n return res.status(error.status).json({ error: error.message })\n }\n throw error\n }\n }\n case 'serials':\n case 'register-at-booth': {\n const readers = await import('./pos-hardware-readers')\n try {\n if (action === 'serials') {\n const saved = await readers.recordPosHardwareSerials({\n config,\n registerOrderId: typeof body['registerOrderId'] === 'string' ? body['registerOrderId'] : null,\n orderId: typeof body['orderId'] === 'string' ? body['orderId'] : null,\n serials: body['serials'],\n })\n return res.status(200).json({ ok: true, serials: saved.serials, recorded: saved.recorded })\n }\n if (!posIdempotencyKey(req)) return res.status(400).json({ error: 'Missing Idempotency-Key' })\n const registerOrderId = typeof body['registerOrderId'] === 'string' ? body['registerOrderId'] : ''\n const orderId = registerOrderId\n ? (await import('./pos-hardware')).posHardwareInPersonOrderId(config.sellerHostId, registerOrderId)\n : String(body['orderId'] ?? '')\n const { order, readerId, storeAddress } = await readers.registerPosHardwareAtBooth({\n config,\n orderId,\n registrationCode: body['registrationCode'],\n label: body['label'],\n address: body['address'],\n uid: staff.uid,\n })\n await audit(\n staff,\n 'pos-hardware-register-at-booth',\n {\n readerId,\n hostId: order.hostId,\n orgId: order.orgId,\n // That the buyer's store address was typed here, and where:\n // the store's reader Location was made from it. The street\n // stays with the store, never in the audit log.\n ...(storeAddress\n ? {\n storeAddressEntered: {\n city: storeAddress.city,\n state: storeAddress.state ?? null,\n country: storeAddress.country,\n },\n }\n : {}),\n },\n orderId,\n )\n return res.status(200).json({\n ok: true,\n readerId,\n storeAddressSaved: Boolean(storeAddress),\n order: toAttachView(orderId, order),\n })\n } catch (error) {\n if (error instanceof readers.PosHardwareReaderRefusal) {\n return res\n .status(error.status)\n .json({ error: error.message, ...(error.reason ? { reason: error.reason } : {}) })\n }\n throw error\n }\n }\n case 'attach':\n case 'detach': {\n if (!posIdempotencyKey(req)) return res.status(400).json({ error: 'Missing Idempotency-Key' })\n const attach = await import('./pos-hardware-attach')\n try {\n if (action === 'detach') {\n const orderId = String(body['orderId'] ?? '')\n const { order } = await attach.detachPosHardwareSale({ config, orderId })\n await audit(staff, 'pos-hardware-sale-detach', { orderId }, orderId)\n return res.status(200).json({ ok: true, order: toAttachView(orderId, order) })\n }\n const buyer = await attach.checkHardwareBuyer((body['buyer'] ?? {}) as Record<string, unknown>)\n const outcome = await attach.attachPosHardwareSale({\n config,\n buyer,\n attachedBy: staff.uid,\n registerOrderId: typeof body['registerOrderId'] === 'string' ? body['registerOrderId'] : null,\n orderId: typeof body['orderId'] === 'string' ? body['orderId'] : null,\n })\n const target = outcome.outcome === 'waiting' ? null : outcome.orderId\n await audit(\n staff,\n 'pos-hardware-sale-attach',\n {\n outcome: outcome.outcome,\n uid: buyer.uid,\n orgId: buyer.orgId,\n hostId: buyer.hostId,\n email: buyer.uid ? null : maskEmailAddress(buyer.email),\n ...(outcome.outcome === 'waiting' ? { registerOrderId: outcome.registerOrderId } : {}),\n },\n target,\n )\n return res.status(200).json(\n outcome.outcome === 'waiting'\n ? { outcome: 'waiting' }\n : { outcome: outcome.outcome, order: toAttachView(outcome.orderId, outcome.order) },\n )\n } catch (error) {\n if (error instanceof attach.PosHardwareAttachRefusal) {\n return res.status(error.status).json({ error: error.message })\n }\n throw error\n }\n }\n default:\n return res.status(400).json({ error: 'Unknown action' })\n }\n } catch (error) {\n console.error('[pos-hardware-sale]', action, error)\n return res.status(500).json({ error: 'The card reader sale could not answer' })\n }\n}\n\n/**\n * A sale on the To attach list, as the register shows it: what was sold and\n * when, the register order it came from, and what is known of the buyer —\n * the receipt address, or the address or account a register user gave.\n */\nexport function toAttachView(id: string, order: PosHardwareOrder) {\n return {\n id,\n number: posHardwareOrderNumber(id),\n registerOrderId: order.posSale?.orderId ?? null,\n registerNumber: order.posSale?.number ?? null,\n kiosk: order.posSale?.kiosk === true,\n /** Bought from the store's own product pages or cart (AGL-4038), not at the register. */\n online: order.source === 'storefront',\n offline: order.posSale?.offline === true,\n lines: (order.lines ?? []).map((line) => ({ sku: line.sku, name: line.name, quantity: line.quantity })),\n totalCents: order.totalCents ?? 0,\n createdAtMs: order.createdAtMs ?? 0,\n // The buyer's address in full, as the lookup shows it (AGL-4038): the\n // account's, a receipt's, or one typed for a buyer with no account.\n contactEmail: order.contactEmail ?? null,\n attached: order.attachment?.state === 'attached',\n /** Attached with the buyer's store chosen: a reader can be registered to it here. */\n storeChosen: order.attachment?.state === 'attached' && Boolean(order.hostId),\n /** Readers on the sale, and how many have a serial or are set up. */\n readers: (order.units ?? []).length,\n serialsTaken: (order.units ?? []).filter((unit) => unit.serialNumber).length,\n readersSetUp: (order.units ?? []).filter((unit) => unit.readerId).length,\n /** A buyer with an account and no workspace yet. */\n awaitingWorkspace: Boolean(order.attachment?.uid),\n /** A buyer with no account yet, invited to sign up. */\n invited: Boolean(order.attachment?.email && !order.attachment?.uid),\n }\n}\n\nexport type ToAttachView = ReturnType<typeof toAttachView>\n\n/**\n * One row of the platform's audit log for a lookup or an attachment: who on\n * the selling store did it, and what — never the buyer's full address.\n */\nasync function audit(\n staff: PosStaff,\n action: string,\n after: Record<string, unknown>,\n orderId: string | null = null,\n): Promise<void> {\n const firestore = firebaseAdmin.app().firestore()\n await addAdminAudit(firestore, {\n action,\n actorUid: staff.uid,\n actorEmail: null,\n scope: 'posHardwareSale',\n target: orderId ? `posHardwareSales/${orderId}` : `hosts/${staff.hostId}`,\n orgId: staff.orgId,\n before: null,\n after,\n at: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n })\n}\n"],"names":["consumeRateLimit","firebaseAdmin","addAdminAudit","maskEmailAddress","POS_HARDWARE_SKUS","authorizePosStaff","posIdempotencyKey","posRequestBody","isPosHardwareSellerStore","posHardwareInPersonConfig","posHardwareOrderNumber","BUYER_LOOKUPS_PER_WINDOW","LOOKUP_WINDOW_MS","posHardwareSaleHandler","req","res","body","method","status","json","error","hostId","String","action","permission","undefined","gate","staff","config","seller","orgId","items","map","sku","id","name","displayName","kind","inPerson","sweepInPersonPosHardwareSales","pending","pendingInPersonPosHardwareOrders","orders","order","toAttachView","query","trim","slice","length","rate","uid","limit","windowMs","allowed","found","findHardwareBuyers","audit","matched","people","person","workspaces","workspace","terms","registerOrderId","posHardwareTermsView","posHardwareTermsStatus","requestPosHardwareTermsOnDisplay","ok","device","posHardwareTermsDevice","headers","acceptance","recordPosHardwareTermsAcceptance","staffUid","version","PosHardwareTermsRefusal","message","readers","storeAddress","saved","recordPosHardwareSerials","orderId","serials","recorded","posHardwareInPersonOrderId","sellerHostId","readerId","registerPosHardwareAtBooth","registrationCode","label","address","storeAddressEntered","city","state","country","storeAddressSaved","Boolean","PosHardwareReaderRefusal","reason","attach","detachPosHardwareSale","buyer","checkHardwareBuyer","outcome","attachPosHardwareSale","attachedBy","target","email","PosHardwareAttachRefusal","console","number","posSale","registerNumber","kiosk","online","source","offline","lines","line","quantity","totalCents","createdAtMs","contactEmail","attached","attachment","storeChosen","units","serialsTaken","filter","unit","serialNumber","readersSetUp","awaitingWorkspace","invited","after","firestore","app","actorUid","actorEmail","scope","before","at","FieldValue","serverTimestamp"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,gBAAgB,EAAEC,aAAa,QAAQ,2BAA0B;AAC1E,S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d+G,KAA8B,EAC9BrD,UAAyB,IAAI;IAE7B,MAAMsD,YAAYtI,cAAcuI,GAAG,GAAGD,SAAS;IAC/C,MAAMrI,cAAcqI,WAAW;QAC7BhH;QACAkH,UAAU9G,MAAMuB,GAAG;QACnBwF,YAAY;QACZC,OAAO;QACPjC,QAAQzB,UAAU,CAAC,iBAAiB,EAAEA,SAAS,GAAG,CAAC,MAAM,EAAEtD,MAAMN,MAAM,EAAE;QACzES,OAAOH,MAAMG,KAAK;QAClB8G,QAAQ;QACRN;QACAO,IAAI5I,cAAcsI,SAAS,CAACO,UAAU,CAACC,eAAe;IACxD;AACF"}
|
|
@@ -24,9 +24,10 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
24
24
|
*
|
|
25
25
|
* - **sold online from the shop** — on the platform's own account — under
|
|
26
26
|
* "Card reader shop (online)";
|
|
27
|
-
* - **sold
|
|
28
|
-
*
|
|
29
|
-
* (`own-store-tax-return-source.ts`),
|
|
27
|
+
* - **sold by the operator's own store**, in person at its register or
|
|
28
|
+
* online from its product pages and cart: already in that store's sale,
|
|
29
|
+
* which the own-stores section folds in (`own-store-tax-return-source.ts`),
|
|
30
|
+
* so NOT again here. Only a sale whose
|
|
30
31
|
* store is not one of the operator's own (the store was moved, or no
|
|
31
32
|
* workspace is named as the operator's own) is folded in from its record
|
|
32
33
|
* here, and a review finding says so.
|
|
@@ -51,7 +52,9 @@ import { posHardwareRefundStamp, posHardwareRowInPeriod, posHardwareTaxableBase,
|
|
|
51
52
|
/** The part an in-person sale at a store that is not the operator's own folds in under. */ export const POS_HARDWARE_IN_PERSON_PART_ID = 'posHardwareInPerson';
|
|
52
53
|
/** Where one retained sale record folds into the filing figures. See the module note. */ export function posHardwareFoldedAs(row, options = {}) {
|
|
53
54
|
var _options_ownHostIds;
|
|
54
|
-
|
|
55
|
+
// Sold by the operator's own store, at its register or online (AGL-4038):
|
|
56
|
+
// in that store's sale, as every other sale it makes.
|
|
57
|
+
if (row.source !== 'in_person' && row.source !== 'storefront') return 'shop';
|
|
55
58
|
const host = typeof row.posHostId === 'string' ? row.posHostId : '';
|
|
56
59
|
return host && ((_options_ownHostIds = options.ownHostIds) == null ? void 0 : _options_ownHostIds.has(host)) ? 'store register sale' : 'in-person record';
|
|
57
60
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-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 * The POS hardware shop's sales on the operator's sales tax return (AGL-4038).\n *\n * The operator is the seller of record for every card reader order, so these\n * are its OWN sales, unlike the storefront's facilitated ones beside them.\n * They FOLD INTO the filing figures (Items 1–2 for Texas) as the operator's\n * own sales outside its invoices, through the contract's `operatorSales`:\n *\n * - **sold online from the shop** — on the platform's own account — under\n * \"Card reader shop (online)\";\n * - **sold in person** at the operator's own store's register: already in\n * that store's register sale, which the own-stores section folds in\n * (`own-store-tax-return-source.ts`), so NOT again here. Only a sale whose\n * store is not one of the operator's own (the store was moved, or no\n * workspace is named as the operator's own) is folded in from its record\n * here, and a review finding says so.\n *\n * This card states, worded for the filing jurisdiction:\n *\n * - **every card reader sale by ship-to state** (in person: where the store\n * is), with the refunds of the period beside them — the figure an\n * economic-nexus threshold elsewhere is measured against;\n * - **every order in the period** in the working papers, each with where it\n * is folded in.\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 { centsToDollars } from '@aglyn/aglyn/app-utils/tax-jurisdiction-figures'\nimport type {\n TaxReturnExportBlock,\n TaxReturnFiling,\n TaxReturnFinding,\n TaxReturnOperatorSalesPart,\n TaxReturnSectionFigure,\n TaxReturnSectionTable,\n TaxReturnSourceAnswer,\n TaxReturnSourceRequest,\n} from '@aglyn/aglyn/plugin-manager/plugin-tax-return-sources'\nimport { POS_HARDWARE_SALES_COLLECTION } from '../model/pos-hardware'\nimport {\n posHardwareRefundStamp,\n posHardwareRowInPeriod,\n posHardwareTaxableBase,\n posHardwareTaxSummary,\n type PosHardwareTaxJurisdiction,\n type PosHardwareTaxRowInput,\n type PosHardwareTaxSummary,\n} from '../model/pos-hardware-tax-summary'\n\n/** The section's id, unique on the return. */\nexport const POS_HARDWARE_TAX_SECTION_ID = 'posHardware'\n\n/** The part the shop's online sales fold into the filing figures under. */\nexport const POS_HARDWARE_SHOP_PART_ID = 'posHardwareShop'\n/** The part an in-person sale at a store that is not the operator's own folds in under. */\nexport const POS_HARDWARE_IN_PERSON_PART_ID = 'posHardwareInPerson'\n\n/** Where an order is folded into the filing figures. */\nexport type PosHardwareFoldedAs = 'shop' | 'store register sale' | 'in-person record'\n\n/** Who decides where a record folds in: the operator's own stores, by site id. */\nexport interface PosHardwareFoldOptions {\n /** The sites of the operator's own stores, whose register sales the own-stores section folds in. */\n ownHostIds?: ReadonlySet<string>\n}\n\n/** Where one retained sale record folds into the filing figures. See the module note. */\nexport function posHardwareFoldedAs(\n row: Pick<PosHardwareTaxRowInput, 'source' | 'posHostId'>,\n options: PosHardwareFoldOptions = {},\n): PosHardwareFoldedAs {\n if (row.source !== 'in_person') return 'shop'\n const host = typeof row.posHostId === 'string' ? row.posHostId : ''\n return host && options.ownHostIds?.has(host) ? 'store register sale' : 'in-person record'\n}\n\n/**\n * The operator's own hardware sales the filing figures fold in from this\n * section: the shop's online sales, and any in-person sale whose store is not\n * the operator's own. Every figure is the summary's own math over that part's\n * records, so the card and the figures cannot disagree.\n */\nexport function posHardwareOperatorSales(\n rows: readonly PosHardwareTaxRowInput[],\n period: { start: Date; end: Date },\n options: PosHardwareFoldOptions = {},\n): TaxReturnOperatorSalesPart[] {\n const parts: Array<{ id: string; label: string; foldedAs: PosHardwareFoldedAs }> = [\n { id: POS_HARDWARE_SHOP_PART_ID, label: 'Card reader shop (online)', foldedAs: 'shop' },\n {\n id: POS_HARDWARE_IN_PERSON_PART_ID,\n label: 'Card readers sold in person (store not read)',\n foldedAs: 'in-person record',\n },\n ]\n return parts.flatMap(({ id, label, foldedAs }) => {\n const summary = posHardwareTaxSummary(\n rows.filter((row) => posHardwareFoldedAs(row, options) === foldedAs),\n period,\n )\n const byJurisdiction = Object.fromEntries(\n Object.entries(summary.byJurisdiction).map(([jurisdiction, figures]) => [\n jurisdiction,\n {\n transactionCount: figures.transactionCount,\n totalSalesCents: figures.totalSalesCents,\n taxableSalesCents: figures.taxableSalesCents,\n taxCollectedCents: figures.taxCollectedCents,\n refundCount: figures.refundedOrders,\n refundedSalesCents: figures.refundedSalesCents,\n refundedTaxCents: figures.refundedTaxCents,\n },\n ]),\n )\n // The shop's part is always stated, so its zero is a figure; an empty\n // in-person part is simply not there.\n return foldedAs === 'shop' || Object.keys(byJurisdiction).length ? [{ id, label, byJurisdiction }] : []\n })\n}\n\n/** One order as the working papers carry it: amounts and the region, no buyer. */\nexport interface PosHardwareTaxRow {\n orderId: string\n paidAt: string | null\n status: string | null\n state: string | null\n country: string | null\n totalSalesCents: number\n taxableSalesCents: number | null\n taxCents: number\n refundedCents: number\n refundedAt: string | null\n /** How the order counts in this period. */\n inPeriodAs: 'sale' | 'refund' | 'sale and refund'\n /** Where it is folded into the filing figures. */\n foldedAs: PosHardwareFoldedAs\n}\n\nconst isoOrNull = (value: number | null): string | null =>\n value === null ? null : new Date(value).toISOString()\n\nconst numberOrNull = (value: unknown): number | null =>\n typeof value === 'number' && Number.isFinite(value) ? value : null\n\nconst textOrNull = (value: unknown): string | null =>\n typeof value === 'string' && value ? value : null\n\nconst emptyFigures = (): PosHardwareTaxJurisdiction => ({\n transactionCount: 0,\n totalSalesCents: 0,\n taxableSalesCents: 0,\n taxCollectedCents: 0,\n taxabilityReasons: {},\n rates: [],\n untaxedOrders: 0,\n refundedOrders: 0,\n refundedSalesCents: 0,\n refundedTaxCents: 0,\n})\n\n/** The filing jurisdiction's hardware figures, or zeros when none sold there. */\nexport function posHardwareFilingFigures(\n summary: PosHardwareTaxSummary,\n filing: TaxReturnFiling,\n): PosHardwareTaxJurisdiction {\n return summary.byJurisdiction[filing.code] ?? emptyFigures()\n}\n\n/** The section's findings. The platform raises the non-zero ones. */\nexport function posHardwareTaxFindings(\n summary: PosHardwareTaxSummary,\n filing: TaxReturnFiling,\n operatorSales: readonly TaxReturnOperatorSalesPart[] = [],\n): TaxReturnFinding[] {\n const brand = PLATFORM_BRAND_NAME\n const figures = posHardwareFilingFigures(summary, filing)\n const unread = operatorSales.find((part) => part.id === POS_HARDWARE_IN_PERSON_PART_ID)\n return [\n {\n // REVIEW: the sales ARE in the figures, from their hardware records;\n // the rest of that store's sales are not, because it is not one of the\n // operator's own stores.\n id: 'posHardwareInPersonStoreNotRead',\n severity: 'review',\n count: Object.values(unread?.byJurisdiction ?? {}).reduce((sum, part) => sum + part.transactionCount, 0),\n label: `Card readers sold in person at a store that is not one of ${brand}’s own`,\n detail:\n `Folded into ${filing.figuresName} from their hardware records. The store that sold them is not a ` +\n `site of the workspace named as ${brand}’s own (POS_HARDWARE_SELLER_ORG_ID), so its other sales are ` +\n 'not in the figures. Name the workspace, or check the store was moved on purpose.',\n },\n {\n id: 'posHardwareUntaxed',\n severity: 'review',\n count: figures.untaxedOrders,\n label: `Card reader hardware sold into ${filing.label} without tax`,\n detail:\n 'Sold while Stripe Tax was off for the hardware shop, so no tax was ' +\n `collected. If the sale was taxable in ${filing.label}, the tax is ` +\n `still owed, out of ${brand}’s receipt.`,\n },\n {\n id: 'posHardwareMissingTaxableBase',\n severity: 'review',\n count: summary.attention.ordersMissingTaxableBase,\n label: 'Card reader hardware orders with tax but no stated base',\n detail:\n 'Tax was collected but Stripe’s taxable_amount was not recorded on the ' +\n 'order, so the hardware taxable-sales line understates the base. Read ' +\n 'the Checkout Session in Stripe with the tax breakdown expanded.',\n },\n {\n id: 'posHardwareMissingShipTo',\n severity: 'review',\n count: summary.attention.ordersMissingShipTo,\n label: 'Card reader hardware orders with no ship-to region',\n detail:\n 'Listed as Not stated, and in no state’s figures. If the order shipped ' +\n `to ${filing.label}, the hardware lines understate its sales.`,\n },\n {\n id: 'posHardwareCanceledWithoutRefund',\n severity: 'review',\n count: summary.attention.canceledWithoutRefund,\n label: 'Canceled card reader hardware orders with no refund recorded',\n detail:\n 'Counted as sales: the order is marked canceled or refunded, but no ' +\n 'refund was recorded on it. Check the payment in Stripe.',\n },\n ]\n}\n\n/** One ship-to state's row, ready to print. */\nexport interface PosHardwareJurisdictionRow {\n jurisdiction: string\n isFilingJurisdiction: boolean\n orders: number\n totalSalesCents: number\n taxableSalesCents: number\n taxCollectedCents: number\n refundedOrders: number\n refundedSalesCents: number\n refundedTaxCents: number\n}\n\n/** Every ship-to state, the filing jurisdiction first, then by sales. */\nexport function posHardwareJurisdictionRows(\n summary: PosHardwareTaxSummary,\n filing: TaxReturnFiling,\n): PosHardwareJurisdictionRow[] {\n return Object.entries(summary.byJurisdiction)\n .map(([jurisdiction, figures]) => ({\n jurisdiction,\n isFilingJurisdiction: jurisdiction === filing.code,\n orders: figures.transactionCount,\n totalSalesCents: figures.totalSalesCents,\n taxableSalesCents: figures.taxableSalesCents,\n taxCollectedCents: figures.taxCollectedCents,\n refundedOrders: figures.refundedOrders,\n refundedSalesCents: figures.refundedSalesCents,\n refundedTaxCents: figures.refundedTaxCents,\n }))\n .sort(\n (a, b) =>\n Number(b.isFilingJurisdiction) - Number(a.isFilingJurisdiction) ||\n b.totalSalesCents - a.totalSalesCents ||\n a.jurisdiction.localeCompare(b.jurisdiction),\n )\n}\n\nconst dollars = (centsValue: number) => `$${centsToDollars(centsValue)}`\n\nfunction posHardwareTables(summary: PosHardwareTaxSummary, filing: TaxReturnFiling): TaxReturnSectionTable[] {\n return [\n {\n description:\n 'Sales by where each order shipped, which is where its sales tax is ' +\n 'sourced, and the refunds made in this period beside them. A state ' +\n 'other than the one filed here is the figure an economic-nexus ' +\n 'threshold there is measured against.',\n columns: [\n { label: 'Ship-to state' },\n { label: 'Orders', numeric: true },\n { label: 'Total sales', numeric: true, money: true },\n { label: 'Taxable sales', numeric: true, money: true },\n { label: 'Tax collected', numeric: true, money: true },\n { label: 'Refunded in period', numeric: true, money: true },\n { label: 'Tax refunded', numeric: true, money: true },\n ],\n rows: posHardwareJurisdictionRows(summary, filing).map((row) => ({\n key: row.jurisdiction,\n cells: [\n {\n text: row.jurisdiction === 'unknown' ? 'Not stated' : row.jurisdiction,\n ...(row.isFilingJurisdiction ? { tag: { label: 'Registered', tone: 'attention' as const } } : {}),\n ...(row.refundedOrders\n ? { caption: `${row.refundedOrders} refund${row.refundedOrders === 1 ? '' : 's'} in this period` }\n : {}),\n },\n { text: String(row.orders) },\n { text: dollars(row.totalSalesCents), strong: row.isFilingJurisdiction },\n { text: dollars(row.taxableSalesCents) },\n { text: dollars(row.taxCollectedCents) },\n { text: dollars(row.refundedSalesCents) },\n { text: dollars(row.refundedTaxCents) },\n ],\n })),\n empty: 'No card reader hardware was sold or refunded in this period.',\n footnote:\n 'Every card reader sale, online and in person. The online ones are folded into the filing figures ' +\n 'as “Card reader shop (online)”; one sold in person is in its store’s register sale there. ' +\n 'Test-mode orders are in no figure. A refund is counted in the period it was made, whenever the ' +\n 'order was paid.',\n },\n ]\n}\n\nfunction posHardwareFigures(summary: PosHardwareTaxSummary): TaxReturnSectionFigure[] {\n const figures: TaxReturnSectionFigure[] = [\n {\n label: 'Orders paid in this period',\n value: String(summary.orders),\n note: 'Every ship-to state. Live orders only.',\n },\n ]\n if (summary.excluded.testModeOrders) {\n figures.push({\n label: 'Test-mode orders left out',\n value: String(summary.excluded.testModeOrders),\n note: 'Made with Stripe’s test keys, so not sales: in no figure above.',\n })\n }\n return figures\n}\n\n/** One record as the working papers carry it, for an order the period counts. */\nfunction projectRow(\n row: PosHardwareTaxRowInput,\n period: { start: Date; end: Date },\n options: PosHardwareFoldOptions,\n): PosHardwareTaxRow {\n const placed = posHardwareRowInPeriod(row, period)\n const total = Number(row.totalCents ?? 0) || 0\n const tax = Number(row.taxCents ?? 0) || 0\n return {\n orderId: row.orderId,\n paidAt: isoOrNull(numberOrNull(row.paidAtMs)),\n status: textOrNull(row.status),\n state: textOrNull(row.shipTo?.state),\n country: textOrNull(row.shipTo?.country),\n totalSalesCents: total - tax,\n taxableSalesCents: posHardwareTaxableBase(Array.isArray(row.taxLines) ? row.taxLines : []),\n taxCents: tax,\n refundedCents: Number(row.refundedCents ?? 0) || 0,\n refundedAt: isoOrNull(posHardwareRefundStamp(row)),\n inPeriodAs: placed.sale && placed.refund ? 'sale and refund' : placed.sale ? 'sale' : 'refund',\n foldedAs: posHardwareFoldedAs(row, options),\n }\n}\n\nfunction posHardwareExports(\n summary: PosHardwareTaxSummary,\n filing: TaxReturnFiling,\n rows: readonly PosHardwareTaxRow[],\n): TaxReturnExportBlock[] {\n const brand = PLATFORM_BRAND_NAME\n const states = posHardwareJurisdictionRows(summary, filing)\n return [\n {\n placement: 'jurisdictions',\n rows: [\n [`Card reader hardware — ${brand}’s OWN sales by ship-to state (folded into the filing figures above, by source)`],\n [\n 'Ship-to state',\n 'Orders',\n 'Total sales (USD)',\n 'Taxable sales (USD)',\n 'Tax collected (USD)',\n 'Refunded in period (USD)',\n 'Tax refunded (USD)',\n ],\n ...(states.length\n ? states.map((row) => [\n row.jurisdiction,\n String(row.orders),\n centsToDollars(row.totalSalesCents),\n centsToDollars(row.taxableSalesCents),\n centsToDollars(row.taxCollectedCents),\n centsToDollars(row.refundedSalesCents),\n centsToDollars(row.refundedTaxCents),\n ])\n : [['—', '0', '0.00', '0.00', '0.00', '0.00', '0.00']]),\n ],\n },\n {\n placement: 'sections',\n rows: [\n ['Card reader hardware orders in this period (posHardwareSales) — folded into the filing figures as each says'],\n [\n 'Order',\n 'Paid (UTC)',\n 'Status',\n 'Ship-to state',\n 'Country',\n 'Total sales (USD)',\n 'Taxable sales (USD)',\n 'Tax collected (USD)',\n 'Refunded (USD)',\n 'Refunded at (UTC)',\n 'In this period as',\n 'Folded in as',\n ],\n ...rows.map((row) => [\n row.orderId,\n row.paidAt ?? '',\n row.status ?? '',\n row.state ?? '',\n row.country ?? '',\n centsToDollars(row.totalSalesCents),\n row.taxableSalesCents === null ? 'not stated' : centsToDollars(row.taxableSalesCents),\n centsToDollars(row.taxCents),\n centsToDollars(row.refundedCents),\n row.refundedAt ?? '',\n row.inPeriodAs,\n row.foldedAs === 'shop'\n ? 'Card reader shop (online)'\n : row.foldedAs === 'store register sale'\n ? 'its store’s register sale'\n : 'Card readers sold in person (store not read)',\n ]),\n ],\n },\n ]\n}\n\n/**\n * The hardware section for one period, from records already read. Pure, so\n * the section a preparer reads can be proved from fixtures.\n */\nexport function posHardwareTaxReturnAnswer(\n read: { rows: readonly PosHardwareTaxRowInput[]; truncated: boolean; undatedRows: number },\n request: TaxReturnSourceRequest,\n options: PosHardwareFoldOptions = {},\n): TaxReturnSourceAnswer {\n const brand = PLATFORM_BRAND_NAME\n const { filing } = request\n const period = { start: request.start, end: request.end }\n const summary = posHardwareTaxSummary(read.rows, period)\n const operatorSales = posHardwareOperatorSales(read.rows, period, options)\n const seen = new Set<string>()\n const rows = read.rows\n .filter((row) => {\n if (!row?.orderId || seen.has(row.orderId) || row.livemode !== true) return false\n seen.add(row.orderId)\n const placed = posHardwareRowInPeriod(row, period)\n return placed.sale || placed.refund\n })\n .map((row) => projectRow(row, period, options))\n return {\n id: POS_HARDWARE_TAX_SECTION_ID,\n name: 'Card reader hardware',\n title: `Card reader hardware — ${brand}’s own sales`,\n help:\n `Card readers and accessories ${brand} sold to workspaces, online from the POS hardware shop and ` +\n `in person at its own store. ${brand} is the seller, so these are its own sales, folded into the ` +\n 'filing figures above.',\n intro:\n `${brand} is the seller of record for every card reader order, so these are ` +\n `${brand}’s OWN sales, not facilitated ones, and they are folded into ${filing.figuresName}: ` +\n 'the online ones as “Card reader shop (online)”, one sold in person in its store’s register sale. ' +\n 'Refunds are counted in the period they were made and never netted.',\n truncated: read.truncated,\n undatedRows: read.undatedRows,\n findings: posHardwareTaxFindings(summary, filing, operatorSales),\n filingLines: [],\n operatorSales,\n tables: posHardwareTables(summary, filing),\n figures: posHardwareFigures(summary),\n exports: posHardwareExports(summary, filing, rows),\n summary,\n rows,\n }\n}\n\n/**\n * Reads the period's hardware records and answers for them.\n *\n * Three range queries, because a record counts in a period two ways — paid\n * in it, or refunded in it (by the stamp of the status that refunded it) —\n * and a fourth, the honesty check: a range query cannot match a record whose\n * `paidAtMs` is null, so those are counted over all of them and the platform\n * blocks the return on any. Each is a single-field range, served by\n * Firestore's automatic index. A query that reaches the row cap marks the\n * section truncated, and the platform blocks on that too.\n */\nexport async function readPosHardwareTaxReturn(\n request: TaxReturnSourceRequest,\n options: PosHardwareFoldOptions = {},\n): Promise<TaxReturnSourceAnswer> {\n const collection = firebaseAdmin.app().firestore().collection(POS_HARDWARE_SALES_COLLECTION)\n const startMs = request.start.getTime()\n const endMs = request.end.getTime()\n const inRange = (field: string) =>\n collection.where(field, '>=', startMs).where(field, '<', endMs).limit(request.rowCap + 1).get()\n const [paid, refunded, canceled, undated] = await Promise.all([\n inRange('paidAtMs'),\n inRange('refundedAtMs'),\n inRange('canceledAtMs'),\n collection.where('paidAtMs', '==', null).count().get(),\n ])\n const byId = new Map<string, PosHardwareTaxRowInput>()\n for (const snapshot of [paid, refunded, canceled]) {\n for (const doc of snapshot.docs.slice(0, request.rowCap)) {\n if (!byId.has(doc.id)) {\n byId.set(doc.id, { ...(doc.data() as Omit<PosHardwareTaxRowInput, 'orderId'>), orderId: doc.id })\n }\n }\n }\n return posHardwareTaxReturnAnswer(\n {\n rows: [...byId.values()],\n truncated: [paid, refunded, canceled].some((snapshot) => snapshot.size > request.rowCap),\n undatedRows: Number(undated.data().count ?? 0),\n },\n request,\n options,\n )\n}\n"],"names":["firebaseAdmin","PLATFORM_BRAND_NAME","centsToDollars","POS_HARDWARE_SALES_COLLECTION","posHardwareRefundStamp","posHardwareRowInPeriod","posHardwareTaxableBase","posHardwareTaxSummary","POS_HARDWARE_TAX_SECTION_ID","POS_HARDWARE_SHOP_PART_ID","POS_HARDWARE_IN_PERSON_PART_ID","posHardwareFoldedAs","row","options","source","host","posHostId","ownHostIds","has","posHardwareOperatorSales","rows","period","parts","id","label","foldedAs","flatMap","summary","filter","byJurisdiction","Object","fromEntries","entries","map","jurisdiction","figures","transactionCount","totalSalesCents","taxableSalesCents","taxCollectedCents","refundCount","refundedOrders","refundedSalesCents","refundedTaxCents","keys","length","isoOrNull","value","Date","toISOString","numberOrNull","Number","isFinite","textOrNull","emptyFigures","taxabilityReasons","rates","untaxedOrders","posHardwareFilingFigures","filing","code","posHardwareTaxFindings","operatorSales","brand","unread","find","part","severity","count","values","reduce","sum","detail","figuresName","attention","ordersMissingTaxableBase","ordersMissingShipTo","canceledWithoutRefund","posHardwareJurisdictionRows","isFilingJurisdiction","orders","sort","a","b","localeCompare","dollars","centsValue","posHardwareTables","description","columns","numeric","money","key","cells","text","tag","tone","caption","String","strong","empty","footnote","posHardwareFigures","note","excluded","testModeOrders","push","projectRow","placed","total","totalCents","tax","taxCents","orderId","paidAt","paidAtMs","status","state","shipTo","country","Array","isArray","taxLines","refundedCents","refundedAt","inPeriodAs","sale","refund","posHardwareExports","states","placement","posHardwareTaxReturnAnswer","read","request","start","end","seen","Set","livemode","add","name","title","help","intro","truncated","undatedRows","findings","filingLines","tables","exports","readPosHardwareTaxReturn","undated","collection","app","firestore","startMs","getTime","endMs","inRange","field","where","limit","rowCap","get","paid","refunded","canceled","Promise","all","byId","Map","snapshot","doc","docs","slice","set","data","some","size"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,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-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 * The POS hardware shop's sales on the operator's sales tax return (AGL-4038).\n *\n * The operator is the seller of record for every card reader order, so these\n * are its OWN sales, unlike the storefront's facilitated ones beside them.\n * They FOLD INTO the filing figures (Items 1–2 for Texas) as the operator's\n * own sales outside its invoices, through the contract's `operatorSales`:\n *\n * - **sold online from the shop** — on the platform's own account — under\n * \"Card reader shop (online)\";\n * - **sold by the operator's own store**, in person at its register or\n * online from its product pages and cart: already in that store's sale,\n * which the own-stores section folds in (`own-store-tax-return-source.ts`),\n * so NOT again here. Only a sale whose\n * store is not one of the operator's own (the store was moved, or no\n * workspace is named as the operator's own) is folded in from its record\n * here, and a review finding says so.\n *\n * This card states, worded for the filing jurisdiction:\n *\n * - **every card reader sale by ship-to state** (in person: where the store\n * is), with the refunds of the period beside them — the figure an\n * economic-nexus threshold elsewhere is measured against;\n * - **every order in the period** in the working papers, each with where it\n * is folded in.\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 { centsToDollars } from '@aglyn/aglyn/app-utils/tax-jurisdiction-figures'\nimport type {\n TaxReturnExportBlock,\n TaxReturnFiling,\n TaxReturnFinding,\n TaxReturnOperatorSalesPart,\n TaxReturnSectionFigure,\n TaxReturnSectionTable,\n TaxReturnSourceAnswer,\n TaxReturnSourceRequest,\n} from '@aglyn/aglyn/plugin-manager/plugin-tax-return-sources'\nimport { POS_HARDWARE_SALES_COLLECTION } from '../model/pos-hardware'\nimport {\n posHardwareRefundStamp,\n posHardwareRowInPeriod,\n posHardwareTaxableBase,\n posHardwareTaxSummary,\n type PosHardwareTaxJurisdiction,\n type PosHardwareTaxRowInput,\n type PosHardwareTaxSummary,\n} from '../model/pos-hardware-tax-summary'\n\n/** The section's id, unique on the return. */\nexport const POS_HARDWARE_TAX_SECTION_ID = 'posHardware'\n\n/** The part the shop's online sales fold into the filing figures under. */\nexport const POS_HARDWARE_SHOP_PART_ID = 'posHardwareShop'\n/** The part an in-person sale at a store that is not the operator's own folds in under. */\nexport const POS_HARDWARE_IN_PERSON_PART_ID = 'posHardwareInPerson'\n\n/** Where an order is folded into the filing figures. */\nexport type PosHardwareFoldedAs = 'shop' | 'store register sale' | 'in-person record'\n\n/** Who decides where a record folds in: the operator's own stores, by site id. */\nexport interface PosHardwareFoldOptions {\n /** The sites of the operator's own stores, whose register sales the own-stores section folds in. */\n ownHostIds?: ReadonlySet<string>\n}\n\n/** Where one retained sale record folds into the filing figures. See the module note. */\nexport function posHardwareFoldedAs(\n row: Pick<PosHardwareTaxRowInput, 'source' | 'posHostId'>,\n options: PosHardwareFoldOptions = {},\n): PosHardwareFoldedAs {\n // Sold by the operator's own store, at its register or online (AGL-4038):\n // in that store's sale, as every other sale it makes.\n if (row.source !== 'in_person' && row.source !== 'storefront') return 'shop'\n const host = typeof row.posHostId === 'string' ? row.posHostId : ''\n return host && options.ownHostIds?.has(host) ? 'store register sale' : 'in-person record'\n}\n\n/**\n * The operator's own hardware sales the filing figures fold in from this\n * section: the shop's online sales, and any in-person sale whose store is not\n * the operator's own. Every figure is the summary's own math over that part's\n * records, so the card and the figures cannot disagree.\n */\nexport function posHardwareOperatorSales(\n rows: readonly PosHardwareTaxRowInput[],\n period: { start: Date; end: Date },\n options: PosHardwareFoldOptions = {},\n): TaxReturnOperatorSalesPart[] {\n const parts: Array<{ id: string; label: string; foldedAs: PosHardwareFoldedAs }> = [\n { id: POS_HARDWARE_SHOP_PART_ID, label: 'Card reader shop (online)', foldedAs: 'shop' },\n {\n id: POS_HARDWARE_IN_PERSON_PART_ID,\n label: 'Card readers sold in person (store not read)',\n foldedAs: 'in-person record',\n },\n ]\n return parts.flatMap(({ id, label, foldedAs }) => {\n const summary = posHardwareTaxSummary(\n rows.filter((row) => posHardwareFoldedAs(row, options) === foldedAs),\n period,\n )\n const byJurisdiction = Object.fromEntries(\n Object.entries(summary.byJurisdiction).map(([jurisdiction, figures]) => [\n jurisdiction,\n {\n transactionCount: figures.transactionCount,\n totalSalesCents: figures.totalSalesCents,\n taxableSalesCents: figures.taxableSalesCents,\n taxCollectedCents: figures.taxCollectedCents,\n refundCount: figures.refundedOrders,\n refundedSalesCents: figures.refundedSalesCents,\n refundedTaxCents: figures.refundedTaxCents,\n },\n ]),\n )\n // The shop's part is always stated, so its zero is a figure; an empty\n // in-person part is simply not there.\n return foldedAs === 'shop' || Object.keys(byJurisdiction).length ? [{ id, label, byJurisdiction }] : []\n })\n}\n\n/** One order as the working papers carry it: amounts and the region, no buyer. */\nexport interface PosHardwareTaxRow {\n orderId: string\n paidAt: string | null\n status: string | null\n state: string | null\n country: string | null\n totalSalesCents: number\n taxableSalesCents: number | null\n taxCents: number\n refundedCents: number\n refundedAt: string | null\n /** How the order counts in this period. */\n inPeriodAs: 'sale' | 'refund' | 'sale and refund'\n /** Where it is folded into the filing figures. */\n foldedAs: PosHardwareFoldedAs\n}\n\nconst isoOrNull = (value: number | null): string | null =>\n value === null ? null : new Date(value).toISOString()\n\nconst numberOrNull = (value: unknown): number | null =>\n typeof value === 'number' && Number.isFinite(value) ? value : null\n\nconst textOrNull = (value: unknown): string | null =>\n typeof value === 'string' && value ? value : null\n\nconst emptyFigures = (): PosHardwareTaxJurisdiction => ({\n transactionCount: 0,\n totalSalesCents: 0,\n taxableSalesCents: 0,\n taxCollectedCents: 0,\n taxabilityReasons: {},\n rates: [],\n untaxedOrders: 0,\n refundedOrders: 0,\n refundedSalesCents: 0,\n refundedTaxCents: 0,\n})\n\n/** The filing jurisdiction's hardware figures, or zeros when none sold there. */\nexport function posHardwareFilingFigures(\n summary: PosHardwareTaxSummary,\n filing: TaxReturnFiling,\n): PosHardwareTaxJurisdiction {\n return summary.byJurisdiction[filing.code] ?? emptyFigures()\n}\n\n/** The section's findings. The platform raises the non-zero ones. */\nexport function posHardwareTaxFindings(\n summary: PosHardwareTaxSummary,\n filing: TaxReturnFiling,\n operatorSales: readonly TaxReturnOperatorSalesPart[] = [],\n): TaxReturnFinding[] {\n const brand = PLATFORM_BRAND_NAME\n const figures = posHardwareFilingFigures(summary, filing)\n const unread = operatorSales.find((part) => part.id === POS_HARDWARE_IN_PERSON_PART_ID)\n return [\n {\n // REVIEW: the sales ARE in the figures, from their hardware records;\n // the rest of that store's sales are not, because it is not one of the\n // operator's own stores.\n id: 'posHardwareInPersonStoreNotRead',\n severity: 'review',\n count: Object.values(unread?.byJurisdiction ?? {}).reduce((sum, part) => sum + part.transactionCount, 0),\n label: `Card readers sold in person at a store that is not one of ${brand}’s own`,\n detail:\n `Folded into ${filing.figuresName} from their hardware records. The store that sold them is not a ` +\n `site of the workspace named as ${brand}’s own (POS_HARDWARE_SELLER_ORG_ID), so its other sales are ` +\n 'not in the figures. Name the workspace, or check the store was moved on purpose.',\n },\n {\n id: 'posHardwareUntaxed',\n severity: 'review',\n count: figures.untaxedOrders,\n label: `Card reader hardware sold into ${filing.label} without tax`,\n detail:\n 'Sold while Stripe Tax was off for the hardware shop, so no tax was ' +\n `collected. If the sale was taxable in ${filing.label}, the tax is ` +\n `still owed, out of ${brand}’s receipt.`,\n },\n {\n id: 'posHardwareMissingTaxableBase',\n severity: 'review',\n count: summary.attention.ordersMissingTaxableBase,\n label: 'Card reader hardware orders with tax but no stated base',\n detail:\n 'Tax was collected but Stripe’s taxable_amount was not recorded on the ' +\n 'order, so the hardware taxable-sales line understates the base. Read ' +\n 'the Checkout Session in Stripe with the tax breakdown expanded.',\n },\n {\n id: 'posHardwareMissingShipTo',\n severity: 'review',\n count: summary.attention.ordersMissingShipTo,\n label: 'Card reader hardware orders with no ship-to region',\n detail:\n 'Listed as Not stated, and in no state’s figures. If the order shipped ' +\n `to ${filing.label}, the hardware lines understate its sales.`,\n },\n {\n id: 'posHardwareCanceledWithoutRefund',\n severity: 'review',\n count: summary.attention.canceledWithoutRefund,\n label: 'Canceled card reader hardware orders with no refund recorded',\n detail:\n 'Counted as sales: the order is marked canceled or refunded, but no ' +\n 'refund was recorded on it. Check the payment in Stripe.',\n },\n ]\n}\n\n/** One ship-to state's row, ready to print. */\nexport interface PosHardwareJurisdictionRow {\n jurisdiction: string\n isFilingJurisdiction: boolean\n orders: number\n totalSalesCents: number\n taxableSalesCents: number\n taxCollectedCents: number\n refundedOrders: number\n refundedSalesCents: number\n refundedTaxCents: number\n}\n\n/** Every ship-to state, the filing jurisdiction first, then by sales. */\nexport function posHardwareJurisdictionRows(\n summary: PosHardwareTaxSummary,\n filing: TaxReturnFiling,\n): PosHardwareJurisdictionRow[] {\n return Object.entries(summary.byJurisdiction)\n .map(([jurisdiction, figures]) => ({\n jurisdiction,\n isFilingJurisdiction: jurisdiction === filing.code,\n orders: figures.transactionCount,\n totalSalesCents: figures.totalSalesCents,\n taxableSalesCents: figures.taxableSalesCents,\n taxCollectedCents: figures.taxCollectedCents,\n refundedOrders: figures.refundedOrders,\n refundedSalesCents: figures.refundedSalesCents,\n refundedTaxCents: figures.refundedTaxCents,\n }))\n .sort(\n (a, b) =>\n Number(b.isFilingJurisdiction) - Number(a.isFilingJurisdiction) ||\n b.totalSalesCents - a.totalSalesCents ||\n a.jurisdiction.localeCompare(b.jurisdiction),\n )\n}\n\nconst dollars = (centsValue: number) => `$${centsToDollars(centsValue)}`\n\nfunction posHardwareTables(summary: PosHardwareTaxSummary, filing: TaxReturnFiling): TaxReturnSectionTable[] {\n return [\n {\n description:\n 'Sales by where each order shipped, which is where its sales tax is ' +\n 'sourced, and the refunds made in this period beside them. A state ' +\n 'other than the one filed here is the figure an economic-nexus ' +\n 'threshold there is measured against.',\n columns: [\n { label: 'Ship-to state' },\n { label: 'Orders', numeric: true },\n { label: 'Total sales', numeric: true, money: true },\n { label: 'Taxable sales', numeric: true, money: true },\n { label: 'Tax collected', numeric: true, money: true },\n { label: 'Refunded in period', numeric: true, money: true },\n { label: 'Tax refunded', numeric: true, money: true },\n ],\n rows: posHardwareJurisdictionRows(summary, filing).map((row) => ({\n key: row.jurisdiction,\n cells: [\n {\n text: row.jurisdiction === 'unknown' ? 'Not stated' : row.jurisdiction,\n ...(row.isFilingJurisdiction ? { tag: { label: 'Registered', tone: 'attention' as const } } : {}),\n ...(row.refundedOrders\n ? { caption: `${row.refundedOrders} refund${row.refundedOrders === 1 ? '' : 's'} in this period` }\n : {}),\n },\n { text: String(row.orders) },\n { text: dollars(row.totalSalesCents), strong: row.isFilingJurisdiction },\n { text: dollars(row.taxableSalesCents) },\n { text: dollars(row.taxCollectedCents) },\n { text: dollars(row.refundedSalesCents) },\n { text: dollars(row.refundedTaxCents) },\n ],\n })),\n empty: 'No card reader hardware was sold or refunded in this period.',\n footnote:\n 'Every card reader sale, online and in person. The online ones are folded into the filing figures ' +\n 'as “Card reader shop (online)”; one sold in person is in its store’s register sale there. ' +\n 'Test-mode orders are in no figure. A refund is counted in the period it was made, whenever the ' +\n 'order was paid.',\n },\n ]\n}\n\nfunction posHardwareFigures(summary: PosHardwareTaxSummary): TaxReturnSectionFigure[] {\n const figures: TaxReturnSectionFigure[] = [\n {\n label: 'Orders paid in this period',\n value: String(summary.orders),\n note: 'Every ship-to state. Live orders only.',\n },\n ]\n if (summary.excluded.testModeOrders) {\n figures.push({\n label: 'Test-mode orders left out',\n value: String(summary.excluded.testModeOrders),\n note: 'Made with Stripe’s test keys, so not sales: in no figure above.',\n })\n }\n return figures\n}\n\n/** One record as the working papers carry it, for an order the period counts. */\nfunction projectRow(\n row: PosHardwareTaxRowInput,\n period: { start: Date; end: Date },\n options: PosHardwareFoldOptions,\n): PosHardwareTaxRow {\n const placed = posHardwareRowInPeriod(row, period)\n const total = Number(row.totalCents ?? 0) || 0\n const tax = Number(row.taxCents ?? 0) || 0\n return {\n orderId: row.orderId,\n paidAt: isoOrNull(numberOrNull(row.paidAtMs)),\n status: textOrNull(row.status),\n state: textOrNull(row.shipTo?.state),\n country: textOrNull(row.shipTo?.country),\n totalSalesCents: total - tax,\n taxableSalesCents: posHardwareTaxableBase(Array.isArray(row.taxLines) ? row.taxLines : []),\n taxCents: tax,\n refundedCents: Number(row.refundedCents ?? 0) || 0,\n refundedAt: isoOrNull(posHardwareRefundStamp(row)),\n inPeriodAs: placed.sale && placed.refund ? 'sale and refund' : placed.sale ? 'sale' : 'refund',\n foldedAs: posHardwareFoldedAs(row, options),\n }\n}\n\nfunction posHardwareExports(\n summary: PosHardwareTaxSummary,\n filing: TaxReturnFiling,\n rows: readonly PosHardwareTaxRow[],\n): TaxReturnExportBlock[] {\n const brand = PLATFORM_BRAND_NAME\n const states = posHardwareJurisdictionRows(summary, filing)\n return [\n {\n placement: 'jurisdictions',\n rows: [\n [`Card reader hardware — ${brand}’s OWN sales by ship-to state (folded into the filing figures above, by source)`],\n [\n 'Ship-to state',\n 'Orders',\n 'Total sales (USD)',\n 'Taxable sales (USD)',\n 'Tax collected (USD)',\n 'Refunded in period (USD)',\n 'Tax refunded (USD)',\n ],\n ...(states.length\n ? states.map((row) => [\n row.jurisdiction,\n String(row.orders),\n centsToDollars(row.totalSalesCents),\n centsToDollars(row.taxableSalesCents),\n centsToDollars(row.taxCollectedCents),\n centsToDollars(row.refundedSalesCents),\n centsToDollars(row.refundedTaxCents),\n ])\n : [['—', '0', '0.00', '0.00', '0.00', '0.00', '0.00']]),\n ],\n },\n {\n placement: 'sections',\n rows: [\n ['Card reader hardware orders in this period (posHardwareSales) — folded into the filing figures as each says'],\n [\n 'Order',\n 'Paid (UTC)',\n 'Status',\n 'Ship-to state',\n 'Country',\n 'Total sales (USD)',\n 'Taxable sales (USD)',\n 'Tax collected (USD)',\n 'Refunded (USD)',\n 'Refunded at (UTC)',\n 'In this period as',\n 'Folded in as',\n ],\n ...rows.map((row) => [\n row.orderId,\n row.paidAt ?? '',\n row.status ?? '',\n row.state ?? '',\n row.country ?? '',\n centsToDollars(row.totalSalesCents),\n row.taxableSalesCents === null ? 'not stated' : centsToDollars(row.taxableSalesCents),\n centsToDollars(row.taxCents),\n centsToDollars(row.refundedCents),\n row.refundedAt ?? '',\n row.inPeriodAs,\n row.foldedAs === 'shop'\n ? 'Card reader shop (online)'\n : row.foldedAs === 'store register sale'\n ? 'its store’s register sale'\n : 'Card readers sold in person (store not read)',\n ]),\n ],\n },\n ]\n}\n\n/**\n * The hardware section for one period, from records already read. Pure, so\n * the section a preparer reads can be proved from fixtures.\n */\nexport function posHardwareTaxReturnAnswer(\n read: { rows: readonly PosHardwareTaxRowInput[]; truncated: boolean; undatedRows: number },\n request: TaxReturnSourceRequest,\n options: PosHardwareFoldOptions = {},\n): TaxReturnSourceAnswer {\n const brand = PLATFORM_BRAND_NAME\n const { filing } = request\n const period = { start: request.start, end: request.end }\n const summary = posHardwareTaxSummary(read.rows, period)\n const operatorSales = posHardwareOperatorSales(read.rows, period, options)\n const seen = new Set<string>()\n const rows = read.rows\n .filter((row) => {\n if (!row?.orderId || seen.has(row.orderId) || row.livemode !== true) return false\n seen.add(row.orderId)\n const placed = posHardwareRowInPeriod(row, period)\n return placed.sale || placed.refund\n })\n .map((row) => projectRow(row, period, options))\n return {\n id: POS_HARDWARE_TAX_SECTION_ID,\n name: 'Card reader hardware',\n title: `Card reader hardware — ${brand}’s own sales`,\n help:\n `Card readers and accessories ${brand} sold to workspaces, online from the POS hardware shop and ` +\n `in person at its own store. ${brand} is the seller, so these are its own sales, folded into the ` +\n 'filing figures above.',\n intro:\n `${brand} is the seller of record for every card reader order, so these are ` +\n `${brand}’s OWN sales, not facilitated ones, and they are folded into ${filing.figuresName}: ` +\n 'the online ones as “Card reader shop (online)”, one sold in person in its store’s register sale. ' +\n 'Refunds are counted in the period they were made and never netted.',\n truncated: read.truncated,\n undatedRows: read.undatedRows,\n findings: posHardwareTaxFindings(summary, filing, operatorSales),\n filingLines: [],\n operatorSales,\n tables: posHardwareTables(summary, filing),\n figures: posHardwareFigures(summary),\n exports: posHardwareExports(summary, filing, rows),\n summary,\n rows,\n }\n}\n\n/**\n * Reads the period's hardware records and answers for them.\n *\n * Three range queries, because a record counts in a period two ways — paid\n * in it, or refunded in it (by the stamp of the status that refunded it) —\n * and a fourth, the honesty check: a range query cannot match a record whose\n * `paidAtMs` is null, so those are counted over all of them and the platform\n * blocks the return on any. Each is a single-field range, served by\n * Firestore's automatic index. A query that reaches the row cap marks the\n * section truncated, and the platform blocks on that too.\n */\nexport async function readPosHardwareTaxReturn(\n request: TaxReturnSourceRequest,\n options: PosHardwareFoldOptions = {},\n): Promise<TaxReturnSourceAnswer> {\n const collection = firebaseAdmin.app().firestore().collection(POS_HARDWARE_SALES_COLLECTION)\n const startMs = request.start.getTime()\n const endMs = request.end.getTime()\n const inRange = (field: string) =>\n collection.where(field, '>=', startMs).where(field, '<', endMs).limit(request.rowCap + 1).get()\n const [paid, refunded, canceled, undated] = await Promise.all([\n inRange('paidAtMs'),\n inRange('refundedAtMs'),\n inRange('canceledAtMs'),\n collection.where('paidAtMs', '==', null).count().get(),\n ])\n const byId = new Map<string, PosHardwareTaxRowInput>()\n for (const snapshot of [paid, refunded, canceled]) {\n for (const doc of snapshot.docs.slice(0, request.rowCap)) {\n if (!byId.has(doc.id)) {\n byId.set(doc.id, { ...(doc.data() as Omit<PosHardwareTaxRowInput, 'orderId'>), orderId: doc.id })\n }\n }\n }\n return posHardwareTaxReturnAnswer(\n {\n rows: [...byId.values()],\n truncated: [paid, refunded, canceled].some((snapshot) => snapshot.size > request.rowCap),\n undatedRows: Number(undated.data().count ?? 0),\n },\n request,\n options,\n )\n}\n"],"names":["firebaseAdmin","PLATFORM_BRAND_NAME","centsToDollars","POS_HARDWARE_SALES_COLLECTION","posHardwareRefundStamp","posHardwareRowInPeriod","posHardwareTaxableBase","posHardwareTaxSummary","POS_HARDWARE_TAX_SECTION_ID","POS_HARDWARE_SHOP_PART_ID","POS_HARDWARE_IN_PERSON_PART_ID","posHardwareFoldedAs","row","options","source","host","posHostId","ownHostIds","has","posHardwareOperatorSales","rows","period","parts","id","label","foldedAs","flatMap","summary","filter","byJurisdiction","Object","fromEntries","entries","map","jurisdiction","figures","transactionCount","totalSalesCents","taxableSalesCents","taxCollectedCents","refundCount","refundedOrders","refundedSalesCents","refundedTaxCents","keys","length","isoOrNull","value","Date","toISOString","numberOrNull","Number","isFinite","textOrNull","emptyFigures","taxabilityReasons","rates","untaxedOrders","posHardwareFilingFigures","filing","code","posHardwareTaxFindings","operatorSales","brand","unread","find","part","severity","count","values","reduce","sum","detail","figuresName","attention","ordersMissingTaxableBase","ordersMissingShipTo","canceledWithoutRefund","posHardwareJurisdictionRows","isFilingJurisdiction","orders","sort","a","b","localeCompare","dollars","centsValue","posHardwareTables","description","columns","numeric","money","key","cells","text","tag","tone","caption","String","strong","empty","footnote","posHardwareFigures","note","excluded","testModeOrders","push","projectRow","placed","total","totalCents","tax","taxCents","orderId","paidAt","paidAtMs","status","state","shipTo","country","Array","isArray","taxLines","refundedCents","refundedAt","inPeriodAs","sale","refund","posHardwareExports","states","placement","posHardwareTaxReturnAnswer","read","request","start","end","seen","Set","livemode","add","name","title","help","intro","truncated","undatedRows","findings","filingLines","tables","exports","readPosHardwareTaxReturn","undated","collection","app","firestore","startMs","getTime","endMs","inRange","field","where","limit","rowCap","get","paid","refunded","canceled","Promise","all","byId","Map","snapshot","doc","docs","slice","set","data","some","size"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BC,GAED,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SAASC,mBA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_extends";
|
|
17
17
|
import { firebaseAdmin } from "@aglyn/tenant-data-admin";
|
|
18
|
-
import { decodePosHardwareLines, isPosHardwareShippingMethod, POS_HARDWARE_CURRENCY, POS_HARDWARE_METADATA_TYPE, POS_HARDWARE_ORDER_ID, POS_HARDWARE_SHIPPING_LABELS, posHardwareSaleRecord, posHardwareSaleSetOptions } from "../model/pos-hardware.js";
|
|
18
|
+
import { decodePosHardwareLines, isPosHardwareShippingMethod, POS_HARDWARE_CURRENCY, POS_HARDWARE_METADATA_TYPE, POS_HARDWARE_ORDER_ID, POS_HARDWARE_SHIPPING_LABELS, posHardwareOrderUnits, posHardwareSaleRecord, posHardwareSaleSetOptions } from "../model/pos-hardware.js";
|
|
19
|
+
import { posHardwareTermsFromMetadata } from "../model/pos-hardware-terms.js";
|
|
19
20
|
import { hardwareOrdersRef, posHardwareSaleRef } from "./pos-hardware.js";
|
|
20
21
|
import { raisePosHardwareOrderAlert, sendPosHardwareEmail } from "./pos-hardware-notify.js";
|
|
21
22
|
import { posStripe } from "./pos-stripe.js";
|
|
@@ -92,9 +93,13 @@ const cents = (value)=>{
|
|
|
92
93
|
const taxCents = cents(session == null ? void 0 : (_session_total_details = session.total_details) == null ? void 0 : _session_total_details.amount_tax);
|
|
93
94
|
const totalCents = (session == null ? void 0 : session.amount_total) != null ? cents(session.amount_total) : subtotalCents + shippingCents + taxCents;
|
|
94
95
|
const paymentIntent = session == null ? void 0 : session.payment_intent;
|
|
96
|
+
// The terms of sale and business use the buyer ticked on the Hardware card
|
|
97
|
+
// (AGL-4038), accepted when the session was made.
|
|
98
|
+
const createdMs = Number(session == null ? void 0 : session.created) > 0 ? Number(session.created) * 1000 : now;
|
|
99
|
+
const termsAcceptance = posHardwareTermsFromMetadata(metadata, createdMs);
|
|
95
100
|
return {
|
|
96
101
|
orderId,
|
|
97
|
-
order: {
|
|
102
|
+
order: _extends({
|
|
98
103
|
orgId,
|
|
99
104
|
hostId,
|
|
100
105
|
createdBy: String((_metadata_uid = metadata.uid) != null ? _metadata_uid : ''),
|
|
@@ -125,7 +130,15 @@ const cents = (value)=>{
|
|
|
125
130
|
createdAtMs: now,
|
|
126
131
|
updatedAtMs: now,
|
|
127
132
|
paidAtMs: now
|
|
128
|
-
}
|
|
133
|
+
}, termsAcceptance ? {
|
|
134
|
+
termsAcceptance
|
|
135
|
+
} : {}, {
|
|
136
|
+
// One per reader, for its serial when staff set it up before it ships.
|
|
137
|
+
units: posHardwareOrderUnits({
|
|
138
|
+
lines
|
|
139
|
+
}),
|
|
140
|
+
serialNumbers: []
|
|
141
|
+
})
|
|
129
142
|
};
|
|
130
143
|
}
|
|
131
144
|
/**
|