@aglyn/plugins-commerce 1.29.0 → 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
@@ -19,6 +19,7 @@ import type { PicklistValue } from '@aglyn/aglyn/app-utils/picklists';
19
19
  import type { TransferApplyResult, TransferApplyWriter, TransferLookupResult, TransferPicklistList, TransferReadOptions, TransferReadPage, TransferResourceContext, TransferRevertDecisions, TransferRevertResult } from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources';
20
20
  import { type HostProduct, type SmartCollectionRules } from '../model/commerce';
21
21
  import { type ProductPlannedRow } from './product-transfer';
22
+ import { type ProductImageCopierDeps } from './product-image-copy.server';
22
23
  import { type Firestore } from './server-common';
23
24
  /** The smart collections a product's write answers (AGL-3321). */
24
25
  export declare function readSmartCollections(firestore: Firestore, ctx: TransferResourceContext): Promise<SmartCollectionRules[]>;
@@ -43,7 +44,32 @@ export declare function addProductCategories(ctx: TransferResourceContext, pickl
43
44
  * for new products, then the fold of `planProductTransfer`.
44
45
  */
45
46
  export declare function planProducts(ctx: TransferResourceContext, input: BuildTransferPlanInput, firestore?: Firestore): Promise<TransferPlan>;
47
+ /** The photo addresses a planned row copies: a new product's, or the photos a row changes. */
48
+ export declare function rowPhotoUrls(row: ProductPlannedRow): string[];
49
+ /**
50
+ * A library file a row's write named for a copied photo, kept with its undo
51
+ * entry. Undo asks the library to remove each, and the library removes only
52
+ * the ones this job stored and nothing still uses.
53
+ */
54
+ export interface ImportedProductMedia {
55
+ mediaId: string;
56
+ src: string;
57
+ key: string;
58
+ /** The photo's address in the file. */
59
+ url: string;
60
+ }
61
+ interface SettledPhotos {
62
+ row: ProductPlannedRow;
63
+ failed: Array<{
64
+ url: string;
65
+ reason: string;
66
+ }>;
67
+ created: ImportedProductMedia[];
68
+ }
69
+ /** A row's result sentence for the photos that were not copied, naming the product. */
70
+ export declare function photoFailureMessage(name: string, failed: SettledPhotos['failed']): string | undefined;
46
71
  /** Writes one chunk of planned product rows through the product write path. */
47
- export declare function applyProducts(ctx: TransferResourceContext, chunk: TransferChunk<ProductPlannedRow>, writer: TransferApplyWriter, firestore?: Firestore): Promise<TransferApplyResult>;
48
- /** Reverses one chunk: a created product deleted, an updated one's fields and variants put back. */
49
- export declare function revertProducts(ctx: TransferResourceContext, snapshot: TransferUndoSnapshot, decisions?: TransferRevertDecisions, firestore?: Firestore): Promise<TransferRevertResult>;
72
+ export declare function applyProducts(ctx: TransferResourceContext, chunk: TransferChunk<ProductPlannedRow>, writer: TransferApplyWriter, firestore?: Firestore, images?: ProductImageCopierDeps): Promise<TransferApplyResult>;
73
+ /** Reverses one chunk: a created product deleted, an updated one's fields and variants put back, and the photos it stored removed. */
74
+ export declare function revertProducts(ctx: TransferResourceContext, snapshot: TransferUndoSnapshot, decisions?: TransferRevertDecisions, firestore?: Firestore, images?: Pick<ProductImageCopierDeps, 'ingest'>): Promise<TransferRevertResult>;
75
+ export {};
@@ -19,9 +19,14 @@ import * as Aglyn from "@aglyn/aglyn/server";
19
19
  import { countLiveDocuments } from "@aglyn/aglyn/app-utils/live-document-count";
20
20
  import { buildMatchLookup } from "@aglyn/aglyn/data-transfer";
21
21
  import { firebaseAdmin, getOrgForHost, logHostActivity } from "@aglyn/tenant-data-admin";
22
+ import { pluginMediaIngest } from "@aglyn/aglyn/plugin-manager/plugin-media-ingest";
23
+ import { parseMediaRef } from "@aglyn/aglyn/app-utils/media-ref";
22
24
  import { PRODUCT_LIST_QUERY } from "../constants/product-list-query.js";
23
25
  import { commerceSlug, liftLegacyProduct, productCollectionIds, productSearchFields, productStockFields, variantMatrixProblem } from "../model/commerce.js";
24
26
  import { PRODUCT_CATEGORY_PICKLIST, PRODUCT_FIELD, PRODUCT_FIXED_PICKLISTS, PRODUCT_LEVEL_FIELDS, PRODUCT_VARIANT_ORDER, applyProductRow, createProductDocument, planProductTransfer, productExportRowCount, productExportRows, productPlanHandles, productRecord, productRowChanges, productVariantKey } from "./product-transfer.js";
27
+ import { PRODUCT_IMPORT_FOLDER_NAME, PRODUCT_IMPORT_IMAGE_SLOT_MS, productImageCell } from "./product-images.js";
28
+ import { productImageCopier, productImageKey } from "./product-image-copy.server.js";
29
+ import { productFileSource } from "./product-sources.js";
25
30
  import { NOTHING, ROW_BUDGET_MS, eachSourceDoc, firestoreOf, hostRefOf, readSourcePage, readerSeesHost, revertEntries, withoutUndefined } from "./server-common.js";
26
31
  const ID_IN_MAX = 30;
27
32
  function productsOf(firestore, ctx) {
@@ -256,6 +261,48 @@ const isLive = (data)=>Boolean(data) && ((data == null ? void 0 : data['deletedA
256
261
  * Plan
257
262
  *-----------------------------------------*/ const newId = ()=>Aglyn.createResourceUid();
258
263
  const newVariantId = ()=>`v${Aglyn.createResourceUid().slice(0, 10)}`;
264
+ /**
265
+ * The photos the matched products already show that an earlier import
266
+ * copied (AGL-4245), by the photo's key: each library file a product names
267
+ * is read once (a Firestore read, no file and no network), and one carrying
268
+ * an `importedFrom` key answers for the address that key was made from. So
269
+ * the same file imported again plans its photos as the files they already
270
+ * are. A photo a product does not show, or whose file was deleted since,
271
+ * is copied again.
272
+ */ async function copiedPhotosOf(firestore, ctx, existing) {
273
+ const hostId = ctx.hostId;
274
+ const named = new Map();
275
+ for (const record of existing.values()){
276
+ var _record_PRODUCT_FIELD_image, _record_PRODUCT_VARIANT_ORDER;
277
+ const values = [
278
+ ...(_record_PRODUCT_FIELD_image = record[PRODUCT_FIELD.image]) != null ? _record_PRODUCT_FIELD_image : []
279
+ ];
280
+ for (const variantId of (_record_PRODUCT_VARIANT_ORDER = record[PRODUCT_VARIANT_ORDER]) != null ? _record_PRODUCT_VARIANT_ORDER : []){
281
+ var _record_productVariantKey;
282
+ values.push((_record_productVariantKey = record[productVariantKey(variantId)]) == null ? void 0 : _record_productVariantKey[PRODUCT_FIELD.variantImage]);
283
+ }
284
+ for (const value of values){
285
+ const ref = parseMediaRef(value);
286
+ if (ref && ref.scope === hostId && !named.has(ref.mediaId)) named.set(ref.mediaId, String(value));
287
+ }
288
+ }
289
+ const byKey = new Map();
290
+ const media = hostRefOf(firestore, ctx).collection('media');
291
+ const ids = [
292
+ ...named.keys()
293
+ ];
294
+ for(let at = 0; at < ids.length; at += ID_IN_MAX){
295
+ const docs = await firestore.getAll(...ids.slice(at, at + ID_IN_MAX).map((id)=>media.doc(id)));
296
+ for (const doc of docs){
297
+ const key = doc.exists ? doc.get('importedFrom.key') : null;
298
+ if (typeof key === 'string' && key && !doc.get('deletedAt')) byKey.set(key, named.get(doc.id));
299
+ }
300
+ }
301
+ return (url)=>{
302
+ var _byKey_get;
303
+ return byKey.size ? (_byKey_get = byKey.get(productImageKey(url))) != null ? _byKey_get : null : null;
304
+ };
305
+ }
259
306
  /**
260
307
  * The dry run: the slugs a new product would collide with (a deleted
261
308
  * product's included, which still holds its address) and the plan's room
@@ -285,7 +332,10 @@ const newVariantId = ()=>`v${Aglyn.createResourceUid().slice(0, 10)}`;
285
332
  newProductId: newId,
286
333
  newVariantId,
287
334
  slugTaken: (slug)=>taken.has(slug),
288
- maxCreates
335
+ maxCreates,
336
+ // A Wix or Squarespace file, by its headers (AGL-4245).
337
+ source: productFileSource(ctx.headers, input.rows),
338
+ copiedPhoto: await copiedPhotosOf(firestore, ctx, input.existing)
289
339
  });
290
340
  }
291
341
  /*------------------------------------------
@@ -295,7 +345,150 @@ const newVariantId = ()=>`v${Aglyn.createResourceUid().slice(0, 10)}`;
295
345
  super(message), this.reason = reason;
296
346
  }
297
347
  };
298
- /** Writes one chunk of planned product rows through the product write path. */ export async function applyProducts(ctx, chunk, writer, firestore = firestoreOf()) {
348
+ /*------------------------------------------
349
+ * Photos (AGL-4245)
350
+ *-----------------------------------------*/ /** The photo addresses a planned row copies: a new product's, or the photos a row changes. */ export function rowPhotoUrls(row) {
351
+ const plan = row.commerce;
352
+ const values = [];
353
+ if ((plan == null ? void 0 : plan.role) === 'create' && plan.create) {
354
+ var _plan_create_values_PRODUCT_FIELD_image;
355
+ values.push(...(_plan_create_values_PRODUCT_FIELD_image = plan.create.values[PRODUCT_FIELD.image]) != null ? _plan_create_values_PRODUCT_FIELD_image : []);
356
+ for (const variant of plan.create.variants)values.push(variant.values[PRODUCT_FIELD.variantImage]);
357
+ } else if ((plan == null ? void 0 : plan.role) === 'update') {
358
+ for (const change of row.diff){
359
+ if (change.fieldId === PRODUCT_FIELD.image && Array.isArray(change.after)) values.push(...change.after);
360
+ if (change.fieldId === PRODUCT_FIELD.variantImage) values.push(change.after);
361
+ }
362
+ }
363
+ const urls = [];
364
+ for (const value of values){
365
+ const cell = productImageCell(value);
366
+ if ((cell == null ? void 0 : cell.kind) === 'copy' && !urls.includes(cell.url)) urls.push(cell.url);
367
+ }
368
+ return urls;
369
+ }
370
+ /**
371
+ * The row with each address it names swapped for the library file it was
372
+ * copied to: a photo that was not copied is left out (a product whose every
373
+ * new photo failed keeps the ones it has), and why is kept for its result.
374
+ * Every library file it names is listed for its undo.
375
+ */ function settlePhotos(row, copier) {
376
+ const failed = [];
377
+ const created = [];
378
+ const swap = (value)=>{
379
+ const cell = productImageCell(value);
380
+ if (!cell) return null;
381
+ if (cell.kind === 'stored') return cell.value;
382
+ if (cell.kind === 'skip') return null;
383
+ const answer = copier.result(cell.url);
384
+ if (!(answer == null ? void 0 : answer.ok)) {
385
+ var _ref;
386
+ if (!failed.some((entry)=>entry.url === cell.url)) failed.push({
387
+ url: cell.url,
388
+ reason: (_ref = answer == null ? void 0 : answer.reason) != null ? _ref : 'it could not be copied'
389
+ });
390
+ return null;
391
+ }
392
+ if (!created.some((entry)=>entry.mediaId === answer.mediaId)) {
393
+ created.push({
394
+ mediaId: answer.mediaId,
395
+ src: answer.src,
396
+ key: answer.key,
397
+ url: cell.url
398
+ });
399
+ }
400
+ return answer.src;
401
+ };
402
+ const swapList = (value)=>{
403
+ const out = [];
404
+ for (const entry of Array.isArray(value) ? value : []){
405
+ const next = swap(entry);
406
+ if (next && !out.includes(next)) out.push(next);
407
+ }
408
+ return out;
409
+ };
410
+ const plan = row.commerce;
411
+ if (plan.role === 'create' && plan.create) {
412
+ const values = _extends({}, plan.create.values);
413
+ if (PRODUCT_FIELD.image in values) {
414
+ const list = swapList(values[PRODUCT_FIELD.image]);
415
+ if (list.length) values[PRODUCT_FIELD.image] = list;
416
+ else delete values[PRODUCT_FIELD.image];
417
+ }
418
+ const variants = plan.create.variants.map((variant)=>{
419
+ if (!(PRODUCT_FIELD.variantImage in variant.values)) return variant;
420
+ const next = _extends({}, variant.values);
421
+ const image = swap(next[PRODUCT_FIELD.variantImage]);
422
+ if (image) next[PRODUCT_FIELD.variantImage] = image;
423
+ else delete next[PRODUCT_FIELD.variantImage];
424
+ return _extends({}, variant, {
425
+ values: next
426
+ });
427
+ });
428
+ return {
429
+ row: _extends({}, row, {
430
+ commerce: _extends({}, plan, {
431
+ create: _extends({}, plan.create, {
432
+ values,
433
+ variants
434
+ })
435
+ })
436
+ }),
437
+ failed,
438
+ created
439
+ };
440
+ }
441
+ if (plan.role !== 'update') return {
442
+ row,
443
+ failed,
444
+ created
445
+ };
446
+ const diff = row.diff.flatMap((change)=>{
447
+ if (change.fieldId === PRODUCT_FIELD.image && Array.isArray(change.after)) {
448
+ const list = swapList(change.after);
449
+ return list.length ? [
450
+ _extends({}, change, {
451
+ after: list
452
+ })
453
+ ] : [];
454
+ }
455
+ if (change.fieldId === PRODUCT_FIELD.variantImage && !isBlankCell(change.after)) {
456
+ const image = swap(change.after);
457
+ return image ? [
458
+ _extends({}, change, {
459
+ after: image
460
+ })
461
+ ] : [];
462
+ }
463
+ return [
464
+ change
465
+ ];
466
+ });
467
+ return {
468
+ row: _extends({}, row, {
469
+ diff
470
+ }),
471
+ failed,
472
+ created
473
+ };
474
+ }
475
+ const isBlankCell = (value)=>value === null || value === undefined || String(value).trim() === '';
476
+ /** A row's result sentence for the photos that were not copied, naming the product. */ export function photoFailureMessage(name, failed) {
477
+ if (!failed.length) return undefined;
478
+ const count = failed.length;
479
+ const listed = failed.slice(0, 3).map((entry)=>`${entry.url} (${entry.reason})`).join('; ');
480
+ const more = count > 3 ? `; and ${count - 3} more` : '';
481
+ return `${count} photo${count === 1 ? '' : 's'} of "${name || 'this product'}" could not be copied: ${listed}${more}. ` + `The product was saved without ${count === 1 ? 'it' : 'them'}; add ${count === 1 ? 'it' : 'them'} on the product.`;
482
+ }
483
+ /** The library files an undo entry's write stored. */ function importedMediaOf(entry) {
484
+ var _ref;
485
+ var _entry_extras;
486
+ const list = (_ref = (_entry_extras = entry.extras) == null ? void 0 : _entry_extras['importedMedia']) != null ? _ref : [];
487
+ return list.filter((item)=>Boolean(item) && typeof item.mediaId === 'string' && typeof item.key === 'string');
488
+ }
489
+ /** Writes one chunk of planned product rows through the product write path. */ export async function applyProducts(ctx, chunk, writer, firestore = firestoreOf(), images = {
490
+ ingest: pluginMediaIngest()
491
+ }) {
299
492
  var _ref, _ctx_actorUid;
300
493
  const results = [];
301
494
  const undo = [];
@@ -313,6 +506,13 @@ const newVariantId = ()=>`v${Aglyn.createResourceUid().slice(0, 10)}`;
313
506
  };
314
507
  const logged = new Set();
315
508
  const adjustments = [];
509
+ // The chunk's photos (AGL-4245): copied before the row that names them is written.
510
+ const copier = productImageCopier(_extends({
511
+ hostId,
512
+ uid: ctx.actorUid
513
+ }, ctx.jobId ? {
514
+ jobId: ctx.jobId
515
+ } : {}), images);
316
516
  const done = async (result, entry)=>{
317
517
  results.push(result);
318
518
  if (entry) undo.push(entry);
@@ -325,8 +525,7 @@ const newVariantId = ()=>`v${Aglyn.createResourceUid().slice(0, 10)}`;
325
525
  continue;
326
526
  }
327
527
  if (writer.timeLeftMs() < ROW_BUDGET_MS) break;
328
- const plan = row.commerce;
329
- if (!plan) {
528
+ if (!row.commerce) {
330
529
  await done({
331
530
  row: row.index,
332
531
  outcome: 'failed',
@@ -334,6 +533,26 @@ const newVariantId = ()=>`v${Aglyn.createResourceUid().slice(0, 10)}`;
334
533
  });
335
534
  continue;
336
535
  }
536
+ // A row's photos are copied first, never starting one that could not
537
+ // finish in this pass; a row whose photos run out of time is written on
538
+ // the next pass, which finds every photo this one stored.
539
+ const photoUrls = rowPhotoUrls(row);
540
+ if (copier.pending(photoUrls).length) {
541
+ if (writer.timeLeftMs() < ROW_BUDGET_MS + PRODUCT_IMPORT_IMAGE_SLOT_MS) break;
542
+ const finished = await copier.copy(photoUrls, Date.now() + writer.timeLeftMs() - ROW_BUDGET_MS);
543
+ if (!finished) break;
544
+ }
545
+ const settled = photoUrls.length ? settlePhotos(row, copier) : {
546
+ row,
547
+ failed: [],
548
+ created: []
549
+ };
550
+ const plan = settled.row.commerce;
551
+ const extras = settled.created.length ? {
552
+ extras: {
553
+ importedMedia: settled.created
554
+ }
555
+ } : {};
337
556
  const ref = products.doc(plan.productId);
338
557
  try {
339
558
  if (plan.role === 'create') {
@@ -367,16 +586,19 @@ const newVariantId = ()=>`v${Aglyn.createResourceUid().slice(0, 10)}`;
367
586
  name: product.name
368
587
  });
369
588
  }
370
- await done({
589
+ const message = photoFailureMessage(product.name, settled.failed);
590
+ await done(_extends({
371
591
  row: row.index,
372
592
  outcome: 'created',
373
593
  recordId: plan.productId
374
- }, {
594
+ }, message ? {
595
+ message
596
+ } : {}), _extends({
375
597
  row: row.index,
376
598
  recordId: plan.productId,
377
599
  action: 'created',
378
600
  written: undoKeys(productRecord(product, names))
379
- });
601
+ }, extras));
380
602
  continue;
381
603
  }
382
604
  if (plan.role === 'part') {
@@ -399,7 +621,7 @@ const newVariantId = ()=>`v${Aglyn.createResourceUid().slice(0, 10)}`;
399
621
  continue;
400
622
  }
401
623
  // An existing product: this row's changes, read and written in one transaction.
402
- const changes = productRowChanges(row);
624
+ const changes = productRowChanges(settled.row);
403
625
  const outcome = await firestore.runTransaction(async (tx)=>{
404
626
  var _next_modifierGroups;
405
627
  const snapshot = await tx.get(ref);
@@ -466,17 +688,20 @@ const newVariantId = ()=>`v${Aglyn.createResourceUid().slice(0, 10)}`;
466
688
  name: outcome.next.name
467
689
  });
468
690
  }
469
- await done({
691
+ const message = photoFailureMessage(outcome.next.name, settled.failed);
692
+ await done(_extends({
470
693
  row: row.index,
471
694
  outcome: 'updated',
472
695
  recordId: plan.productId
473
- }, {
696
+ }, message ? {
697
+ message
698
+ } : {}), _extends({
474
699
  row: row.index,
475
700
  recordId: plan.productId,
476
701
  action: 'updated',
477
702
  previous: undoKeys(before, touched),
478
703
  written: undoKeys(afterRecord, touched)
479
- });
704
+ }, extras));
480
705
  } catch (error) {
481
706
  if (!(error instanceof RowRefusal)) throw error;
482
707
  await done({
@@ -503,13 +728,59 @@ const newVariantId = ()=>`v${Aglyn.createResourceUid().slice(0, 10)}`;
503
728
  }
504
729
  /*------------------------------------------
505
730
  * Undo
506
- *-----------------------------------------*/ /** Reverses one chunk: a created product deleted, an updated one's fields and variants put back. */ export async function revertProducts(ctx, snapshot, decisions, firestore = firestoreOf()) {
731
+ *-----------------------------------------*/ /**
732
+ * The library files an undone chunk's writes named (AGL-4245), handed to the
733
+ * library to remove once this chunk's own products are put back: a record
734
+ * kept on undo keeps its files, and the library removes only what this job
735
+ * stored and its usage scan finds nowhere, a page or another product's
736
+ * variant included. A file kept for being in use is a note on the undo,
737
+ * cleared when a later chunk removes it.
738
+ */ async function removeImportedProductMedia(ctx, snapshot, kept, ingest) {
739
+ const notes = {};
740
+ if (!(ingest == null ? void 0 : ingest.removeImportedPhotos) || !ctx.hostId || !ctx.actorUid) return notes;
741
+ const media = new Map();
742
+ for (const entry of snapshot.entries){
743
+ if (kept.has(entry.recordId)) continue;
744
+ for (const item of importedMediaOf(entry))media.set(item.mediaId, item);
745
+ }
746
+ if (!media.size) return notes;
747
+ try {
748
+ const answer = await ingest.removeImportedPhotos({
749
+ hostId: ctx.hostId,
750
+ uid: ctx.actorUid,
751
+ jobId: snapshot.jobId,
752
+ photos: [
753
+ ...media.values()
754
+ ].map((item)=>({
755
+ mediaId: item.mediaId,
756
+ sourceKey: item.key
757
+ }))
758
+ });
759
+ for (const mediaId of answer.removed)notes[`photo:${mediaId}`] = null;
760
+ const where = answer.usedBy.slice(0, 3).join(', ') + (answer.usedBy.length > 3 ? ` and ${answer.usedBy.length - 3} more` : '');
761
+ for (const mediaId of answer.kept){
762
+ var _media_get;
763
+ const url = (_media_get = media.get(mediaId)) == null ? void 0 : _media_get.url;
764
+ notes[`photo:${mediaId}`] = `A photo this import copied${url ? ` (${url})` : ''} stays in your media library, in the "${PRODUCT_IMPORT_FOLDER_NAME}" folder, because it is still in use${where ? `: ${where}` : ''}.`;
765
+ }
766
+ } catch (error) {
767
+ // A file left behind is a file the owner can delete; the undo of the products stands.
768
+ console.warn('[commerce] imported photos could not be removed on undo', {
769
+ hostId: ctx.hostId,
770
+ error
771
+ });
772
+ }
773
+ return notes;
774
+ }
775
+ /** Reverses one chunk: a created product deleted, an updated one's fields and variants put back, and the photos it stored removed. */ export async function revertProducts(ctx, snapshot, decisions, firestore = firestoreOf(), images = {
776
+ ingest: pluginMediaIngest()
777
+ }) {
507
778
  const products = productsOf(firestore, ctx);
508
779
  const names = await readCategoryNames(firestore, ctx);
509
780
  const categoryIdsOf = categoryIdsBy(names);
510
781
  const smart = await readSmartCollections(firestore, ctx);
511
782
  const { Timestamp, FieldValue } = firebaseAdmin.firestore;
512
- return revertEntries(snapshot, decisions, {
783
+ const reverted = await revertEntries(snapshot, decisions, {
513
784
  async current (entry) {
514
785
  const doc = await products.doc(entry.recordId).get();
515
786
  return doc.exists && isLive(doc.data()) ? productRecord(liftLegacyProduct(doc.data()), names) : null;
@@ -562,6 +833,11 @@ const newVariantId = ()=>`v${Aglyn.createResourceUid().slice(0, 10)}`;
562
833
  });
563
834
  }
564
835
  });
836
+ const kept = new Set(reverted.conflicts.map((step)=>step.recordId));
837
+ const notes = await removeImportedProductMedia(ctx, snapshot, kept, images.ingest);
838
+ return Object.keys(notes).length ? _extends({}, reverted, {
839
+ notes
840
+ }) : reverted;
565
841
  }
566
842
 
567
843
  //# sourceMappingURL=products.server.js.map