@aglyn/plugins-commerce 1.13.0 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +30 -6
- 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 +280 -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 +25 -5
- package/src/lib/components/product-detail.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 +24 -0
- package/src/lib/model/commerce-payment-methods.js +35 -0
- 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 +4 -6
- package/src/lib/server/billing-webhook.js +109 -51
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/cart-checkout.js +45 -10
- 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/checkout.js +58 -16
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/draft-order.js +7 -3
- package/src/lib/server/draft-order.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/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/quote-pay.js +8 -4
- package/src/lib/server/quote-pay.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/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
|
|
@@ -14,6 +15,7 @@
|
|
|
14
15
|
* See the License for the specific language governing permissions and
|
|
15
16
|
* limitations under the License.
|
|
16
17
|
*/ import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
|
|
18
|
+
import { findUserByEmailAcrossPools } from "@aglyn/tenant-data-admin/server/auth-pools";
|
|
17
19
|
import * as CommerceModel from "../model/index.js";
|
|
18
20
|
import { isPosHardwareSkuId, normalizePosHardwareSerial } from "../model/pos-hardware.js";
|
|
19
21
|
import { inPersonPosHardwareOrder, posHardwareRegisterShare } from "../model/pos-hardware-in-person.js";
|
|
@@ -21,6 +23,10 @@ import { hardwareOrdersRef, posHardwareInPersonConfig, posHardwareInPersonOrderI
|
|
|
21
23
|
import { recordPosHardwareOrder } from "./pos-hardware-webhook.js";
|
|
22
24
|
import { posStripeTestMode } from "./pos-stripe.js";
|
|
23
25
|
/** How many marked sales one sweep records at most. */ export const IN_PERSON_SWEEP_LIMIT = 25;
|
|
26
|
+
/** A paid online order's statuses once the store marked it shipped, which still record. */ const SHIPPED_ONLINE = new Set([
|
|
27
|
+
'fulfilled',
|
|
28
|
+
'partially_fulfilled'
|
|
29
|
+
]);
|
|
24
30
|
/** Statuses after which a marked sale can never be paid, so the mark is dropped. */ const NEVER_PAID = new Set([
|
|
25
31
|
'cancelled',
|
|
26
32
|
'canceled',
|
|
@@ -60,12 +66,21 @@ function registerOrderRef(hostId, orderId) {
|
|
|
60
66
|
const profile = await firestore().collection('profiles').doc(ownerUid).get();
|
|
61
67
|
return text(profile.get('stripeAccountId'));
|
|
62
68
|
}
|
|
69
|
+
/** Whether an account already uses this address; an unanswerable lookup reads as yes, so no stray sign-up invitation goes out. */ async function buyerHasAccount(email) {
|
|
70
|
+
try {
|
|
71
|
+
return Boolean(await findUserByEmailAcrossPools(email));
|
|
72
|
+
} catch (error) {
|
|
73
|
+
console.error('[pos-hardware-in-person] account lookup failed', error);
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
63
77
|
/**
|
|
64
|
-
* Records the hardware order of one
|
|
78
|
+
* Records the hardware order of one sale on the seller store, at its
|
|
79
|
+
* register or online (AGL-4038), once.
|
|
65
80
|
* Never throws for a sale that is not one: it says why it did nothing.
|
|
66
81
|
*/ export async function recordInPersonPosHardwareSale(hostId, registerOrderId, options = {}) {
|
|
67
|
-
var _ref, _ref1, _ref2, _ref3, _order_paidAtMs, _text,
|
|
68
|
-
var _order_totals, _order_totals1,
|
|
82
|
+
var _ref, _ref1, _ref2, _ref3, _ref4, _order_paidAtMs, _ref5, _order_shippingAddress, _text, _order_hardwareBuyer, _text1, _order_currency;
|
|
83
|
+
var _order_totals, _order_totals1, _order_totals2, _text2, _payments_find, _hardwareOrder_attachment, _hardwareOrder_attachment1;
|
|
69
84
|
const config = options.config === undefined ? posHardwareInPersonConfig() : options.config;
|
|
70
85
|
if (!config) return {
|
|
71
86
|
outcome: 'off'
|
|
@@ -79,9 +94,15 @@ function registerOrderRef(hostId, orderId) {
|
|
|
79
94
|
outcome: 'missing'
|
|
80
95
|
};
|
|
81
96
|
const order = snapshot.data();
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
97
|
+
// An order from the store's own product pages and cart (AGL-4038), rather
|
|
98
|
+
// than its register: it ships, and its buyer is whoever paid online. Its
|
|
99
|
+
// store order may already be marked fulfilled; it was paid all the same.
|
|
100
|
+
const online = order.channel === 'online';
|
|
101
|
+
if (order.status !== 'paid' && !(online && SHIPPED_ONLINE.has(String(order.status)))) {
|
|
102
|
+
return {
|
|
103
|
+
outcome: 'not-paid'
|
|
104
|
+
};
|
|
105
|
+
}
|
|
85
106
|
const lineItems = Array.isArray(order.lineItems) ? order.lineItems : [];
|
|
86
107
|
const productIds = [
|
|
87
108
|
...new Set(lineItems.map((line)=>{
|
|
@@ -102,11 +123,13 @@ function registerOrderRef(hostId, orderId) {
|
|
|
102
123
|
unitAmountCents: Number(line.unitAmountCents)
|
|
103
124
|
};
|
|
104
125
|
});
|
|
105
|
-
const share = posHardwareRegisterShare({
|
|
126
|
+
const share = posHardwareRegisterShare(_extends({
|
|
106
127
|
lines,
|
|
107
128
|
discountCents: Number((_ref = (_order_totals = order.totals) == null ? void 0 : _order_totals.discountCents) != null ? _ref : 0),
|
|
108
129
|
taxCents: Number((_ref1 = (_order_totals1 = order.totals) == null ? void 0 : _order_totals1.taxCents) != null ? _ref1 : 0)
|
|
109
|
-
}
|
|
130
|
+
}, online ? {
|
|
131
|
+
shippingCents: Number((_ref2 = (_order_totals2 = order.totals) == null ? void 0 : _order_totals2.shippingCents) != null ? _ref2 : 0)
|
|
132
|
+
} : {}));
|
|
110
133
|
if (!share) {
|
|
111
134
|
// Marked when it was rung, but no line is hardware now: nothing to record.
|
|
112
135
|
if (order.hardwareSalePending) {
|
|
@@ -127,8 +150,25 @@ function registerOrderRef(hostId, orderId) {
|
|
|
127
150
|
storeTax(hostId),
|
|
128
151
|
storeStripeAccount(hostId)
|
|
129
152
|
]);
|
|
130
|
-
const paidAtMs = Number((
|
|
131
|
-
const
|
|
153
|
+
const paidAtMs = Number((_ref3 = (_ref4 = (_order_paidAtMs = order.paidAtMs) != null ? _order_paidAtMs : order.createdAtMs) != null ? _ref4 : options.now) != null ? _ref3 : Date.now());
|
|
154
|
+
const receiptEmail = (_ref5 = (_text2 = text(order.customerEmail)) == null ? void 0 : _text2.toLowerCase()) != null ? _ref5 : null;
|
|
155
|
+
const shippingAddress = (_order_shippingAddress = order.shippingAddress) != null ? _order_shippingAddress : null;
|
|
156
|
+
const shipName = (_text = text(shippingAddress == null ? void 0 : shippingAddress.name)) != null ? _text : text(order.customerName);
|
|
157
|
+
// Online, the buyer is whoever paid: their address and name, to attach
|
|
158
|
+
// when they sign up or pair a reader, or by staff from To attach.
|
|
159
|
+
const buyer = online ? (_order_hardwareBuyer = order.hardwareBuyer) != null ? _order_hardwareBuyer : _extends({
|
|
160
|
+
uid: null,
|
|
161
|
+
orgId: null,
|
|
162
|
+
hostId: null,
|
|
163
|
+
email: receiptEmail,
|
|
164
|
+
attachedBy: '',
|
|
165
|
+
attachedAtMs: paidAtMs
|
|
166
|
+
}, shipName ? {
|
|
167
|
+
name: shipName
|
|
168
|
+
} : {}, shippingAddress ? {
|
|
169
|
+
address: shippingAddress
|
|
170
|
+
} : {}) : order.hardwareBuyer;
|
|
171
|
+
const hardwareOrder = inPersonPosHardwareOrder(_extends({
|
|
132
172
|
sellerHostId: config.sellerHostId,
|
|
133
173
|
sellerOrgId: config.sellerOrgId,
|
|
134
174
|
registerOrderId,
|
|
@@ -139,9 +179,9 @@ function registerOrderRef(hostId, orderId) {
|
|
|
139
179
|
share,
|
|
140
180
|
paidAtMs,
|
|
141
181
|
tenders: payments.map((payment)=>payment.method),
|
|
142
|
-
paymentLinkSessionId: (
|
|
143
|
-
receiptEmail
|
|
144
|
-
buyer
|
|
182
|
+
paymentLinkSessionId: (_text1 = text((_payments_find = payments.find((payment)=>payment.checkoutSessionId)) == null ? void 0 : _payments_find.checkoutSessionId)) != null ? _text1 : text(order.checkoutSessionId),
|
|
183
|
+
receiptEmail,
|
|
184
|
+
buyer,
|
|
145
185
|
termsAcceptance: order.hardwareTermsAcceptance,
|
|
146
186
|
serials: (Array.isArray(order.hardwareSerials) ? order.hardwareSerials : []).map(normalizePosHardwareSerial).filter(Boolean),
|
|
147
187
|
taxRegion: tax.region,
|
|
@@ -151,7 +191,13 @@ function registerOrderRef(hostId, orderId) {
|
|
|
151
191
|
// deployment's, so a test deployment's booth is never a real sale.
|
|
152
192
|
livemode: livemodes.length ? livemodes.every(Boolean) : !posStripeTestMode(),
|
|
153
193
|
currency: String((_order_currency = order.currency) != null ? _order_currency : 'usd').toLowerCase()
|
|
154
|
-
}
|
|
194
|
+
}, online ? {
|
|
195
|
+
storefront: {
|
|
196
|
+
name: shipName,
|
|
197
|
+
phone: text(order.customerPhone),
|
|
198
|
+
address: shippingAddress
|
|
199
|
+
}
|
|
200
|
+
} : {}));
|
|
155
201
|
const { created } = await recordPosHardwareOrder(orderId, hardwareOrder);
|
|
156
202
|
// The mark comes off once the order exists, by this call or an earlier one.
|
|
157
203
|
await orderRef.set({
|
|
@@ -160,10 +206,19 @@ function registerOrderRef(hostId, orderId) {
|
|
|
160
206
|
}, {
|
|
161
207
|
merge: true
|
|
162
208
|
});
|
|
209
|
+
if (created && online) {
|
|
210
|
+
// Staff prepare and ship it: the same alert a Hardware card order raises.
|
|
211
|
+
await (await import("./pos-hardware-notify.js")).raisePosHardwareOrderAlert(orderId, hardwareOrder);
|
|
212
|
+
}
|
|
163
213
|
// A buyer with no account, named at the register while the sale was open,
|
|
164
|
-
// is invited to sign up now that there is an order to point them at.
|
|
214
|
+
// is invited to sign up now that there is an order to point them at. One
|
|
215
|
+
// who paid online is invited only when no account has their address: one
|
|
216
|
+
// that does is attached by staff from To attach, or by pairing a reader.
|
|
165
217
|
if (created && ((_hardwareOrder_attachment = hardwareOrder.attachment) == null ? void 0 : _hardwareOrder_attachment.state) === 'pending' && hardwareOrder.attachment.email) {
|
|
166
|
-
|
|
218
|
+
const hasAccount = online && await buyerHasAccount(hardwareOrder.attachment.email);
|
|
219
|
+
if (!hasAccount) {
|
|
220
|
+
await (await import("./pos-hardware-attach.js")).invitePendingBuyer(orderId, hardwareOrder.orgId, hardwareOrder);
|
|
221
|
+
}
|
|
167
222
|
}
|
|
168
223
|
return {
|
|
169
224
|
outcome: created ? 'recorded' : 'already',
|
|
@@ -197,7 +252,7 @@ function registerOrderRef(hostId, orderId) {
|
|
|
197
252
|
});
|
|
198
253
|
continue;
|
|
199
254
|
}
|
|
200
|
-
if (status !== 'paid') continue;
|
|
255
|
+
if (status !== 'paid' && !SHIPPED_ONLINE.has(status)) continue;
|
|
201
256
|
const outcome = await recordInPersonPosHardwareSale(config.sellerHostId, String(doc.id), {
|
|
202
257
|
config
|
|
203
258
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-in-person.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport * as CommerceModel from '../model'\nimport {\n isPosHardwareSkuId,\n normalizePosHardwareSerial,\n type PosHardwareInPersonConfig,\n type PosHardwareOrder,\n type PosHardwareTaxRegion,\n} from '../model/pos-hardware'\nimport {\n inPersonPosHardwareOrder,\n posHardwareRegisterShare,\n type PosHardwareRegisterLine,\n} from '../model/pos-hardware-in-person'\nimport { hardwareOrdersRef, posHardwareInPersonConfig, posHardwareInPersonOrderId } from './pos-hardware'\nimport { recordPosHardwareOrder } from './pos-hardware-webhook'\nimport { posStripeTestMode } from './pos-stripe'\n\n/*==========================================\n * RECORDING A REGISTER SALE OF HARDWARE (AGL-4038).\n *\n * The platform's own store sells a card reader at its register; once the\n * sale is paid this writes the hardware order it becomes — attached to the\n * buyer's workspace when a register user attached one, PENDING on the\n * selling workspace's \"To attach\" list otherwise — and its retained sale\n * record, through the shop's own recorder.\n *\n * ONE SALE IS ONE ORDER. The order's id is derived from the register sale\n * (`posHardwareInPersonOrderId`) and the recorder writes it once by that id,\n * so the completion listener, a replayed webhook, an offline sync and the\n * sweep below can all reach the same sale and only the first writes.\n *\n * NOTHING IS LOST TO A FAILED LISTENER. Listeners on a completed sale are\n * logged and swallowed (the money is already taken), so the sale is marked\n * `hardwareSalePending` when it is written (`pos-hardware-sale-fields.ts`)\n * and the mark is cleared only once the order exists. The sweep records\n * every paid sale still marked, each time the To attach list is read.\n *=========================================*/\n\nexport type InPersonRecordOutcome =\n | { outcome: 'off' | 'not-seller' | 'missing' | 'not-paid' | 'no-hardware' }\n | { outcome: 'recorded' | 'already'; orderId: string; orgId: string; pending: boolean }\n\n/** How many marked sales one sweep records at most. */\nexport const IN_PERSON_SWEEP_LIMIT = 25\n\n/** Statuses after which a marked sale can never be paid, so the mark is dropped. */\nconst NEVER_PAID = new Set(['cancelled', 'canceled', 'voided', 'refunded', 'expired'])\n\nconst text = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() ? value.trim() : null\n\nfunction firestore() {\n return firebaseAdmin.app().firestore()\n}\n\nfunction registerOrderRef(hostId: string, orderId: string) {\n return firestore().collection('hosts').doc(hostId).collection('orders').doc(orderId)\n}\n\n/** Where the store taxes from, and its rate there, from its own tax settings. */\nasync function storeTax(hostId: string): Promise<{ region: PosHardwareTaxRegion | null; ratePct: number | null }> {\n const settings = await firestore().collection('hosts').doc(hostId).collection('settings').doc('store').get()\n const tax = (settings.get('tax') ?? {}) as CommerceModel.TaxSettings\n const origin = tax.origin ?? {}\n const country = text(origin.country)?.toUpperCase() ?? null\n const rate = country ? CommerceModel.resolveTaxRate(tax, origin) : null\n return {\n region: country ? { country, state: text(origin.state)?.toUpperCase() ?? null, postalCode: null } : null,\n ratePct: rate && Number.isFinite(rate.pct) ? rate.pct : null,\n }\n}\n\n/** The store owner's connected Stripe account, where the store's card money goes. */\nasync function storeStripeAccount(hostId: string): Promise<string | null> {\n const owner = await getOrgForHost(hostId).catch(() => null)\n const ownerUid = text((owner?.org as { ownerUid?: unknown } | undefined)?.ownerUid)\n if (!ownerUid) return null\n const profile = await firestore().collection('profiles').doc(ownerUid).get()\n return text(profile.get('stripeAccountId'))\n}\n\n/**\n * Records the hardware order of one register sale on the seller store, once.\n * Never throws for a sale that is not one: it says why it did nothing.\n */\nexport async function recordInPersonPosHardwareSale(\n hostId: string,\n registerOrderId: string,\n options: { offline?: boolean; config?: PosHardwareInPersonConfig | null; now?: number } = {},\n): Promise<InPersonRecordOutcome> {\n const config = options.config === undefined ? posHardwareInPersonConfig() : options.config\n if (!config) return { outcome: 'off' }\n if (hostId !== config.sellerHostId) return { outcome: 'not-seller' }\n const orderRef = registerOrderRef(hostId, registerOrderId)\n const snapshot = await orderRef.get()\n if (!snapshot.exists) return { outcome: 'missing' }\n const order = snapshot.data() as CommerceModel.HostOrder & {\n paidAtMs?: number\n checkoutSessionId?: string\n customerEmail?: string | null\n }\n if (order.status !== 'paid') return { outcome: 'not-paid' }\n\n const lineItems = Array.isArray(order.lineItems) ? order.lineItems : []\n const productIds = [...new Set(lineItems.map((line) => String(line.productId ?? '')).filter(Boolean))]\n const products = new Map(\n (\n await Promise.all(\n productIds.map((id) => firestore().collection('hosts').doc(hostId).collection('products').doc(id).get()),\n )\n ).map((doc: any) => [String(doc.id), doc.exists ? (doc.data() as CommerceModel.HostProduct) : null]),\n )\n const lines: PosHardwareRegisterLine[] = lineItems.map((line) => {\n const sku = products.get(String(line.productId))?.hardwareSku\n return {\n sku: isPosHardwareSkuId(sku) ? sku : null,\n quantity: Number(line.quantity),\n unitAmountCents: Number(line.unitAmountCents),\n }\n })\n const share = posHardwareRegisterShare({\n lines,\n discountCents: Number(order.totals?.discountCents ?? 0),\n taxCents: Number(order.totals?.taxCents ?? 0),\n })\n if (!share) {\n // Marked when it was rung, but no line is hardware now: nothing to record.\n if (order.hardwareSalePending) {\n await orderRef.set({ hardwareSalePending: firebaseAdmin.firestore.FieldValue.delete() }, { merge: true })\n }\n return { outcome: 'no-hardware' }\n }\n\n const orderId = posHardwareInPersonOrderId(hostId, registerOrderId)\n const payments = CommerceModel.orderPayments(order).filter((payment) => payment.status === 'succeeded')\n const livemodes = payments.map((payment) => payment.livemode).filter((mode): mode is boolean => typeof mode === 'boolean')\n const [tax, stripeAccountId] = await Promise.all([storeTax(hostId), storeStripeAccount(hostId)])\n const paidAtMs = Number(order.paidAtMs ?? order.createdAtMs ?? options.now ?? Date.now())\n const hardwareOrder: PosHardwareOrder = inPersonPosHardwareOrder({\n sellerHostId: config.sellerHostId,\n sellerOrgId: config.sellerOrgId,\n registerOrderId,\n number: Number.isFinite(Number(order.number)) ? Number(order.number) : null,\n registerId: text(order.registerId),\n kiosk: order.posSource === 'kiosk',\n offline: options.offline === true || Boolean((order as { offline?: unknown }).offline),\n share,\n paidAtMs,\n tenders: payments.map((payment) => payment.method),\n paymentLinkSessionId:\n text(payments.find((payment) => payment.checkoutSessionId)?.checkoutSessionId) ?? text(order.checkoutSessionId),\n receiptEmail: text(order.customerEmail)?.toLowerCase() ?? null,\n buyer: order.hardwareBuyer,\n termsAcceptance: order.hardwareTermsAcceptance,\n serials: (Array.isArray(order.hardwareSerials) ? order.hardwareSerials : [])\n .map(normalizePosHardwareSerial)\n .filter(Boolean),\n taxRegion: tax.region,\n ratePct: tax.ratePct,\n stripeAccountId,\n // A card payment says which mode it was in; a cash sale takes the\n // deployment's, so a test deployment's booth is never a real sale.\n livemode: livemodes.length ? livemodes.every(Boolean) : !posStripeTestMode(),\n currency: String((order as { currency?: unknown }).currency ?? 'usd').toLowerCase(),\n })\n\n const { created } = await recordPosHardwareOrder(orderId, hardwareOrder)\n // The mark comes off once the order exists, by this call or an earlier one.\n await orderRef.set(\n { hardwareOrderId: orderId, hardwareSalePending: firebaseAdmin.firestore.FieldValue.delete() },\n { merge: true },\n )\n // A buyer with no account, named at the register while the sale was open,\n // is invited to sign up now that there is an order to point them at.\n if (created && hardwareOrder.attachment?.state === 'pending' && hardwareOrder.attachment.email) {\n await (await import('./pos-hardware-attach')).invitePendingBuyer(orderId, hardwareOrder.orgId, hardwareOrder)\n }\n return {\n outcome: created ? 'recorded' : 'already',\n orderId,\n orgId: hardwareOrder.orgId,\n pending: hardwareOrder.attachment?.state === 'pending',\n }\n}\n\n/**\n * Records every paid sale on the seller store that is still marked, at most\n * {@link IN_PERSON_SWEEP_LIMIT} a time, and drops the mark from a sale that\n * can no longer be paid. Never throws: a sale it cannot record stays marked\n * for the next sweep.\n */\nexport async function sweepInPersonPosHardwareSales(\n config: PosHardwareInPersonConfig | null = posHardwareInPersonConfig(),\n): Promise<{ recorded: number; failed: number }> {\n if (!config) return { recorded: 0, failed: 0 }\n const marked = await firestore()\n .collection('hosts')\n .doc(config.sellerHostId)\n .collection('orders')\n .where('hardwareSalePending', '==', true)\n .limit(IN_PERSON_SWEEP_LIMIT)\n .get()\n let recorded = 0\n let failed = 0\n for (const doc of marked.docs as Array<{ id: string; ref: any; get: (field: string) => unknown }>) {\n const status = String(doc.get('status') ?? '')\n try {\n if (NEVER_PAID.has(status)) {\n await doc.ref.set({ hardwareSalePending: firebaseAdmin.firestore.FieldValue.delete() }, { merge: true })\n continue\n }\n if (status !== 'paid') continue\n const outcome = await recordInPersonPosHardwareSale(config.sellerHostId, String(doc.id), { config })\n if (outcome.outcome === 'recorded') recorded += 1\n } catch (error) {\n failed += 1\n console.error('[pos-hardware-in-person] a marked sale could not be recorded', doc.id, error)\n }\n }\n return { recorded, failed }\n}\n\n/** The \"To attach\" list: the selling workspace's pending in-person orders, newest first. */\nexport async function pendingInPersonPosHardwareOrders(\n config: PosHardwareInPersonConfig,\n limit = 50,\n): Promise<Array<{ id: string; order: PosHardwareOrder }>> {\n const snapshot = await hardwareOrdersRef(config.sellerOrgId)\n .where('attachment.state', '==', 'pending')\n .orderBy('createdAtMs', 'desc')\n .limit(limit)\n .get()\n return snapshot.docs.map((doc: any) => ({ id: String(doc.id), order: doc.data() as PosHardwareOrder }))\n}\n\n/**\n * What the completion listener runs for a sale on the seller store. Never\n * throws into a sale: a failure is logged and the sale stays marked for the\n * sweep.\n */\nexport async function recordCompletedSaleHardware(event: {\n hostId: string\n orderId: string\n offline?: boolean\n}): Promise<void> {\n try {\n await recordInPersonPosHardwareSale(event.hostId, event.orderId, { offline: event.offline === true })\n } catch (error) {\n console.error('[pos-hardware-in-person] sale not recorded; the sweep will', event.orderId, error)\n }\n}\n"],"names":["firebaseAdmin","getOrgForHost","CommerceModel","isPosHardwareSkuId","normalizePosHardwareSerial","inPersonPosHardwareOrder","posHardwareRegisterShare","hardwareOrdersRef","posHardwareInPersonConfig","posHardwareInPersonOrderId","recordPosHardwareOrder","posStripeTestMode","IN_PERSON_SWEEP_LIMIT","NEVER_PAID","Set","text","value","trim","firestore","app","registerOrderRef","hostId","orderId","collection","doc","storeTax","settings","tax","get","origin","country","toUpperCase","rate","resolveTaxRate","region","state","postalCode","ratePct","Number","isFinite","pct","storeStripeAccount","owner","catch","ownerUid","org","profile","recordInPersonPosHardwareSale","registerOrderId","options","order","payments","hardwareOrder","config","undefined","outcome","sellerHostId","orderRef","snapshot","exists","data","status","lineItems","Array","isArray","productIds","map","line","String","productId","filter","Boolean","products","Map","Promise","all","id","lines","sku","hardwareSku","quantity","unitAmountCents","share","discountCents","totals","taxCents","hardwareSalePending","set","FieldValue","delete","merge","orderPayments","payment","livemodes","livemode","mode","stripeAccountId","paidAtMs","createdAtMs","now","Date","sellerOrgId","number","registerId","kiosk","posSource","offline","tenders","method","paymentLinkSessionId","find","checkoutSessionId","receiptEmail","customerEmail","toLowerCase","buyer","hardwareBuyer","termsAcceptance","hardwareTermsAcceptance","serials","hardwareSerials","taxRegion","length","every","currency","created","hardwareOrderId","attachment","email","invitePendingBuyer","orgId","pending","sweepInPersonPosHardwareSales","recorded","failed","marked","where","limit","docs","has","ref","error","console","pendingInPersonPosHardwareOrders","orderBy","recordCompletedSaleHardware","event"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,EAAEC,aAAa,QAAQ,2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AAI;QAAuB,CAAA;AACtG;AAEA;;;;CAIC,GACD,OAAO,eAAeqF,4BAA4BC,KAIjD;IACC,IAAI;QACF,MAAMnG,8BAA8BmG,MAAM7H,MAAM,EAAE6H,MAAM5H,OAAO,EAAE;YAAEoF,SAASwC,MAAMxC,OAAO,KAAK;QAAK;IACrG,EAAE,OAAOmC,OAAO;QACdC,QAAQD,KAAK,CAAC,8DAA8DK,MAAM5H,OAAO,EAAEuH;IAC7F;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-in-person.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { findUserByEmailAcrossPools } from '@aglyn/tenant-data-admin/server/auth-pools'\nimport * as CommerceModel from '../model'\nimport {\n isPosHardwareSkuId,\n normalizePosHardwareSerial,\n type PosHardwareInPersonConfig,\n type PosHardwareOrder,\n type PosHardwareTaxRegion,\n} from '../model/pos-hardware'\nimport {\n inPersonPosHardwareOrder,\n posHardwareRegisterShare,\n type PosHardwareRegisterLine,\n} from '../model/pos-hardware-in-person'\nimport { hardwareOrdersRef, posHardwareInPersonConfig, posHardwareInPersonOrderId } from './pos-hardware'\nimport { recordPosHardwareOrder } from './pos-hardware-webhook'\nimport { posStripeTestMode } from './pos-stripe'\n\n/*==========================================\n * RECORDING A REGISTER SALE OF HARDWARE (AGL-4038).\n *\n * The platform's own store sells a card reader at its register; once the\n * sale is paid this writes the hardware order it becomes — attached to the\n * buyer's workspace when a register user attached one, PENDING on the\n * selling workspace's \"To attach\" list otherwise — and its retained sale\n * record, through the shop's own recorder.\n *\n * ONE SALE IS ONE ORDER. The order's id is derived from the register sale\n * (`posHardwareInPersonOrderId`) and the recorder writes it once by that id,\n * so the completion listener, a replayed webhook, an offline sync and the\n * sweep below can all reach the same sale and only the first writes.\n *\n * NOTHING IS LOST TO A FAILED LISTENER. Listeners on a completed sale are\n * logged and swallowed (the money is already taken), so the sale is marked\n * `hardwareSalePending` when it is written (`pos-hardware-sale-fields.ts`)\n * and the mark is cleared only once the order exists. The sweep records\n * every paid sale still marked, each time the To attach list is read.\n *=========================================*/\n\nexport type InPersonRecordOutcome =\n | { outcome: 'off' | 'not-seller' | 'missing' | 'not-paid' | 'no-hardware' }\n | { outcome: 'recorded' | 'already'; orderId: string; orgId: string; pending: boolean }\n\n/** How many marked sales one sweep records at most. */\nexport const IN_PERSON_SWEEP_LIMIT = 25\n\n/** A paid online order's statuses once the store marked it shipped, which still record. */\nconst SHIPPED_ONLINE = new Set(['fulfilled', 'partially_fulfilled'])\n\n/** Statuses after which a marked sale can never be paid, so the mark is dropped. */\nconst NEVER_PAID = new Set(['cancelled', 'canceled', 'voided', 'refunded', 'expired'])\n\nconst text = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() ? value.trim() : null\n\nfunction firestore() {\n return firebaseAdmin.app().firestore()\n}\n\nfunction registerOrderRef(hostId: string, orderId: string) {\n return firestore().collection('hosts').doc(hostId).collection('orders').doc(orderId)\n}\n\n/** Where the store taxes from, and its rate there, from its own tax settings. */\nasync function storeTax(hostId: string): Promise<{ region: PosHardwareTaxRegion | null; ratePct: number | null }> {\n const settings = await firestore().collection('hosts').doc(hostId).collection('settings').doc('store').get()\n const tax = (settings.get('tax') ?? {}) as CommerceModel.TaxSettings\n const origin = tax.origin ?? {}\n const country = text(origin.country)?.toUpperCase() ?? null\n const rate = country ? CommerceModel.resolveTaxRate(tax, origin) : null\n return {\n region: country ? { country, state: text(origin.state)?.toUpperCase() ?? null, postalCode: null } : null,\n ratePct: rate && Number.isFinite(rate.pct) ? rate.pct : null,\n }\n}\n\n/** The store owner's connected Stripe account, where the store's card money goes. */\nasync function storeStripeAccount(hostId: string): Promise<string | null> {\n const owner = await getOrgForHost(hostId).catch(() => null)\n const ownerUid = text((owner?.org as { ownerUid?: unknown } | undefined)?.ownerUid)\n if (!ownerUid) return null\n const profile = await firestore().collection('profiles').doc(ownerUid).get()\n return text(profile.get('stripeAccountId'))\n}\n\n/** Whether an account already uses this address; an unanswerable lookup reads as yes, so no stray sign-up invitation goes out. */\nasync function buyerHasAccount(email: string): Promise<boolean> {\n try {\n return Boolean(await findUserByEmailAcrossPools(email))\n } catch (error) {\n console.error('[pos-hardware-in-person] account lookup failed', error)\n return true\n }\n}\n\n/**\n * Records the hardware order of one sale on the seller store, at its\n * register or online (AGL-4038), once.\n * Never throws for a sale that is not one: it says why it did nothing.\n */\nexport async function recordInPersonPosHardwareSale(\n hostId: string,\n registerOrderId: string,\n options: { offline?: boolean; config?: PosHardwareInPersonConfig | null; now?: number } = {},\n): Promise<InPersonRecordOutcome> {\n const config = options.config === undefined ? posHardwareInPersonConfig() : options.config\n if (!config) return { outcome: 'off' }\n if (hostId !== config.sellerHostId) return { outcome: 'not-seller' }\n const orderRef = registerOrderRef(hostId, registerOrderId)\n const snapshot = await orderRef.get()\n if (!snapshot.exists) return { outcome: 'missing' }\n const order = snapshot.data() as CommerceModel.HostOrder & {\n paidAtMs?: number\n checkoutSessionId?: string\n customerEmail?: string | null\n }\n // An order from the store's own product pages and cart (AGL-4038), rather\n // than its register: it ships, and its buyer is whoever paid online. Its\n // store order may already be marked fulfilled; it was paid all the same.\n const online = order.channel === 'online'\n if (order.status !== 'paid' && !(online && SHIPPED_ONLINE.has(String(order.status)))) {\n return { outcome: 'not-paid' }\n }\n\n const lineItems = Array.isArray(order.lineItems) ? order.lineItems : []\n const productIds = [...new Set(lineItems.map((line) => String(line.productId ?? '')).filter(Boolean))]\n const products = new Map(\n (\n await Promise.all(\n productIds.map((id) => firestore().collection('hosts').doc(hostId).collection('products').doc(id).get()),\n )\n ).map((doc: any) => [String(doc.id), doc.exists ? (doc.data() as CommerceModel.HostProduct) : null]),\n )\n const lines: PosHardwareRegisterLine[] = lineItems.map((line) => {\n const sku = products.get(String(line.productId))?.hardwareSku\n return {\n sku: isPosHardwareSkuId(sku) ? sku : null,\n quantity: Number(line.quantity),\n unitAmountCents: Number(line.unitAmountCents),\n }\n })\n const share = posHardwareRegisterShare({\n lines,\n discountCents: Number(order.totals?.discountCents ?? 0),\n taxCents: Number(order.totals?.taxCents ?? 0),\n ...(online ? { shippingCents: Number(order.totals?.shippingCents ?? 0) } : {}),\n })\n if (!share) {\n // Marked when it was rung, but no line is hardware now: nothing to record.\n if (order.hardwareSalePending) {\n await orderRef.set({ hardwareSalePending: firebaseAdmin.firestore.FieldValue.delete() }, { merge: true })\n }\n return { outcome: 'no-hardware' }\n }\n\n const orderId = posHardwareInPersonOrderId(hostId, registerOrderId)\n const payments = CommerceModel.orderPayments(order).filter((payment) => payment.status === 'succeeded')\n const livemodes = payments.map((payment) => payment.livemode).filter((mode): mode is boolean => typeof mode === 'boolean')\n const [tax, stripeAccountId] = await Promise.all([storeTax(hostId), storeStripeAccount(hostId)])\n const paidAtMs = Number(order.paidAtMs ?? order.createdAtMs ?? options.now ?? Date.now())\n const receiptEmail = text(order.customerEmail)?.toLowerCase() ?? null\n const shippingAddress = order.shippingAddress ?? null\n const shipName = text(shippingAddress?.name) ?? text(order.customerName)\n // Online, the buyer is whoever paid: their address and name, to attach\n // when they sign up or pair a reader, or by staff from To attach.\n const buyer = online\n ? (order.hardwareBuyer ?? {\n uid: null,\n orgId: null,\n hostId: null,\n email: receiptEmail,\n attachedBy: '',\n attachedAtMs: paidAtMs,\n ...(shipName ? { name: shipName } : {}),\n ...(shippingAddress ? { address: shippingAddress as never } : {}),\n })\n : order.hardwareBuyer\n const hardwareOrder: PosHardwareOrder = inPersonPosHardwareOrder({\n sellerHostId: config.sellerHostId,\n sellerOrgId: config.sellerOrgId,\n registerOrderId,\n number: Number.isFinite(Number(order.number)) ? Number(order.number) : null,\n registerId: text(order.registerId),\n kiosk: order.posSource === 'kiosk',\n offline: options.offline === true || Boolean((order as { offline?: unknown }).offline),\n share,\n paidAtMs,\n tenders: payments.map((payment) => payment.method),\n paymentLinkSessionId:\n text(payments.find((payment) => payment.checkoutSessionId)?.checkoutSessionId) ?? text(order.checkoutSessionId),\n receiptEmail,\n buyer,\n termsAcceptance: order.hardwareTermsAcceptance,\n serials: (Array.isArray(order.hardwareSerials) ? order.hardwareSerials : [])\n .map(normalizePosHardwareSerial)\n .filter(Boolean),\n taxRegion: tax.region,\n ratePct: tax.ratePct,\n stripeAccountId,\n // A card payment says which mode it was in; a cash sale takes the\n // deployment's, so a test deployment's booth is never a real sale.\n livemode: livemodes.length ? livemodes.every(Boolean) : !posStripeTestMode(),\n currency: String((order as { currency?: unknown }).currency ?? 'usd').toLowerCase(),\n ...(online\n ? { storefront: { name: shipName, phone: text(order.customerPhone), address: shippingAddress } }\n : {}),\n })\n\n const { created } = await recordPosHardwareOrder(orderId, hardwareOrder)\n // The mark comes off once the order exists, by this call or an earlier one.\n await orderRef.set(\n { hardwareOrderId: orderId, hardwareSalePending: firebaseAdmin.firestore.FieldValue.delete() },\n { merge: true },\n )\n if (created && online) {\n // Staff prepare and ship it: the same alert a Hardware card order raises.\n await (await import('./pos-hardware-notify')).raisePosHardwareOrderAlert(orderId, hardwareOrder)\n }\n // A buyer with no account, named at the register while the sale was open,\n // is invited to sign up now that there is an order to point them at. One\n // who paid online is invited only when no account has their address: one\n // that does is attached by staff from To attach, or by pairing a reader.\n if (created && hardwareOrder.attachment?.state === 'pending' && hardwareOrder.attachment.email) {\n const hasAccount = online && (await buyerHasAccount(hardwareOrder.attachment.email))\n if (!hasAccount) {\n await (await import('./pos-hardware-attach')).invitePendingBuyer(orderId, hardwareOrder.orgId, hardwareOrder)\n }\n }\n return {\n outcome: created ? 'recorded' : 'already',\n orderId,\n orgId: hardwareOrder.orgId,\n pending: hardwareOrder.attachment?.state === 'pending',\n }\n}\n\n/**\n * Records every paid sale on the seller store that is still marked, at most\n * {@link IN_PERSON_SWEEP_LIMIT} a time, and drops the mark from a sale that\n * can no longer be paid. Never throws: a sale it cannot record stays marked\n * for the next sweep.\n */\nexport async function sweepInPersonPosHardwareSales(\n config: PosHardwareInPersonConfig | null = posHardwareInPersonConfig(),\n): Promise<{ recorded: number; failed: number }> {\n if (!config) return { recorded: 0, failed: 0 }\n const marked = await firestore()\n .collection('hosts')\n .doc(config.sellerHostId)\n .collection('orders')\n .where('hardwareSalePending', '==', true)\n .limit(IN_PERSON_SWEEP_LIMIT)\n .get()\n let recorded = 0\n let failed = 0\n for (const doc of marked.docs as Array<{ id: string; ref: any; get: (field: string) => unknown }>) {\n const status = String(doc.get('status') ?? '')\n try {\n if (NEVER_PAID.has(status)) {\n await doc.ref.set({ hardwareSalePending: firebaseAdmin.firestore.FieldValue.delete() }, { merge: true })\n continue\n }\n if (status !== 'paid' && !SHIPPED_ONLINE.has(status)) continue\n const outcome = await recordInPersonPosHardwareSale(config.sellerHostId, String(doc.id), { config })\n if (outcome.outcome === 'recorded') recorded += 1\n } catch (error) {\n failed += 1\n console.error('[pos-hardware-in-person] a marked sale could not be recorded', doc.id, error)\n }\n }\n return { recorded, failed }\n}\n\n/** The \"To attach\" list: the selling workspace's pending in-person orders, newest first. */\nexport async function pendingInPersonPosHardwareOrders(\n config: PosHardwareInPersonConfig,\n limit = 50,\n): Promise<Array<{ id: string; order: PosHardwareOrder }>> {\n const snapshot = await hardwareOrdersRef(config.sellerOrgId)\n .where('attachment.state', '==', 'pending')\n .orderBy('createdAtMs', 'desc')\n .limit(limit)\n .get()\n return snapshot.docs.map((doc: any) => ({ id: String(doc.id), order: doc.data() as PosHardwareOrder }))\n}\n\n/**\n * What the completion listener runs for a sale on the seller store. Never\n * throws into a sale: a failure is logged and the sale stays marked for the\n * sweep.\n */\nexport async function recordCompletedSaleHardware(event: {\n hostId: string\n orderId: string\n offline?: boolean\n}): Promise<void> {\n try {\n await recordInPersonPosHardwareSale(event.hostId, event.orderId, { offline: event.offline === true })\n } catch (error) {\n console.error('[pos-hardware-in-person] sale not recorded; the sweep will', event.orderId, error)\n }\n}\n"],"names":["firebaseAdmin","getOrgForHost","findUserByEmailAcrossPools","CommerceModel","isPosHardwareSkuId","normalizePosHardwareSerial","inPersonPosHardwareOrder","posHardwareRegisterShare","hardwareOrdersRef","posHardwareInPersonConfig","posHardwareInPersonOrderId","recordPosHardwareOrder","posStripeTestMode","IN_PERSON_SWEEP_LIMIT","SHIPPED_ONLINE","Set","NEVER_PAID","text","value","trim","firestore","app","registerOrderRef","hostId","orderId","collection","doc","storeTax","settings","tax","get","origin","country","toUpperCase","rate","resolveTaxRate","region","state","postalCode","ratePct","Number","isFinite","pct","storeStripeAccount","owner","catch","ownerUid","org","profile","buyerHasAccount","email","Boolean","error","console","recordInPersonPosHardwareSale","registerOrderId","options","order","payments","hardwareOrder","config","undefined","outcome","sellerHostId","orderRef","snapshot","exists","data","online","channel","status","has","String","lineItems","Array","isArray","productIds","map","line","productId","filter","products","Map","Promise","all","id","lines","sku","hardwareSku","quantity","unitAmountCents","share","discountCents","totals","taxCents","shippingCents","hardwareSalePending","set","FieldValue","delete","merge","orderPayments","payment","livemodes","livemode","mode","stripeAccountId","paidAtMs","createdAtMs","now","Date","receiptEmail","customerEmail","toLowerCase","shippingAddress","shipName","name","customerName","buyer","hardwareBuyer","uid","orgId","attachedBy","attachedAtMs","address","sellerOrgId","number","registerId","kiosk","posSource","offline","tenders","method","paymentLinkSessionId","find","checkoutSessionId","termsAcceptance","hardwareTermsAcceptance","serials","hardwareSerials","taxRegion","length","every","currency","storefront","phone","customerPhone","created","hardwareOrderId","raisePosHardwareOrderAlert","attachment","hasAccount","invitePendingBuyer","pending","sweepInPersonPosHardwareSales","recorded","failed","marked","where","limit","docs","ref","pendingInPersonPosHardw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;AAC5B;AAEA,0FAA0F,GAC1F,OAAO,eAAeM,iCACpBtG,MAAiC,EACjCmG,QAAQ,EAAE;IAEV,MAAM9F,WAAW,MAAMzD,kBAAkBoD,OAAOiE,WAAW,EACxDiC,KAAK,CAAC,oBAAoB,MAAM,WAChCK,OAAO,CAAC,eAAe,QACvBJ,KAAK,CAACA,OACNjI,GAAG;IACN,OAAOmC,SAAS+F,IAAI,CAACnF,GAAG,CAAC,CAACnD,MAAc,CAAA;YAAE2D,IAAIb,OAAO9C,IAAI2D,EAAE;YAAG5B,OAAO/B,IAAIyC,IAAI;QAAuB,CAAA;AACtG;AAEA;;;;CAIC,GACD,OAAO,eAAeiG,4BAA4BC,KAIjD;IACC,IAAI;QACF,MAAM/G,8BAA8B+G,MAAM9I,MAAM,EAAE8I,MAAM7I,OAAO,EAAE;YAAE0G,SAASmC,MAAMnC,OAAO,KAAK;QAAK;IACrG,EAAE,OAAO9E,OAAO;QACdC,QAAQD,KAAK,CAAC,8DAA8DiH,MAAM7I,OAAO,EAAE4B;IAC7F;AACF"}
|
|
@@ -17,6 +17,8 @@
|
|
|
17
17
|
import { POS_HARDWARE_EMAIL_KEYS } from '@aglyn/shared-util-email';
|
|
18
18
|
import { type PosHardwareCancelReason, type PosHardwareOrder } from '../model/pos-hardware';
|
|
19
19
|
export type PosHardwareEmailKind = keyof typeof POS_HARDWARE_EMAIL_KEYS;
|
|
20
|
+
/** The steps the delivered email gives: pair the reader, or it is already set up. */
|
|
21
|
+
export declare function posHardwareSetupSteps(order: Pick<PosHardwareOrder, 'units' | 'lines'>): string;
|
|
20
22
|
/** The merge values for one order's emails. Exported for the render spec. */
|
|
21
23
|
export declare function posHardwareEmailMerge(orderId: string, order: PosHardwareOrder, names: {
|
|
22
24
|
site: string;
|
|
@@ -23,7 +23,7 @@ import { filterSuppressedEmails } from "@aglyn/tenant-data-admin/server/email-su
|
|
|
23
23
|
import { orgSystemEmailBrand, renderSystemEmailContent } from "@aglyn/tenant-data-admin/server/render-system-email";
|
|
24
24
|
import { COMMERCE_POS_HARDWARE_CANCELED_AFTER_ORDERING, COMMERCE_POS_HARDWARE_ORDER, COMMERCE_POS_HARDWARE_REFUND_FAILED } from "../constants/operator-alerts.js";
|
|
25
25
|
import { carrierLabelFor } from "../model/tracking-url.js";
|
|
26
|
-
import { formatPosHardwareCents, POS_HARDWARE_ANCHOR } from "../model/pos-hardware.js";
|
|
26
|
+
import { formatPosHardwareCents, POS_HARDWARE_ANCHOR, posHardwareOrderUnits } from "../model/pos-hardware.js";
|
|
27
27
|
import { hardwareOrdersRef, posHardwareOrderNumber, posSettingsUrl } from "./pos-hardware.js";
|
|
28
28
|
/** The lines as the emails list them, one per item. */ function itemsText(order) {
|
|
29
29
|
var _order_lines;
|
|
@@ -48,7 +48,19 @@ function shipToText(order) {
|
|
|
48
48
|
}
|
|
49
49
|
async function siteAndOrgNames(order) {
|
|
50
50
|
var _ref;
|
|
51
|
+
var _order_attachment, _order_posSale;
|
|
51
52
|
const firestore = firebaseAdmin.app().firestore();
|
|
53
|
+
// Bought from the platform's own store and not yet in the buyer's
|
|
54
|
+
// workspace (AGL-4038): it is for their business, which has no workspace
|
|
55
|
+
// here yet, and the selling store's name says where it came from.
|
|
56
|
+
if (((_order_attachment = order.attachment) == null ? void 0 : _order_attachment.state) === 'pending' && ((_order_posSale = order.posSale) == null ? void 0 : _order_posSale.hostId)) {
|
|
57
|
+
const seller = await firestore.collection('hosts').doc(order.posSale.hostId).get().catch(()=>null);
|
|
58
|
+
return {
|
|
59
|
+
site: (seller == null ? void 0 : seller.exists) ? hostDisplayName(seller.data(), order.posSale.hostId) : 'our store',
|
|
60
|
+
org: PENDING_BUYER,
|
|
61
|
+
ban: false
|
|
62
|
+
};
|
|
63
|
+
}
|
|
52
64
|
const [host, org] = await Promise.all([
|
|
53
65
|
firestore.collection('hosts').doc(order.hostId).get().catch(()=>null),
|
|
54
66
|
firestore.collection('orgs').doc(order.orgId).get().catch(()=>null)
|
|
@@ -70,6 +82,7 @@ async function siteAndOrgNames(order) {
|
|
|
70
82
|
returnRefunded: (number)=>`We refunded your returned card reader order ${number}`
|
|
71
83
|
};
|
|
72
84
|
/** The fallback a workspace with no name gets in a sentence. */ const UNNAMED_WORKSPACE = 'your workspace';
|
|
85
|
+
/** Who a sale not yet in anyone's workspace is for, in a sentence. */ const PENDING_BUYER = 'your business';
|
|
73
86
|
/**
|
|
74
87
|
* Who canceled the order and why, as the email's first sentence; the
|
|
75
88
|
* template goes on "It had not shipped yet, so we refunded …".
|
|
@@ -85,12 +98,21 @@ async function siteAndOrgNames(order) {
|
|
|
85
98
|
if (reason === 'account-closed') return 'the account that placed it was closed';
|
|
86
99
|
return 'staff canceled it';
|
|
87
100
|
}
|
|
101
|
+
/** The steps the delivered email gives: pair the reader, or it is already set up. */ export function posHardwareSetupSteps(order) {
|
|
102
|
+
const units = posHardwareOrderUnits(order);
|
|
103
|
+
if (units.length && units.every((unit)=>unit.readerId)) {
|
|
104
|
+
return 'We set your reader up on your store before it shipped.\n' + '1. Charge it and switch it on.\n' + '2. Connect it to Wi-Fi from the reader’s Settings.\n' + '3. It shows on the POS devices card, ready for a register.';
|
|
105
|
+
}
|
|
106
|
+
return '1. Charge it and switch it on.\n' + '2. Connect it to Wi-Fi from the reader’s Settings.\n' + '3. On the reader, generate a pairing code.\n' + '4. On the POS devices card, choose Add card reader and enter the code.';
|
|
107
|
+
}
|
|
88
108
|
/** The merge values for one order's emails. Exported for the render spec. */ export async function posHardwareEmailMerge(orderId, order, names) {
|
|
89
109
|
var _order_totalCents, _ref, _ref1, _ref2, _ref3, _order_refundedCents, _ref4, _ref5, _ref6, _order_refunds, _order_totalCents1, _order_refundedCents1;
|
|
90
110
|
var _order_shipping, _order_tracking, _order_tracking1, _order_tracking2, _slice_;
|
|
91
|
-
|
|
111
|
+
// An order with no store yet (AGL-4038) has no settings page to link: the
|
|
112
|
+
// console's front door, where signing in or up leads to it.
|
|
113
|
+
const base = order.hostId ? await posSettingsUrl(order.hostId) : platformConsoleOrigin();
|
|
92
114
|
const [path] = base.split('#');
|
|
93
|
-
const ordersUrl = `${path}#${POS_HARDWARE_ANCHOR}
|
|
115
|
+
const ordersUrl = order.hostId ? `${path}#${POS_HARDWARE_ANCHOR}` : path;
|
|
94
116
|
return {
|
|
95
117
|
'org.name': names.org,
|
|
96
118
|
'site.name': names.site,
|
|
@@ -104,7 +126,10 @@ async function siteAndOrgNames(order) {
|
|
|
104
126
|
// An unknown carrier has no tracker to link; the card shows the number.
|
|
105
127
|
'order.trackingUrl': (_ref2 = (_order_tracking2 = order.tracking) == null ? void 0 : _order_tracking2.url) != null ? _ref2 : ordersUrl,
|
|
106
128
|
'order.ordersUrl': ordersUrl,
|
|
107
|
-
'order.setupUrl': `${path}#pos-devices
|
|
129
|
+
'order.setupUrl': order.hostId ? `${path}#pos-devices` : path,
|
|
130
|
+
// What arrived: readers registered to the store before they shipped
|
|
131
|
+
// (AGL-4038) only need power and Wi-Fi; any other is paired by its code.
|
|
132
|
+
'order.setupSteps': posHardwareSetupSteps(order),
|
|
108
133
|
// What Stripe reported refunding, or the whole charge where it has not.
|
|
109
134
|
'order.refunded': formatPosHardwareCents((_ref3 = (_order_refundedCents = order.refundedCents) != null ? _order_refundedCents : order.totalCents) != null ? _ref3 : 0),
|
|
110
135
|
// This refund alone, for an order refunded in parts; the whole of it otherwise.
|
|
@@ -291,7 +316,7 @@ export async function sendPosHardwareInvite(orderId, order) {
|
|
|
291
316
|
reason: staffReasonText(reason, order.orgId),
|
|
292
317
|
error: error || 'no reason given',
|
|
293
318
|
paymentIntentId: (_order_stripePaymentIntentId = order.stripePaymentIntentId) != null ? _order_stripePaymentIntentId : 'for this order (no payment id is recorded on it)',
|
|
294
|
-
orderedNote: order.status === 'ordered' ? `. It had already been placed with Stripe${stripeOrderId ? ` as ${stripeOrderId}` : ''}, so cancel it there too before it ships` : ''
|
|
319
|
+
orderedNote: order.status === 'ordered' || order.status === 'received' ? `. It had already been placed with Stripe${stripeOrderId ? ` as ${stripeOrderId}` : ''}, so cancel it there too before it ships` : ''
|
|
295
320
|
}
|
|
296
321
|
});
|
|
297
322
|
} catch (failure) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-notify.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 { formatOperatorAlertAmount } from '@aglyn/aglyn/app-utils/operator-alerts'\nimport {\n isAccountBanLockdownReason,\n normalizeOrgLockdown,\n} from '@aglyn/aglyn/app-utils/lockdown'\nimport { POS_HARDWARE_EMAIL_KEYS, sendEmail } from '@aglyn/shared-util-email'\nimport { platformConsoleOrigin } from '@aglyn/aglyn/app-utils/platform-brand'\nimport {\n firebaseAdmin,\n hostDisplayName,\n meterPlatformEmail,\n raiseOperatorAlert,\n} from '@aglyn/tenant-data-admin'\nimport { filterSuppressedEmails } from '@aglyn/tenant-data-admin/server/email-suppression'\nimport {\n orgSystemEmailBrand,\n renderSystemEmailContent,\n} from '@aglyn/tenant-data-admin/server/render-system-email'\nimport {\n COMMERCE_POS_HARDWARE_CANCELED_AFTER_ORDERING,\n COMMERCE_POS_HARDWARE_ORDER,\n COMMERCE_POS_HARDWARE_REFUND_FAILED,\n} from '../constants/operator-alerts'\nimport { carrierLabelFor } from '../model/tracking-url'\nimport {\n formatPosHardwareCents,\n POS_HARDWARE_ANCHOR,\n type PosHardwareCancelReason,\n type PosHardwareOrder,\n} from '../model/pos-hardware'\nimport { hardwareOrdersRef, posHardwareOrderNumber, posSettingsUrl } from './pos-hardware'\n\n/*==========================================\n * TELLING PEOPLE ABOUT A HARDWARE ORDER (AGL-4038).\n *\n * The buyer gets a system email at each step they wait on: received, shipped\n * (with the carrier and tracking link) and delivered (with the way to set the\n * reader up), and canceled and refunded when staff cancel it before it ships\n * and choose to tell them, or the workspace is deleted or their account is\n * closed first; a reader bought in person gets \"refunded\" when staff refund\n * it and choose to tell them. The canceled and refunded emails are sent\n * ONCE, by a claim on the order ({@link sendPosHardwareEmailOnce}), so the\n * staff page and a closure never both send one. Staff get the \"New hardware order\" operator alert,\n * because in phase 1 a person places every order with Stripe, and an alert\n * when a closure cancels an order already placed with Stripe or Stripe\n * refuses a closure's refund.\n *\n * Never throws. The order is already recorded when any of these run, and a\n * lost email must not undo it or turn a webhook into a redelivery.\n *=========================================*/\n\nexport type PosHardwareEmailKind = keyof typeof POS_HARDWARE_EMAIL_KEYS\n\n/** The lines as the emails list them, one per item. */\nfunction itemsText(order: PosHardwareOrder): string {\n return (order.lines ?? []).map((line) => `${line.name} × ${line.quantity}`).join('\\n')\n}\n\nfunction shipToText(order: PosHardwareOrder): string {\n const address = order.shipping?.address\n const cityLine = address\n ? [address.city, [address.state, address.postalCode].filter(Boolean).join(' ')].filter(Boolean).join(', ')\n : ''\n return [order.shipping?.name, address?.line1, address?.line2, cityLine].filter(Boolean).join('\\n')\n}\n\nasync function siteAndOrgNames(order: PosHardwareOrder): Promise<{ site: string; org: string; ban: boolean }> {\n const firestore = firebaseAdmin.app().firestore()\n const [host, org] = await Promise.all([\n firestore.collection('hosts').doc(order.hostId).get().catch(() => null),\n firestore.collection('orgs').doc(order.orgId).get().catch(() => null),\n ])\n const lock = normalizeOrgLockdown(org?.data() as never)\n return {\n site: host?.exists ? hostDisplayName(host.data() as Record<string, unknown>, order.hostId) : 'your site',\n org: String(org?.get('name') ?? '').trim() || UNNAMED_WORKSPACE,\n ban: Boolean(lock && isAccountBanLockdownReason(lock.reason)),\n }\n}\n\n/** The fallback subject and first line, when no design renders. */\nconst FALLBACK: Record<PosHardwareEmailKind, (number: string) => string> = {\n received: (number) => `We have your card reader order ${number}`,\n shipped: (number) => `Your card reader order ${number} has shipped`,\n delivered: (number) => `Your card reader order ${number} was delivered`,\n canceled: (number) => `Your card reader order ${number} was canceled and refunded`,\n refunded: (number) => `Your refund for card reader order ${number}`,\n invited: (number) => `Your card reader order ${number} is waiting for your account`,\n returnRefunded: (number) => `We refunded your returned card reader order ${number}`,\n}\n\n/** The fallback a workspace with no name gets in a sentence. */\nconst UNNAMED_WORKSPACE = 'your workspace'\n\n/**\n * Who canceled the order and why, as the email's first sentence; the\n * template goes on \"It had not shipped yet, so we refunded …\".\n */\nfunction cancelReasonText(reason: PosHardwareCancelReason | undefined, org: string): string {\n if (reason === 'workspace-closed') {\n return org && org !== UNNAMED_WORKSPACE\n ? `We canceled your order because the ${org} workspace was deleted.`\n : 'We canceled your order because your workspace was deleted.'\n }\n if (reason === 'account-closed') return 'We canceled your order because the account that placed it was closed.'\n return 'Our team canceled your order.'\n}\n\n/** Why, for staff: the closure that canceled it, never who the buyer was. */\nfunction staffReasonText(reason: PosHardwareCancelReason, orgId: string): string {\n if (reason === 'workspace-closed') return `its workspace ${orgId} was deleted`\n if (reason === 'account-closed') return 'the account that placed it was closed'\n return 'staff canceled it'\n}\n\n/** The merge values for one order's emails. Exported for the render spec. */\nexport async function posHardwareEmailMerge(\n orderId: string,\n order: PosHardwareOrder,\n names: { site: string; org: string },\n): Promise<Record<string, string>> {\n const base = await posSettingsUrl(order.hostId)\n const [path] = base.split('#')\n const ordersUrl = `${path}#${POS_HARDWARE_ANCHOR}`\n return {\n 'org.name': names.org,\n 'site.name': names.site,\n 'order.number': posHardwareOrderNumber(orderId),\n 'order.items': itemsText(order),\n 'order.total': formatPosHardwareCents(order.totalCents ?? 0),\n 'order.shipTo': shipToText(order),\n 'order.shippingMethod': order.shipping?.label ?? '',\n 'order.carrier': carrierLabelFor(order.tracking?.carrier) || 'the carrier',\n 'order.trackingNumber': order.tracking?.number ?? '',\n // An unknown carrier has no tracker to link; the card shows the number.\n 'order.trackingUrl': order.tracking?.url ?? ordersUrl,\n 'order.ordersUrl': ordersUrl,\n 'order.setupUrl': `${path}#pos-devices`,\n // What Stripe reported refunding, or the whole charge where it has not.\n 'order.refunded': formatPosHardwareCents(order.refundedCents ?? order.totalCents ?? 0),\n // This refund alone, for an order refunded in parts; the whole of it otherwise.\n 'order.refundedNow': formatPosHardwareCents(\n (order.refunds ?? []).slice(-1)[0]?.cents ?? order.refundedCents ?? order.totalCents ?? 0,\n ),\n 'order.cancelReason': cancelReasonText(order.cancelReason, names.org),\n // What a return kept back: the original shipping and any restocking fee.\n 'order.kept': formatPosHardwareCents(Math.max(0, (order.totalCents ?? 0) - (order.refundedCents ?? 0))),\n }\n}\n\n/** What became of one email. */\nexport type PosHardwareEmailOutcome =\n /** Sent. */\n | 'sent'\n /** Nobody to send it to: no address, suppressed, or the account is banned. */\n | 'skipped'\n /** The send failed, and may be tried again. */\n | 'failed'\n\nexport async function sendPosHardwareEmail(\n kind: PosHardwareEmailKind,\n orderId: string,\n order: PosHardwareOrder,\n): Promise<PosHardwareEmailOutcome> {\n try {\n const to = String(order.contactEmail ?? '').trim()\n if (!to) return 'skipped'\n const names = await siteAndOrgNames(order)\n // A ban is a ban (AGL-3420): after its notice the account is sent nothing.\n if (names.ban) return 'skipped'\n const [recipient] = await filterSuppressedEmails([to])\n if (!recipient) return 'skipped'\n const merge = await posHardwareEmailMerge(orderId, order, names)\n const subject = FALLBACK[kind](merge['order.number'])\n // A refund in person is in the selling workspace's brand, as its\n // invitation is; the rest in the buyer's.\n const brand = await orgSystemEmailBrand(kind === 'refunded' ? (order.posSale?.orgId ?? order.orgId) : order.orgId)\n // A canceled order's workspace may be gone, so its fallback names the\n // refund rather than linking a card that no longer opens.\n const last =\n kind === 'canceled'\n ? `Refunded: ${merge['order.refunded']}`\n : kind === 'refunded'\n ? `Refunded now: ${merge['order.refundedNow']}`\n : merge['order.ordersUrl']\n const content = await renderSystemEmailContent(POS_HARDWARE_EMAIL_KEYS[kind], merge, brand, {\n subject,\n text: `${subject}\\n\\n${merge['order.items']}\\n\\n${last}`,\n })\n const result = await sendEmail({\n to: recipient,\n ...content,\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: POS_HARDWARE_EMAIL_KEYS[kind],\n })\n if (!result.sent) return 'failed'\n await meterPlatformEmail(1)\n return 'sent'\n } catch (error) {\n console.error('[pos-hardware] email failed', kind, orderId, error)\n return 'failed'\n }\n}\n\n/** How long a claimed send that never finished holds the next one back. */\nconst EMAIL_CLAIM_STALE_MS = 10 * 60 * 1000\n\n/**\n * Sends one email for an order ONCE, under `key` (the kind by default; one\n * per refund for a refund in parts). The claim is a field on the order,\n * `buyerEmails.{key}`, taken in a transaction before the send, so the staff\n * page and a closure, a retried press or two staff at once, send it once\n * between them. A send that failed can be claimed again; one that found\n * nobody to send to is not tried again. Never throws.\n */\nexport async function sendPosHardwareEmailOnce(\n kind: PosHardwareEmailKind,\n orderId: string,\n order: PosHardwareOrder,\n key: string = kind,\n): Promise<PosHardwareEmailOutcome | 'already'> {\n try {\n const firestore = firebaseAdmin.app().firestore()\n const ref = hardwareOrdersRef(order.orgId).doc(orderId)\n const claimed = await firestore.runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) return false\n const held = (snapshot.data()?.buyerEmails ?? {})[key] as { state?: string; atMs?: number } | undefined\n const now = Date.now()\n if (held?.state === 'sent' || held?.state === 'skipped') return false\n if (held?.state === 'sending' && now - Number(held.atMs ?? 0) < EMAIL_CLAIM_STALE_MS) return false\n transaction.set(ref, { buyerEmails: { [key]: { state: 'sending', atMs: now } } }, { merge: true })\n return true\n })\n if (!claimed) return 'already'\n const outcome = await sendPosHardwareEmail(kind, orderId, order)\n await ref\n .set({ buyerEmails: { [key]: { state: outcome === 'sent' ? 'sent' : outcome, atMs: Date.now() } } }, { merge: true })\n .catch((error: unknown) => console.error('[pos-hardware] email claim not settled', kind, orderId, error))\n return outcome\n } catch (error) {\n console.error('[pos-hardware] email claim failed', kind, orderId, error)\n return 'failed'\n }\n}\n\n/**\n * The invitation to sign up (AGL-4038), for someone who bought a card reader\n * in person at the platform's own store with no account yet: create the\n * account with this address and the order joins their workspace on its own.\n * Sent in the selling workspace's brand, which is the platform's. Never\n * throws; the caller has already claimed the send.\n */\n/** The invitation's merge values. Exported for the render spec. */\nexport function posHardwareInviteMerge(orderId: string, order: PosHardwareOrder): Record<string, string> {\n return {\n 'order.number': posHardwareOrderNumber(orderId),\n 'order.items': itemsText(order),\n 'order.total': formatPosHardwareCents(order.totalCents ?? 0),\n 'order.signUpUrl': `${platformConsoleOrigin()}/signup`,\n }\n}\n\nexport async function sendPosHardwareInvite(orderId: string, order: PosHardwareOrder): Promise<void> {\n try {\n const to = String(order.attachment?.email ?? '').trim()\n if (!to) return\n const [recipient] = await filterSuppressedEmails([to])\n if (!recipient) return\n const merge = posHardwareInviteMerge(orderId, order)\n const signUpUrl = merge['order.signUpUrl']\n const subject = FALLBACK.invited(merge['order.number'])\n const brand = await orgSystemEmailBrand(order.posSale?.orgId ?? order.orgId)\n const content = await renderSystemEmailContent(POS_HARDWARE_EMAIL_KEYS.invited, merge, brand, {\n subject,\n text: `${subject}\\n\\n${merge['order.items']}\\n\\nCreate your account with this email address: ${signUpUrl}`,\n })\n const result = await sendEmail({\n to: recipient,\n ...content,\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: POS_HARDWARE_EMAIL_KEYS.invited,\n })\n if (result.sent) await meterPlatformEmail(1)\n } catch (error) {\n console.error('[pos-hardware] invitation failed', orderId, error)\n }\n}\n\n/**\n * A closure canceled an order staff had already placed with Stripe: the\n * merchant is refunded, and Stripe will still ship it unless someone cancels\n * it there. Once per order.\n */\nexport async function raisePosHardwareCanceledAfterOrderingAlert(\n orderId: string,\n order: PosHardwareOrder,\n reason: PosHardwareCancelReason,\n): Promise<void> {\n try {\n const stripeOrderId = String(order.stripeHardwareOrderId ?? '').trim()\n await raiseOperatorAlert(COMMERCE_POS_HARDWARE_CANCELED_AFTER_ORDERING, {\n dedupeKey: orderId,\n orgId: order.orgId,\n hostId: order.hostId,\n context: {\n orderNumber: posHardwareOrderNumber(orderId),\n amount: formatOperatorAlertAmount(order.totalCents ?? 0),\n items: (order.lines ?? []).map((line) => `${line.quantity} × ${line.name}`).join(', '),\n reason: staffReasonText(reason, order.orgId),\n stripeOrder: stripeOrderId ? ` (Stripe order ${stripeOrderId})` : '',\n },\n })\n } catch (error) {\n console.error('[pos-hardware] canceled-after-ordering alert failed', orderId, error)\n }\n}\n\n/**\n * Stripe refused a closure's refund, and the closure went ahead without it.\n * Carries the payment to refund by hand, never the buyer.\n */\nexport async function raisePosHardwareRefundFailedAlert(\n orderId: string,\n order: PosHardwareOrder,\n reason: PosHardwareCancelReason,\n error: string,\n): Promise<void> {\n try {\n const stripeOrderId = String(order.stripeHardwareOrderId ?? '').trim()\n await raiseOperatorAlert(COMMERCE_POS_HARDWARE_REFUND_FAILED, {\n dedupeKey: orderId,\n orgId: order.orgId,\n hostId: order.hostId,\n context: {\n orderNumber: posHardwareOrderNumber(orderId),\n amount: formatOperatorAlertAmount(order.totalCents ?? 0),\n reason: staffReasonText(reason, order.orgId),\n error: error || 'no reason given',\n paymentIntentId: order.stripePaymentIntentId ?? 'for this order (no payment id is recorded on it)',\n orderedNote:\n order.status === 'ordered'\n ? `. It had already been placed with Stripe${stripeOrderId ? ` as ${stripeOrderId}` : ''}, so cancel it there too before it ships`\n : '',\n },\n })\n } catch (failure) {\n console.error('[pos-hardware] refund-failed alert failed', orderId, failure)\n }\n}\n\n/** \"New hardware order\", once per order. */\nexport async function raisePosHardwareOrderAlert(orderId: string, order: PosHardwareOrder): Promise<void> {\n try {\n const names = await siteAndOrgNames(order)\n await raiseOperatorAlert(COMMERCE_POS_HARDWARE_ORDER, {\n dedupeKey: orderId,\n orgId: order.orgId,\n hostId: order.hostId,\n context: {\n orderNumber: posHardwareOrderNumber(orderId),\n amount: formatOperatorAlertAmount(order.totalCents ?? 0),\n site: `${names.site} (${order.hostId})`,\n items: (order.lines ?? []).map((line) => `${line.quantity} × ${line.name}`).join(', '),\n shipping: order.shipping?.label ?? 'shipping',\n },\n })\n } catch (error) {\n console.error('[pos-hardware] operator alert failed', orderId, error)\n }\n}\n"],"names":["formatOperatorAlertAmount","isAccountBanLockdownReason","normalizeOrgLockdown","POS_HARDWARE_EMAIL_KEYS","sendEmail","platformConsoleOrigin","firebaseAdmin","hostDisplayName","meterPlatformEmail","raiseOperatorAlert","filterSuppressedEmails","orgSystemEmailBrand","renderSystemEmailContent","COMMERCE_POS_HARDWARE_CANCELED_AFTER_ORDERING","COMMERCE_POS_HARDWARE_ORDER","COMMERCE_POS_HARDWARE_REFUND_FAILED","carrierLabelFor","formatPosHardwareCents","POS_HARDWARE_ANCHOR","hardwareOrdersRef","posHardwareOrderNumber","posSettingsUrl","itemsText","order","lines","map","line","name","quantity","join","shipToText","address","shipping","cityLine","city","state","postalCode","filter","Boolean","line1","line2","siteAndOrgNames","firestore","app","host","org","Promise","all","collection","doc","hostId","get","catch","orgId","lock","data","site","exists","String","trim","UNNAMED_WORKSPACE","ban","reason","FALLBACK","received","number","shipped","delivered","canceled","refunded","invited","returnRefunded","cancelReasonText","staffReasonText","posHardwareEmailMerge","orderId","names","base","path","split","ordersUrl","totalCents","label","tracking","carrier","url","refundedCents","refunds","slice","cents","cancelReason","Math","max","sendPosHardwareEmail","kind","to","contactEmail","recipient","merge","subject","brand","posSale","last","content","text","result","fromName","context","sent","error","console","EMAIL_CLAIM_STALE_MS","sendPosHardwareEmailOnce","key","ref","claimed","runTransaction","transaction","held","snapshot","buyerEmails","now","Date","Number","atMs","set","outcome","posHardwareInviteMerge","sendPosHardwareInvite","attachment","email","signUpUrl","raisePosHardwareCanceledAfterOrderingAlert","stripeOrderId","stripeHardwareOrderId","dedupeKey","orderNumber","amount","items","stripeOrder","raisePosHardwareRefundFailedAlert","paymentIntentId","stripePaymentIntentId","order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/plugins/commerce/src/lib/server/pos-hardware-notify.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 { formatOperatorAlertAmount } from '@aglyn/aglyn/app-utils/operator-alerts'\nimport {\n isAccountBanLockdownReason,\n normalizeOrgLockdown,\n} from '@aglyn/aglyn/app-utils/lockdown'\nimport { POS_HARDWARE_EMAIL_KEYS, sendEmail } from '@aglyn/shared-util-email'\nimport { platformConsoleOrigin } from '@aglyn/aglyn/app-utils/platform-brand'\nimport {\n firebaseAdmin,\n hostDisplayName,\n meterPlatformEmail,\n raiseOperatorAlert,\n} from '@aglyn/tenant-data-admin'\nimport { filterSuppressedEmails } from '@aglyn/tenant-data-admin/server/email-suppression'\nimport {\n orgSystemEmailBrand,\n renderSystemEmailContent,\n} from '@aglyn/tenant-data-admin/server/render-system-email'\nimport {\n COMMERCE_POS_HARDWARE_CANCELED_AFTER_ORDERING,\n COMMERCE_POS_HARDWARE_ORDER,\n COMMERCE_POS_HARDWARE_REFUND_FAILED,\n} from '../constants/operator-alerts'\nimport { carrierLabelFor } from '../model/tracking-url'\nimport {\n formatPosHardwareCents,\n POS_HARDWARE_ANCHOR,\n posHardwareOrderUnits,\n type PosHardwareCancelReason,\n type PosHardwareOrder,\n} from '../model/pos-hardware'\nimport { hardwareOrdersRef, posHardwareOrderNumber, posSettingsUrl } from './pos-hardware'\n\n/*==========================================\n * TELLING PEOPLE ABOUT A HARDWARE ORDER (AGL-4038).\n *\n * The buyer gets a system email at each step they wait on: received, shipped\n * (with the carrier and tracking link) and delivered (with the way to set the\n * reader up), and canceled and refunded when staff cancel it before it ships\n * and choose to tell them, or the workspace is deleted or their account is\n * closed first; a reader bought in person gets \"refunded\" when staff refund\n * it and choose to tell them. The canceled and refunded emails are sent\n * ONCE, by a claim on the order ({@link sendPosHardwareEmailOnce}), so the\n * staff page and a closure never both send one. Staff get the \"New hardware order\" operator alert,\n * because in phase 1 a person places every order with Stripe, and an alert\n * when a closure cancels an order already placed with Stripe or Stripe\n * refuses a closure's refund.\n *\n * Never throws. The order is already recorded when any of these run, and a\n * lost email must not undo it or turn a webhook into a redelivery.\n *=========================================*/\n\nexport type PosHardwareEmailKind = keyof typeof POS_HARDWARE_EMAIL_KEYS\n\n/** The lines as the emails list them, one per item. */\nfunction itemsText(order: PosHardwareOrder): string {\n return (order.lines ?? []).map((line) => `${line.name} × ${line.quantity}`).join('\\n')\n}\n\nfunction shipToText(order: PosHardwareOrder): string {\n const address = order.shipping?.address\n const cityLine = address\n ? [address.city, [address.state, address.postalCode].filter(Boolean).join(' ')].filter(Boolean).join(', ')\n : ''\n return [order.shipping?.name, address?.line1, address?.line2, cityLine].filter(Boolean).join('\\n')\n}\n\nasync function siteAndOrgNames(order: PosHardwareOrder): Promise<{ site: string; org: string; ban: boolean }> {\n const firestore = firebaseAdmin.app().firestore()\n // Bought from the platform's own store and not yet in the buyer's\n // workspace (AGL-4038): it is for their business, which has no workspace\n // here yet, and the selling store's name says where it came from.\n if (order.attachment?.state === 'pending' && order.posSale?.hostId) {\n const seller = await firestore.collection('hosts').doc(order.posSale.hostId).get().catch(() => null)\n return {\n site: seller?.exists ? hostDisplayName(seller.data() as Record<string, unknown>, order.posSale.hostId) : 'our store',\n org: PENDING_BUYER,\n ban: false,\n }\n }\n const [host, org] = await Promise.all([\n firestore.collection('hosts').doc(order.hostId).get().catch(() => null),\n firestore.collection('orgs').doc(order.orgId).get().catch(() => null),\n ])\n const lock = normalizeOrgLockdown(org?.data() as never)\n return {\n site: host?.exists ? hostDisplayName(host.data() as Record<string, unknown>, order.hostId) : 'your site',\n org: String(org?.get('name') ?? '').trim() || UNNAMED_WORKSPACE,\n ban: Boolean(lock && isAccountBanLockdownReason(lock.reason)),\n }\n}\n\n/** The fallback subject and first line, when no design renders. */\nconst FALLBACK: Record<PosHardwareEmailKind, (number: string) => string> = {\n received: (number) => `We have your card reader order ${number}`,\n shipped: (number) => `Your card reader order ${number} has shipped`,\n delivered: (number) => `Your card reader order ${number} was delivered`,\n canceled: (number) => `Your card reader order ${number} was canceled and refunded`,\n refunded: (number) => `Your refund for card reader order ${number}`,\n invited: (number) => `Your card reader order ${number} is waiting for your account`,\n returnRefunded: (number) => `We refunded your returned card reader order ${number}`,\n}\n\n/** The fallback a workspace with no name gets in a sentence. */\nconst UNNAMED_WORKSPACE = 'your workspace'\n\n/** Who a sale not yet in anyone's workspace is for, in a sentence. */\nconst PENDING_BUYER = 'your business'\n\n/**\n * Who canceled the order and why, as the email's first sentence; the\n * template goes on \"It had not shipped yet, so we refunded …\".\n */\nfunction cancelReasonText(reason: PosHardwareCancelReason | undefined, org: string): string {\n if (reason === 'workspace-closed') {\n return org && org !== UNNAMED_WORKSPACE\n ? `We canceled your order because the ${org} workspace was deleted.`\n : 'We canceled your order because your workspace was deleted.'\n }\n if (reason === 'account-closed') return 'We canceled your order because the account that placed it was closed.'\n return 'Our team canceled your order.'\n}\n\n/** Why, for staff: the closure that canceled it, never who the buyer was. */\nfunction staffReasonText(reason: PosHardwareCancelReason, orgId: string): string {\n if (reason === 'workspace-closed') return `its workspace ${orgId} was deleted`\n if (reason === 'account-closed') return 'the account that placed it was closed'\n return 'staff canceled it'\n}\n\n/** The steps the delivered email gives: pair the reader, or it is already set up. */\nexport function posHardwareSetupSteps(order: Pick<PosHardwareOrder, 'units' | 'lines'>): string {\n const units = posHardwareOrderUnits(order)\n if (units.length && units.every((unit) => unit.readerId)) {\n return (\n 'We set your reader up on your store before it shipped.\\n' +\n '1. Charge it and switch it on.\\n' +\n '2. Connect it to Wi-Fi from the reader’s Settings.\\n' +\n '3. It shows on the POS devices card, ready for a register.'\n )\n }\n return (\n '1. Charge it and switch it on.\\n' +\n '2. Connect it to Wi-Fi from the reader’s Settings.\\n' +\n '3. On the reader, generate a pairing code.\\n' +\n '4. On the POS devices card, choose Add card reader and enter the code.'\n )\n}\n\n/** The merge values for one order's emails. Exported for the render spec. */\nexport async function posHardwareEmailMerge(\n orderId: string,\n order: PosHardwareOrder,\n names: { site: string; org: string },\n): Promise<Record<string, string>> {\n // An order with no store yet (AGL-4038) has no settings page to link: the\n // console's front door, where signing in or up leads to it.\n const base = order.hostId ? await posSettingsUrl(order.hostId) : platformConsoleOrigin()\n const [path] = base.split('#')\n const ordersUrl = order.hostId ? `${path}#${POS_HARDWARE_ANCHOR}` : path\n return {\n 'org.name': names.org,\n 'site.name': names.site,\n 'order.number': posHardwareOrderNumber(orderId),\n 'order.items': itemsText(order),\n 'order.total': formatPosHardwareCents(order.totalCents ?? 0),\n 'order.shipTo': shipToText(order),\n 'order.shippingMethod': order.shipping?.label ?? '',\n 'order.carrier': carrierLabelFor(order.tracking?.carrier) || 'the carrier',\n 'order.trackingNumber': order.tracking?.number ?? '',\n // An unknown carrier has no tracker to link; the card shows the number.\n 'order.trackingUrl': order.tracking?.url ?? ordersUrl,\n 'order.ordersUrl': ordersUrl,\n 'order.setupUrl': order.hostId ? `${path}#pos-devices` : path,\n // What arrived: readers registered to the store before they shipped\n // (AGL-4038) only need power and Wi-Fi; any other is paired by its code.\n 'order.setupSteps': posHardwareSetupSteps(order),\n // What Stripe reported refunding, or the whole charge where it has not.\n 'order.refunded': formatPosHardwareCents(order.refundedCents ?? order.totalCents ?? 0),\n // This refund alone, for an order refunded in parts; the whole of it otherwise.\n 'order.refundedNow': formatPosHardwareCents(\n (order.refunds ?? []).slice(-1)[0]?.cents ?? order.refundedCents ?? order.totalCents ?? 0,\n ),\n 'order.cancelReason': cancelReasonText(order.cancelReason, names.org),\n // What a return kept back: the original shipping and any restocking fee.\n 'order.kept': formatPosHardwareCents(Math.max(0, (order.totalCents ?? 0) - (order.refundedCents ?? 0))),\n }\n}\n\n/** What became of one email. */\nexport type PosHardwareEmailOutcome =\n /** Sent. */\n | 'sent'\n /** Nobody to send it to: no address, suppressed, or the account is banned. */\n | 'skipped'\n /** The send failed, and may be tried again. */\n | 'failed'\n\nexport async function sendPosHardwareEmail(\n kind: PosHardwareEmailKind,\n orderId: string,\n order: PosHardwareOrder,\n): Promise<PosHardwareEmailOutcome> {\n try {\n const to = String(order.contactEmail ?? '').trim()\n if (!to) return 'skipped'\n const names = await siteAndOrgNames(order)\n // A ban is a ban (AGL-3420): after its notice the account is sent nothing.\n if (names.ban) return 'skipped'\n const [recipient] = await filterSuppressedEmails([to])\n if (!recipient) return 'skipped'\n const merge = await posHardwareEmailMerge(orderId, order, names)\n const subject = FALLBACK[kind](merge['order.number'])\n // A refund in person is in the selling workspace's brand, as its\n // invitation is; the rest in the buyer's.\n const brand = await orgSystemEmailBrand(kind === 'refunded' ? (order.posSale?.orgId ?? order.orgId) : order.orgId)\n // A canceled order's workspace may be gone, so its fallback names the\n // refund rather than linking a card that no longer opens.\n const last =\n kind === 'canceled'\n ? `Refunded: ${merge['order.refunded']}`\n : kind === 'refunded'\n ? `Refunded now: ${merge['order.refundedNow']}`\n : merge['order.ordersUrl']\n const content = await renderSystemEmailContent(POS_HARDWARE_EMAIL_KEYS[kind], merge, brand, {\n subject,\n text: `${subject}\\n\\n${merge['order.items']}\\n\\n${last}`,\n })\n const result = await sendEmail({\n to: recipient,\n ...content,\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: POS_HARDWARE_EMAIL_KEYS[kind],\n })\n if (!result.sent) return 'failed'\n await meterPlatformEmail(1)\n return 'sent'\n } catch (error) {\n console.error('[pos-hardware] email failed', kind, orderId, error)\n return 'failed'\n }\n}\n\n/** How long a claimed send that never finished holds the next one back. */\nconst EMAIL_CLAIM_STALE_MS = 10 * 60 * 1000\n\n/**\n * Sends one email for an order ONCE, under `key` (the kind by default; one\n * per refund for a refund in parts). The claim is a field on the order,\n * `buyerEmails.{key}`, taken in a transaction before the send, so the staff\n * page and a closure, a retried press or two staff at once, send it once\n * between them. A send that failed can be claimed again; one that found\n * nobody to send to is not tried again. Never throws.\n */\nexport async function sendPosHardwareEmailOnce(\n kind: PosHardwareEmailKind,\n orderId: string,\n order: PosHardwareOrder,\n key: string = kind,\n): Promise<PosHardwareEmailOutcome | 'already'> {\n try {\n const firestore = firebaseAdmin.app().firestore()\n const ref = hardwareOrdersRef(order.orgId).doc(orderId)\n const claimed = await firestore.runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) return false\n const held = (snapshot.data()?.buyerEmails ?? {})[key] as { state?: string; atMs?: number } | undefined\n const now = Date.now()\n if (held?.state === 'sent' || held?.state === 'skipped') return false\n if (held?.state === 'sending' && now - Number(held.atMs ?? 0) < EMAIL_CLAIM_STALE_MS) return false\n transaction.set(ref, { buyerEmails: { [key]: { state: 'sending', atMs: now } } }, { merge: true })\n return true\n })\n if (!claimed) return 'already'\n const outcome = await sendPosHardwareEmail(kind, orderId, order)\n await ref\n .set({ buyerEmails: { [key]: { state: outcome === 'sent' ? 'sent' : outcome, atMs: Date.now() } } }, { merge: true })\n .catch((error: unknown) => console.error('[pos-hardware] email claim not settled', kind, orderId, error))\n return outcome\n } catch (error) {\n console.error('[pos-hardware] email claim failed', kind, orderId, error)\n return 'failed'\n }\n}\n\n/**\n * The invitation to sign up (AGL-4038), for someone who bought a card reader\n * in person at the platform's own store with no account yet: create the\n * account with this address and the order joins their workspace on its own.\n * Sent in the selling workspace's brand, which is the platform's. Never\n * throws; the caller has already claimed the send.\n */\n/** The invitation's merge values. Exported for the render spec. */\nexport function posHardwareInviteMerge(orderId: string, order: PosHardwareOrder): Record<string, string> {\n return {\n 'order.number': posHardwareOrderNumber(orderId),\n 'order.items': itemsText(order),\n 'order.total': formatPosHardwareCents(order.totalCents ?? 0),\n 'order.signUpUrl': `${platformConsoleOrigin()}/signup`,\n }\n}\n\nexport async function sendPosHardwareInvite(orderId: string, order: PosHardwareOrder): Promise<void> {\n try {\n const to = String(order.attachment?.email ?? '').trim()\n if (!to) return\n const [recipient] = await filterSuppressedEmails([to])\n if (!recipient) return\n const merge = posHardwareInviteMerge(orderId, order)\n const signUpUrl = merge['order.signUpUrl']\n const subject = FALLBACK.invited(merge['order.number'])\n const brand = await orgSystemEmailBrand(order.posSale?.orgId ?? order.orgId)\n const content = await renderSystemEmailContent(POS_HARDWARE_EMAIL_KEYS.invited, merge, brand, {\n subject,\n text: `${subject}\\n\\n${merge['order.items']}\\n\\nCreate your account with this email address: ${signUpUrl}`,\n })\n const result = await sendEmail({\n to: recipient,\n ...content,\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: POS_HARDWARE_EMAIL_KEYS.invited,\n })\n if (result.sent) await meterPlatformEmail(1)\n } catch (error) {\n console.error('[pos-hardware] invitation failed', orderId, error)\n }\n}\n\n/**\n * A closure canceled an order staff had already placed with Stripe: the\n * merchant is refunded, and Stripe will still ship it unless someone cancels\n * it there. Once per order.\n */\nexport async function raisePosHardwareCanceledAfterOrderingAlert(\n orderId: string,\n order: PosHardwareOrder,\n reason: PosHardwareCancelReason,\n): Promise<void> {\n try {\n const stripeOrderId = String(order.stripeHardwareOrderId ?? '').trim()\n await raiseOperatorAlert(COMMERCE_POS_HARDWARE_CANCELED_AFTER_ORDERING, {\n dedupeKey: orderId,\n orgId: order.orgId,\n hostId: order.hostId,\n context: {\n orderNumber: posHardwareOrderNumber(orderId),\n amount: formatOperatorAlertAmount(order.totalCents ?? 0),\n items: (order.lines ?? []).map((line) => `${line.quantity} × ${line.name}`).join(', '),\n reason: staffReasonText(reason, order.orgId),\n stripeOrder: stripeOrderId ? ` (Stripe order ${stripeOrderId})` : '',\n },\n })\n } catch (error) {\n console.error('[pos-hardware] canceled-after-ordering alert failed', orderId, error)\n }\n}\n\n/**\n * Stripe refused a closure's refund, and the closure went ahead without it.\n * Carries the payment to refund by hand, never the buyer.\n */\nexport async function raisePosHardwareRefundFailedAlert(\n orderId: string,\n order: PosHardwareOrder,\n reason: PosHardwareCancelReason,\n error: string,\n): Promise<void> {\n try {\n const stripeOrderId = String(order.stripeHardwareOrderId ?? '').trim()\n await raiseOperatorAlert(COMMERCE_POS_HARDWARE_REFUND_FAILED, {\n dedupeKey: orderId,\n orgId: order.orgId,\n hostId: order.hostId,\n context: {\n orderNumber: posHardwareOrderNumber(orderId),\n amount: formatOperatorAlertAmount(order.totalCents ?? 0),\n reason: staffReasonText(reason, order.orgId),\n error: error || 'no reason given',\n paymentIntentId: order.stripePaymentIntentId ?? 'for this order (no payment id is recorded on it)',\n orderedNote:\n order.status === 'ordered' || order.status === 'received'\n ? `. It had already been placed with Stripe${stripeOrderId ? ` as ${stripeOrderId}` : ''}, so cancel it there too before it ships`\n : '',\n },\n })\n } catch (failure) {\n console.error('[pos-hardware] refund-failed alert failed', orderId, failure)\n }\n}\n\n/** \"New hardware order\", once per order. */\nexport async function raisePosHardwareOrderAlert(orderId: string, order: PosHardwareOrder): Promise<void> {\n try {\n const names = await siteAndOrgNames(order)\n await raiseOperatorAlert(COMMERCE_POS_HARDWARE_ORDER, {\n dedupeKey: orderId,\n orgId: order.orgId,\n hostId: order.hostId,\n context: {\n orderNumber: posHardwareOrderNumber(orderId),\n amount: formatOperatorAlertAmount(order.totalCents ?? 0),\n site: `${names.site} (${order.hostId})`,\n items: (order.lines ?? []).map((line) => `${line.quantity} × ${line.name}`).join(', '),\n shipping: order.shipping?.label ?? 'shipping',\n },\n })\n } catch (error) {\n console.error('[pos-hardware] operator alert failed', orderId, error)\n }\n}\n"],"names":["formatOperatorAlertAmount","isAccountBanLockdownReason","normalizeOrgLockdown","POS_HARDWARE_EMAIL_KEYS","sendEmail","platformConsoleOrigin","firebaseAdmin","hostDisplayName","meterPlatformEmail","raiseOperatorAlert","filterSuppressedEmails","orgSystemEmailBrand","renderSystemEmailContent","COMMERCE_POS_HARDWARE_CANCELED_AFTER_ORDERING","COMMERCE_POS_HARDWARE_ORDER","COMMERCE_POS_HARDWARE_REFUND_FAILED","carrierLabelFor","formatPosHardwareCents","POS_HARDWARE_ANCHOR","posHardwareOrderUnits","hardwareOrdersRef","posHardwareOrderNumber","posSettingsUrl","itemsText","order","lines","map","line","name","quantity","join","shipToText","address","shipping","cityLine","city","state","postalCode","filter","Boolean","line1","line2","siteAndOrgNames","firestore","app","attachment","posSale","hostId","seller","collection","doc","get","catch","site","exists","data","org","PENDING_BUYER","ban","host","Promise","all","orgId","lock","String","trim","UNNAMED_WORKSPACE","reason","FALLBACK","received","number","shipped","delivered","canceled","refunded","invited","returnRefunded","cancelReasonText","staffReasonText","posHardwareSetupSteps","units","length","every","unit","readerId","posHardwareEmailMerge","orderId","names","base","path","split","ordersUrl","totalCents","label","tracking","carrier","url","refundedCents","refunds","slice","cents","cancelReason","Math","max","sendPosHardwareEmail","kind","to","contactEmail","recipient","merge","subject","brand","last","content","text","result","fromName","context","sent","error","console","EMAIL_CLAIM_STALE_MS","sendPosHardwareEmailOnce","key","ref","claimed","runTransaction","transaction","held","snapshot","buyerEmails","now","Date","Number","atMs","set","outcome","posHardwareInviteMerge","sendPosHardwareInvite","email","signUpUrl","raisePosHardwareCanceledAfterOrderingAlert","stripeOrderId","stripeHardwareOrderId","dedupeKey","orderNumber","amount","items","stripeOrder","raisePosHardwareRefundFailedAlert","paymentIntentId","stripePaymentIntentId","orderedNote","status","failure","raisePosHardwareOrderAlert"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,yBAAyB,QAAQ,yCAAwC;AAClF,SACEC,0BAA0B,EAC1BC,oBAAoB,QACf,kCAAiC;AACxC,SAASC,uBAAuB,EAAEC,SAAS,QAAQ,2BAA0B;AAC7E,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,aAAa,EACbC,eAAe,EACfC,kBAAkB,EAClBC,kBAAkB,QACb,2BAA0B;AACjC,SAASC,sBAAsB,QAAQ,oDAAmD;AAC1F,S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kI,WAAW1D;YACXxB,OAAOtC,MAAMsC,KAAK;YAClBf,QAAQvB,MAAMuB,MAAM;YACpBsE,SAAS;gBACP4B,aAAa5H,uBAAuBiE;gBACpC4D,QAAQlJ,2BAA0BwB,oBAAAA,MAAMoE,UAAU,YAAhBpE,oBAAoB;gBACtD6B,MAAM,GAAGkC,MAAMlC,IAAI,CAAC,EAAE,EAAE7B,MAAMuB,MAAM,CAAC,CAAC,CAAC;gBACvCoG,OAAO,EAAC3H,eAAAA,MAAMC,KAAK,YAAXD,eAAe,EAAE,EAAEE,GAAG,CAAC,CAACC,OAAS,GAAGA,KAAKE,QAAQ,CAAC,GAAG,EAAEF,KAAKC,IAAI,EAAE,EAAEE,IAAI,CAAC;gBACjFG,QAAQ,WAAET,kBAAAA,MAAMS,QAAQ,qBAAdT,gBAAgBqE,KAAK,mBAAI;YACrC;QACF;IACF,EAAE,OAAO0B,OAAO;QACdC,QAAQD,KAAK,CAAC,wCAAwCjC,SAASiC;IACjE;AACF"}
|
|
@@ -63,6 +63,31 @@ export declare function recordPosHardwareSerials(input: {
|
|
|
63
63
|
serials: string[];
|
|
64
64
|
recorded: boolean;
|
|
65
65
|
}>;
|
|
66
|
+
/** Records the serial numbers of an order's readers, from the staff page. */
|
|
67
|
+
export declare function recordPosHardwareOrderSerials(input: {
|
|
68
|
+
orgId: string;
|
|
69
|
+
orderId: string;
|
|
70
|
+
serials: unknown;
|
|
71
|
+
}): Promise<PosHardwareOrder>;
|
|
72
|
+
/**
|
|
73
|
+
* Registers one of an order's readers to the buyer's store by the code it
|
|
74
|
+
* shows, from the staff page, before it ships. The order must name the
|
|
75
|
+
* buyer's store (an order from our own store is attached first, from the
|
|
76
|
+
* register's To attach list), and the store's plan must include the point of
|
|
77
|
+
* sale; a store with no reader Location yet is refused with
|
|
78
|
+
* `needs-address`, since only the buyer can say where it is, and the reader
|
|
79
|
+
* is then set up when they pair it.
|
|
80
|
+
*/
|
|
81
|
+
export declare function registerPosHardwareOrderReader(input: {
|
|
82
|
+
orgId: string;
|
|
83
|
+
orderId: string;
|
|
84
|
+
registrationCode: unknown;
|
|
85
|
+
label?: unknown;
|
|
86
|
+
uid: string;
|
|
87
|
+
}): Promise<{
|
|
88
|
+
order: PosHardwareOrder;
|
|
89
|
+
readerId: string;
|
|
90
|
+
}>;
|
|
66
91
|
/**
|
|
67
92
|
* The store a reader bought in person is for, chosen at setup by someone
|
|
68
93
|
* who may set up devices there. The store must be the workspace's.
|