@aglyn/plugins-commerce 1.29.3 → 1.31.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/cart.js +11 -5
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/console/pos/pos-item-dialog.component.js +12 -0
- package/src/lib/components/console/pos/pos-item-dialog.component.js.map +1 -1
- package/src/lib/components/console/pos-kiosk-page.component.js +3 -5
- package/src/lib/components/console/pos-kiosk-page.component.js.map +1 -1
- package/src/lib/components/console/product-add-ons-fields.component.d.ts +11 -0
- package/src/lib/components/console/product-add-ons-fields.component.js +229 -13
- package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +5 -0
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/product-traffic-card.component.d.ts +24 -0
- package/src/lib/components/console/product-traffic-card.component.js +172 -0
- package/src/lib/components/console/product-traffic-card.component.js.map +1 -0
- package/src/lib/components/console/products-hub-card.component.js +181 -59
- package/src/lib/components/console/products-hub-card.component.js.map +1 -1
- package/src/lib/components/console/quote-editor-dialog.component.js +38 -0
- package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/shipping-settings-card.component.js +31 -9
- package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
- package/src/lib/components/product-add-ons.d.ts +21 -0
- package/src/lib/components/product-add-ons.js +77 -1
- package/src/lib/components/product-add-ons.js.map +1 -1
- package/src/lib/components/product-builder-mockup.d.ts +1 -1
- package/src/lib/components/product-builder-mockup.js +17 -5
- package/src/lib/components/product-builder-mockup.js.map +1 -1
- package/src/lib/components/product-choice-cards.js +14 -2
- package/src/lib/components/product-choice-cards.js.map +1 -1
- package/src/lib/model/commerce-pos-kiosk.js +8 -2
- package/src/lib/model/commerce-pos-kiosk.js.map +1 -1
- package/src/lib/model/commerce-pos-offline.d.ts +1 -1
- package/src/lib/model/commerce-pos-offline.js +8 -2
- package/src/lib/model/commerce-pos-offline.js.map +1 -1
- package/src/lib/model/commerce-quote-request.d.ts +1 -0
- package/src/lib/model/commerce-quote-request.js +6 -2
- package/src/lib/model/commerce-quote-request.js.map +1 -1
- package/src/lib/model/commerce-quotes.js +10 -5
- package/src/lib/model/commerce-quotes.js.map +1 -1
- package/src/lib/model/commerce-record-routes.js +31 -0
- package/src/lib/model/commerce-record-routes.js.map +1 -1
- package/src/lib/model/commerce-shipping.d.ts +39 -16
- package/src/lib/model/commerce-shipping.js +315 -30
- package/src/lib/model/commerce-shipping.js.map +1 -1
- package/src/lib/model/commerce.js +1 -1
- package/src/lib/model/commerce.js.map +1 -1
- package/src/lib/model/product-modifiers.d.ts +53 -2
- package/src/lib/model/product-modifiers.js +127 -27
- package/src/lib/model/product-modifiers.js.map +1 -1
- package/src/lib/model/product-write.d.ts +10 -1
- package/src/lib/model/product-write.js +13 -2
- package/src/lib/model/product-write.js.map +1 -1
- package/src/lib/server/carrier-shipping.js +3 -2
- package/src/lib/server/carrier-shipping.js.map +1 -1
- package/src/lib/server/cart-checkout.js +10 -4
- package/src/lib/server/cart-checkout.js.map +1 -1
- package/src/lib/server/cart.js +2 -2
- package/src/lib/server/cart.js.map +1 -1
- package/src/lib/server/checkout.js +6 -4
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/draft-order.js +3 -3
- package/src/lib/server/draft-order.js.map +1 -1
- package/src/lib/server/pos-kiosk.js +1 -4
- package/src/lib/server/pos-kiosk.js.map +1 -1
- package/src/lib/server/product.d.ts +5 -0
- package/src/lib/server/product.js +10 -2
- package/src/lib/server/product.js.map +1 -1
- package/src/lib/server/products-write.js +10 -2
- package/src/lib/server/products-write.js.map +1 -1
- package/src/lib/transfer/product-register-cells.d.ts +7 -0
- package/src/lib/transfer/product-register-cells.js +88 -10
- package/src/lib/transfer/product-register-cells.js.map +1 -1
|
@@ -40,9 +40,50 @@
|
|
|
40
40
|
* one price for a bundle ("Weekend kit: 4 walls, 4 weights, a bag"), and the
|
|
41
41
|
* card folds its contents out. Display only: a combo is priced and sold as
|
|
42
42
|
* the one choice it is.
|
|
43
|
-
|
|
43
|
+
*
|
|
44
|
+
* WRITE-INS (write-ins). A group of `kind: 'text'` asks the
|
|
45
|
+
* shopper to type an answer instead of picking one: the name and number
|
|
46
|
+
* printed on a sign, an engraving, a cake message. It holds exactly one option, which carries what a
|
|
47
|
+
* filled answer adds to the price (by variant too) and its helper note, so
|
|
48
|
+
* pricing, ids and every path that carries picks stay the same; the pick
|
|
49
|
+
* adds the `text`. The answer is checked and cleaned on the server like any
|
|
50
|
+
* pick ({@link cleanWriteIn}) and prints on the line as "Engraving: For
|
|
51
|
+
* Sam". With write-ins and required size groups, one variant sells a set
|
|
52
|
+
* of pieces in any combination of sizes, with no cap on combinations.
|
|
53
|
+
*=========================================*/ /** One choice in a modifier group. `priceCents` is added to the item, 0 for free. */ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
54
|
+
export const POS_MAX_MODIFIER_GROUPS = 10;
|
|
44
55
|
export const POS_MAX_MODIFIER_OPTIONS = 20;
|
|
45
56
|
/** $1,000 on one modifier: anything larger is a product, not an add-on. */ export const POS_MAX_MODIFIER_PRICE_CENTS = 100000;
|
|
57
|
+
/** The longest answer a write-in can take: a name or a short message fits well inside. */ export const MAX_WRITE_IN_LENGTH = 40;
|
|
58
|
+
/** A write-in's length when the merchant sets none. */ export const DEFAULT_WRITE_IN_LENGTH = 20;
|
|
59
|
+
/** How much of a typed answer is carried before its group checks it. */ const WRITE_IN_INPUT_BOUND = 200;
|
|
60
|
+
/** Whether a group is a write-in the shopper types. */ export function modifierGroupIsWriteIn(group) {
|
|
61
|
+
return (group == null ? void 0 : group.kind) === 'text';
|
|
62
|
+
}
|
|
63
|
+
/** A write-in's longest answer. */ export function writeInMaxLength(group) {
|
|
64
|
+
const length = group.maxLength;
|
|
65
|
+
return typeof length === 'number' && Number.isInteger(length) && length >= 1 && length <= MAX_WRITE_IN_LENGTH ? length : DEFAULT_WRITE_IN_LENGTH;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* A write-in's answer cleaned for the order: control characters and runs of
|
|
69
|
+
* spaces gone, trimmed, cut at the group's length. Empty when nothing is left.
|
|
70
|
+
* Without a group the answer is only bounded, so a too-long one still reaches
|
|
71
|
+
* the check that names it.
|
|
72
|
+
*/ export function cleanWriteIn(raw, group) {
|
|
73
|
+
if (typeof raw !== 'string') return '';
|
|
74
|
+
const limit = group ? writeInMaxLength(group) : WRITE_IN_INPUT_BOUND;
|
|
75
|
+
const flat = raw// eslint-disable-next-line no-control-regex
|
|
76
|
+
.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, ' ').replace(/\s+/g, ' ').trim();
|
|
77
|
+
return Array.from(flat).slice(0, limit).join('').trim();
|
|
78
|
+
}
|
|
79
|
+
/** Why a write-in's answer cannot be sold, or null when it can. An empty answer is the minimum's business. */ export function writeInProblem(group, raw) {
|
|
80
|
+
const typed = cleanWriteIn(raw);
|
|
81
|
+
if (!typed) return null;
|
|
82
|
+
const limit = writeInMaxLength(group);
|
|
83
|
+
if (Array.from(typed).length > limit) return `${group.name} takes up to ${limit} characters.`;
|
|
84
|
+
if (group.digitsOnly && !/^[0-9]+$/.test(typed)) return `${group.name} takes numbers only.`;
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
46
87
|
/** Whether a choice is a combo: it lists what it includes (AGL-4205). */ export function modifierOptionIsCombo(option) {
|
|
47
88
|
return Array.isArray(option.includes) && option.includes.length > 0 && option.includes.every((item)=>typeof item === 'string');
|
|
48
89
|
}
|
|
@@ -62,6 +103,22 @@ function modifierPriceIsValid(price) {
|
|
|
62
103
|
groupIds.add(group.id);
|
|
63
104
|
if (!String((_group_name = group.name) != null ? _group_name : '').trim()) return 'Name every modifier group';
|
|
64
105
|
const options = Array.isArray(group.options) ? group.options : [];
|
|
106
|
+
if (group.kind != null && group.kind !== 'text') return `“${group.name}” is a list of choices or a write-in`;
|
|
107
|
+
if (group.kind === 'text') {
|
|
108
|
+
if (options.length !== 1) return `“${group.name}” is a write-in and holds one field`;
|
|
109
|
+
if (group.max !== 1 || group.min !== 0 && group.min !== 1) {
|
|
110
|
+
return `“${group.name}” is a write-in: required or not, one answer`;
|
|
111
|
+
}
|
|
112
|
+
if (group.maxLength != null && (!Number.isInteger(group.maxLength) || group.maxLength < 1 || group.maxLength > MAX_WRITE_IN_LENGTH)) {
|
|
113
|
+
return `“${group.name}” takes 1 to ${MAX_WRITE_IN_LENGTH} characters`;
|
|
114
|
+
}
|
|
115
|
+
if (group.digitsOnly != null && typeof group.digitsOnly !== 'boolean') {
|
|
116
|
+
return `“${group.name}” takes numbers only or any text`;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (group.nameOnOrder != null && typeof group.nameOnOrder !== 'boolean') {
|
|
120
|
+
return `“${group.name}” prints its name on the order or not`;
|
|
121
|
+
}
|
|
65
122
|
if (options.length === 0) return `Add a choice to “${group.name}”`;
|
|
66
123
|
if (options.length > POS_MAX_MODIFIER_OPTIONS) {
|
|
67
124
|
return `“${group.name}” has more than ${POS_MAX_MODIFIER_OPTIONS} choices`;
|
|
@@ -132,12 +189,29 @@ function modifierPriceIsValid(price) {
|
|
|
132
189
|
/** The picks a request names, as ids only, bounded; nothing for a value that is not a list. */ export function modifierSelectionFrom(raw) {
|
|
133
190
|
return (Array.isArray(raw) ? raw : []).slice(0, POS_MAX_MODIFIER_GROUPS * POS_MAX_MODIFIER_OPTIONS).map((entry)=>{
|
|
134
191
|
var _ref, _ref1;
|
|
135
|
-
|
|
192
|
+
const pick = {
|
|
136
193
|
groupId: String((_ref = entry == null ? void 0 : entry.groupId) != null ? _ref : ''),
|
|
137
194
|
optionId: String((_ref1 = entry == null ? void 0 : entry.optionId) != null ? _ref1 : '')
|
|
138
195
|
};
|
|
196
|
+
// A write-in's answer, bounded here and checked against its group when priced.
|
|
197
|
+
const text = cleanWriteIn(entry == null ? void 0 : entry.text);
|
|
198
|
+
if (text) pick.text = text;
|
|
199
|
+
return pick;
|
|
139
200
|
});
|
|
140
201
|
}
|
|
202
|
+
/** A pick as the order keeps it: a choice, or a write-in with its answer. */ function soldModifier(group, option, variantId, text) {
|
|
203
|
+
return _extends({
|
|
204
|
+
groupId: group.id,
|
|
205
|
+
optionId: option.id,
|
|
206
|
+
group: group.name,
|
|
207
|
+
name: option.name,
|
|
208
|
+
priceCents: modifierOptionPriceCents(option, variantId)
|
|
209
|
+
}, text ? {
|
|
210
|
+
text
|
|
211
|
+
} : {}, group.nameOnOrder === true ? {
|
|
212
|
+
nameOnOrder: true
|
|
213
|
+
} : {});
|
|
214
|
+
}
|
|
141
215
|
/**
|
|
142
216
|
* Prices a line's chosen modifiers from the PRODUCT, in group order, and
|
|
143
217
|
* checks every group's minimum and maximum. Unknown ids, a repeated choice
|
|
@@ -167,6 +241,20 @@ function modifierPriceIsValid(price) {
|
|
|
167
241
|
}
|
|
168
242
|
const modifiers = [];
|
|
169
243
|
for (const group of groups){
|
|
244
|
+
if (modifierGroupIsWriteIn(group)) {
|
|
245
|
+
// A write-in (write-ins): its answer is checked, cleaned and kept.
|
|
246
|
+
const option = group.options[0];
|
|
247
|
+
const pick = picks.find((entry)=>entry.groupId === group.id && entry.optionId === option.id);
|
|
248
|
+
const problem = writeInProblem(group, pick == null ? void 0 : pick.text);
|
|
249
|
+
if (problem) return refuse(`${problem} (${product.name})`);
|
|
250
|
+
const text = cleanWriteIn(pick == null ? void 0 : pick.text, group);
|
|
251
|
+
if (!text) {
|
|
252
|
+
if (group.min > 0) return refuse(`Fill in ${group.name.toLowerCase()} for ${product.name}.`);
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
modifiers.push(soldModifier(group, option, variantId, text));
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
170
258
|
const chosen = group.options.filter((option)=>picks.some((pick)=>pick.groupId === group.id && pick.optionId === option.id));
|
|
171
259
|
if (chosen.length < group.min) {
|
|
172
260
|
return refuse(`Choose ${group.name.toLowerCase()} for ${product.name}.`);
|
|
@@ -174,15 +262,7 @@ function modifierPriceIsValid(price) {
|
|
|
174
262
|
if (chosen.length > group.max) {
|
|
175
263
|
return refuse(`Choose at most ${group.max} for ${group.name.toLowerCase()} on ${product.name}.`);
|
|
176
264
|
}
|
|
177
|
-
for (const option of chosen)
|
|
178
|
-
modifiers.push({
|
|
179
|
-
groupId: group.id,
|
|
180
|
-
optionId: option.id,
|
|
181
|
-
group: group.name,
|
|
182
|
-
name: option.name,
|
|
183
|
-
priceCents: modifierOptionPriceCents(option, variantId)
|
|
184
|
-
});
|
|
185
|
-
}
|
|
265
|
+
for (const option of chosen)modifiers.push(soldModifier(group, option, variantId, undefined));
|
|
186
266
|
}
|
|
187
267
|
return {
|
|
188
268
|
ok: true,
|
|
@@ -210,16 +290,13 @@ function modifierPriceIsValid(price) {
|
|
|
210
290
|
const picks = modifierSelectionFrom(raw);
|
|
211
291
|
const modifiers = [];
|
|
212
292
|
for (const group of productModifierGroups(product)){
|
|
293
|
+
const writeIn = modifierGroupIsWriteIn(group);
|
|
213
294
|
for (const option of group.options){
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
name: option.name,
|
|
220
|
-
priceCents: modifierOptionPriceCents(option, variantId)
|
|
221
|
-
});
|
|
222
|
-
}
|
|
295
|
+
const pick = picks.find((entry)=>entry.groupId === group.id && entry.optionId === option.id);
|
|
296
|
+
if (!pick) continue;
|
|
297
|
+
const text = writeIn ? cleanWriteIn(pick.text, group) : undefined;
|
|
298
|
+
if (writeIn && !text) continue;
|
|
299
|
+
modifiers.push(soldModifier(group, option, variantId, text));
|
|
223
300
|
}
|
|
224
301
|
}
|
|
225
302
|
return modifiers;
|
|
@@ -232,17 +309,24 @@ function modifierPriceIsValid(price) {
|
|
|
232
309
|
return /Remove it and add it again/.test(reason) ? reason : `${reason} Remove it and add it again from its page.`;
|
|
233
310
|
}
|
|
234
311
|
/** The picks a priced line keeps: ids only, in the product's group order. */ export function modifierSelectionOf(modifiers) {
|
|
235
|
-
return modifiers.map((modifier)=>({
|
|
312
|
+
return modifiers.map((modifier)=>_extends({
|
|
236
313
|
groupId: modifier.groupId,
|
|
237
314
|
optionId: modifier.optionId
|
|
238
|
-
}
|
|
315
|
+
}, modifier.text ? {
|
|
316
|
+
text: modifier.text
|
|
317
|
+
} : {}));
|
|
239
318
|
}
|
|
240
319
|
/**
|
|
241
320
|
* The picks as one metadata value (AGL-4100), for a payment processor that
|
|
242
321
|
* holds strings only: `[["group","option"],…]`. Empty for no picks.
|
|
243
322
|
*/ export function encodeModifierSelection(selection) {
|
|
244
323
|
if (!(selection == null ? void 0 : selection.length)) return '';
|
|
245
|
-
|
|
324
|
+
// A write-in's answer rides as a third entry: `[["group","option","For Sam"],…]`.
|
|
325
|
+
return JSON.stringify(selection.map((pick)=>pick.text ? [
|
|
326
|
+
pick.groupId,
|
|
327
|
+
pick.optionId,
|
|
328
|
+
pick.text
|
|
329
|
+
] : [
|
|
246
330
|
pick.groupId,
|
|
247
331
|
pick.optionId
|
|
248
332
|
]));
|
|
@@ -252,16 +336,32 @@ function modifierPriceIsValid(price) {
|
|
|
252
336
|
try {
|
|
253
337
|
const parsed = JSON.parse(value);
|
|
254
338
|
if (!Array.isArray(parsed)) return [];
|
|
255
|
-
return parsed.filter((pair)=>Array.isArray(pair) && typeof pair[0] === 'string' && typeof pair[1] === 'string').slice(0, POS_MAX_MODIFIER_GROUPS * POS_MAX_MODIFIER_OPTIONS).map(([groupId, optionId])=>
|
|
339
|
+
return parsed.filter((pair)=>Array.isArray(pair) && typeof pair[0] === 'string' && typeof pair[1] === 'string').slice(0, POS_MAX_MODIFIER_GROUPS * POS_MAX_MODIFIER_OPTIONS).map(([groupId, optionId, typed])=>{
|
|
340
|
+
const text = cleanWriteIn(typed);
|
|
341
|
+
return text ? {
|
|
342
|
+
groupId,
|
|
343
|
+
optionId,
|
|
344
|
+
text
|
|
345
|
+
} : {
|
|
256
346
|
groupId,
|
|
257
347
|
optionId
|
|
258
|
-
}
|
|
348
|
+
};
|
|
349
|
+
});
|
|
259
350
|
} catch (unused) {
|
|
260
351
|
return [];
|
|
261
352
|
}
|
|
262
353
|
}
|
|
354
|
+
/**
|
|
355
|
+
* How one modifier prints on a line: its name (`Oat milk`), its group and
|
|
356
|
+
* name when the group asks for it (`Size: M`), or a write-in's name
|
|
357
|
+
* and answer (`Engraving: For Sam`).
|
|
358
|
+
*/ export function modifierLineText(modifier) {
|
|
359
|
+
if (modifier.text) return `${modifier.group || modifier.name}: ${modifier.text}`;
|
|
360
|
+
if (modifier.nameOnOrder && modifier.group) return `${modifier.group}: ${modifier.name}`;
|
|
361
|
+
return modifier.name;
|
|
362
|
+
}
|
|
263
363
|
/** The label a line prints: the variant, then each modifier (`Large / Oat milk, Extra shot`). */ export function lineLabelWithModifiers(variantLabel, modifiers) {
|
|
264
|
-
const added = modifiers.map(
|
|
364
|
+
const added = modifiers.map(modifierLineText).join(', ');
|
|
265
365
|
return [
|
|
266
366
|
variantLabel,
|
|
267
367
|
added
|
|
@@ -270,7 +370,7 @@ function modifierPriceIsValid(price) {
|
|
|
270
370
|
/** Two lines merge only when they are the same item with the same choices. */ export function modifierSelectionKey(selection) {
|
|
271
371
|
return [
|
|
272
372
|
...selection != null ? selection : []
|
|
273
|
-
].map((pick)
|
|
373
|
+
].map((pick)=>pick.text ? `${pick.groupId}:${pick.optionId}=${pick.text}` : `${pick.groupId}:${pick.optionId}`).sort().join('|');
|
|
274
374
|
}
|
|
275
375
|
|
|
276
376
|
//# sourceMappingURL=product-modifiers.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/product-modifiers.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * REGISTER MODIFIERS AND QUICK KEYS (AGL-3607).\n *\n * A modifier is a choice added to an item as it is rung up — \"Oat milk\",\n * \"Extra shot +$0.75\", \"No onions\" — that is not a stocked variant. Groups\n * live on the product (`modifierGroups`); the register sends the chosen\n * option ids with each line and the SERVER prices them from the product\n * document, so a register never names what a modifier costs.\n *\n * A chosen modifier is folded into the line's `variantLabel` as well as kept\n * structured in `modifiers`: every receipt, email, order view and export\n * already prints the label, so the choice reaches all of them without each\n * learning a new field.\n *\n * ADD-ONS ON THE WEBSITE (AGL-4100). A group switched to \"Show on the\n * website\" (`online`) is offered on the product's page too, and a cart line,\n * Buy now and the order carry its picks the same way: ids from the shopper,\n * prices from the product. A choice may cost more on one variant than\n * another (`priceCentsByVariant`), which is how one page sells a canopy whose\n * walls cost more at a larger size without a variant for every combination.\n *\n * THE PRODUCT BUILDER (AGL-4205). A choice may carry a picture and a short\n * note, which a product page set to show its choices as picture cards draws\n * on the choice's card. A choice that lists what it `includes` is a combo:\n * one price for a bundle (\"Weekend kit: 4 walls, 4 weights, a bag\"), and the\n * card folds its contents out. Display only: a combo is priced and sold as\n * the one choice it is.\n *=========================================*/\n\n/** One choice in a modifier group. `priceCents` is added to the item, 0 for free. */\nexport interface ProductModifierOption {\n id: string\n name: string\n priceCents: number\n /**\n * What the choice adds on one variant, keyed by variant id (AGL-4100):\n * walls cost more on a larger canopy. A variant not listed pays\n * `priceCents`. Read through {@link modifierOptionPriceCents}.\n */\n priceCentsByVariant?: Record<string, number>\n /** A picture of the choice, from the media library, for its card (AGL-4205). */\n imageUrl?: string\n /** A short line under the choice on its card (AGL-4205): \"Blocks wind on one side\". */\n note?: string\n /**\n * What a combo holds (AGL-4205), one item per entry: \"Full wall ×2\". A\n * choice with any is shown as a combo whose contents fold out.\n */\n includes?: string[]\n}\n\n/**\n * A set of choices offered together (\"Milk\", \"Add-ons\"). `min` of 1 or more\n * makes it required; `max` caps how many can be picked (1 = pick one).\n */\nexport interface ProductModifierGroup {\n id: string\n name: string\n min: number\n max: number\n options: ProductModifierOption[]\n /**\n * Offered on the product's page on the website as well as at the register\n * (AGL-4100), \"Show on the website\". Absent reads as register only, so a\n * group made before the switch changes nothing on a live store; the\n * console makes new groups with it on.\n */\n online?: boolean\n}\n\n/** A modifier as the order line keeps it: names and price as sold. */\nexport interface OrderLineModifier {\n groupId: string\n optionId: string\n group: string\n name: string\n priceCents: number\n}\n\n/** What the register sends for a line: the option ids it picked, nothing priced. */\nexport interface ModifierSelection {\n groupId: string\n optionId: string\n}\n\nexport const POS_MAX_MODIFIER_GROUPS = 10\nexport const POS_MAX_MODIFIER_OPTIONS = 20\n/** $1,000 on one modifier: anything larger is a product, not an add-on. */\nexport const POS_MAX_MODIFIER_PRICE_CENTS = 100_000\n/** Whether a choice is a combo: it lists what it includes (AGL-4205). */\nexport function modifierOptionIsCombo(option: Pick<ProductModifierOption, 'includes'>): boolean {\n return (\n Array.isArray(option.includes) &&\n option.includes.length > 0 &&\n option.includes.every((item) => typeof item === 'string')\n )\n}\n\nfunction modifierPriceIsValid(price: unknown): boolean {\n return (\n typeof price === 'number' &&\n Number.isInteger(price) &&\n price >= 0 &&\n price <= POS_MAX_MODIFIER_PRICE_CENTS\n )\n}\n\n/** Why a product's modifier groups cannot be saved, or null when they can. */\nexport function modifierGroupsProblem(groups: unknown): string | null {\n if (groups == null) return null\n if (!Array.isArray(groups)) return 'Modifiers must be a list'\n if (groups.length > POS_MAX_MODIFIER_GROUPS) {\n return `At most ${POS_MAX_MODIFIER_GROUPS} modifier groups per product`\n }\n const groupIds = new Set<string>()\n for (const group of groups as ProductModifierGroup[]) {\n if (!group?.id || groupIds.has(group.id)) return 'Modifier groups need unique ids'\n groupIds.add(group.id)\n if (!String(group.name ?? '').trim()) return 'Name every modifier group'\n const options = Array.isArray(group.options) ? group.options : []\n if (options.length === 0) return `Add a choice to “${group.name}”`\n if (options.length > POS_MAX_MODIFIER_OPTIONS) {\n return `“${group.name}” has more than ${POS_MAX_MODIFIER_OPTIONS} choices`\n }\n const optionIds = new Set<string>()\n for (const option of options) {\n if (!option?.id || optionIds.has(option.id)) return 'Modifier choices need unique ids'\n optionIds.add(option.id)\n if (!String(option.name ?? '').trim()) return `Name every choice in “${group.name}”`\n const price = option.priceCents\n if (!modifierPriceIsValid(price)) {\n return `“${option.name}” needs a price of $0 to $1,000`\n }\n const byVariant = option.priceCentsByVariant\n if (byVariant != null) {\n if (typeof byVariant !== 'object' || Array.isArray(byVariant)) {\n return `“${option.name}” has prices that are not a list by option`\n }\n if (Object.values(byVariant).some((cents) => !modifierPriceIsValid(cents))) {\n return `“${option.name}” needs a price of $0 to $1,000 for each option it is priced by`\n }\n }\n }\n if (group.online != null && typeof group.online !== 'boolean') {\n return `“${group.name}” is shown on the website or not`\n }\n const { min, max } = group\n if (!Number.isInteger(min) || min < 0) return `“${group.name}” needs a minimum of 0 or more`\n if (!Number.isInteger(max) || max < 1 || max > options.length) {\n return `“${group.name}” allows 1 to ${options.length} choices`\n }\n if (min > max) return `“${group.name}” requires more choices than it allows`\n }\n return null\n}\n\n/** How a variant is named in a choice's price list, in the editor and in an import file. */\nexport function variantPriceLabel(variant: { options?: Record<string, string> }): string {\n const values = Object.values(variant.options ?? {}).filter(Boolean)\n return values.length ? values.join(' / ') : 'Default'\n}\n\n/** The product's groups, or none when they are missing or malformed. */\nexport function productModifierGroups(product: {\n modifierGroups?: unknown\n}): ProductModifierGroup[] {\n const groups = product?.modifierGroups\n if (!Array.isArray(groups) || modifierGroupsProblem(groups)) return []\n return groups as ProductModifierGroup[]\n}\n\n/** Whether a group must be answered before the item can be added. */\nexport function modifierGroupRequired(group: ProductModifierGroup): boolean {\n return group.min > 0\n}\n\n/**\n * The groups the product's page on the website offers (AGL-4100): those\n * switched to \"Show on the website\". A register-only group is never sent to\n * a shopper, never asked of one and never priced on an online order.\n */\nexport function websiteModifierGroups(product: { modifierGroups?: unknown }): ProductModifierGroup[] {\n return productModifierGroups(product).filter((group) => group.online === true)\n}\n\n/** Whether the website must ask a shopper a choice before the item goes in a cart. */\nexport function websiteModifiersRequired(product: { modifierGroups?: unknown }): boolean {\n return websiteModifierGroups(product).some(modifierGroupRequired)\n}\n\n/**\n * What one choice adds to one unit of the picked variant (AGL-4100): its\n * price on that variant where it has one, else its own price.\n */\nexport function modifierOptionPriceCents(\n option: Pick<ProductModifierOption, 'priceCents' | 'priceCentsByVariant'>,\n variantId?: string | null,\n): number {\n const byVariant = variantId ? option.priceCentsByVariant?.[variantId] : undefined\n return typeof byVariant === 'number' && Number.isFinite(byVariant) ? byVariant : option.priceCents\n}\n\n/** A line's chosen modifiers, priced. */\nexport interface ResolvedLineModifiers {\n ok: boolean\n /** The chosen modifiers, in group order; empty when not `ok`. */\n modifiers: OrderLineModifier[]\n /** What they add to one unit, in cents. */\n extraCents: number\n /** What to fix, when not `ok`. */\n error?: string\n}\n\n/** The picks a request names, as ids only, bounded; nothing for a value that is not a list. */\nexport function modifierSelectionFrom(raw: unknown): ModifierSelection[] {\n return (Array.isArray(raw) ? raw : [])\n .slice(0, POS_MAX_MODIFIER_GROUPS * POS_MAX_MODIFIER_OPTIONS)\n .map((entry: any) => ({\n groupId: String(entry?.groupId ?? ''),\n optionId: String(entry?.optionId ?? ''),\n }))\n}\n\n/**\n * Prices a line's chosen modifiers from the PRODUCT, in group order, and\n * checks every group's minimum and maximum. Unknown ids, a repeated choice\n * and a group answered past its maximum are refused with what to fix.\n *\n * `variantId` is the variant the line sells (AGL-4100): a choice priced by\n * variant adds its price on that one. Without it every choice adds its own\n * `priceCents`, as it always did.\n */\nexport function resolveLineModifiers(\n product: { name?: string; modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): ResolvedLineModifiers {\n const refuse = (error: string): ResolvedLineModifiers => ({\n ok: false,\n modifiers: [],\n extraCents: 0,\n error,\n })\n const groups = productModifierGroups(product)\n const picks = modifierSelectionFrom(raw)\n const seen = new Set<string>()\n for (const pick of picks) {\n const key = `${pick.groupId}:${pick.optionId}`\n if (seen.has(key)) return refuse(`A choice on ${product.name} was picked twice.`)\n seen.add(key)\n const group = groups.find((entry) => entry.id === pick.groupId)\n if (!group || !group.options.some((option) => option.id === pick.optionId)) {\n return refuse(`A choice on ${product.name} is no longer offered. Remove it and add it again.`)\n }\n }\n const modifiers: OrderLineModifier[] = []\n for (const group of groups) {\n const chosen = group.options.filter((option) =>\n picks.some((pick) => pick.groupId === group.id && pick.optionId === option.id),\n )\n if (chosen.length < group.min) {\n return refuse(`Choose ${group.name.toLowerCase()} for ${product.name}.`)\n }\n if (chosen.length > group.max) {\n return refuse(`Choose at most ${group.max} for ${group.name.toLowerCase()} on ${product.name}.`)\n }\n for (const option of chosen) {\n modifiers.push({\n groupId: group.id,\n optionId: option.id,\n group: group.name,\n name: option.name,\n priceCents: modifierOptionPriceCents(option, variantId),\n })\n }\n }\n return {\n ok: true,\n modifiers,\n extraCents: modifiers.reduce((sum, modifier) => sum + modifier.priceCents, 0),\n }\n}\n\n/**\n * {@link resolveLineModifiers} for a sale made online (AGL-4100): only the\n * groups shown on the website are offered, asked or priced. A register-only\n * group, required or not, is not the shopper's to answer.\n */\nexport function resolveWebsiteLineModifiers(\n product: { name?: string; modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): ResolvedLineModifiers {\n return resolveLineModifiers(\n { name: product.name, modifierGroups: websiteModifierGroups(product) },\n raw,\n variantId,\n )\n}\n\n/**\n * The modifiers a PAID line names, for its order record (AGL-4100): every\n * pick the product still offers, in group order, priced as it is now, with no\n * minimum or maximum asked. The money was taken when the sale was priced;\n * a choice the merchant removed since is left off the record, never a reason\n * to lose the order.\n */\nexport function soldLineModifiers(\n product: { modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): OrderLineModifier[] {\n const picks = modifierSelectionFrom(raw)\n const modifiers: OrderLineModifier[] = []\n for (const group of productModifierGroups(product)) {\n for (const option of group.options) {\n if (picks.some((pick) => pick.groupId === group.id && pick.optionId === option.id)) {\n modifiers.push({\n groupId: group.id,\n optionId: option.id,\n group: group.name,\n name: option.name,\n priceCents: modifierOptionPriceCents(option, variantId),\n })\n }\n }\n }\n return modifiers\n}\n\n/**\n * What a shopper is told about a cart line whose add-ons no longer answer\n * the product (AGL-4100): the resolver's reason, and how to put it right.\n */\nexport function cartLineModifierProblem(error: string | undefined): string {\n const reason = String(error ?? '').trim() || 'The choices on this item have changed.'\n return /Remove it and add it again/.test(reason)\n ? reason\n : `${reason} Remove it and add it again from its page.`\n}\n\n/** The picks a priced line keeps: ids only, in the product's group order. */\nexport function modifierSelectionOf(\n modifiers: readonly Pick<OrderLineModifier, 'groupId' | 'optionId'>[],\n): ModifierSelection[] {\n return modifiers.map((modifier) => ({ groupId: modifier.groupId, optionId: modifier.optionId }))\n}\n\n/**\n * The picks as one metadata value (AGL-4100), for a payment processor that\n * holds strings only: `[[\"group\",\"option\"],…]`. Empty for no picks.\n */\nexport function encodeModifierSelection(selection: readonly ModifierSelection[] | undefined): string {\n if (!selection?.length) return ''\n return JSON.stringify(selection.map((pick) => [pick.groupId, pick.optionId]))\n}\n\n/** {@link encodeModifierSelection} read back; nothing for a value it did not write. */\nexport function decodeModifierSelection(value: unknown): ModifierSelection[] {\n if (typeof value !== 'string' || !value) return []\n try {\n const parsed: unknown = JSON.parse(value)\n if (!Array.isArray(parsed)) return []\n return parsed\n .filter(\n (pair): pair is [string, string] =>\n Array.isArray(pair) && typeof pair[0] === 'string' && typeof pair[1] === 'string',\n )\n .slice(0, POS_MAX_MODIFIER_GROUPS * POS_MAX_MODIFIER_OPTIONS)\n .map(([groupId, optionId]) => ({ groupId, optionId }))\n } catch {\n return []\n }\n}\n\n/** The label a line prints: the variant, then each modifier (`Large / Oat milk, Extra shot`). */\nexport function lineLabelWithModifiers(\n variantLabel: string | undefined,\n modifiers: readonly Pick<OrderLineModifier, 'name'>[],\n): string {\n const added = modifiers.map((modifier) => modifier.name).join(', ')\n return [variantLabel, added].filter(Boolean).join(' / ')\n}\n\n/** Two lines merge only when they are the same item with the same choices. */\nexport function modifierSelectionKey(selection: readonly ModifierSelection[] | undefined): string {\n return [...(selection ?? [])]\n .map((pick) => `${pick.groupId}:${pick.optionId}`)\n .sort()\n .join('|')\n}\n"],"names":["POS_MAX_MODIFIER_GROUPS","POS_MAX_MODIFIER_OPTIONS","POS_MAX_MODIFIER_PRICE_CENTS","modifierOptionIsCombo","option","Array","isArray","includes","length","every","item","modifierPriceIsValid","price","Number","isInteger","modifierGroupsProblem","groups","groupIds","Set","group","id","has","add","String","name","trim","options","optionIds","priceCents","byVariant","priceCentsByVariant","Object","values","some","cents","online","min","max","variantPriceLabel","variant","filter","Boolean","join","productModifierGroups","product","modifierGroups","modifierGroupRequired","websiteModifierGroups","websiteModifiersRequired","modifierOptionPriceCents","variantId","undefined","isFinite","modifierSelectionFrom","raw","slice","map","entry","groupId","optionId","resolveLineModifiers","refuse","error","ok","modifiers","extraCents","picks","seen","pick","key","find","chosen","toLowerCase","push","reduce","sum","modifier","resolveWebsiteLineModifiers","soldLineModifiers","cartLineModifierProblem","reason","test","modifierSelectionOf","encodeModifierSelection","selection","JSON","stringify","decodeModifierSelection","value","parsed","parse","pair","lineLabelWithModifiers","variantLabel","added","modifierSelectionKey","sort"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA2B2C,GAE3C,mFAAmF,GAwDnF,OAAO,MAAMA,0BAA0B,GAAE;AACzC,OAAO,MAAMC,2BAA2B,GAAE;AAC1C,yEAAyE,GACzE,OAAO,MAAMC,+BAA+B,OAAO;AACnD,uEAAuE,GACvE,OAAO,SAASC,sBAAsBC,MAA+C;IACnF,OACEC,MAAMC,OAAO,CAACF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AAOA,IAAI,CAAC,EAAE,KAAK,YAAY,OAAOA,IAAI,CAAC,EAAE,KAAK,UAE5EpC,KAAK,CAAC,GAAGvD,0BAA0BC,0BACnCuD,GAAG,CAAC,CAAC,CAACE,SAASC,SAAS,GAAM,CAAA;gBAAED;gBAASC;YAAS,CAAA;IACvD,EAAE,eAAM;QACN,OAAO,EAAE;IACX;AACF;AAEA,+FAA+F,GAC/F,OAAO,SAASiC,uBACdC,YAAgC,EAChC7B,SAAqD;IAErD,MAAM8B,QAAQ9B,UAAUR,GAAG,CAAC,CAACoB,WAAaA,SAASpD,IAAI,EAAEkB,IAAI,CAAC;IAC9D,OAAO;QAACmD;QAAcC;KAAM,CAACtD,MAAM,CAACC,SAASC,IAAI,CAAC;AACpD;AAEA,4EAA4E,GAC5E,OAAO,SAASqD,qBAAqBX,SAAmD;IACtF,OAAO;WAAKA,oBAAAA,YAAa,EAAE;KAAE,CAC1B5B,GAAG,CAAC,CAACY,OAAS,GAAGA,KAAKV,OAAO,CAAC,CAAC,EAAEU,KAAKT,QAAQ,EAAE,EAChDqC,IAAI,GACJtD,IAAI,CAAC;AACV"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/product-modifiers.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * REGISTER MODIFIERS AND QUICK KEYS (AGL-3607).\n *\n * A modifier is a choice added to an item as it is rung up — \"Oat milk\",\n * \"Extra shot +$0.75\", \"No onions\" — that is not a stocked variant. Groups\n * live on the product (`modifierGroups`); the register sends the chosen\n * option ids with each line and the SERVER prices them from the product\n * document, so a register never names what a modifier costs.\n *\n * A chosen modifier is folded into the line's `variantLabel` as well as kept\n * structured in `modifiers`: every receipt, email, order view and export\n * already prints the label, so the choice reaches all of them without each\n * learning a new field.\n *\n * ADD-ONS ON THE WEBSITE (AGL-4100). A group switched to \"Show on the\n * website\" (`online`) is offered on the product's page too, and a cart line,\n * Buy now and the order carry its picks the same way: ids from the shopper,\n * prices from the product. A choice may cost more on one variant than\n * another (`priceCentsByVariant`), which is how one page sells a canopy whose\n * walls cost more at a larger size without a variant for every combination.\n *\n * THE PRODUCT BUILDER (AGL-4205). A choice may carry a picture and a short\n * note, which a product page set to show its choices as picture cards draws\n * on the choice's card. A choice that lists what it `includes` is a combo:\n * one price for a bundle (\"Weekend kit: 4 walls, 4 weights, a bag\"), and the\n * card folds its contents out. Display only: a combo is priced and sold as\n * the one choice it is.\n *\n * WRITE-INS (write-ins). A group of `kind: 'text'` asks the\n * shopper to type an answer instead of picking one: the name and number\n * printed on a sign, an engraving, a cake message. It holds exactly one option, which carries what a\n * filled answer adds to the price (by variant too) and its helper note, so\n * pricing, ids and every path that carries picks stay the same; the pick\n * adds the `text`. The answer is checked and cleaned on the server like any\n * pick ({@link cleanWriteIn}) and prints on the line as \"Engraving: For\n * Sam\". With write-ins and required size groups, one variant sells a set\n * of pieces in any combination of sizes, with no cap on combinations.\n *=========================================*/\n\n/** One choice in a modifier group. `priceCents` is added to the item, 0 for free. */\nexport interface ProductModifierOption {\n id: string\n name: string\n priceCents: number\n /**\n * What the choice adds on one variant, keyed by variant id (AGL-4100):\n * walls cost more on a larger canopy. A variant not listed pays\n * `priceCents`. Read through {@link modifierOptionPriceCents}.\n */\n priceCentsByVariant?: Record<string, number>\n /** A picture of the choice, from the media library, for its card (AGL-4205). */\n imageUrl?: string\n /** A short line under the choice on its card (AGL-4205): \"Blocks wind on one side\". */\n note?: string\n /**\n * What a combo holds (AGL-4205), one item per entry: \"Full wall ×2\". A\n * choice with any is shown as a combo whose contents fold out.\n */\n includes?: string[]\n}\n\n/**\n * A set of choices offered together (\"Milk\", \"Add-ons\"). `min` of 1 or more\n * makes it required; `max` caps how many can be picked (1 = pick one).\n */\nexport interface ProductModifierGroup {\n id: string\n name: string\n min: number\n max: number\n options: ProductModifierOption[]\n /**\n * `'text'` makes the group a write-in: the shopper types the answer (a\n * name, a number) into one field. Absent is a group of choices. A write-in\n * holds exactly one option, which names it and prices it.\n */\n kind?: ProductModifierGroupKind\n /** A write-in's longest answer, 1 to {@link MAX_WRITE_IN_LENGTH}; {@link DEFAULT_WRITE_IN_LENGTH} when absent. */\n maxLength?: number\n /** A write-in that takes digits only, such as a number. */\n digitsOnly?: boolean\n /**\n * Print the group's name before the choice on the order, receipt and\n * emails (\"Size: M\"), for choices that do not say what they are on\n * their own. A write-in always prints its name.\n */\n nameOnOrder?: boolean\n /**\n * Offered on the product's page on the website as well as at the register\n * (AGL-4100), \"Show on the website\". Absent reads as register only, so a\n * group made before the switch changes nothing on a live store; the\n * console makes new groups with it on.\n */\n online?: boolean\n}\n\n/** What a group is: choices to pick from, or a write-in the shopper types. */\nexport type ProductModifierGroupKind = 'text'\n\n/** A modifier as the order line keeps it: names and price as sold. */\nexport interface OrderLineModifier {\n groupId: string\n optionId: string\n group: string\n name: string\n priceCents: number\n /** A write-in's answer as sold, such as the text to engrave. */\n text?: string\n /** The group's name prints before the choice on the line (\"Size: M\"). */\n nameOnOrder?: boolean\n}\n\n/** What the register sends for a line: the option ids it picked, nothing priced. */\nexport interface ModifierSelection {\n groupId: string\n optionId: string\n /** A write-in's answer, as typed; the server cleans and checks it. */\n text?: string\n}\n\nexport const POS_MAX_MODIFIER_GROUPS = 10\nexport const POS_MAX_MODIFIER_OPTIONS = 20\n/** $1,000 on one modifier: anything larger is a product, not an add-on. */\nexport const POS_MAX_MODIFIER_PRICE_CENTS = 100_000\n/** The longest answer a write-in can take: a name or a short message fits well inside. */\nexport const MAX_WRITE_IN_LENGTH = 40\n/** A write-in's length when the merchant sets none. */\nexport const DEFAULT_WRITE_IN_LENGTH = 20\n/** How much of a typed answer is carried before its group checks it. */\nconst WRITE_IN_INPUT_BOUND = 200\n\n/** Whether a group is a write-in the shopper types. */\nexport function modifierGroupIsWriteIn(group: Pick<ProductModifierGroup, 'kind'> | null | undefined): boolean {\n return group?.kind === 'text'\n}\n\n/** A write-in's longest answer. */\nexport function writeInMaxLength(group: Pick<ProductModifierGroup, 'maxLength'>): number {\n const length = group.maxLength\n return typeof length === 'number' && Number.isInteger(length) && length >= 1 && length <= MAX_WRITE_IN_LENGTH\n ? length\n : DEFAULT_WRITE_IN_LENGTH\n}\n\n/**\n * A write-in's answer cleaned for the order: control characters and runs of\n * spaces gone, trimmed, cut at the group's length. Empty when nothing is left.\n * Without a group the answer is only bounded, so a too-long one still reaches\n * the check that names it.\n */\nexport function cleanWriteIn(raw: unknown, group?: Pick<ProductModifierGroup, 'maxLength'> | null): string {\n if (typeof raw !== 'string') return ''\n const limit = group ? writeInMaxLength(group) : WRITE_IN_INPUT_BOUND\n const flat = raw\n // eslint-disable-next-line no-control-regex\n .replace(/[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n return Array.from(flat).slice(0, limit).join('').trim()\n}\n\n/** Why a write-in's answer cannot be sold, or null when it can. An empty answer is the minimum's business. */\nexport function writeInProblem(\n group: Pick<ProductModifierGroup, 'name' | 'maxLength' | 'digitsOnly'>,\n raw: unknown,\n): string | null {\n const typed = cleanWriteIn(raw)\n if (!typed) return null\n const limit = writeInMaxLength(group)\n if (Array.from(typed).length > limit) return `${group.name} takes up to ${limit} characters.`\n if (group.digitsOnly && !/^[0-9]+$/.test(typed)) return `${group.name} takes numbers only.`\n return null\n}\n/** Whether a choice is a combo: it lists what it includes (AGL-4205). */\nexport function modifierOptionIsCombo(option: Pick<ProductModifierOption, 'includes'>): boolean {\n return (\n Array.isArray(option.includes) &&\n option.includes.length > 0 &&\n option.includes.every((item) => typeof item === 'string')\n )\n}\n\nfunction modifierPriceIsValid(price: unknown): boolean {\n return (\n typeof price === 'number' &&\n Number.isInteger(price) &&\n price >= 0 &&\n price <= POS_MAX_MODIFIER_PRICE_CENTS\n )\n}\n\n/** Why a product's modifier groups cannot be saved, or null when they can. */\nexport function modifierGroupsProblem(groups: unknown): string | null {\n if (groups == null) return null\n if (!Array.isArray(groups)) return 'Modifiers must be a list'\n if (groups.length > POS_MAX_MODIFIER_GROUPS) {\n return `At most ${POS_MAX_MODIFIER_GROUPS} modifier groups per product`\n }\n const groupIds = new Set<string>()\n for (const group of groups as ProductModifierGroup[]) {\n if (!group?.id || groupIds.has(group.id)) return 'Modifier groups need unique ids'\n groupIds.add(group.id)\n if (!String(group.name ?? '').trim()) return 'Name every modifier group'\n const options = Array.isArray(group.options) ? group.options : []\n if (group.kind != null && group.kind !== 'text') return `“${group.name}” is a list of choices or a write-in`\n if (group.kind === 'text') {\n if (options.length !== 1) return `“${group.name}” is a write-in and holds one field`\n if (group.max !== 1 || (group.min !== 0 && group.min !== 1)) {\n return `“${group.name}” is a write-in: required or not, one answer`\n }\n if (\n group.maxLength != null &&\n (!Number.isInteger(group.maxLength) || group.maxLength < 1 || group.maxLength > MAX_WRITE_IN_LENGTH)\n ) {\n return `“${group.name}” takes 1 to ${MAX_WRITE_IN_LENGTH} characters`\n }\n if (group.digitsOnly != null && typeof group.digitsOnly !== 'boolean') {\n return `“${group.name}” takes numbers only or any text`\n }\n }\n if (group.nameOnOrder != null && typeof group.nameOnOrder !== 'boolean') {\n return `“${group.name}” prints its name on the order or not`\n }\n if (options.length === 0) return `Add a choice to “${group.name}”`\n if (options.length > POS_MAX_MODIFIER_OPTIONS) {\n return `“${group.name}” has more than ${POS_MAX_MODIFIER_OPTIONS} choices`\n }\n const optionIds = new Set<string>()\n for (const option of options) {\n if (!option?.id || optionIds.has(option.id)) return 'Modifier choices need unique ids'\n optionIds.add(option.id)\n if (!String(option.name ?? '').trim()) return `Name every choice in “${group.name}”`\n const price = option.priceCents\n if (!modifierPriceIsValid(price)) {\n return `“${option.name}” needs a price of $0 to $1,000`\n }\n const byVariant = option.priceCentsByVariant\n if (byVariant != null) {\n if (typeof byVariant !== 'object' || Array.isArray(byVariant)) {\n return `“${option.name}” has prices that are not a list by option`\n }\n if (Object.values(byVariant).some((cents) => !modifierPriceIsValid(cents))) {\n return `“${option.name}” needs a price of $0 to $1,000 for each option it is priced by`\n }\n }\n }\n if (group.online != null && typeof group.online !== 'boolean') {\n return `“${group.name}” is shown on the website or not`\n }\n const { min, max } = group\n if (!Number.isInteger(min) || min < 0) return `“${group.name}” needs a minimum of 0 or more`\n if (!Number.isInteger(max) || max < 1 || max > options.length) {\n return `“${group.name}” allows 1 to ${options.length} choices`\n }\n if (min > max) return `“${group.name}” requires more choices than it allows`\n }\n return null\n}\n\n/** How a variant is named in a choice's price list, in the editor and in an import file. */\nexport function variantPriceLabel(variant: { options?: Record<string, string> }): string {\n const values = Object.values(variant.options ?? {}).filter(Boolean)\n return values.length ? values.join(' / ') : 'Default'\n}\n\n/** The product's groups, or none when they are missing or malformed. */\nexport function productModifierGroups(product: {\n modifierGroups?: unknown\n}): ProductModifierGroup[] {\n const groups = product?.modifierGroups\n if (!Array.isArray(groups) || modifierGroupsProblem(groups)) return []\n return groups as ProductModifierGroup[]\n}\n\n/** Whether a group must be answered before the item can be added. */\nexport function modifierGroupRequired(group: ProductModifierGroup): boolean {\n return group.min > 0\n}\n\n/**\n * The groups the product's page on the website offers (AGL-4100): those\n * switched to \"Show on the website\". A register-only group is never sent to\n * a shopper, never asked of one and never priced on an online order.\n */\nexport function websiteModifierGroups(product: { modifierGroups?: unknown }): ProductModifierGroup[] {\n return productModifierGroups(product).filter((group) => group.online === true)\n}\n\n/** Whether the website must ask a shopper a choice before the item goes in a cart. */\nexport function websiteModifiersRequired(product: { modifierGroups?: unknown }): boolean {\n return websiteModifierGroups(product).some(modifierGroupRequired)\n}\n\n/**\n * What one choice adds to one unit of the picked variant (AGL-4100): its\n * price on that variant where it has one, else its own price.\n */\nexport function modifierOptionPriceCents(\n option: Pick<ProductModifierOption, 'priceCents' | 'priceCentsByVariant'>,\n variantId?: string | null,\n): number {\n const byVariant = variantId ? option.priceCentsByVariant?.[variantId] : undefined\n return typeof byVariant === 'number' && Number.isFinite(byVariant) ? byVariant : option.priceCents\n}\n\n/** A line's chosen modifiers, priced. */\nexport interface ResolvedLineModifiers {\n ok: boolean\n /** The chosen modifiers, in group order; empty when not `ok`. */\n modifiers: OrderLineModifier[]\n /** What they add to one unit, in cents. */\n extraCents: number\n /** What to fix, when not `ok`. */\n error?: string\n}\n\n/** The picks a request names, as ids only, bounded; nothing for a value that is not a list. */\nexport function modifierSelectionFrom(raw: unknown): ModifierSelection[] {\n return (Array.isArray(raw) ? raw : [])\n .slice(0, POS_MAX_MODIFIER_GROUPS * POS_MAX_MODIFIER_OPTIONS)\n .map((entry: any): ModifierSelection => {\n const pick: ModifierSelection = {\n groupId: String(entry?.groupId ?? ''),\n optionId: String(entry?.optionId ?? ''),\n }\n // A write-in's answer, bounded here and checked against its group when priced.\n const text = cleanWriteIn(entry?.text)\n if (text) pick.text = text\n return pick\n })\n}\n\n/** A pick as the order keeps it: a choice, or a write-in with its answer. */\nfunction soldModifier(\n group: ProductModifierGroup,\n option: ProductModifierOption,\n variantId: string | null | undefined,\n text: string | undefined,\n): OrderLineModifier {\n return {\n groupId: group.id,\n optionId: option.id,\n group: group.name,\n name: option.name,\n priceCents: modifierOptionPriceCents(option, variantId),\n ...(text ? { text } : {}),\n ...(group.nameOnOrder === true ? { nameOnOrder: true } : {}),\n }\n}\n\n/**\n * Prices a line's chosen modifiers from the PRODUCT, in group order, and\n * checks every group's minimum and maximum. Unknown ids, a repeated choice\n * and a group answered past its maximum are refused with what to fix.\n *\n * `variantId` is the variant the line sells (AGL-4100): a choice priced by\n * variant adds its price on that one. Without it every choice adds its own\n * `priceCents`, as it always did.\n */\nexport function resolveLineModifiers(\n product: { name?: string; modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): ResolvedLineModifiers {\n const refuse = (error: string): ResolvedLineModifiers => ({\n ok: false,\n modifiers: [],\n extraCents: 0,\n error,\n })\n const groups = productModifierGroups(product)\n const picks = modifierSelectionFrom(raw)\n const seen = new Set<string>()\n for (const pick of picks) {\n const key = `${pick.groupId}:${pick.optionId}`\n if (seen.has(key)) return refuse(`A choice on ${product.name} was picked twice.`)\n seen.add(key)\n const group = groups.find((entry) => entry.id === pick.groupId)\n if (!group || !group.options.some((option) => option.id === pick.optionId)) {\n return refuse(`A choice on ${product.name} is no longer offered. Remove it and add it again.`)\n }\n }\n const modifiers: OrderLineModifier[] = []\n for (const group of groups) {\n if (modifierGroupIsWriteIn(group)) {\n // A write-in (write-ins): its answer is checked, cleaned and kept.\n const option = group.options[0]\n const pick = picks.find((entry) => entry.groupId === group.id && entry.optionId === option.id)\n const problem = writeInProblem(group, pick?.text)\n if (problem) return refuse(`${problem} (${product.name})`)\n const text = cleanWriteIn(pick?.text, group)\n if (!text) {\n if (group.min > 0) return refuse(`Fill in ${group.name.toLowerCase()} for ${product.name}.`)\n continue\n }\n modifiers.push(soldModifier(group, option, variantId, text))\n continue\n }\n const chosen = group.options.filter((option) =>\n picks.some((pick) => pick.groupId === group.id && pick.optionId === option.id),\n )\n if (chosen.length < group.min) {\n return refuse(`Choose ${group.name.toLowerCase()} for ${product.name}.`)\n }\n if (chosen.length > group.max) {\n return refuse(`Choose at most ${group.max} for ${group.name.toLowerCase()} on ${product.name}.`)\n }\n for (const option of chosen) modifiers.push(soldModifier(group, option, variantId, undefined))\n }\n return {\n ok: true,\n modifiers,\n extraCents: modifiers.reduce((sum, modifier) => sum + modifier.priceCents, 0),\n }\n}\n\n/**\n * {@link resolveLineModifiers} for a sale made online (AGL-4100): only the\n * groups shown on the website are offered, asked or priced. A register-only\n * group, required or not, is not the shopper's to answer.\n */\nexport function resolveWebsiteLineModifiers(\n product: { name?: string; modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): ResolvedLineModifiers {\n return resolveLineModifiers(\n { name: product.name, modifierGroups: websiteModifierGroups(product) },\n raw,\n variantId,\n )\n}\n\n/**\n * The modifiers a PAID line names, for its order record (AGL-4100): every\n * pick the product still offers, in group order, priced as it is now, with no\n * minimum or maximum asked. The money was taken when the sale was priced;\n * a choice the merchant removed since is left off the record, never a reason\n * to lose the order.\n */\nexport function soldLineModifiers(\n product: { modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): OrderLineModifier[] {\n const picks = modifierSelectionFrom(raw)\n const modifiers: OrderLineModifier[] = []\n for (const group of productModifierGroups(product)) {\n const writeIn = modifierGroupIsWriteIn(group)\n for (const option of group.options) {\n const pick = picks.find((entry) => entry.groupId === group.id && entry.optionId === option.id)\n if (!pick) continue\n const text = writeIn ? cleanWriteIn(pick.text, group) : undefined\n if (writeIn && !text) continue\n modifiers.push(soldModifier(group, option, variantId, text))\n }\n }\n return modifiers\n}\n\n/**\n * What a shopper is told about a cart line whose add-ons no longer answer\n * the product (AGL-4100): the resolver's reason, and how to put it right.\n */\nexport function cartLineModifierProblem(error: string | undefined): string {\n const reason = String(error ?? '').trim() || 'The choices on this item have changed.'\n return /Remove it and add it again/.test(reason)\n ? reason\n : `${reason} Remove it and add it again from its page.`\n}\n\n/** The picks a priced line keeps: ids only, in the product's group order. */\nexport function modifierSelectionOf(\n modifiers: readonly (Pick<OrderLineModifier, 'groupId' | 'optionId'> & { text?: string })[],\n): ModifierSelection[] {\n return modifiers.map((modifier) => ({\n groupId: modifier.groupId,\n optionId: modifier.optionId,\n ...(modifier.text ? { text: modifier.text } : {}),\n }))\n}\n\n/**\n * The picks as one metadata value (AGL-4100), for a payment processor that\n * holds strings only: `[[\"group\",\"option\"],…]`. Empty for no picks.\n */\nexport function encodeModifierSelection(selection: readonly ModifierSelection[] | undefined): string {\n if (!selection?.length) return ''\n // A write-in's answer rides as a third entry: `[[\"group\",\"option\",\"For Sam\"],…]`.\n return JSON.stringify(\n selection.map((pick) => (pick.text ? [pick.groupId, pick.optionId, pick.text] : [pick.groupId, pick.optionId])),\n )\n}\n\n/** {@link encodeModifierSelection} read back; nothing for a value it did not write. */\nexport function decodeModifierSelection(value: unknown): ModifierSelection[] {\n if (typeof value !== 'string' || !value) return []\n try {\n const parsed: unknown = JSON.parse(value)\n if (!Array.isArray(parsed)) return []\n return parsed\n .filter(\n (pair): pair is [string, string, unknown?] =>\n Array.isArray(pair) && typeof pair[0] === 'string' && typeof pair[1] === 'string',\n )\n .slice(0, POS_MAX_MODIFIER_GROUPS * POS_MAX_MODIFIER_OPTIONS)\n .map(([groupId, optionId, typed]) => {\n const text = cleanWriteIn(typed)\n return text ? { groupId, optionId, text } : { groupId, optionId }\n })\n } catch {\n return []\n }\n}\n\n/** A modifier as {@link modifierLineText} reads it. */\nexport type PrintedModifier = Pick<OrderLineModifier, 'name'> &\n Partial<Pick<OrderLineModifier, 'group' | 'text' | 'nameOnOrder'>>\n\n/**\n * How one modifier prints on a line: its name (`Oat milk`), its group and\n * name when the group asks for it (`Size: M`), or a write-in's name\n * and answer (`Engraving: For Sam`).\n */\nexport function modifierLineText(modifier: PrintedModifier): string {\n if (modifier.text) return `${modifier.group || modifier.name}: ${modifier.text}`\n if (modifier.nameOnOrder && modifier.group) return `${modifier.group}: ${modifier.name}`\n return modifier.name\n}\n\n/** The label a line prints: the variant, then each modifier (`Large / Oat milk, Extra shot`). */\nexport function lineLabelWithModifiers(variantLabel: string | undefined, modifiers: readonly PrintedModifier[]): string {\n const added = modifiers.map(modifierLineText).join(', ')\n return [variantLabel, added].filter(Boolean).join(' / ')\n}\n\n/** Two lines merge only when they are the same item with the same choices. */\nexport function modifierSelectionKey(selection: readonly ModifierSelection[] | undefined): string {\n return [...(selection ?? [])]\n .map((pick) => (pick.text ? `${pick.groupId}:${pick.optionId}=${pick.text}` : `${pick.groupId}:${pick.optionId}`))\n .sort()\n .join('|')\n}\n"],"names":["POS_MAX_MODIFIER_GROUPS","POS_MAX_MODIFIER_OPTIONS","POS_MAX_MODIFIER_PRICE_CENTS","MAX_WRITE_IN_LENGTH","DEFAULT_WRITE_IN_LENGTH","WRITE_IN_INPUT_BOUND","modifierGroupIsWriteIn","group","kind","writeInMaxLength","length","maxLength","Number","isInteger","cleanWriteIn","raw","limit","flat","replace","trim","Array","from","slice","join","writeInProblem","typed","name","digitsOnly","test","modifierOptionIsCombo","option","isArray","includes","every","item","modifierPriceIsValid","price","modifierGroupsProblem","groups","groupIds","Set","id","has","add","String","options","max","min","nameOnOrder","optionIds","priceCents","byVariant","priceCentsByVariant","Object","values","some","cents","online","variantPriceLabel","variant","filter","Boolean","productModifierGroups","product","modifierGroups","modifierGroupRequired","websiteModifierGroups","websiteModifiersRequired","modifierOptionPriceCents","variantId","undefined","isFinite","modifierSelectionFrom","map","entry","pick","groupId","optionId","text","soldModifier","resolveLineModifiers","refuse","error","ok","modifiers","extraCents","picks","seen","key","find","problem","toLowerCase","push","chosen","reduce","sum","modifier","resolveWebsiteLineModifiers","soldLineModifiers","writeIn","cartLineModifierProblem","reason","modifierSelectionOf","encodeModifierSelection","selection","JSON","stringify","decodeModifierSelection","value","parsed","parse","pair","modifierLineText","lineLabelWithModifiers","variantLabel","added","modifierSelectionKey","sort"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAqC2C,GAE3C,mFAAmF;AAiFnF,OAAO,MAAMA,0BAA0B,GAAE;AACzC,OAAO,MAAMC,2BAA2B,GAAE;AAC1C,yEAAyE,GACzE,OAAO,MAAMC,+BAA+B,OAAO;AACnD,wFAAwF,GACxF,OAAO,MAAMC,sBAAsB,GAAE;AACrC,qDAAqD,GACrD,OAAO,MAAMC,0BAA0B,GAAE;AACzC,sEAAsE,GACtE,MAAMC,uBAAuB;AAE7B,qDAAqD,GACrD,OAAO,SAASC,uBAAuBC,KAA4D;IACjG,OAAOA,CAAAA,yBAAAA,MAAOC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QAAyB;IACxD,IAAIA,SAASlB,IAAI,EAAE,OAAO,GAAGkB,SAASzF,KAAK,IAAIyF,SAAStE,IAAI,CAAC,EAAE,EAAEsE,SAASlB,IAAI,EAAE;IAChF,IAAIkB,SAAShD,WAAW,IAAIgD,SAASzF,KAAK,EAAE,OAAO,GAAGyF,SAASzF,KAAK,CAAC,EAAE,EAAEyF,SAAStE,IAAI,EAAE;IACxF,OAAOsE,SAAStE,IAAI;AACtB;AAEA,+FAA+F,GAC/F,OAAO,SAASuF,uBAAuBC,YAAgC,EAAE9B,SAAqC;IAC5G,MAAM+B,QAAQ/B,UAAUX,GAAG,CAACuC,kBAAkBzF,IAAI,CAAC;IACnD,OAAO;QAAC2F;QAAcC;KAAM,CAACvD,MAAM,CAACC,SAAStC,IAAI,CAAC;AACpD;AAEA,4EAA4E,GAC5E,OAAO,SAAS6F,qBAAqBZ,SAAmD;IACtF,OAAO;WAAKA,oBAAAA,YAAa,EAAE;KAAE,CAC1B/B,GAAG,CAAC,CAACE,OAAUA,KAAKG,IAAI,GAAG,GAAGH,KAAKC,OAAO,CAAC,CAAC,EAAED,KAAKE,QAAQ,CAAC,CAAC,EAAEF,KAAKG,IAAI,EAAE,GAAG,GAAGH,KAAKC,OAAO,CAAC,CAAC,EAAED,KAAKE,QAAQ,EAAE,EAC/GwC,IAAI,GACJ9F,IAAI,CAAC;AACV"}
|
|
@@ -210,11 +210,21 @@ export declare function productDuplicateSlugBase(slug: string | undefined, name:
|
|
|
210
210
|
* source's would sort and find it by the source's name) and stock fields, and
|
|
211
211
|
* not the source's SKU and barcode keys, which are derived again from its
|
|
212
212
|
* variants. The caller adds the claimed `slug`'s smart-collection membership.
|
|
213
|
+
*
|
|
214
|
+
* Everything the merchant made is copied: options, every variant, add-ons and
|
|
215
|
+
* write-ins (`modifierGroups`), photos, SEO, categories, tags. The source's
|
|
216
|
+
* OWN bookkeeping is not: the checkout holds on its stock (`stockHolds`, which
|
|
217
|
+
* no checkout of the copy would ever release), its soft delete, and who made
|
|
218
|
+
* it and when, which the create stamps afresh.
|
|
213
219
|
*/
|
|
214
220
|
export declare function productDuplicateFields(product: HostProduct & {
|
|
215
221
|
$id?: string;
|
|
216
222
|
skus?: string[];
|
|
217
223
|
barcodes?: string[];
|
|
224
|
+
stockHolds?: unknown;
|
|
225
|
+
createdAt?: unknown;
|
|
226
|
+
updatedAt?: unknown;
|
|
227
|
+
createdBy?: unknown;
|
|
218
228
|
}, slug: string, nowMs: number): {
|
|
219
229
|
slug: string;
|
|
220
230
|
status: "draft";
|
|
@@ -275,7 +285,6 @@ export declare function productDuplicateFields(product: HostProduct & {
|
|
|
275
285
|
offerOnKiosk?: boolean;
|
|
276
286
|
hardwareSku?: string;
|
|
277
287
|
checkIn?: import("./commerce-check-in-product").ProductCheckIn;
|
|
278
|
-
deletedAt?: number | null;
|
|
279
288
|
priceUsd?: number;
|
|
280
289
|
imageUrl?: string;
|
|
281
290
|
};
|
|
@@ -155,11 +155,22 @@ import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_wi
|
|
|
155
155
|
* source's would sort and find it by the source's name) and stock fields, and
|
|
156
156
|
* not the source's SKU and barcode keys, which are derived again from its
|
|
157
157
|
* variants. The caller adds the claimed `slug`'s smart-collection membership.
|
|
158
|
+
*
|
|
159
|
+
* Everything the merchant made is copied: options, every variant, add-ons and
|
|
160
|
+
* write-ins (`modifierGroups`), photos, SEO, categories, tags. The source's
|
|
161
|
+
* OWN bookkeeping is not: the checkout holds on its stock (`stockHolds`, which
|
|
162
|
+
* no checkout of the copy would ever release), its soft delete, and who made
|
|
163
|
+
* it and when, which the create stamps afresh.
|
|
158
164
|
*/ export function productDuplicateFields(product, slug, nowMs) {
|
|
159
|
-
const { $id: _sourceId, skus: _skus, barcodes: _barcodes } = product, copy = _object_without_properties_loose(product, [
|
|
165
|
+
const { $id: _sourceId, skus: _skus, barcodes: _barcodes, stockHolds: _stockHolds, createdAt: _createdAt, updatedAt: _updatedAt, createdBy: _createdBy, deletedAt: _deletedAt } = product, copy = _object_without_properties_loose(product, [
|
|
160
166
|
"$id",
|
|
161
167
|
"skus",
|
|
162
|
-
"barcodes"
|
|
168
|
+
"barcodes",
|
|
169
|
+
"stockHolds",
|
|
170
|
+
"createdAt",
|
|
171
|
+
"updatedAt",
|
|
172
|
+
"createdBy",
|
|
173
|
+
"deletedAt"
|
|
163
174
|
]);
|
|
164
175
|
return _extends({}, copy, productSearchFields({
|
|
165
176
|
name: productDuplicateName(product.name),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/product-write.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n adjustVariantInventory,\n COMMERCE_DEFAULT_PRICE_USD,\n commerceSlug,\n expandVariantMatrix,\n type HostProduct,\n type ProductOption,\n type ProductVariant,\n type InventoryAdjustment,\n type InventoryAdjustmentReason,\n productSearchFields,\n productStockFields,\n type SmartCollectionRules,\n variantHasPrice,\n} from './commerce'\n\n/*\n * WHAT A PRODUCT SAVE AND A STOCK ADJUSTMENT WRITE, worked out once.\n *\n * The console's product editor and its Adjust stock dialog compute these\n * fields in the browser before their Firestore writes; the native apps save\n * through `commerce/products/save` and `commerce/products/stock`, which run\n * this same code on the server. One computation, so a product saved from a\n * phone carries exactly the search keys, stock verdict, price, image and\n * smart-collection membership the console would have written.\n */\n\n/** The longest product name a save keeps: {@link productSaveFields} cuts a longer one here. */\nexport const PRODUCT_NAME_MAX_LENGTH = 120\n\n/** A product as the editor holds it: the stored fields plus keys the listener or a seed may carry. */\nexport type EditedProduct = HostProduct & {\n $id?: string\n skus?: string[]\n barcodes?: string[]\n stockHolds?: Record<string, unknown>\n}\n\n/**\n * The fields a product save writes, before its collection membership and its\n * timestamps: the product as edited, with\n *\n * - `$id` dropped (AGL-1374): the listener's synthetic key, never a field;\n * - the seed's `skus` / `barcodes` dropped (AGL-3321): `productSearchFields`\n * omits each when no variant has one, so a seeded copy would outlive the\n * last SKU;\n * - the trimmed name with the search keys derived from it, together, so the\n * two cannot drift (AGL-2501);\n * - a slug, the primary variant's price, the stock fields, the first image\n * and `updatedAtMs`.\n */\nexport function productSaveFields(current: EditedProduct, nowMs: number) {\n const {\n $id: _syntheticId,\n skus: _seededSkus,\n barcodes: _seededBarcodes,\n // A sample the merchant saves is theirs now (AGL-4065).\n sample: _sample,\n ...currentFields\n } = current\n const primaryVariant = current.variants[0]\n return {\n ...currentFields,\n ...productSearchFields({\n name: current.name.trim().slice(0, PRODUCT_NAME_MAX_LENGTH),\n variants: current.variants,\n }),\n slug: current.slug || commerceSlug(current.name),\n // The legacy flat price, only where there is one (AGL-3676): an owner\n // may save a product before pricing it, and an unpriced product is not\n // a free one. `null` rather than absent, so an edit's full replace and\n // the native save write the same field.\n priceUsd: variantHasPrice(primaryVariant) ? primaryVariant.priceUsd : null,\n ...productStockFields({\n variants: current.variants,\n oversellPolicy: current.oversellPolicy,\n }),\n imageUrl: current.mediaUrls?.[0] ?? current.imageUrl ?? null,\n updatedAtMs: nowMs,\n }\n}\n\n/**\n * A product nobody has saved yet, as the editor starts one: a draft, at the\n * default price (AGL-3676), for the owner to change or clear.\n */\nexport function blankProductDraft(): HostProduct {\n return {\n name: '',\n slug: '',\n type: 'physical',\n status: 'draft',\n variants: [{ id: 'default', priceUsd: COMMERCE_DEFAULT_PRICE_USD }],\n }\n}\n\n/** Stable key for matching variants across matrix regenerations. */\nexport function variantComboKey(options: Record<string, string> | undefined): string {\n return Object.entries(options ?? {})\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([name, value]) => `${name}:${value}`)\n .join('|')\n}\n\n/**\n * The variants a change of option VALUES makes, as the editor rebuilds them:\n * one per combination of `options`, each an existing variant with the same\n * selections where there is one (so its id, price, SKU and stock survive the\n * change), and otherwise a new variant at the first variant's price (none\n * where it has none, the default on a product with no variant yet) and stock.\n *\n * Ask {@link variantMatrixProblem} first: past the ceiling the editor keeps\n * the variants as they are and refuses the save (AGL-4100). A rename is not\n * a change of values; it goes through `renameProductOptions` (AGL-3066).\n */\nexport function variantsForOptions(\n at: Pick<HostProduct, 'variants'>,\n options: ProductOption[],\n nowMs: number,\n): ProductVariant[] {\n const previous = new Map(at.variants.map((variant) => [variantComboKey(variant.options), variant]))\n const fallback = at.variants[0]\n return expandVariantMatrix(options).map(\n (combo, comboIndex) =>\n previous.get(variantComboKey(combo)) ??\n // An unpriced variant is stored with no `priceUsd` (AGL-3676), as a\n // proposed product's are; the type names the priced shape.\n ({\n id: `v${nowMs.toString(36)}${comboIndex}`,\n options: combo,\n ...(fallback\n ? variantHasPrice(fallback)\n ? { priceUsd: fallback.priceUsd }\n : {}\n : { priceUsd: COMMERCE_DEFAULT_PRICE_USD }),\n inventory: fallback?.inventory ?? null,\n } as ProductVariant),\n )\n}\n\n/** What the smart-collection rules are matched against: the saved name with the product's own facts. */\nexport function productMembershipInput(\n fields: { name: string },\n current: Pick<HostProduct, 'type' | 'tags' | 'categoryIds' | 'variants'>,\n) {\n return {\n name: fields.name,\n type: current.type,\n tags: current.tags,\n categoryIds: current.categoryIds,\n variants: current.variants,\n }\n}\n\n/**\n * An EDIT's replacing write, without its membership and server timestamp:\n * live stock holds are not the editor's to write (AGL-2356), so the seed's\n * are dropped and the stored ones carried; the product stays live\n * (`deletedAt: null`, AGL-3321).\n */\nexport function productEditWrite(\n fields: ReturnType<typeof productSaveFields>,\n liveHolds: Record<string, unknown> | null | undefined,\n) {\n const { stockHolds: _seededHolds, ...withoutHolds } = fields as typeof fields & {\n stockHolds?: Record<string, unknown>\n }\n return {\n ...withoutHolds,\n ...(liveHolds ? { stockHolds: liveHolds } : {}),\n deletedAt: null,\n }\n}\n\n/** A duplicate's name: the source's, marked as a copy. */\nexport function productDuplicateName(name: string): string {\n return `${name} (copy)`\n}\n\n/** The slug a duplicate starts from, before the store is asked which are taken. */\nexport function productDuplicateSlugBase(slug: string | undefined, name: string): string {\n return commerceSlug(`${slug || commerceSlug(name)}-copy`)\n}\n\n/**\n * What Duplicate writes (the products list's Duplicate, AGL-3321): the source\n * as a draft under the copy's name, with the COPY's search keys (spreading the\n * source's would sort and find it by the source's name) and stock fields, and\n * not the source's SKU and barcode keys, which are derived again from its\n * variants. The caller adds the claimed `slug`'s smart-collection membership.\n */\nexport function productDuplicateFields(\n product: HostProduct & { $id?: string; skus?: string[]; barcodes?: string[] },\n slug: string,\n nowMs: number,\n) {\n const { $id: _sourceId, skus: _skus, barcodes: _barcodes, ...copy } = product\n return {\n ...copy,\n ...productSearchFields({ name: productDuplicateName(product.name), variants: product.variants }),\n ...productStockFields(product),\n slug,\n status: 'draft' as const,\n createdAtMs: nowMs,\n updatedAtMs: nowMs,\n }\n}\n\n/** A smart collection as `hosts/{hostId}/collections` stores it, as the membership rules read it. */\nexport function smartCollectionRulesOf(id: string, data: Record<string, unknown>): SmartCollectionRules {\n return {\n id,\n rules: (data['rules'] as SmartCollectionRules['rules']) ?? [],\n matchAll: data['matchAll'] as boolean | undefined,\n }\n}\n\n/** One stock adjustment, as the Adjust stock dialog asks for it. */\nexport interface StockAdjustment {\n variantId: string\n delta: number\n reason: InventoryAdjustmentReason\n locationId?: string\n}\n\n/**\n * The product update and the ledger row one stock adjustment writes: the\n * variants with the count moved, the stock fields that move with it\n * (AGL-3321), and the same `inventoryAdjustments` row the sale webhook writes\n * (AGL-281). A zero or non-numeric delta writes nothing.\n */\nexport function stockAdjustmentWrite(\n product: HostProduct,\n productId: string,\n adjustment: StockAdjustment,\n nowMs: number,\n): { update: Record<string, unknown>; ledger: InventoryAdjustment } | null {\n const delta = Math.round(Number(adjustment.delta))\n if (!delta) return null\n const variants = adjustVariantInventory(product, adjustment.variantId, delta, adjustment.locationId || undefined)\n return {\n update: {\n variants,\n ...productStockFields({ ...product, variants }),\n updatedAtMs: nowMs,\n },\n ledger: {\n productId,\n variantId: adjustment.variantId,\n delta,\n reason: adjustment.reason,\n ...(adjustment.locationId ? { locationId: adjustment.locationId } : {}),\n atMs: nowMs,\n },\n }\n}\n"],"names":["adjustVariantInventory","COMMERCE_DEFAULT_PRICE_USD","commerceSlug","expandVariantMatrix","productSearchFields","productStockFields","variantHasPrice","PRODUCT_NAME_MAX_LENGTH","productSaveFields","current","nowMs","$id","_syntheticId","skus","_seededSkus","barcodes","_seededBarcodes","sample","_sample","currentFields","primaryVariant","variants","name","trim","slice","slug","priceUsd","oversellPolicy","imageUrl","mediaUrls","updatedAtMs","blankProductDraft","type","status","id","variantComboKey","options","Object","entries","sort","a","b","localeCompare","map","value","join","variantsForOptions","at","previous","Map","variant","fallback","combo","comboIndex","get","toString","inventory","productMembershipInput","fields","tags","categoryIds","productEditWrite","liveHolds","stockHolds","_seededHolds","withoutHolds","deletedAt","productDuplicateName","productDuplicateSlugBase","productDuplicateFields","product","_sourceId","_skus","_barcodes","copy","createdAtMs","smartCollectionRulesOf","data","rules","matchAll","stockAdjustmentWrite","productId","adjustment","delta","Math","round","Number","variantId","locationId","undefined","update","ledger","reason","atMs"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,sBAAsB,EACtBC,0BAA0B,EAC1BC,YAAY,EACZC,mBAAmB,EAMnBC,mBAAmB,EACnBC,kBAAkB,EAElBC,eAAe,QACV,gBAAY;AAEnB;;;;;;;;;CASC,GAED,6FAA6F,GAC7F,OAAO,MAAMC,0BAA0B,IAAG;AAU1C;;;;;;;;;;;;CAYC,GACD,OAAO,SAASC,kBAAkBC,OAAsB,EAAEC,KAAa;QA0BzDD;QAAAA;IAzBZ,MAAM,EACJE,KAAKC,YAAY,EACjBC,MAAMC,WAAW,EAC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],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n adjustVariantInventory,\n COMMERCE_DEFAULT_PRICE_USD,\n commerceSlug,\n expandVariantMatrix,\n type HostProduct,\n type ProductOption,\n type ProductVariant,\n type InventoryAdjustment,\n type InventoryAdjustmentReason,\n productSearchFields,\n productStockFields,\n type SmartCollectionRules,\n variantHasPrice,\n} from './commerce'\n\n/*\n * WHAT A PRODUCT SAVE AND A STOCK ADJUSTMENT WRITE, worked out once.\n *\n * The console's product editor and its Adjust stock dialog compute these\n * fields in the browser before their Firestore writes; the native apps save\n * through `commerce/products/save` and `commerce/products/stock`, which run\n * this same code on the server. One computation, so a product saved from a\n * phone carries exactly the search keys, stock verdict, price, image and\n * smart-collection membership the console would have written.\n */\n\n/** The longest product name a save keeps: {@link productSaveFields} cuts a longer one here. */\nexport const PRODUCT_NAME_MAX_LENGTH = 120\n\n/** A product as the editor holds it: the stored fields plus keys the listener or a seed may carry. */\nexport type EditedProduct = HostProduct & {\n $id?: string\n skus?: string[]\n barcodes?: string[]\n stockHolds?: Record<string, unknown>\n}\n\n/**\n * The fields a product save writes, before its collection membership and its\n * timestamps: the product as edited, with\n *\n * - `$id` dropped (AGL-1374): the listener's synthetic key, never a field;\n * - the seed's `skus` / `barcodes` dropped (AGL-3321): `productSearchFields`\n * omits each when no variant has one, so a seeded copy would outlive the\n * last SKU;\n * - the trimmed name with the search keys derived from it, together, so the\n * two cannot drift (AGL-2501);\n * - a slug, the primary variant's price, the stock fields, the first image\n * and `updatedAtMs`.\n */\nexport function productSaveFields(current: EditedProduct, nowMs: number) {\n const {\n $id: _syntheticId,\n skus: _seededSkus,\n barcodes: _seededBarcodes,\n // A sample the merchant saves is theirs now (AGL-4065).\n sample: _sample,\n ...currentFields\n } = current\n const primaryVariant = current.variants[0]\n return {\n ...currentFields,\n ...productSearchFields({\n name: current.name.trim().slice(0, PRODUCT_NAME_MAX_LENGTH),\n variants: current.variants,\n }),\n slug: current.slug || commerceSlug(current.name),\n // The legacy flat price, only where there is one (AGL-3676): an owner\n // may save a product before pricing it, and an unpriced product is not\n // a free one. `null` rather than absent, so an edit's full replace and\n // the native save write the same field.\n priceUsd: variantHasPrice(primaryVariant) ? primaryVariant.priceUsd : null,\n ...productStockFields({\n variants: current.variants,\n oversellPolicy: current.oversellPolicy,\n }),\n imageUrl: current.mediaUrls?.[0] ?? current.imageUrl ?? null,\n updatedAtMs: nowMs,\n }\n}\n\n/**\n * A product nobody has saved yet, as the editor starts one: a draft, at the\n * default price (AGL-3676), for the owner to change or clear.\n */\nexport function blankProductDraft(): HostProduct {\n return {\n name: '',\n slug: '',\n type: 'physical',\n status: 'draft',\n variants: [{ id: 'default', priceUsd: COMMERCE_DEFAULT_PRICE_USD }],\n }\n}\n\n/** Stable key for matching variants across matrix regenerations. */\nexport function variantComboKey(options: Record<string, string> | undefined): string {\n return Object.entries(options ?? {})\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([name, value]) => `${name}:${value}`)\n .join('|')\n}\n\n/**\n * The variants a change of option VALUES makes, as the editor rebuilds them:\n * one per combination of `options`, each an existing variant with the same\n * selections where there is one (so its id, price, SKU and stock survive the\n * change), and otherwise a new variant at the first variant's price (none\n * where it has none, the default on a product with no variant yet) and stock.\n *\n * Ask {@link variantMatrixProblem} first: past the ceiling the editor keeps\n * the variants as they are and refuses the save (AGL-4100). A rename is not\n * a change of values; it goes through `renameProductOptions` (AGL-3066).\n */\nexport function variantsForOptions(\n at: Pick<HostProduct, 'variants'>,\n options: ProductOption[],\n nowMs: number,\n): ProductVariant[] {\n const previous = new Map(at.variants.map((variant) => [variantComboKey(variant.options), variant]))\n const fallback = at.variants[0]\n return expandVariantMatrix(options).map(\n (combo, comboIndex) =>\n previous.get(variantComboKey(combo)) ??\n // An unpriced variant is stored with no `priceUsd` (AGL-3676), as a\n // proposed product's are; the type names the priced shape.\n ({\n id: `v${nowMs.toString(36)}${comboIndex}`,\n options: combo,\n ...(fallback\n ? variantHasPrice(fallback)\n ? { priceUsd: fallback.priceUsd }\n : {}\n : { priceUsd: COMMERCE_DEFAULT_PRICE_USD }),\n inventory: fallback?.inventory ?? null,\n } as ProductVariant),\n )\n}\n\n/** What the smart-collection rules are matched against: the saved name with the product's own facts. */\nexport function productMembershipInput(\n fields: { name: string },\n current: Pick<HostProduct, 'type' | 'tags' | 'categoryIds' | 'variants'>,\n) {\n return {\n name: fields.name,\n type: current.type,\n tags: current.tags,\n categoryIds: current.categoryIds,\n variants: current.variants,\n }\n}\n\n/**\n * An EDIT's replacing write, without its membership and server timestamp:\n * live stock holds are not the editor's to write (AGL-2356), so the seed's\n * are dropped and the stored ones carried; the product stays live\n * (`deletedAt: null`, AGL-3321).\n */\nexport function productEditWrite(\n fields: ReturnType<typeof productSaveFields>,\n liveHolds: Record<string, unknown> | null | undefined,\n) {\n const { stockHolds: _seededHolds, ...withoutHolds } = fields as typeof fields & {\n stockHolds?: Record<string, unknown>\n }\n return {\n ...withoutHolds,\n ...(liveHolds ? { stockHolds: liveHolds } : {}),\n deletedAt: null,\n }\n}\n\n/** A duplicate's name: the source's, marked as a copy. */\nexport function productDuplicateName(name: string): string {\n return `${name} (copy)`\n}\n\n/** The slug a duplicate starts from, before the store is asked which are taken. */\nexport function productDuplicateSlugBase(slug: string | undefined, name: string): string {\n return commerceSlug(`${slug || commerceSlug(name)}-copy`)\n}\n\n/**\n * What Duplicate writes (the products list's Duplicate, AGL-3321): the source\n * as a draft under the copy's name, with the COPY's search keys (spreading the\n * source's would sort and find it by the source's name) and stock fields, and\n * not the source's SKU and barcode keys, which are derived again from its\n * variants. The caller adds the claimed `slug`'s smart-collection membership.\n *\n * Everything the merchant made is copied: options, every variant, add-ons and\n * write-ins (`modifierGroups`), photos, SEO, categories, tags. The source's\n * OWN bookkeeping is not: the checkout holds on its stock (`stockHolds`, which\n * no checkout of the copy would ever release), its soft delete, and who made\n * it and when, which the create stamps afresh.\n */\nexport function productDuplicateFields(\n product: HostProduct & {\n $id?: string\n skus?: string[]\n barcodes?: string[]\n stockHolds?: unknown\n createdAt?: unknown\n updatedAt?: unknown\n createdBy?: unknown\n },\n slug: string,\n nowMs: number,\n) {\n const {\n $id: _sourceId,\n skus: _skus,\n barcodes: _barcodes,\n stockHolds: _stockHolds,\n createdAt: _createdAt,\n updatedAt: _updatedAt,\n createdBy: _createdBy,\n deletedAt: _deletedAt,\n ...copy\n } = product\n return {\n ...copy,\n ...productSearchFields({ name: productDuplicateName(product.name), variants: product.variants }),\n ...productStockFields(product),\n slug,\n status: 'draft' as const,\n createdAtMs: nowMs,\n updatedAtMs: nowMs,\n }\n}\n\n/** A smart collection as `hosts/{hostId}/collections` stores it, as the membership rules read it. */\nexport function smartCollectionRulesOf(id: string, data: Record<string, unknown>): SmartCollectionRules {\n return {\n id,\n rules: (data['rules'] as SmartCollectionRules['rules']) ?? [],\n matchAll: data['matchAll'] as boolean | undefined,\n }\n}\n\n/** One stock adjustment, as the Adjust stock dialog asks for it. */\nexport interface StockAdjustment {\n variantId: string\n delta: number\n reason: InventoryAdjustmentReason\n locationId?: string\n}\n\n/**\n * The product update and the ledger row one stock adjustment writes: the\n * variants with the count moved, the stock fields that move with it\n * (AGL-3321), and the same `inventoryAdjustments` row the sale webhook writes\n * (AGL-281). A zero or non-numeric delta writes nothing.\n */\nexport function stockAdjustmentWrite(\n product: HostProduct,\n productId: string,\n adjustment: StockAdjustment,\n nowMs: number,\n): { update: Record<string, unknown>; ledger: InventoryAdjustment } | null {\n const delta = Math.round(Number(adjustment.delta))\n if (!delta) return null\n const variants = adjustVariantInventory(product, adjustment.variantId, delta, adjustment.locationId || undefined)\n return {\n update: {\n variants,\n ...productStockFields({ ...product, variants }),\n updatedAtMs: nowMs,\n },\n ledger: {\n productId,\n variantId: adjustment.variantId,\n delta,\n reason: adjustment.reason,\n ...(adjustment.locationId ? { locationId: adjustment.locationId } : {}),\n atMs: nowMs,\n },\n }\n}\n"],"names":["adjustVariantInventory","COMMERCE_DEFAULT_PRICE_USD","commerceSlug","expandVariantMatrix","productSearchFields","productStockFields","variantHasPrice","PRODUCT_NAME_MAX_LENGTH","productSaveFields","current","nowMs","$id","_syntheticId","skus","_seededSkus","barcodes","_seededBarcodes","sample","_sample","currentFields","primaryVariant","variants","name","trim","slice","slug","priceUsd","oversellPolicy","imageUrl","mediaUrls","updatedAtMs","blankProductDraft","type","status","id","variantComboKey","options","Object","entries","sort","a","b","localeCompare","map","value","join","variantsForOptions","at","previous","Map","variant","fallback","combo","comboIndex","get","toString","inventory","productMembershipInput","fields","tags","categoryIds","productEditWrite","liveHolds","stockHolds","_seededHolds","withoutHolds","deletedAt","productDuplicateName","productDuplicateSlugBase","productDuplicateFields","product","_sourceId","_skus","_barcodes","_stockHolds","createdAt","_createdAt","updatedAt","_updatedAt","createdBy","_createdBy","_deletedAt","copy","createdAtMs","smartCollectionRulesOf","data","rules","matchAll","stockAdjustmentWrite","productId","adjustment","delta","Math","round","Number","variantId","locationId","undefined","update","ledger","reason","atMs"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,sBAAsB,EACtBC,0BAA0B,EAC1BC,YAAY,EACZC,mBAAmB,EAMnBC,mBAAmB,EACnBC,kBAAkB,EAElBC,eAAe,QACV,gBAAY;AAEnB;;;;;;;;;CASC,GAED,6FAA6F,GAC7F,OAAO,MAAMC,0BAA0B,IAAG;AAU1C;;;;;;;;;;;;CAYC,GACD,OAAO,SAASC,kBAAkBC,OAAsB,EAAEC,KAAa;QA0BzDD;QAAAA;IAzBZ,MAAM,EACJE,KAAKC,YAAY,EACjBC,MAAMC,WAA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,UAAU;QAAC,IAAI,CAAC;YACrEK,MAAM3F;;IAEV;AACF"}
|
|
@@ -38,12 +38,13 @@ import * as CommerceModel from "../model/index.js";
|
|
|
38
38
|
if (!quoter) return tablePlan();
|
|
39
39
|
const available = await quoter.available(input.hostId).catch(()=>false);
|
|
40
40
|
if (!available) return tablePlan();
|
|
41
|
-
const
|
|
41
|
+
const countries = CommerceModel.checkoutShippingCountries(settings);
|
|
42
|
+
const country = CommerceModel.normalizeCheckoutShippingCountry(input.destination.country, countries);
|
|
42
43
|
if (!country) {
|
|
43
44
|
// Carrier prices differ by address by construction, so a session that
|
|
44
45
|
// does not know the destination cannot be honest about any of them.
|
|
45
46
|
return {
|
|
46
|
-
countries
|
|
47
|
+
countries,
|
|
47
48
|
options: [],
|
|
48
49
|
refusal: 'destination-required'
|
|
49
50
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/carrier-shipping.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n pluginShippingRateQuoter,\n quotePluginShippingRates,\n type PluginShippingParcel,\n} from '@aglyn/aglyn/plugin-manager/plugin-shipping-rates'\nimport * as CommerceModel from '../model'\n\n/**\n * LIVE CARRIER RATES AT CHECKOUT (AGL-3612): the `carrier` rate kind, priced\n * by asking core's `core.shipping-rate-quoter` — whichever plugin quotes\n * carriers — and never by importing it.\n *\n * ## Quoted before the session exists, on every door\n *\n * Stripe's hosted Checkout cannot change a session's shipping options once\n * the shopper types an address (\"The hosted page integration doesn't support\n * dynamically customizing shipping options\"), and the in-page form can only\n * by a server update after the fact — while this module's callers fix the\n * platform fee and the Connect transfer from the session's options at\n * creation. So the quote is taken BEFORE the session, against the\n * destination the shopper declares (country and postal code), and the\n * session is then restricted to that country exactly as a zone rate is\n * (AGL-1721). The same code serves cart checkout, buy-now and a draft\n * order's link, hosted and in-page, and the fee arithmetic downstream sees\n * ordinary options.\n *\n * ## The fallback is the merchant's own\n *\n * No quoter, a quoter not available for this site, or a quote that fails or\n * takes longer than {@link CommerceModel.CARRIER_QUOTE_TIMEOUT_MS}: the plan\n * is exactly the one {@link CommerceModel.planCheckoutShipping} makes from\n * the table, where a carrier rate offers nothing and its fallback rate is\n * offered. A store with no carrier rate never reaches the quoter at all, so\n * its sessions are byte-identical to the ones before this existed.\n */\n\nexport interface CarrierShippingCart {\n subtotalCents: number\n totalGrams: number\n /** One parcel's dimensions, when the cart is one product that has them. */\n parcel?: Omit<PluginShippingParcel, 'weightGrams'>\n}\n\nexport interface CarrierShippingDestination {\n country?: unknown\n postalCode?: unknown\n state?: unknown\n city?: unknown\n}\n\n/** A postal code a shopper declared, trimmed and bounded, or `undefined`. */\nexport function normalizeCheckoutPostalCode(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const code = value.trim().toUpperCase().slice(0, 12)\n return /^[A-Z0-9][A-Z0-9 -]{1,11}$/.test(code) ? code : undefined\n}\n\nexport type CarrierShippingPlan = CommerceModel.CheckoutShippingPlan & {\n /** Set when the plan offers live quotes: the postal code they were priced for. */\n quotedPostalCode?: string\n /**\n * The destination's zone prices by carrier and the store can quote, but the\n * shopper has not said where in the country: ask for a postal code.\n */\n needsPostalCode?: boolean\n}\n\n/** What a shopper is told when a postal code is needed. */\nexport const CARRIER_POSTAL_CODE_MESSAGE = 'Enter the postal code you’re shipping to.'\n\n/**\n * The shipping half of a session for a store that may price by carrier.\n * See the module comment; `planCheckoutShipping` is the whole answer for any\n * store without a carrier rate.\n */\nexport async function planCheckoutShippingWithCarriers(input: {\n hostId: string\n settings: CommerceModel.ShippingSettings | undefined\n cart: CarrierShippingCart\n destination: CarrierShippingDestination\n currency?: string\n timeoutMs?: number\n}): Promise<CarrierShippingPlan> {\n const { settings, cart } = input\n const tablePlan = () =>\n CommerceModel.planCheckoutShipping(\n settings,\n { subtotalCents: cart.subtotalCents, totalGrams: cart.totalGrams },\n input.destination.country,\n )\n if (!CommerceModel.hasCarrierRates(settings)) return tablePlan()\n const quoter = pluginShippingRateQuoter()\n if (!quoter) return tablePlan()\n const available = await quoter.available(input.hostId).catch(() => false)\n if (!available) return tablePlan()\n\n const country = CommerceModel.normalizeCheckoutShippingCountry(input.destination.country)\n if (!country) {\n // Carrier prices differ by address by construction, so a session that\n // does not know the destination cannot be honest about any of them.\n return { countries: CommerceModel.CHECKOUT_SHIPPING_COUNTRIES, options: [], refusal: 'destination-required' }\n }\n const carrierRates = CommerceModel.carrierRatesFor(settings, country)\n if (!carrierRates.length) return tablePlan()\n const postalCode = normalizeCheckoutPostalCode(input.destination.postalCode)\n if (!postalCode) {\n return {\n countries: [country],\n options: [],\n refusal: 'destination-required',\n needsPostalCode: true,\n }\n }\n\n const currency = String(input.currency ?? 'usd').toLowerCase()\n const quotes = await quotePluginShippingRates(\n {\n hostId: input.hostId,\n to: {\n country,\n postalCode,\n ...(typeof input.destination.state === 'string' && input.destination.state.trim()\n ? { state: input.destination.state.trim().slice(0, 40) }\n : {}),\n ...(typeof input.destination.city === 'string' && input.destination.city.trim()\n ? { city: input.destination.city.trim().slice(0, 80) }\n : {}),\n },\n parcels: [{ weightGrams: Math.max(0, Math.round(cart.totalGrams)), ...(cart.parcel ?? {}) }],\n currency,\n valueCents: Math.max(0, Math.round(cart.subtotalCents)),\n },\n { timeoutMs: input.timeoutMs ?? CommerceModel.CARRIER_QUOTE_TIMEOUT_MS },\n )\n if (!quotes || !quotes.length) return tablePlan()\n\n const quoted: CommerceModel.ResolvedShippingRate[] = []\n const hidden = new Set<string>()\n for (const rate of carrierRates) {\n const services = (rate.carrier?.services ?? []).map((key) => key.toLowerCase())\n const offered = quotes.filter(\n (quote) => quote.currency === currency && (!services.length || services.includes(quote.serviceKey.toLowerCase())),\n )\n if (!offered.length) continue\n if (rate.carrier?.fallbackRateId) hidden.add(rate.carrier.fallbackRateId)\n for (const quote of offered) {\n quoted.push({\n rateId: CommerceModel.carrierOptionRateId(rate.id, quote.serviceKey),\n name: (quote.estimatedDays\n ? `${quote.label} (${quote.estimatedDays} business day${quote.estimatedDays === 1 ? '' : 's'})`\n : quote.label\n ).slice(0, 100),\n amountCents: CommerceModel.carrierOptionAmountCents(quote.amountCents, rate.carrier),\n })\n }\n }\n if (!quoted.length) return tablePlan()\n\n // The table's own options for this destination stay — a flat rate the\n // merchant offers beside carriers, local pickup — less any fallback a\n // carrier rate replaced now that it has quotes.\n const table = CommerceModel.resolveCheckoutShippingOptions(\n settings,\n [country],\n { subtotalCents: cart.subtotalCents, totalGrams: cart.totalGrams },\n ).filter((option) => !hidden.has(option.rateId))\n // One option per name: two carrier rates quoting the same service keep the\n // cheaper, so a shopper never sees the same service twice.\n const byName = new Map<string, CommerceModel.ResolvedShippingRate>()\n for (const option of [...table, ...quoted]) {\n const existing = byName.get(option.name)\n if (!existing || option.amountCents < existing.amountCents) byName.set(option.name, option)\n }\n const options = [...byName.values()]\n .sort((a, b) => a.amountCents - b.amountCents || a.rateId.localeCompare(b.rateId))\n .slice(0, CommerceModel.MAX_CHECKOUT_SHIPPING_OPTIONS)\n return { countries: [country], options, quotedPostalCode: postalCode }\n}\n"],"names":["pluginShippingRateQuoter","quotePluginShippingRates","CommerceModel","normalizeCheckoutPostalCode","value","undefined","code","trim","toUpperCase","slice","test","CARRIER_POSTAL_CODE_MESSAGE","planCheckoutShippingWithCarriers","input","cart","settings","tablePlan","planCheckoutShipping","subtotalCents","totalGrams","destination","country","hasCarrierRates","quoter","available","hostId","catch","normalizeCheckoutShippingCountry","countries","CHECKOUT_SHIPPING_COUNTRIES","options","refusal","carrierRates","carrierRatesFor","length","postalCode","needsPostalCode","currency","String","toLowerCase","quotes","to","state","city","parcels","weightGrams","Math","max","round","parcel","valueCents","timeoutMs","CARRIER_QUOTE_TIMEOUT_MS","quoted","hidden","Set","rate","services","carrier","map","key","offered","filter","quote","includes","serviceKey","fallbackRateId","add","push","rateId","carrierOptionRateId","id","name","estimatedDays","label","amountCents","carrierOptionAmountCents","table","resolveCheckoutShippingOptions","option","has","byName","Map","existing","get","set","values","sort","a","b","localeCompare","MAX_CHECKOUT_SHIPPING_OPTIONS","quotedPostalCode"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,wBAAwB,EACxBC,wBAAwB,QAEnB,oDAAmD;AAC1D,YAAYC,mBAAmB,oBAAU;AA6CzC,2EAA2E,GAC3E,OAAO,SAASC,4BAA4BC,KAAc;IACxD,IAAI,OAAOA,UAAU,UAAU,OAAOC;IACtC,MAAMC,OAAOF,MAAMG,IAAI,GAAGC,WAAW,GAAGC,KAAK,CAAC,GAAG;IACjD,OAAO,6BAA6BC,IAAI,CAACJ,QAAQA,OAAOD;AAC1D;AAYA,yDAAyD,GACzD,OAAO,MAAMM,8BAA8B,4CAA2C;AAEtF;;;;CAIC,GACD,OAAO,eAAeC,iCAAiCC,KAOtD;QAgCyBA,iBAcmDC,cAI5DD;IAjDf,MAAM,EAAEE,QAAQ,EAAED,IAAI,EAAE,GAAGD;IAC3B,MAAMG,YAAY,IAChBd,cAAce,oBAAoB,CAChCF,UACA;YAAEG,eAAeJ,KAAKI,aAAa;YAAEC,YAAYL,KAAKK,UAAU;QAAC,GACjEN,MAAMO,WAAW,CAACC,OAAO;IAE7B,IAAI,CAACnB,cAAcoB,eAAe,CAACP,WAAW,OAAOC;IACrD,MAAMO,SAASvB;IACf,IAAI,CAACuB,QAAQ,OAAOP;IACpB,MAAMQ,YAAY,MAAMD,OAAOC,SAAS,CAACX,MAAMY,MAAM,EAAEC,KAAK,CAAC,IAAM;IACnE,IAAI,CAACF,WAAW,OAAOR;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AI,CAACL,OAAOnB,MAAM,EAAE,OAAOlB;IAE3B,sEAAsE;IACtE,sEAAsE;IACtE,gDAAgD;IAChD,MAAM6D,QAAQ3E,cAAc4E,8BAA8B,CACxD/D,UACA;QAACM;KAAQ,EACT;QAAEH,eAAeJ,KAAKI,aAAa;QAAEC,YAAYL,KAAKK,UAAU;IAAC,GACjE2C,MAAM,CAAC,CAACiB,SAAW,CAACzB,OAAO0B,GAAG,CAACD,OAAOV,MAAM;IAC9C,2EAA2E;IAC3E,2DAA2D;IAC3D,MAAMY,SAAS,IAAIC;IACnB,KAAK,MAAMH,UAAU;WAAIF;WAAUxB;KAAO,CAAE;QAC1C,MAAM8B,WAAWF,OAAOG,GAAG,CAACL,OAAOP,IAAI;QACvC,IAAI,CAACW,YAAYJ,OAAOJ,WAAW,GAAGQ,SAASR,WAAW,EAAEM,OAAOI,GAAG,CAACN,OAAOP,IAAI,EAAEO;IACtF;IACA,MAAMjD,UAAU;WAAImD,OAAOK,MAAM;KAAG,CACjCC,IAAI,CAAC,CAACC,GAAGC,IAAMD,EAAEb,WAAW,GAAGc,EAAEd,WAAW,IAAIa,EAAEnB,MAAM,CAACqB,aAAa,CAACD,EAAEpB,MAAM,GAC/E5D,KAAK,CAAC,GAAGP,cAAcyF,6BAA6B;IACvD,OAAO;QAAE/D,WAAW;YAACP;SAAQ;QAAES;QAAS8D,kBAAkBzD;IAAW;AACvE"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/carrier-shipping.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n pluginShippingRateQuoter,\n quotePluginShippingRates,\n type PluginShippingParcel,\n} from '@aglyn/aglyn/plugin-manager/plugin-shipping-rates'\nimport * as CommerceModel from '../model'\n\n/**\n * LIVE CARRIER RATES AT CHECKOUT (AGL-3612): the `carrier` rate kind, priced\n * by asking core's `core.shipping-rate-quoter` — whichever plugin quotes\n * carriers — and never by importing it.\n *\n * ## Quoted before the session exists, on every door\n *\n * Stripe's hosted Checkout cannot change a session's shipping options once\n * the shopper types an address (\"The hosted page integration doesn't support\n * dynamically customizing shipping options\"), and the in-page form can only\n * by a server update after the fact — while this module's callers fix the\n * platform fee and the Connect transfer from the session's options at\n * creation. So the quote is taken BEFORE the session, against the\n * destination the shopper declares (country and postal code), and the\n * session is then restricted to that country exactly as a zone rate is\n * (AGL-1721). The same code serves cart checkout, buy-now and a draft\n * order's link, hosted and in-page, and the fee arithmetic downstream sees\n * ordinary options.\n *\n * ## The fallback is the merchant's own\n *\n * No quoter, a quoter not available for this site, or a quote that fails or\n * takes longer than {@link CommerceModel.CARRIER_QUOTE_TIMEOUT_MS}: the plan\n * is exactly the one {@link CommerceModel.planCheckoutShipping} makes from\n * the table, where a carrier rate offers nothing and its fallback rate is\n * offered. A store with no carrier rate never reaches the quoter at all, so\n * its sessions are byte-identical to the ones before this existed.\n */\n\nexport interface CarrierShippingCart {\n subtotalCents: number\n totalGrams: number\n /** One parcel's dimensions, when the cart is one product that has them. */\n parcel?: Omit<PluginShippingParcel, 'weightGrams'>\n}\n\nexport interface CarrierShippingDestination {\n country?: unknown\n postalCode?: unknown\n state?: unknown\n city?: unknown\n}\n\n/** A postal code a shopper declared, trimmed and bounded, or `undefined`. */\nexport function normalizeCheckoutPostalCode(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const code = value.trim().toUpperCase().slice(0, 12)\n return /^[A-Z0-9][A-Z0-9 -]{1,11}$/.test(code) ? code : undefined\n}\n\nexport type CarrierShippingPlan = CommerceModel.CheckoutShippingPlan & {\n /** Set when the plan offers live quotes: the postal code they were priced for. */\n quotedPostalCode?: string\n /**\n * The destination's zone prices by carrier and the store can quote, but the\n * shopper has not said where in the country: ask for a postal code.\n */\n needsPostalCode?: boolean\n}\n\n/** What a shopper is told when a postal code is needed. */\nexport const CARRIER_POSTAL_CODE_MESSAGE = 'Enter the postal code you’re shipping to.'\n\n/**\n * The shipping half of a session for a store that may price by carrier.\n * See the module comment; `planCheckoutShipping` is the whole answer for any\n * store without a carrier rate.\n */\nexport async function planCheckoutShippingWithCarriers(input: {\n hostId: string\n settings: CommerceModel.ShippingSettings | undefined\n cart: CarrierShippingCart\n destination: CarrierShippingDestination\n currency?: string\n timeoutMs?: number\n}): Promise<CarrierShippingPlan> {\n const { settings, cart } = input\n const tablePlan = () =>\n CommerceModel.planCheckoutShipping(\n settings,\n { subtotalCents: cart.subtotalCents, totalGrams: cart.totalGrams },\n input.destination.country,\n )\n if (!CommerceModel.hasCarrierRates(settings)) return tablePlan()\n const quoter = pluginShippingRateQuoter()\n if (!quoter) return tablePlan()\n const available = await quoter.available(input.hostId).catch(() => false)\n if (!available) return tablePlan()\n\n const countries = CommerceModel.checkoutShippingCountries(settings)\n const country = CommerceModel.normalizeCheckoutShippingCountry(input.destination.country, countries)\n if (!country) {\n // Carrier prices differ by address by construction, so a session that\n // does not know the destination cannot be honest about any of them.\n return { countries, options: [], refusal: 'destination-required' }\n }\n const carrierRates = CommerceModel.carrierRatesFor(settings, country)\n if (!carrierRates.length) return tablePlan()\n const postalCode = normalizeCheckoutPostalCode(input.destination.postalCode)\n if (!postalCode) {\n return {\n countries: [country],\n options: [],\n refusal: 'destination-required',\n needsPostalCode: true,\n }\n }\n\n const currency = String(input.currency ?? 'usd').toLowerCase()\n const quotes = await quotePluginShippingRates(\n {\n hostId: input.hostId,\n to: {\n country,\n postalCode,\n ...(typeof input.destination.state === 'string' && input.destination.state.trim()\n ? { state: input.destination.state.trim().slice(0, 40) }\n : {}),\n ...(typeof input.destination.city === 'string' && input.destination.city.trim()\n ? { city: input.destination.city.trim().slice(0, 80) }\n : {}),\n },\n parcels: [{ weightGrams: Math.max(0, Math.round(cart.totalGrams)), ...(cart.parcel ?? {}) }],\n currency,\n valueCents: Math.max(0, Math.round(cart.subtotalCents)),\n },\n { timeoutMs: input.timeoutMs ?? CommerceModel.CARRIER_QUOTE_TIMEOUT_MS },\n )\n if (!quotes || !quotes.length) return tablePlan()\n\n const quoted: CommerceModel.ResolvedShippingRate[] = []\n const hidden = new Set<string>()\n for (const rate of carrierRates) {\n const services = (rate.carrier?.services ?? []).map((key) => key.toLowerCase())\n const offered = quotes.filter(\n (quote) => quote.currency === currency && (!services.length || services.includes(quote.serviceKey.toLowerCase())),\n )\n if (!offered.length) continue\n if (rate.carrier?.fallbackRateId) hidden.add(rate.carrier.fallbackRateId)\n for (const quote of offered) {\n quoted.push({\n rateId: CommerceModel.carrierOptionRateId(rate.id, quote.serviceKey),\n name: (quote.estimatedDays\n ? `${quote.label} (${quote.estimatedDays} business day${quote.estimatedDays === 1 ? '' : 's'})`\n : quote.label\n ).slice(0, 100),\n amountCents: CommerceModel.carrierOptionAmountCents(quote.amountCents, rate.carrier),\n })\n }\n }\n if (!quoted.length) return tablePlan()\n\n // The table's own options for this destination stay — a flat rate the\n // merchant offers beside carriers, local pickup — less any fallback a\n // carrier rate replaced now that it has quotes.\n const table = CommerceModel.resolveCheckoutShippingOptions(\n settings,\n [country],\n { subtotalCents: cart.subtotalCents, totalGrams: cart.totalGrams },\n ).filter((option) => !hidden.has(option.rateId))\n // One option per name: two carrier rates quoting the same service keep the\n // cheaper, so a shopper never sees the same service twice.\n const byName = new Map<string, CommerceModel.ResolvedShippingRate>()\n for (const option of [...table, ...quoted]) {\n const existing = byName.get(option.name)\n if (!existing || option.amountCents < existing.amountCents) byName.set(option.name, option)\n }\n const options = [...byName.values()]\n .sort((a, b) => a.amountCents - b.amountCents || a.rateId.localeCompare(b.rateId))\n .slice(0, CommerceModel.MAX_CHECKOUT_SHIPPING_OPTIONS)\n return { countries: [country], options, quotedPostalCode: postalCode }\n}\n"],"names":["pluginShippingRateQuoter","quotePluginShippingRates","CommerceModel","normalizeCheckoutPostalCode","value","undefined","code","trim","toUpperCase","slice","test","CARRIER_POSTAL_CODE_MESSAGE","planCheckoutShippingWithCarriers","input","cart","settings","tablePlan","planCheckoutShipping","subtotalCents","totalGrams","destination","country","hasCarrierRates","quoter","available","hostId","catch","countries","checkoutShippingCountries","normalizeCheckoutShippingCountry","options","refusal","carrierRates","carrierRatesFor","length","postalCode","needsPostalCode","currency","String","toLowerCase","quotes","to","state","city","parcels","weightGrams","Math","max","round","parcel","valueCents","timeoutMs","CARRIER_QUOTE_TIMEOUT_MS","quoted","hidden","Set","rate","services","carrier","map","key","offered","filter","quote","includes","serviceKey","fallbackRateId","add","push","rateId","carrierOptionRateId","id","name","estimatedDays","label","amountCents","carrierOptionAmountCents","table","resolveCheckoutShippingOptions","option","has","byName","Map","existing","get","set","values","sort","a","b","localeCompare","MAX_CHECKOUT_SHIPPING_OPTIONS","quotedPostalCode"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,wBAAwB,EACxBC,wBAAwB,QAEnB,oDAAmD;AAC1D,YAAYC,mBAAmB,oBAAU;AA6CzC,2EAA2E,GAC3E,OAAO,SAASC,4BAA4BC,KAAc;IACxD,IAAI,OAAOA,UAAU,UAAU,OAAOC;IACtC,MAAMC,OAAOF,MAAMG,IAAI,GAAGC,WAAW,GAAGC,KAAK,CAAC,GAAG;IACjD,OAAO,6BAA6BC,IAAI,CAACJ,QAAQA,OAAOD;AAC1D;AAYA,yDAAyD,GACzD,OAAO,MAAMM,8BAA8B,4CAA2C;AAEtF;;;;CAIC,GACD,OAAO,eAAeC,iCAAiCC,KAOtD;QAiCyBA,iBAcmDC,cAI5DD;IAlDf,MAAM,EAAEE,QAAQ,EAAED,IAAI,EAAE,GAAGD;IAC3B,MAAMG,YAAY,IAChBd,cAAce,oBAAoB,CAChCF,UACA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