@aglyn/plugins-commerce 1.29.1 → 1.29.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/console/checkout-tax-blocked-notice.component.d.ts +18 -0
  3. package/src/lib/components/console/checkout-tax-blocked-notice.component.js +67 -0
  4. package/src/lib/components/console/checkout-tax-blocked-notice.component.js.map +1 -0
  5. package/src/lib/components/console/payments-settings-card.component.d.ts +2 -2
  6. package/src/lib/components/console/payments-settings-card.component.js +99 -5
  7. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  8. package/src/lib/components/console/product-editor-dialog.component.js +14 -3
  9. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  10. package/src/lib/components/console/stripe-tax-readiness.component.d.ts +45 -0
  11. package/src/lib/components/console/stripe-tax-readiness.component.js +276 -0
  12. package/src/lib/components/console/stripe-tax-readiness.component.js.map +1 -0
  13. package/src/lib/components/console/tax-settings-card.component.js +22 -8
  14. package/src/lib/components/console/tax-settings-card.component.js.map +1 -1
  15. package/src/lib/constants/operator-alerts.d.ts +9 -0
  16. package/src/lib/constants/operator-alerts.js +22 -1
  17. package/src/lib/constants/operator-alerts.js.map +1 -1
  18. package/src/lib/declarations.server.js +11 -0
  19. package/src/lib/declarations.server.js.map +1 -1
  20. package/src/lib/model/commerce-tax-readiness.d.ts +79 -0
  21. package/src/lib/model/commerce-tax-readiness.js +99 -0
  22. package/src/lib/model/commerce-tax-readiness.js.map +1 -0
  23. package/src/lib/model/commerce.d.ts +7 -0
  24. package/src/lib/model/commerce.js +17 -4
  25. package/src/lib/model/commerce.js.map +1 -1
  26. package/src/lib/model/payments-setup-status.d.ts +68 -0
  27. package/src/lib/model/payments-setup-status.js +103 -0
  28. package/src/lib/model/payments-setup-status.js.map +1 -0
  29. package/src/lib/plan-entitlements.d.ts +2 -1
  30. package/src/lib/plan-entitlements.js +2 -1
  31. package/src/lib/plan-entitlements.js.map +1 -1
  32. package/src/lib/server/cart-checkout.js +3 -0
  33. package/src/lib/server/cart-checkout.js.map +1 -1
  34. package/src/lib/server/checkout-tax-refusal.d.ts +51 -0
  35. package/src/lib/server/checkout-tax-refusal.js +133 -0
  36. package/src/lib/server/checkout-tax-refusal.js.map +1 -0
  37. package/src/lib/server/checkout.d.ts +2 -1
  38. package/src/lib/server/checkout.js +7 -2
  39. package/src/lib/server/checkout.js.map +1 -1
  40. package/src/lib/server/connect-prefill.d.ts +65 -0
  41. package/src/lib/server/connect-prefill.js +85 -0
  42. package/src/lib/server/connect-prefill.js.map +1 -0
  43. package/src/lib/server/connect.d.ts +4 -2
  44. package/src/lib/server/connect.js +117 -37
  45. package/src/lib/server/connect.js.map +1 -1
  46. package/src/lib/server/draft-order.js +4 -2
  47. package/src/lib/server/draft-order.js.map +1 -1
  48. package/src/lib/server/pos-order.js +1 -1
  49. package/src/lib/server/pos-order.js.map +1 -1
  50. package/src/lib/server/product-writer.d.ts +27 -0
  51. package/src/lib/server/product-writer.js +174 -4
  52. package/src/lib/server/product-writer.js.map +1 -1
  53. package/src/lib/server/quote-pay.d.ts +6 -0
  54. package/src/lib/server/quote-pay.js +8 -2
  55. package/src/lib/server/quote-pay.js.map +1 -1
  56. package/src/lib/server/seller-stripe-account.d.ts +19 -0
  57. package/src/lib/server/seller-stripe-account.js +40 -4
  58. package/src/lib/server/seller-stripe-account.js.map +1 -1
  59. package/src/lib/server/site-page-resolver.d.ts +1 -6
  60. package/src/lib/server/site-page-resolver.js +4 -12
  61. package/src/lib/server/site-page-resolver.js.map +1 -1
  62. package/src/lib/server/site-search.d.ts +43 -0
  63. package/src/lib/server/site-search.js +124 -0
  64. package/src/lib/server/site-search.js.map +1 -0
  65. package/src/lib/server/tax-readiness.d.ts +56 -0
  66. package/src/lib/server/tax-readiness.js +169 -0
  67. package/src/lib/server/tax-readiness.js.map +1 -0
  68. package/src/lib/server.js +6 -0
  69. package/src/lib/server.js.map +1 -1
  70. package/src/lib/transfer/product-image-copy.server.d.ts +77 -0
  71. package/src/lib/transfer/product-image-copy.server.js +307 -0
  72. package/src/lib/transfer/product-image-copy.server.js.map +1 -0
  73. package/src/lib/transfer/product-images.d.ts +62 -0
  74. package/src/lib/transfer/product-images.js +143 -0
  75. package/src/lib/transfer/product-images.js.map +1 -0
  76. package/src/lib/transfer/product-sources.d.ts +92 -0
  77. package/src/lib/transfer/product-sources.js +519 -0
  78. package/src/lib/transfer/product-sources.js.map +1 -0
  79. package/src/lib/transfer/product-transfer.d.ts +26 -1
  80. package/src/lib/transfer/product-transfer.js +283 -11
  81. package/src/lib/transfer/product-transfer.js.map +1 -1
  82. package/src/lib/transfer/products.server.d.ts +29 -3
  83. package/src/lib/transfer/products.server.js +289 -13
  84. package/src/lib/transfer/products.server.js.map +1 -1
@@ -27,9 +27,21 @@ import { withoutUndefined } from "../transfer/server-common.js";
27
27
  'description',
28
28
  'mediaUrls',
29
29
  'tags',
30
+ 'seo',
30
31
  'options',
31
32
  'variants'
32
33
  ];
34
+ /** The source's search words, only where the product has none of its own. */ function seoFrom(source, current) {
35
+ var _current_title, _source_title, _current_description, _source_description;
36
+ const title = (current == null ? void 0 : (_current_title = current.title) == null ? void 0 : _current_title.trim()) ? current.title : source == null ? void 0 : (_source_title = source.title) == null ? void 0 : _source_title.trim().slice(0, 60);
37
+ const description = (current == null ? void 0 : (_current_description = current.description) == null ? void 0 : _current_description.trim()) ? current.description : source == null ? void 0 : (_source_description = source.description) == null ? void 0 : _source_description.trim().slice(0, 155);
38
+ if (!title && !description && !current) return undefined;
39
+ return _extends({}, current != null ? current : {}, title ? {
40
+ title
41
+ } : {}, description ? {
42
+ description
43
+ } : {});
44
+ }
33
45
  /** How many suffixed addresses a new product tries before it gives up. */ const SLUG_TRIES = 30;
34
46
  const SLUGS_PER_QUERY = 30;
35
47
  const newVariantId = ()=>`v${Aglyn.createResourceUid().slice(0, 10)}`;
@@ -59,6 +71,99 @@ function priceUsd(minor) {
59
71
  }
60
72
  return next;
61
73
  }
74
+ const norm = (value)=>String(value != null ? value : '').trim().toLowerCase();
75
+ /**
76
+ * Pairs each sourced configuration that names no variant id with one the
77
+ * product already has (AGL-3641 linking): first by SKU, then by the same
78
+ * choices whatever the options are called. This is what lets a merchant
79
+ * link a product they made by hand, or copied from another store, to the
80
+ * source without losing its variants, their ids or the orders that name
81
+ * them. A current variant is claimed once.
82
+ */ export function matchSourcedVariants(source, current) {
83
+ const known = new Set(current.map((variant)=>variant.id));
84
+ const claimed = new Set(source.map((variant)=>variant.variantId).filter((id)=>Boolean(id && known.has(id))));
85
+ const free = ()=>current.filter((variant)=>!claimed.has(variant.id));
86
+ const choices = (options)=>Object.values(options != null ? options : {}).map(norm).filter(Boolean).sort().join('|');
87
+ const ids = source.map((variant)=>variant.variantId && known.has(variant.variantId) ? variant.variantId : undefined);
88
+ const claim = (index, found)=>{
89
+ if (!found) return;
90
+ ids[index] = found.id;
91
+ claimed.add(found.id);
92
+ };
93
+ source.forEach((variant, index)=>{
94
+ if (ids[index] || !variant.sku) return;
95
+ claim(index, free().find((candidate)=>candidate.sku && norm(candidate.sku) === norm(variant.sku)));
96
+ });
97
+ source.forEach((variant, index)=>{
98
+ if (ids[index]) return;
99
+ const wanted = choices(variant.options);
100
+ claim(index, free().find((candidate)=>choices(candidate.options) === wanted));
101
+ });
102
+ // A product with one configuration on both sides is the same one.
103
+ if (source.length === 1 && current.length === 1 && !ids[0] && !claimed.has(current[0].id)) ids[0] = current[0].id;
104
+ return ids;
105
+ }
106
+ /**
107
+ * The merchant's own words for the options, kept across a re-sync (AGL-3641):
108
+ * a variant the product already had says what each of the source's option
109
+ * names and values is called here, so a store that renamed "Colors" to
110
+ * "Color" or "Heather Grey" to "Grey" keeps its labels. A name or value with
111
+ * no consistent counterpart keeps the source's word.
112
+ */ export function keepMerchantLabels(source, current, ids) {
113
+ const byId = new Map(current.variants.map((variant)=>[
114
+ variant.id,
115
+ variant
116
+ ]));
117
+ const currentNames = current.options.map((option)=>option.name);
118
+ const sameShape = currentNames.length === source.options.length;
119
+ const nameFor = (index)=>sameShape && currentNames[index] ? currentNames[index] : source.options[index].name;
120
+ // Per option position: source value -> merchant value, only where every pair agrees.
121
+ const valueMaps = source.options.map(()=>new Map());
122
+ if (sameShape) {
123
+ source.variants.forEach((variant, at)=>{
124
+ const id = ids[at];
125
+ const existing = id ? byId.get(id) : undefined;
126
+ if (!existing) return;
127
+ source.options.forEach((option, index)=>{
128
+ var _existing_options;
129
+ const from = variant.options[option.name];
130
+ const to = (_existing_options = existing.options) == null ? void 0 : _existing_options[currentNames[index]];
131
+ if (!from || !to) return;
132
+ const map = valueMaps[index];
133
+ if (!map.has(from)) map.set(from, to);
134
+ else if (map.get(from) !== to) map.set(from, null);
135
+ });
136
+ });
137
+ // Two source values renamed to one label would merge choices: keep the source's words for those.
138
+ valueMaps.forEach((map)=>{
139
+ var _seen_get, _seen_get1;
140
+ const seen = new Map();
141
+ for (const to of map.values())if (to) seen.set(to, ((_seen_get = seen.get(to)) != null ? _seen_get : 0) + 1);
142
+ for (const [from, to] of map)if (to && ((_seen_get1 = seen.get(to)) != null ? _seen_get1 : 0) > 1) map.set(from, null);
143
+ });
144
+ }
145
+ const label = (index, value)=>{
146
+ var _valueMaps_index;
147
+ return ((_valueMaps_index = valueMaps[index]) == null ? void 0 : _valueMaps_index.get(value)) || value;
148
+ };
149
+ return {
150
+ options: source.options.map((option, index)=>({
151
+ name: nameFor(index),
152
+ values: [
153
+ ...new Set(option.values.map((value)=>label(index, value)))
154
+ ]
155
+ })),
156
+ variants: source.variants.map((variant)=>{
157
+ if (source.options.length === 0) return _extends({}, variant.options);
158
+ const out = {};
159
+ source.options.forEach((option, index)=>{
160
+ const value = variant.options[option.name];
161
+ if (value) out[nameFor(index)] = label(index, value);
162
+ });
163
+ return out;
164
+ })
165
+ };
166
+ }
62
167
  async function freeSlug(products, name) {
63
168
  var _candidates_find;
64
169
  const base = commerceSlug(name).slice(0, 80) || 'product';
@@ -111,6 +216,7 @@ export async function upsertSourcedProduct(write, firestore = firebaseAdmin.app(
111
216
  // An update, when the product is still there.
112
217
  if (write.productId && isDocumentId(write.productId)) {
113
218
  const ref = products.doc(write.productId);
219
+ let matched = 0;
114
220
  const updated = await firestore.runTransaction(async (tx)=>{
115
221
  const snapshot = await tx.get(ref);
116
222
  const data = snapshot.data();
@@ -124,14 +230,38 @@ export async function upsertSourcedProduct(write, firestore = firebaseAdmin.app(
124
230
  variant.id,
125
231
  variant
126
232
  ]));
127
- const next = _extends({}, current, {
233
+ // Pair by SKU and plain choices, learn the merchant's labels from those pairs,
234
+ // then pair the rest by their choices in the merchant's words.
235
+ const first = matchSourcedVariants(source.variants, current.variants);
236
+ const learned = keepMerchantLabels(source, current, first);
237
+ const ids = matchSourcedVariants(source.variants.map((variant, index)=>_extends({}, variant, {
238
+ options: learned.variants[index]
239
+ }, first[index] ? {
240
+ variantId: first[index]
241
+ } : {})), current.variants);
242
+ matched = ids.filter(Boolean).length;
243
+ const labels = flags.content ? {
128
244
  options: source.options.map((option)=>({
129
245
  name: option.name,
130
246
  values: [
131
247
  ...option.values
132
248
  ]
133
249
  })),
134
- variants: source.variants.map((variant)=>variantFrom(variant, variant.variantId ? byId.get(variant.variantId) : undefined, flags))
250
+ variants: source.variants.map((variant)=>_extends({}, variant.options))
251
+ } : keepMerchantLabels(source, current, ids);
252
+ const seo = seoFrom(source.seo, current.seo);
253
+ const next = _extends({}, current, seo ? {
254
+ seo
255
+ } : {}, {
256
+ options: labels.options.map((option)=>({
257
+ name: option.name,
258
+ values: [
259
+ ...option.values
260
+ ]
261
+ })),
262
+ variants: source.variants.map((variant, index)=>variantFrom(_extends({}, variant, {
263
+ options: labels.variants[index]
264
+ }), ids[index] ? byId.get(ids[index]) : undefined, flags))
135
265
  }, flags.content ? _extends({
136
266
  name,
137
267
  description,
@@ -177,7 +307,8 @@ export async function upsertSourcedProduct(write, firestore = firebaseAdmin.app(
177
307
  return {
178
308
  outcome: updated.changed ? 'updated' : 'unchanged',
179
309
  productId: write.productId,
180
- variants: mapping(updated.next)
310
+ variants: mapping(updated.next),
311
+ matched
181
312
  };
182
313
  }
183
314
  }
@@ -204,6 +335,8 @@ export async function upsertSourcedProduct(write, firestore = firebaseAdmin.app(
204
335
  tags: [
205
336
  ...source.tags
206
337
  ]
338
+ } : {}, seoFrom(source.seo, undefined) ? {
339
+ seo: seoFrom(source.seo, undefined)
207
340
  } : {}, {
208
341
  options: source.options.map((option)=>({
209
342
  name: option.name,
@@ -257,8 +390,45 @@ export async function upsertSourcedProduct(write, firestore = firebaseAdmin.app(
257
390
  throw error;
258
391
  }
259
392
  }
393
+ /** A sourced product whose source dropped it, back to a draft (AGL-3641). */ export async function unlistSourcedProduct(input, firestore = firebaseAdmin.app().firestore()) {
394
+ if (!isDocumentId(input.hostId) || !isDocumentId(input.productId)) return 'missing';
395
+ const ref = firestore.collection('hosts').doc(input.hostId).collection('products').doc(input.productId);
396
+ const outcome = await firestore.runTransaction(async (tx)=>{
397
+ var _ref;
398
+ const snapshot = await tx.get(ref);
399
+ const data = snapshot.data();
400
+ if (!snapshot.exists || (data == null ? void 0 : data['deletedAt']) !== null && (data == null ? void 0 : data['deletedAt']) !== undefined) return {
401
+ result: 'missing'
402
+ };
403
+ if ((data == null ? void 0 : data.status) !== 'active') return {
404
+ result: 'unchanged'
405
+ };
406
+ tx.update(ref, {
407
+ status: 'draft',
408
+ updatedAtMs: Date.now(),
409
+ updatedAt: firebaseAdmin.firestore.Timestamp.now()
410
+ });
411
+ return {
412
+ result: 'unlisted',
413
+ name: String((_ref = data == null ? void 0 : data.name) != null ? _ref : '')
414
+ };
415
+ });
416
+ if (outcome.result === 'unlisted') {
417
+ var _input_actorUid;
418
+ await logHostActivity(input.hostId, {
419
+ uid: (_input_actorUid = input.actorUid) != null ? _input_actorUid : 'import',
420
+ email: null
421
+ }, 'Took product off sale: its source no longer offers it', {
422
+ type: 'content',
423
+ id: input.productId,
424
+ name: outcome.name
425
+ });
426
+ }
427
+ return outcome.result;
428
+ }
260
429
  export const commerceProductWriter = {
261
- upsertSourced: (write)=>upsertSourcedProduct(write)
430
+ upsertSourced: (write)=>upsertSourcedProduct(write),
431
+ unlistSourced: (input)=>unlistSourcedProduct(input)
262
432
  };
263
433
 
264
434
  //# sourceMappingURL=product-writer.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/product-writer.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 { validateProductForSave } from '../model/product-card-rules'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport { countLiveDocuments } from '@aglyn/aglyn/app-utils/live-document-count'\nimport type {\n PluginProductWriter,\n SourcedProductWrite,\n SourcedProductWriteOutcome,\n} from '@aglyn/aglyn/plugin-manager/plugin-product-writer'\nimport type { TransferResourceContext } from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\nimport { firebaseAdmin, getOrgForHost, logHostActivity } from '@aglyn/tenant-data-admin'\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport {\n commerceSlug,\n liftLegacyProduct,\n type HostProduct,\n type ProductVariant,\n} from '../model/commerce'\nimport { derivedKeys, readSmartCollections } from '../transfer/products.server'\nimport { withoutUndefined } from '../transfer/server-common'\n\n/**\n * Products another plugin brings from a source of its own — a print-on-demand\n * service, a supplier — written through the store's own rules (AGL-3641),\n * behind core's `core.product-writer`.\n *\n * The same rules the console's product route and the file import keep: a\n * create is counted against the plan's product allowance in the transaction\n * that makes it, a new product takes an address no other product holds (a\n * deleted one's included), every write carries the search, stock and\n * smart-collection keys every writer derives, and the site's activity says\n * what happened.\n *\n * A configuration the source cannot make now is sold out (`inventory: 0`);\n * one it can is untracked (`inventory: null`), because a made-to-order item\n * has no count to run down.\n */\n\ntype ProductDoc = Partial<HostProduct> & Record<string, unknown>\n\n/** The fields an update compares to tell a change from a repeat. */\nconst COMPARED_KEYS = ['name', 'description', 'mediaUrls', 'tags', 'options', 'variants'] as const\n\n/** How many suffixed addresses a new product tries before it gives up. */\nconst SLUG_TRIES = 30\nconst SLUGS_PER_QUERY = 30\n\nconst newVariantId = () => `v${Aglyn.createResourceUid().slice(0, 10)}`\n\nfunction priceUsd(minor: number): number {\n return Math.round(Math.max(0, Number(minor) || 0)) / 100\n}\n\n/** The variant a sourced configuration becomes, on top of the one it was. */\nfunction variantFrom(\n source: SourcedProductWrite['product']['variants'][number],\n existing: ProductVariant | undefined,\n options: { prices: boolean; content: boolean },\n): ProductVariant {\n const price = existing && !options.prices ? existing.priceUsd : priceUsd(source.priceMinor)\n const next: ProductVariant = {\n ...(existing ?? {}),\n id: existing?.id ?? newVariantId(),\n options: { ...source.options },\n priceUsd: price,\n inventory: source.available ? null : 0,\n }\n delete next.inventoryByLocation\n if (source.sku) next.sku = source.sku.slice(0, 120)\n else delete next.sku\n if (Number.isFinite(source.weightGrams) && Number(source.weightGrams) > 0) {\n next.weightGrams = Math.round(Number(source.weightGrams))\n }\n if (source.imageUrl && (options.content || !existing?.imageUrl)) next.imageUrl = source.imageUrl\n // A price brought below a compare-at that no longer exceeds it would be\n // refused: the strike-through goes, the price stays.\n if (next.compareAtPriceUsd != null && Number(next.compareAtPriceUsd) <= next.priceUsd) {\n delete next.compareAtPriceUsd\n }\n return next\n}\n\nasync function freeSlug(products: FirebaseFirestore.CollectionReference, name: string): Promise<string | null> {\n const base = commerceSlug(name).slice(0, 80) || 'product'\n const candidates = [base, ...Array.from({ length: SLUG_TRIES - 1 }, (_, index) => `${base}-${index + 2}`)]\n const taken = new Set<string>()\n for (let at = 0; at < candidates.length; at += SLUGS_PER_QUERY) {\n const slice = candidates.slice(at, at + SLUGS_PER_QUERY)\n for (const doc of (await products.where('slug', 'in', slice).get()).docs) taken.add(String(doc.get('slug')))\n }\n return candidates.find((candidate) => !taken.has(candidate)) ?? null\n}\n\nclass WriteRefusal extends Error {\n constructor(readonly outcome: Exclude<SourcedProductWriteOutcome, { productId: string }>) {\n super(outcome.outcome)\n }\n}\n\nexport async function upsertSourcedProduct(\n write: SourcedProductWrite,\n firestore: FirebaseFirestore.Firestore = firebaseAdmin.app().firestore(),\n): Promise<SourcedProductWriteOutcome> {\n const { hostId, product: source } = write\n if (!isDocumentId(hostId)) return { outcome: 'no_store' }\n const owner = await getOrgForHost(hostId)\n if (!owner || !Aglyn.checkEntitlement(owner.org as never, 'commerce')) return { outcome: 'no_store' }\n const org = owner.org\n const products = firestore.collection('hosts').doc(hostId).collection('products')\n const smart = await readSmartCollections(firestore, { hostId } as TransferResourceContext)\n const { Timestamp } = firebaseAdmin.firestore\n const actor = { uid: write.actorUid ?? 'import', email: null }\n const name = source.name.trim().slice(0, 200)\n const description = (source.description ?? '').trim().slice(0, 20_000)\n\n const mapping = (product: HostProduct) =>\n source.variants.map((variant, index) => ({ key: variant.key, variantId: product.variants[index].id }))\n\n try {\n // An update, when the product is still there.\n if (write.productId && isDocumentId(write.productId)) {\n const ref = products.doc(write.productId)\n const updated = await firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref)\n const data = snapshot.data() as ProductDoc | undefined\n if (!snapshot.exists || (data?.['deletedAt'] !== null && data?.['deletedAt'] !== undefined)) return null\n const current = liftLegacyProduct(data as ProductDoc)\n const flags = { prices: write.prices === true, content: write.content === true }\n const byId = new Map(current.variants.map((variant) => [variant.id, variant]))\n const next: HostProduct = {\n ...current,\n options: source.options.map((option) => ({ name: option.name, values: [...option.values] })),\n variants: source.variants.map((variant) =>\n variantFrom(variant, variant.variantId ? byId.get(variant.variantId) : undefined, flags),\n ),\n ...(flags.content\n ? {\n name,\n description,\n mediaUrls: [...source.mediaUrls],\n ...(source.tags ? { tags: [...source.tags] } : {}),\n }\n : {}),\n }\n const invalid = validateProductForSave(next)\n if (invalid) throw new WriteRefusal({ outcome: 'invalid', message: invalid })\n const changed = COMPARED_KEYS.some(\n (key) =>\n JSON.stringify((next as unknown as Record<string, unknown>)[key] ?? null) !==\n JSON.stringify((current as unknown as Record<string, unknown>)[key] ?? null),\n )\n if (changed) {\n tx.update(\n ref,\n withoutUndefined({\n ...Object.fromEntries(COMPARED_KEYS.map((key) => [key, (next as unknown as Record<string, unknown>)[key]])),\n ...derivedKeys(next, smart),\n updatedAtMs: Date.now(),\n updatedAt: Timestamp.now(),\n }) as FirebaseFirestore.UpdateData<FirebaseFirestore.DocumentData>,\n )\n }\n return { next, changed }\n })\n if (updated) {\n if (updated.changed) {\n await logHostActivity(hostId, actor, 'Updated product from its source', {\n type: 'content',\n id: write.productId,\n name: updated.next.name,\n })\n }\n return {\n outcome: updated.changed ? 'updated' : 'unchanged',\n productId: write.productId,\n variants: mapping(updated.next),\n }\n }\n }\n\n if (write.productId && write.recreate === false) return { outcome: 'missing' }\n\n // A new product.\n const slug = await freeSlug(products, name)\n if (!slug) return { outcome: 'invalid', message: 'Every address for a product of this name is taken. Rename one first.' }\n const productId = Aglyn.createResourceUid()\n const product: HostProduct = {\n name,\n slug,\n description,\n type: 'physical',\n status: write.status === 'active' ? 'active' : 'draft',\n mediaUrls: [...source.mediaUrls],\n ...(source.tags?.length ? { tags: [...source.tags] } : {}),\n options: source.options.map((option) => ({ name: option.name, values: [...option.values] })),\n variants: source.variants.map((variant) => variantFrom(variant, undefined, { prices: true, content: true })),\n oversellPolicy: 'deny',\n }\n const invalid = validateProductForSave(product)\n if (invalid) return { outcome: 'invalid', message: invalid }\n const now = Date.now()\n const ref = products.doc(productId)\n await firestore.runTransaction(async (tx) => {\n // Live products only: a deleted one frees its slot, an archived one keeps it (AGL-3918).\n const used = await countLiveDocuments(products, (aggregate) => tx.get(aggregate))\n const quota = Aglyn.checkQuota(org as never, 'productsPerHost', Number(used) || 0)\n if (!quota.allowed) throw new WriteRefusal({ outcome: 'plan_limit', limit: Number(quota.limit) || 0 })\n tx.create(\n ref,\n withoutUndefined({\n ...product,\n ...derivedKeys(product, smart),\n createdAtMs: now,\n updatedAtMs: now,\n deletedAt: null,\n createdAt: Timestamp.now(),\n updatedAt: Timestamp.now(),\n createdBy: write.actorUid ?? null,\n }),\n )\n })\n await logHostActivity(hostId, actor, 'Imported product', { type: 'content', id: productId, name: product.name })\n return { outcome: 'created', productId, variants: mapping(product) }\n } catch (error) {\n if (error instanceof WriteRefusal) return error.outcome\n throw error\n }\n}\n\nexport const commerceProductWriter: PluginProductWriter = {\n upsertSourced: (write) => upsertSourcedProduct(write),\n}\n"],"names":["validateProductForSave","Aglyn","countLiveDocuments","firebaseAdmin","getOrgForHost","logHostActivity","isDocumentId","commerceSlug","liftLegacyProduct","derivedKeys","readSmartCollections","withoutUndefined","COMPARED_KEYS","SLUG_TRIES","SLUGS_PER_QUERY","newVariantId","createResourceUid","slice","priceUsd","minor","Math","round","max","Number","variantFrom","source","existing","options","price","prices","priceMinor","next","id","inventory","available","inventoryByLocation","sku","isFinite","weightGrams","imageUrl","content","compareAtPriceUsd","freeSlug","products","name","candidates","base","Array","from","length","_","index","taken","Set","at","doc","where","get","docs","add","String","find","candidate","has","WriteRefusal","Error","outcome","upsertSourcedProduct","write","firestore","app","hostId","product","owner","checkEntitlement","org","collection","smart","Timestamp","actor","uid","actorUid","email","trim","description","mapping","variants","map","variant","key","variantId","productId","ref","updated","runTransaction","tx","snapshot","data","exists","undefined","current","flags","byId","Map","option","values","mediaUrls","tags","invalid","message","changed","some","JSON","stringify","update","Object","fromEntries","updatedAtMs","Date","now","updatedAt","type","recreate","slug","status","oversellPolicy","used","aggregate","quota","checkQuota","allowed","limit","create","createdAtMs","deletedAt","createdAt","createdBy","error","commerceProductWriter","upsertSourced"],"mappings":";AAAA;;;;;;;;;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AMa,QAAQ,YAAdb,kBAAkB;;QAGnC;QACA,MAAM/D,gBAAgBkE,QAAQQ,OAAO,oBAAoB;YAAE0C,MAAM;YAAWzF,IAAI2D;YAAW/C,MAAM4B,QAAQ5B,IAAI;QAAC;QAC9G,OAAO;YAAEsB,SAAS;YAAWyB;YAAWL,UAAUD,QAAQb;QAAS;IACrE,EAAE,OAAOiE,OAAO;QACd,IAAIA,iBAAiBzE,cAAc,OAAOyE,MAAMvE,OAAO;QACvD,MAAMuE;IACR;AACF;AAEA,OAAO,MAAMC,wBAA6C;IACxDC,eAAe,CAACvE,QAAUD,qBAAqBC;AACjD,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/product-writer.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 { validateProductForSave } from '../model/product-card-rules'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport { countLiveDocuments } from '@aglyn/aglyn/app-utils/live-document-count'\nimport type {\n PluginProductWriter,\n SourcedProductWrite,\n SourcedProductWriteOutcome,\n} from '@aglyn/aglyn/plugin-manager/plugin-product-writer'\nimport type { TransferResourceContext } from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\nimport { firebaseAdmin, getOrgForHost, logHostActivity } from '@aglyn/tenant-data-admin'\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport {\n commerceSlug,\n liftLegacyProduct,\n type HostProduct,\n type ProductVariant,\n} from '../model/commerce'\nimport { derivedKeys, readSmartCollections } from '../transfer/products.server'\nimport { withoutUndefined } from '../transfer/server-common'\n\n/**\n * Products another plugin brings from a source of its own — a print-on-demand\n * service, a supplier — written through the store's own rules (AGL-3641),\n * behind core's `core.product-writer`.\n *\n * The same rules the console's product route and the file import keep: a\n * create is counted against the plan's product allowance in the transaction\n * that makes it, a new product takes an address no other product holds (a\n * deleted one's included), every write carries the search, stock and\n * smart-collection keys every writer derives, and the site's activity says\n * what happened.\n *\n * A configuration the source cannot make now is sold out (`inventory: 0`);\n * one it can is untracked (`inventory: null`), because a made-to-order item\n * has no count to run down.\n */\n\ntype ProductDoc = Partial<HostProduct> & Record<string, unknown>\n\n/** The fields an update compares to tell a change from a repeat. */\nconst COMPARED_KEYS = ['name', 'description', 'mediaUrls', 'tags', 'seo', 'options', 'variants'] as const\n\n/** The source's search words, only where the product has none of its own. */\nfunction seoFrom(\n source: SourcedProductWrite['product']['seo'],\n current: HostProduct['seo'] | undefined,\n): HostProduct['seo'] | undefined {\n const title = current?.title?.trim() ? current.title : source?.title?.trim().slice(0, 60)\n const description = current?.description?.trim() ? current.description : source?.description?.trim().slice(0, 155)\n if (!title && !description && !current) return undefined\n return { ...(current ?? {}), ...(title ? { title } : {}), ...(description ? { description } : {}) }\n}\n\n/** How many suffixed addresses a new product tries before it gives up. */\nconst SLUG_TRIES = 30\nconst SLUGS_PER_QUERY = 30\n\nconst newVariantId = () => `v${Aglyn.createResourceUid().slice(0, 10)}`\n\nfunction priceUsd(minor: number): number {\n return Math.round(Math.max(0, Number(minor) || 0)) / 100\n}\n\n/** The variant a sourced configuration becomes, on top of the one it was. */\nfunction variantFrom(\n source: SourcedProductWrite['product']['variants'][number],\n existing: ProductVariant | undefined,\n options: { prices: boolean; content: boolean },\n): ProductVariant {\n const price = existing && !options.prices ? existing.priceUsd : priceUsd(source.priceMinor)\n const next: ProductVariant = {\n ...(existing ?? {}),\n id: existing?.id ?? newVariantId(),\n options: { ...source.options },\n priceUsd: price,\n inventory: source.available ? null : 0,\n }\n delete next.inventoryByLocation\n if (source.sku) next.sku = source.sku.slice(0, 120)\n else delete next.sku\n if (Number.isFinite(source.weightGrams) && Number(source.weightGrams) > 0) {\n next.weightGrams = Math.round(Number(source.weightGrams))\n }\n if (source.imageUrl && (options.content || !existing?.imageUrl)) next.imageUrl = source.imageUrl\n // A price brought below a compare-at that no longer exceeds it would be\n // refused: the strike-through goes, the price stays.\n if (next.compareAtPriceUsd != null && Number(next.compareAtPriceUsd) <= next.priceUsd) {\n delete next.compareAtPriceUsd\n }\n return next\n}\n\nconst norm = (value: unknown) => String(value ?? '').trim().toLowerCase()\n\n/**\n * Pairs each sourced configuration that names no variant id with one the\n * product already has (AGL-3641 linking): first by SKU, then by the same\n * choices whatever the options are called. This is what lets a merchant\n * link a product they made by hand, or copied from another store, to the\n * source without losing its variants, their ids or the orders that name\n * them. A current variant is claimed once.\n */\nexport function matchSourcedVariants(\n source: SourcedProductWrite['product']['variants'],\n current: readonly ProductVariant[],\n): Array<string | undefined> {\n const known = new Set(current.map((variant) => variant.id))\n const claimed = new Set(source.map((variant) => variant.variantId).filter((id): id is string => Boolean(id && known.has(id))))\n const free = () => current.filter((variant) => !claimed.has(variant.id))\n const choices = (options: Record<string, string> | undefined) =>\n Object.values(options ?? {})\n .map(norm)\n .filter(Boolean)\n .sort()\n .join('|')\n const ids: Array<string | undefined> = source.map((variant) =>\n variant.variantId && known.has(variant.variantId) ? variant.variantId : undefined,\n )\n const claim = (index: number, found: ProductVariant | undefined) => {\n if (!found) return\n ids[index] = found.id\n claimed.add(found.id)\n }\n source.forEach((variant, index) => {\n if (ids[index] || !variant.sku) return\n claim(index, free().find((candidate) => candidate.sku && norm(candidate.sku) === norm(variant.sku)))\n })\n source.forEach((variant, index) => {\n if (ids[index]) return\n const wanted = choices(variant.options)\n claim(index, free().find((candidate) => choices(candidate.options) === wanted))\n })\n // A product with one configuration on both sides is the same one.\n if (source.length === 1 && current.length === 1 && !ids[0] && !claimed.has(current[0].id)) ids[0] = current[0].id\n return ids\n}\n\n/**\n * The merchant's own words for the options, kept across a re-sync (AGL-3641):\n * a variant the product already had says what each of the source's option\n * names and values is called here, so a store that renamed \"Colors\" to\n * \"Color\" or \"Heather Grey\" to \"Grey\" keeps its labels. A name or value with\n * no consistent counterpart keeps the source's word.\n */\nexport function keepMerchantLabels(\n source: SourcedProductWrite['product'],\n current: HostProduct,\n ids: ReadonlyArray<string | undefined>,\n): { options: SourcedProductWrite['product']['options']; variants: Array<Record<string, string>> } {\n const byId = new Map(current.variants.map((variant) => [variant.id, variant]))\n const currentNames = current.options.map((option) => option.name)\n const sameShape = currentNames.length === source.options.length\n const nameFor = (index: number) => (sameShape && currentNames[index] ? currentNames[index] : source.options[index].name)\n // Per option position: source value -> merchant value, only where every pair agrees.\n const valueMaps = source.options.map(() => new Map<string, string | null>())\n if (sameShape) {\n source.variants.forEach((variant, at) => {\n const id = ids[at]\n const existing = id ? byId.get(id) : undefined\n if (!existing) return\n source.options.forEach((option, index) => {\n const from = variant.options[option.name]\n const to = existing.options?.[currentNames[index]]\n if (!from || !to) return\n const map = valueMaps[index]\n if (!map.has(from)) map.set(from, to)\n else if (map.get(from) !== to) map.set(from, null)\n })\n })\n // Two source values renamed to one label would merge choices: keep the source's words for those.\n valueMaps.forEach((map) => {\n const seen = new Map<string, number>()\n for (const to of map.values()) if (to) seen.set(to, (seen.get(to) ?? 0) + 1)\n for (const [from, to] of map) if (to && (seen.get(to) ?? 0) > 1) map.set(from, null)\n })\n }\n const label = (index: number, value: string) => valueMaps[index]?.get(value) || value\n return {\n options: source.options.map((option, index) => ({\n name: nameFor(index),\n values: [...new Set(option.values.map((value) => label(index, value)))],\n })),\n variants: source.variants.map((variant) => {\n if (source.options.length === 0) return { ...variant.options }\n const out: Record<string, string> = {}\n source.options.forEach((option, index) => {\n const value = variant.options[option.name]\n if (value) out[nameFor(index)] = label(index, value)\n })\n return out\n }),\n }\n}\n\nasync function freeSlug(products: FirebaseFirestore.CollectionReference, name: string): Promise<string | null> {\n const base = commerceSlug(name).slice(0, 80) || 'product'\n const candidates = [base, ...Array.from({ length: SLUG_TRIES - 1 }, (_, index) => `${base}-${index + 2}`)]\n const taken = new Set<string>()\n for (let at = 0; at < candidates.length; at += SLUGS_PER_QUERY) {\n const slice = candidates.slice(at, at + SLUGS_PER_QUERY)\n for (const doc of (await products.where('slug', 'in', slice).get()).docs) taken.add(String(doc.get('slug')))\n }\n return candidates.find((candidate) => !taken.has(candidate)) ?? null\n}\n\nclass WriteRefusal extends Error {\n constructor(readonly outcome: Exclude<SourcedProductWriteOutcome, { productId: string }>) {\n super(outcome.outcome)\n }\n}\n\nexport async function upsertSourcedProduct(\n write: SourcedProductWrite,\n firestore: FirebaseFirestore.Firestore = firebaseAdmin.app().firestore(),\n): Promise<SourcedProductWriteOutcome> {\n const { hostId, product: source } = write\n if (!isDocumentId(hostId)) return { outcome: 'no_store' }\n const owner = await getOrgForHost(hostId)\n if (!owner || !Aglyn.checkEntitlement(owner.org as never, 'commerce')) return { outcome: 'no_store' }\n const org = owner.org\n const products = firestore.collection('hosts').doc(hostId).collection('products')\n const smart = await readSmartCollections(firestore, { hostId } as TransferResourceContext)\n const { Timestamp } = firebaseAdmin.firestore\n const actor = { uid: write.actorUid ?? 'import', email: null }\n const name = source.name.trim().slice(0, 200)\n const description = (source.description ?? '').trim().slice(0, 20_000)\n\n const mapping = (product: HostProduct) =>\n source.variants.map((variant, index) => ({ key: variant.key, variantId: product.variants[index].id }))\n\n try {\n // An update, when the product is still there.\n if (write.productId && isDocumentId(write.productId)) {\n const ref = products.doc(write.productId)\n let matched = 0\n const updated = await firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref)\n const data = snapshot.data() as ProductDoc | undefined\n if (!snapshot.exists || (data?.['deletedAt'] !== null && data?.['deletedAt'] !== undefined)) return null\n const current = liftLegacyProduct(data as ProductDoc)\n const flags = { prices: write.prices === true, content: write.content === true }\n const byId = new Map(current.variants.map((variant) => [variant.id, variant]))\n // Pair by SKU and plain choices, learn the merchant's labels from those pairs,\n // then pair the rest by their choices in the merchant's words.\n const first = matchSourcedVariants(source.variants, current.variants)\n const learned = keepMerchantLabels(source, current, first)\n const ids = matchSourcedVariants(\n source.variants.map((variant, index) => ({\n ...variant,\n options: learned.variants[index],\n ...(first[index] ? { variantId: first[index] } : {}),\n })),\n current.variants,\n )\n matched = ids.filter(Boolean).length\n const labels = flags.content\n ? {\n options: source.options.map((option) => ({ name: option.name, values: [...option.values] })),\n variants: source.variants.map((variant) => ({ ...variant.options })),\n }\n : keepMerchantLabels(source, current, ids)\n const seo = seoFrom(source.seo, current.seo)\n const next: HostProduct = {\n ...current,\n ...(seo ? { seo } : {}),\n options: labels.options.map((option) => ({ name: option.name, values: [...option.values] })),\n variants: source.variants.map((variant, index) =>\n variantFrom({ ...variant, options: labels.variants[index] }, ids[index] ? byId.get(ids[index] as string) : undefined, flags),\n ),\n ...(flags.content\n ? {\n name,\n description,\n mediaUrls: [...source.mediaUrls],\n ...(source.tags ? { tags: [...source.tags] } : {}),\n }\n : {}),\n }\n const invalid = validateProductForSave(next)\n if (invalid) throw new WriteRefusal({ outcome: 'invalid', message: invalid })\n const changed = COMPARED_KEYS.some(\n (key) =>\n JSON.stringify((next as unknown as Record<string, unknown>)[key] ?? null) !==\n JSON.stringify((current as unknown as Record<string, unknown>)[key] ?? null),\n )\n if (changed) {\n tx.update(\n ref,\n withoutUndefined({\n ...Object.fromEntries(COMPARED_KEYS.map((key) => [key, (next as unknown as Record<string, unknown>)[key]])),\n ...derivedKeys(next, smart),\n updatedAtMs: Date.now(),\n updatedAt: Timestamp.now(),\n }) as FirebaseFirestore.UpdateData<FirebaseFirestore.DocumentData>,\n )\n }\n return { next, changed }\n })\n if (updated) {\n if (updated.changed) {\n await logHostActivity(hostId, actor, 'Updated product from its source', {\n type: 'content',\n id: write.productId,\n name: updated.next.name,\n })\n }\n return {\n outcome: updated.changed ? 'updated' : 'unchanged',\n productId: write.productId,\n variants: mapping(updated.next),\n matched,\n }\n }\n }\n\n if (write.productId && write.recreate === false) return { outcome: 'missing' }\n\n // A new product.\n const slug = await freeSlug(products, name)\n if (!slug) return { outcome: 'invalid', message: 'Every address for a product of this name is taken. Rename one first.' }\n const productId = Aglyn.createResourceUid()\n const product: HostProduct = {\n name,\n slug,\n description,\n type: 'physical',\n status: write.status === 'active' ? 'active' : 'draft',\n mediaUrls: [...source.mediaUrls],\n ...(source.tags?.length ? { tags: [...source.tags] } : {}),\n ...(seoFrom(source.seo, undefined) ? { seo: seoFrom(source.seo, undefined) } : {}),\n options: source.options.map((option) => ({ name: option.name, values: [...option.values] })),\n variants: source.variants.map((variant) => variantFrom(variant, undefined, { prices: true, content: true })),\n oversellPolicy: 'deny',\n }\n const invalid = validateProductForSave(product)\n if (invalid) return { outcome: 'invalid', message: invalid }\n const now = Date.now()\n const ref = products.doc(productId)\n await firestore.runTransaction(async (tx) => {\n // Live products only: a deleted one frees its slot, an archived one keeps it (AGL-3918).\n const used = await countLiveDocuments(products, (aggregate) => tx.get(aggregate))\n const quota = Aglyn.checkQuota(org as never, 'productsPerHost', Number(used) || 0)\n if (!quota.allowed) throw new WriteRefusal({ outcome: 'plan_limit', limit: Number(quota.limit) || 0 })\n tx.create(\n ref,\n withoutUndefined({\n ...product,\n ...derivedKeys(product, smart),\n createdAtMs: now,\n updatedAtMs: now,\n deletedAt: null,\n createdAt: Timestamp.now(),\n updatedAt: Timestamp.now(),\n createdBy: write.actorUid ?? null,\n }),\n )\n })\n await logHostActivity(hostId, actor, 'Imported product', { type: 'content', id: productId, name: product.name })\n return { outcome: 'created', productId, variants: mapping(product) }\n } catch (error) {\n if (error instanceof WriteRefusal) return error.outcome\n throw error\n }\n}\n\n/** A sourced product whose source dropped it, back to a draft (AGL-3641). */\nexport async function unlistSourcedProduct(\n input: { hostId: string; productId: string; actorUid?: string },\n firestore: FirebaseFirestore.Firestore = firebaseAdmin.app().firestore(),\n): Promise<'unlisted' | 'unchanged' | 'missing'> {\n if (!isDocumentId(input.hostId) || !isDocumentId(input.productId)) return 'missing'\n const ref = firestore.collection('hosts').doc(input.hostId).collection('products').doc(input.productId)\n const outcome = await firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref)\n const data = snapshot.data() as ProductDoc | undefined\n if (!snapshot.exists || (data?.['deletedAt'] !== null && data?.['deletedAt'] !== undefined)) return { result: 'missing' as const }\n if (data?.status !== 'active') return { result: 'unchanged' as const }\n tx.update(ref, { status: 'draft', updatedAtMs: Date.now(), updatedAt: firebaseAdmin.firestore.Timestamp.now() })\n return { result: 'unlisted' as const, name: String(data?.name ?? '') }\n })\n if (outcome.result === 'unlisted') {\n await logHostActivity(input.hostId, { uid: input.actorUid ?? 'import', email: null }, 'Took product off sale: its source no longer offers it', {\n type: 'content',\n id: input.productId,\n name: outcome.name,\n })\n }\n return outcome.result\n}\n\nexport const commerceProductWriter: PluginProductWriter = {\n upsertSourced: (write) => upsertSourcedProduct(write),\n unlistSourced: (input) => unlistSourcedProduct(input),\n}\n"],"names":["validateProductForSave","Aglyn","countLiveDocuments","firebaseAdmin","getOrgForHost","logHostActivity","isDocumentId","commerceSlug","liftLegacyProduct","derivedKeys","readSmartCollections","withoutUndefined","COMPARED_KEYS","seoFrom","source","current","title","trim","slice","description","undefined","SLUG_TRIES","SLUGS_PER_QUERY","newVariantId","createResourceUid","priceUsd","minor","Math","round","max","Number","variantFrom","existing","options","price","prices","priceMinor","next","id","inventory","available","inventoryByLocation","sku","isFinite","weightGrams","imageUrl","content","compareAtPriceUsd","norm","value","String","toLowerCase","matchSourcedVariants","known","Set","map","variant","claimed","variantId","filter","Boolean","has","free","choices","Object","values","sort","join","ids","claim","index","found","add","forEach","find","candidate","wanted","length","keepMerchantLabels","byId","Map","variants","currentNames","option","name","sameShape","nameFor","valueMaps","at","get","from","to","set","seen","label","out","freeSlug","products","candidates","base","Array","_","taken","doc","where","docs","WriteRefusal","Error","outcome","upsertSourcedProduct","write","firestore","app","hostId","product","owner","checkEntitlement","org","collection","smart","Timestamp","actor","uid","actorUid","email","mapping","key","productId","ref","matched","updated","runTransaction","tx","snapshot","data","exists","flags","first","learned","labels","seo","mediaUrls","tags","invalid","message","changed","some","JSON","stringify","update","fromEntries","updatedAtMs","Date","now","updatedAt","type","recreate","slug","status","oversellPolicy","used","aggregate","quota","checkQuota","allowed","limit","create","createdAtMs","deletedAt","createdAt","createdBy","error","unlistSourcedProduct","input","result","commerceProductWriter","upsertSourced","unlistSourced"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,iCAA6B;AACpE,YAAYC,WAAW,sBAAqB;AAC5C,SAASC,kBAAkB,QAAQ,6CAA4C;AAO/E,SAASC,aAAa,EAAEC,aAAa,EAAEC,eAAe,QAAQ,2BAA0B;AACxF,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,SACEC,YAAY,EACZC,iBAAiB,QAGZ,uBAAmB;AAC1B,SAASC,WAAW,EAAEC,oBAAoB,QAAQ,iCAA6B;AAC/E,SAASC,gBAAgB,QAAQ,+BAA2B;AAqB5D,kEAAkE,GAClE,MAAMC,gBAAgB;IAAC;IAAQ;IAAe;IAAa;IAAQ;IAAO;IAAW;CAAW;AAEhG,2EAA2E,GAC3E,SAASC,QACPC,MAA6C,EAC7CC,OAAuC;QAEzBA,gBAAyCD,eACnCC,sBAAqDD;IADzE,MAAME,QAAQD,CAAAA,4BAAAA,iBAAAA,QAASC,KAAK,qBAAdD,eAAgBE,IAAI,MAAKF,QAAQC,KAAK,GAAGF,2BAAAA,gBAAAA,OAAQE,KAAK,qBAAbF,cAAeG,IAAI,GAAGC,KAAK,CAAC,GAAG;IACtF,MAAMC,cAAcJ,CAAAA,4BAAAA,uBAAAA,QAASI,WAAW,qBAApBJ,qBAAsBE,IAAI,MAAKF,QAAQI,WAAW,GAAGL,2BAAAA,sBAAAA,OAAQK,WAAW,qBAAnBL,oBAAqBG,IAAI,GAAGC,KAAK,CAAC,GAAG;IAC9G,IAAI,CAACF,SAAS,CAACG,eAAe,CAACJ,SAAS,OAAOK;IAC/C,OAA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AI;IACvE;IACA,IAAIwB,QAAQkE,MAAM,KAAK,YAAY;YACUD;QAA3C,MAAMxK,gBAAgBwK,MAAM5D,MAAM,EAAE;YAAES,GAAG,GAAEmD,kBAAAA,MAAMlD,QAAQ,YAAdkD,kBAAkB;YAAUjD,OAAO;QAAK,GAAG,yDAAyD;YAC7I+B,MAAM;YACNrH,IAAIuI,MAAM9C,SAAS;YACnB3C,MAAMwB,QAAQxB,IAAI;QACpB;IACF;IACA,OAAOwB,QAAQkE,MAAM;AACvB;AAEA,OAAO,MAAMC,wBAA6C;IACxDC,eAAe,CAAClE,QAAUD,qBAAqBC;IAC/CmE,eAAe,CAACJ,QAAUD,qBAAqBC;AACjD,EAAC"}
@@ -61,6 +61,12 @@ export interface QuotePayDeps {
61
61
  * asks Stripe Tax. Absent, `sellerStripeTaxActive` answers.
62
62
  */
63
63
  sellerTaxActive?(accountId: string): Promise<boolean>;
64
+ /**
65
+ * Tells the store's managers, once, that a customer was refused because the
66
+ * store's sales tax is not set up (AGL-4245). Absent,
67
+ * `tellCheckoutTaxRefusal` does.
68
+ */
69
+ tellTaxRefusal?(hostId: string, reason: 'tax-undecided' | 'stripe-tax-not-active'): void;
64
70
  /** Registers the page's domain for Apple Pay; never throws. */
65
71
  ensureDomain(input: Parameters<typeof ensureCheckoutDomain>[0]): Promise<unknown>;
66
72
  /**
@@ -31,6 +31,7 @@ import { MEMBER_SESSIONS_VALID_FROM_FIELD, memberCookieName, parseMemberSession
31
31
  import { ensureCheckoutDomain } from "./payment-method-domains.js";
32
32
  import { verifyQuoteLinkToken } from "./quote-link-token.js";
33
33
  import { SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE, sellerStripeTaxActive } from "./seller-stripe-account.js";
34
+ import { tellCheckoutTaxRefusal } from "./checkout-tax-refusal.js";
34
35
  /*==========================================
35
36
  * THE CUSTOMER'S QUOTE PAGE AND ITS PAY BUTTON (AGL-4094), AND AN
36
37
  * INVOICE'S (AGL-4099).
@@ -571,7 +572,7 @@ const refusal = (status, reason, error, extra = {})=>({
571
572
  }, extra)
572
573
  });
573
574
  /** `POST /api/commerce/quote-pay`: a fresh Checkout Session for the quote. */ export async function handleQuotePay(deps, req) {
574
- var _onAccount_StripeAccount, _ref, _order_checkoutSessionId, _ref1;
575
+ var _deps_tellTaxRefusal, _onAccount_StripeAccount, _ref, _order_checkoutSessionId, _ref1;
575
576
  var _order_quote, _order_quote1;
576
577
  if (req.method !== 'POST') return {
577
578
  status: 405,
@@ -639,6 +640,8 @@ const refusal = (status, reason, error, extra = {})=>({
639
640
  if (blocked === 'payments-unavailable') {
640
641
  return refusal(409, blocked, CommerceModel.payLinkPaymentsUnavailableMessage(storeName, kind));
641
642
  }
643
+ const tellTaxRefusal = (_deps_tellTaxRefusal = deps.tellTaxRefusal) != null ? _deps_tellTaxRefusal : tellCheckoutTaxRefusal;
644
+ if (blocked === 'tax-undecided') tellTaxRefusal(hostId, 'tax-undecided');
642
645
  if (blocked) return refusal(409, blocked, CommerceModel.invoicePayRefusalMessage(blocked, storeName, kind));
643
646
  const { owner, accountId, chargeModel } = payments;
644
647
  const direct = chargeModel === 'direct';
@@ -662,7 +665,10 @@ const refusal = (status, reason, error, extra = {})=>({
662
665
  if (direct && charge.taxAtPayment) {
663
666
  var _deps_sellerTaxActive;
664
667
  const taxActive = await ((_deps_sellerTaxActive = deps.sellerTaxActive) != null ? _deps_sellerTaxActive : sellerStripeTaxActive)(String(accountId));
665
- if (!taxActive) return refusal(409, 'seller-tax', SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE);
668
+ if (!taxActive) {
669
+ tellTaxRefusal(hostId, 'stripe-tax-not-active');
670
+ return refusal(409, 'seller-tax', SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE);
671
+ }
666
672
  }
667
673
  const nativeMode = await deps.nativeMode(String((_ref = owner == null ? void 0 : owner.id) != null ? _ref : ''));
668
674
  const site = host;