@open-mercato/sync-akeneo 0.9.1-develop.7575.1.8480826a9b → 0.10.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.
Files changed (26) hide show
  1. package/dist/modules/sync_akeneo/cli.js +2 -19
  2. package/dist/modules/sync_akeneo/cli.js.map +2 -2
  3. package/dist/modules/sync_akeneo/lib/catalog-importer.js +130 -64
  4. package/dist/modules/sync_akeneo/lib/catalog-importer.js.map +2 -2
  5. package/dist/modules/sync_akeneo/lib/client.js +143 -70
  6. package/dist/modules/sync_akeneo/lib/client.js.map +2 -2
  7. package/dist/modules/sync_akeneo/lib/first-import.js +1 -2
  8. package/dist/modules/sync_akeneo/lib/first-import.js.map +2 -2
  9. package/jest.config.cjs +1 -1
  10. package/package.json +12 -9
  11. package/src/modules/sync_akeneo/__tests__/catalog-importer.custom-fields.test.ts +419 -0
  12. package/src/modules/sync_akeneo/__tests__/catalog-importer.media-limits.test.ts +426 -0
  13. package/src/modules/sync_akeneo/__tests__/catalog-importer.media.test.ts +193 -0
  14. package/src/modules/sync_akeneo/__tests__/catalog-importer.numeric-values.test.ts +292 -0
  15. package/src/modules/sync_akeneo/__tests__/catalog-importer.prices.test.ts +47 -0
  16. package/src/modules/sync_akeneo/__tests__/client.response-limits.test.ts +339 -0
  17. package/src/modules/sync_akeneo/__tests__/first-import.test.ts +82 -0
  18. package/src/modules/sync_akeneo/cli.ts +2 -24
  19. package/src/modules/sync_akeneo/i18n/de.json +11 -0
  20. package/src/modules/sync_akeneo/i18n/en.json +11 -0
  21. package/src/modules/sync_akeneo/i18n/es.json +11 -0
  22. package/src/modules/sync_akeneo/i18n/ko.json +11 -0
  23. package/src/modules/sync_akeneo/i18n/pl.json +11 -0
  24. package/src/modules/sync_akeneo/lib/catalog-importer.ts +147 -71
  25. package/src/modules/sync_akeneo/lib/client.ts +174 -98
  26. package/src/modules/sync_akeneo/lib/first-import.ts +0 -1
@@ -1,25 +1,8 @@
1
+ import { parseModuleCliOptions } from "@open-mercato/shared/lib/cli/parseModuleCliOptions";
1
2
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
2
3
  import { applyAkeneoEnvPreset, readAkeneoEnvPreset } from "./lib/preset.js";
3
4
  function parseArgs(args) {
4
- const result = {};
5
- for (let i = 0; i < args.length; i++) {
6
- const arg = args[i];
7
- if (!arg.startsWith("--")) continue;
8
- const key = arg.slice(2);
9
- if (key.includes("=")) {
10
- const [name, value] = key.split("=");
11
- result[name] = value;
12
- continue;
13
- }
14
- const next = args[i + 1];
15
- if (next && !next.startsWith("--")) {
16
- result[key] = next;
17
- i += 1;
18
- continue;
19
- }
20
- result[key] = true;
21
- }
22
- return result;
5
+ return parseModuleCliOptions(args);
23
6
  }
24
7
  function printHelp() {
25
8
  console.log("Usage: yarn mercato sync_akeneo configure-from-env --tenant <tenantId> --org <organizationId> [--force]");
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/modules/sync_akeneo/cli.ts"],
4
- "sourcesContent": ["import type { ModuleCli } from '@open-mercato/shared/modules/registry'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { CredentialsService } from '@open-mercato/core/modules/integrations/lib/credentials-service'\nimport type { IntegrationStateService } from '@open-mercato/core/modules/integrations/lib/state-service'\nimport type { IntegrationLogService } from '@open-mercato/core/modules/integrations/lib/log-service'\nimport { applyAkeneoEnvPreset, readAkeneoEnvPreset } from './lib/preset'\n\nfunction parseArgs(args: string[]): Record<string, string | boolean> {\n const result: Record<string, string | boolean> = {}\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i]\n if (!arg.startsWith('--')) continue\n\n const key = arg.slice(2)\n if (key.includes('=')) {\n const [name, value] = key.split('=')\n result[name] = value\n continue\n }\n\n const next = args[i + 1]\n if (next && !next.startsWith('--')) {\n result[key] = next\n i += 1\n continue\n }\n\n result[key] = true\n }\n\n return result\n}\n\nfunction printHelp(): void {\n console.log('Usage: yarn mercato sync_akeneo configure-from-env --tenant <tenantId> --org <organizationId> [--force]')\n console.log('')\n console.log('Required env vars:')\n console.log(' OM_INTEGRATION_AKENEO_API_URL')\n console.log(' OM_INTEGRATION_AKENEO_CLIENT_ID')\n console.log(' OM_INTEGRATION_AKENEO_CLIENT_SECRET')\n console.log(' OM_INTEGRATION_AKENEO_USERNAME')\n console.log(' OM_INTEGRATION_AKENEO_PASSWORD')\n console.log('')\n console.log('Optional env vars:')\n console.log(' OM_INTEGRATION_AKENEO_PRODUCT_LOCALE')\n console.log(' OM_INTEGRATION_AKENEO_CATEGORY_LOCALE')\n console.log(' OM_INTEGRATION_AKENEO_PRODUCT_CHANNEL')\n console.log(' OM_INTEGRATION_AKENEO_IMPORT_CHANNELS')\n console.log(' OM_INTEGRATION_AKENEO_IMPORT_ALL_CHANNELS')\n console.log(' OM_INTEGRATION_AKENEO_CREATE_MISSING_CHANNELS')\n console.log(' OM_INTEGRATION_AKENEO_SYNC_ASSOCIATIONS')\n console.log(' OM_INTEGRATION_AKENEO_ATTRIBUTE_FAMILY_FILTER')\n console.log(' OM_INTEGRATION_AKENEO_PRODUCTS_SETTINGS_JSON')\n console.log(' OM_INTEGRATION_AKENEO_CATEGORIES_SETTINGS_JSON')\n console.log(' OM_INTEGRATION_AKENEO_ATTRIBUTES_SETTINGS_JSON')\n console.log('')\n console.log('Legacy aliases still work:')\n console.log(' OPENMERCATO_AKENEO_*')\n console.log(' AKENEO_*')\n}\n\nconst configureFromEnvCommand: ModuleCli = {\n command: 'configure-from-env',\n async run(rest) {\n const args = parseArgs(rest)\n const tenantId = String(args.tenantId ?? args.tenant ?? '')\n const organizationId = String(args.organizationId ?? args.orgId ?? args.org ?? '')\n const force = args.force === true\n\n if (!tenantId || !organizationId) {\n printHelp()\n return\n }\n\n const preset = readAkeneoEnvPreset()\n if (!preset) {\n console.error('[sync_akeneo] No Akeneo env preset was found.')\n printHelp()\n process.exitCode = 1\n return\n }\n\n const container = await createRequestContainer()\n try {\n const em = container.resolve('em') as EntityManager\n const credentialsService = container.resolve('integrationCredentialsService') as CredentialsService\n const integrationStateService = container.resolve('integrationStateService') as IntegrationStateService\n const integrationLogService = container.resolve('integrationLogService') as IntegrationLogService\n\n const result = await applyAkeneoEnvPreset({\n em,\n credentialsService,\n integrationStateService,\n integrationLogService,\n scope: { tenantId, organizationId },\n force,\n })\n\n if (result.status === 'skipped') {\n console.log(`[sync_akeneo] Skipped: ${result.reason}`)\n return\n }\n\n console.log('[sync_akeneo] Akeneo credentials and mappings were configured from env.')\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown Akeneo preset error'\n console.error(`[sync_akeneo] ${message}`)\n process.exitCode = 1\n } finally {\n const disposable = container as unknown as { dispose?: () => Promise<void> }\n if (typeof disposable.dispose === 'function') {\n await disposable.dispose()\n }\n }\n },\n}\n\nconst helpCommand: ModuleCli = {\n command: 'help',\n async run() {\n printHelp()\n },\n}\n\nexport default [configureFromEnvCommand, helpCommand]\n"],
5
- "mappings": "AAEA,SAAS,8BAA8B;AAIvC,SAAS,sBAAsB,2BAA2B;AAE1D,SAAS,UAAU,MAAkD;AACnE,QAAM,SAA2C,CAAC;AAElD,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,UAAM,MAAM,KAAK,CAAC;AAClB,QAAI,CAAC,IAAI,WAAW,IAAI,EAAG;AAE3B,UAAM,MAAM,IAAI,MAAM,CAAC;AACvB,QAAI,IAAI,SAAS,GAAG,GAAG;AACrB,YAAM,CAAC,MAAM,KAAK,IAAI,IAAI,MAAM,GAAG;AACnC,aAAO,IAAI,IAAI;AACf;AAAA,IACF;AAEA,UAAM,OAAO,KAAK,IAAI,CAAC;AACvB,QAAI,QAAQ,CAAC,KAAK,WAAW,IAAI,GAAG;AAClC,aAAO,GAAG,IAAI;AACd,WAAK;AACL;AAAA,IACF;AAEA,WAAO,GAAG,IAAI;AAAA,EAChB;AAEA,SAAO;AACT;A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U,QAAQ,IAAI;AACjC,YAAM,qBAAqB,UAAU,QAAQ,+BAA+B;AAC5E,YAAM,0BAA0B,UAAU,QAAQ,yBAAyB;AAC3E,YAAM,wBAAwB,UAAU,QAAQ,uBAAuB;AAEvE,YAAM,SAAS,MAAM,qBAAqB;AAAA,QACxC;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,OAAO,EAAE,UAAU,eAAe;AAAA,QAClC;AAAA,MACF,CAAC;AAED,UAAI,OAAO,WAAW,WAAW;AAC/B,gBAAQ,IAAI,0BAA0B,OAAO,MAAM,EAAE;AACrD;AAAA,MACF;AAEA,cAAQ,IAAI,yEAAyE;AAAA,IACvF,SAAS,OAAO;AACd,YAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU;AACzD,cAAQ,MAAM,iBAAiB,OAAO,EAAE;AACxC,cAAQ,WAAW;AAAA,IACrB,UAAE;AACA,YAAM,aAAa;AACnB,UAAI,OAAO,WAAW,YAAY,YAAY;AAC5C,cAAM,WAAW,QAAQ;AAAA,MAC3B;AAAA,IACF;AAAA,EACF;AACF;AAEA,MAAM,cAAyB;AAAA,EAC7B,SAAS;AAAA,EACT,MAAM,MAAM;AACV,cAAU;AAAA,EACZ;AACF;AAEA,IAAO,cAAQ,CAAC,yBAAyB,WAAW;",
4
+ "sourcesContent": ["import { parseModuleCliOptions } from '@open-mercato/shared/lib/cli/parseModuleCliOptions'\nimport type { ModuleCli } from '@open-mercato/shared/modules/registry'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { CredentialsService } from '@open-mercato/core/modules/integrations/lib/credentials-service'\nimport type { IntegrationStateService } from '@open-mercato/core/modules/integrations/lib/state-service'\nimport type { IntegrationLogService } from '@open-mercato/core/modules/integrations/lib/log-service'\nimport { applyAkeneoEnvPreset, readAkeneoEnvPreset } from './lib/preset'\n\nfunction parseArgs(args: string[]): Record<string, string | boolean> {\n return parseModuleCliOptions(args)\n}\n\nfunction printHelp(): void {\n console.log('Usage: yarn mercato sync_akeneo configure-from-env --tenant <tenantId> --org <organizationId> [--force]')\n console.log('')\n console.log('Required env vars:')\n console.log(' OM_INTEGRATION_AKENEO_API_URL')\n console.log(' OM_INTEGRATION_AKENEO_CLIENT_ID')\n console.log(' OM_INTEGRATION_AKENEO_CLIENT_SECRET')\n console.log(' OM_INTEGRATION_AKENEO_USERNAME')\n console.log(' OM_INTEGRATION_AKENEO_PASSWORD')\n console.log('')\n console.log('Optional env vars:')\n console.log(' OM_INTEGRATION_AKENEO_PRODUCT_LOCALE')\n console.log(' OM_INTEGRATION_AKENEO_CATEGORY_LOCALE')\n console.log(' OM_INTEGRATION_AKENEO_PRODUCT_CHANNEL')\n console.log(' OM_INTEGRATION_AKENEO_IMPORT_CHANNELS')\n console.log(' OM_INTEGRATION_AKENEO_IMPORT_ALL_CHANNELS')\n console.log(' OM_INTEGRATION_AKENEO_CREATE_MISSING_CHANNELS')\n console.log(' OM_INTEGRATION_AKENEO_SYNC_ASSOCIATIONS')\n console.log(' OM_INTEGRATION_AKENEO_ATTRIBUTE_FAMILY_FILTER')\n console.log(' OM_INTEGRATION_AKENEO_PRODUCTS_SETTINGS_JSON')\n console.log(' OM_INTEGRATION_AKENEO_CATEGORIES_SETTINGS_JSON')\n console.log(' OM_INTEGRATION_AKENEO_ATTRIBUTES_SETTINGS_JSON')\n console.log('')\n console.log('Legacy aliases still work:')\n console.log(' OPENMERCATO_AKENEO_*')\n console.log(' AKENEO_*')\n}\n\nconst configureFromEnvCommand: ModuleCli = {\n command: 'configure-from-env',\n async run(rest) {\n const args = parseArgs(rest)\n const tenantId = String(args.tenantId ?? args.tenant ?? '')\n const organizationId = String(args.organizationId ?? args.orgId ?? args.org ?? '')\n const force = args.force === true\n\n if (!tenantId || !organizationId) {\n printHelp()\n return\n }\n\n const preset = readAkeneoEnvPreset()\n if (!preset) {\n console.error('[sync_akeneo] No Akeneo env preset was found.')\n printHelp()\n process.exitCode = 1\n return\n }\n\n const container = await createRequestContainer()\n try {\n const em = container.resolve('em') as EntityManager\n const credentialsService = container.resolve('integrationCredentialsService') as CredentialsService\n const integrationStateService = container.resolve('integrationStateService') as IntegrationStateService\n const integrationLogService = container.resolve('integrationLogService') as IntegrationLogService\n\n const result = await applyAkeneoEnvPreset({\n em,\n credentialsService,\n integrationStateService,\n integrationLogService,\n scope: { tenantId, organizationId },\n force,\n })\n\n if (result.status === 'skipped') {\n console.log(`[sync_akeneo] Skipped: ${result.reason}`)\n return\n }\n\n console.log('[sync_akeneo] Akeneo credentials and mappings were configured from env.')\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown Akeneo preset error'\n console.error(`[sync_akeneo] ${message}`)\n process.exitCode = 1\n } finally {\n const disposable = container as unknown as { dispose?: () => Promise<void> }\n if (typeof disposable.dispose === 'function') {\n await disposable.dispose()\n }\n }\n },\n}\n\nconst helpCommand: ModuleCli = {\n command: 'help',\n async run() {\n printHelp()\n },\n}\n\nexport default [configureFromEnvCommand, helpCommand]\n"],
5
+ "mappings": "AAAA,SAAS,6BAA6B;AAGtC,SAAS,8BAA8B;AAIvC,SAAS,sBAAsB,2BAA2B;AAE1D,SAAS,UAAU,MAAkD;AACnE,SAAO,sBAAsB,IAAI;AACnC;AAEA,SAAS,YAAkB;AACzB,UAAQ,IAAI,yGAAyG;AACrH,UAAQ,IAAI,EAAE;AACd,UAAQ,IAAI,oBAAoB;AAChC,UAAQ,IAAI,iCAAiC;AAC7C,UAAQ,IAAI,mCAAmC;AAC/C,UAAQ,IAAI,uCAAuC;AACnD,UAAQ,IAAI,kCAAkC;AAC9C,UAAQ,IAAI,kCAAkC;AAC9C,UAAQ,IAAI,EAAE;AACd,UAAQ,IAAI,oBAAoB;AAChC,UAAQ,IAAI,wCAAwC;AACpD,UAAQ,IAAI,yCAAyC;AACrD,UAAQ,IAAI,yCAAyC;AACrD,UAAQ,IAAI,yCAAyC;AACrD,UAAQ,IAAI,6CAA6C;AACzD,UAAQ,IAA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,iBAAiB,QAAQ,MAAM,UAAU;AACzD,cAAQ,MAAM,iBAAiB,OAAO,EAAE;AACxC,cAAQ,WAAW;AAAA,IACrB,UAAE;AACA,YAAM,aAAa;AACnB,UAAI,OAAO,WAAW,YAAY,YAAY;AAC5C,cAAM,WAAW,QAAQ;AAAA,MAC3B;AAAA,IACF;AAAA,EACF;AACF;AAEA,MAAM,cAAyB;AAAA,EAC7B,SAAS;AAAA,EACT,MAAM,MAAM;AACV,cAAU;AAAA,EACZ;AACF;AAEA,IAAO,cAAQ,CAAC,yBAAyB,WAAW;",
6
6
  "names": []
7
7
  }
@@ -1,8 +1,11 @@
1
1
  import { randomUUID } from "crypto";
2
2
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
3
3
  import { emitCrudSideEffects, setCustomFieldsIfAny } from "@open-mercato/shared/lib/commands/helpers";
4
+ import { loadCustomFieldSnapshot } from "@open-mercato/shared/lib/commands/customFieldSnapshots";
4
5
  import { withAtomicFlush } from "@open-mercato/shared/lib/commands/flush";
5
6
  import { findOneWithDecryption, findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
7
+ import { isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
8
+ import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
6
9
  import { SyncExternalIdMapping } from "@open-mercato/core/modules/integrations/data/entities";
7
10
  import {
8
11
  CatalogOffer,
@@ -20,9 +23,9 @@ import { normalizeEntityFieldsetConfig } from "@open-mercato/core/modules/entiti
20
23
  import { invalidateDefinitionsCache } from "@open-mercato/core/modules/entities/api/definitions.cache";
21
24
  import { Attachment } from "@open-mercato/core/modules/attachments/data/entities";
22
25
  import { buildAttachmentFileUrl, buildAttachmentImageUrl, slugifyAttachmentFileName } from "@open-mercato/core/modules/attachments/lib/imageUrls";
23
- import { deletePartitionFile, storePartitionFile } from "@open-mercato/core/modules/attachments/lib/storage";
24
- import { ensureDefaultPartitions, resolveDefaultPartitionCode } from "@open-mercato/core/modules/attachments/lib/partitions";
25
- import { mergeAttachmentMetadata } from "@open-mercato/core/modules/attachments/lib/metadata";
26
+ import {
27
+ isScopedAttachmentUploadError
28
+ } from "@open-mercato/core/modules/attachments/lib/scoped-upload-service";
26
29
  import { attachmentCrudEvents, attachmentCrudIndexer } from "@open-mercato/core/modules/attachments/lib/crud";
27
30
  import { emitCatalogQueryIndexEvent } from "@open-mercato/core/modules/catalog/commands/shared";
28
31
  import { SalesChannel } from "@open-mercato/core/modules/sales/data/entities";
@@ -35,8 +38,15 @@ import {
35
38
  slugifyAkeneoCode,
36
39
  buildDefaultAkeneoMapping
37
40
  } from "./shared.js";
41
+ import { isAkeneoResponseTooLargeError } from "./client.js";
38
42
  import { inferAkeneoProductMapping } from "./inference.js";
39
43
  import { normalizeMarkdownText } from "./markdown.js";
44
+ import { decimalToString, parseDecimal } from "@open-mercato/shared/lib/decimal";
45
+ const REJECTED_MEDIA_UPLOAD_CODES = /* @__PURE__ */ new Set([
46
+ "dangerous_executable",
47
+ "max_upload_size",
48
+ "active_content"
49
+ ]);
40
50
  const PRODUCT_ENTITY_ID = "catalog:catalog_product";
41
51
  const VARIANT_ENTITY_ID = "catalog:catalog_product_variant";
42
52
  function readPreferredAkeneoValue(values, attributeCode, locale, channel) {
@@ -269,9 +279,9 @@ function parsePriceCollection(value) {
269
279
  return value.map((entry) => {
270
280
  const record = safeRecord(entry);
271
281
  const currencyCode = typeof record?.currency === "string" ? record.currency.trim().toUpperCase() : "";
272
- const amount = coerceNumber(record?.amount);
282
+ const amount = parseDecimal(record?.amount);
273
283
  if (!currencyCode || amount === null) return null;
274
- return { currencyCode, amount };
284
+ return { currencyCode, amount: decimalToString(amount) };
275
285
  }).filter((entry) => Boolean(entry));
276
286
  }
277
287
  function collectMediaReferences(value) {
@@ -311,6 +321,9 @@ function resolveAkeneoMediaTarget(params) {
311
321
  }
312
322
  return params.mappingTarget;
313
323
  }
324
+ function isEmptyCustomFieldValue(value) {
325
+ return value === null || value === void 0 || Array.isArray(value) && value.length === 0;
326
+ }
314
327
  function resolveCustomFieldValue(value, attribute, kind) {
315
328
  if (kind === "boolean") return coerceBoolean(value);
316
329
  if (kind === "integer") return coerceNumber(value) === null ? null : Math.trunc(Number(value));
@@ -1505,6 +1518,18 @@ async function createAkeneoImporter(client, scope) {
1505
1518
  axisCodes: []
1506
1519
  };
1507
1520
  }
1521
+ async function omitClearsOfEmptyFields(entityId, recordId, values) {
1522
+ if (!Object.values(values).some((value) => value === null)) return values;
1523
+ const current = await loadCustomFieldSnapshot(em, {
1524
+ entityId,
1525
+ recordId,
1526
+ tenantId: scope.tenantId,
1527
+ organizationId: scope.organizationId
1528
+ });
1529
+ return Object.fromEntries(
1530
+ Object.entries(values).filter(([key, value]) => value !== null || !isEmptyCustomFieldValue(current[key]))
1531
+ );
1532
+ }
1508
1533
  async function applyCustomFieldMappings(params) {
1509
1534
  const settings = params.mapping.settings?.products;
1510
1535
  if (!settings || settings.customFieldMappings.length === 0) return;
@@ -1519,32 +1544,32 @@ async function createAkeneoImporter(client, scope) {
1519
1544
  if (!kind) continue;
1520
1545
  const sourceLayers = fieldMapping.target === "product" ? [params.hierarchy.rootValues, params.hierarchy.mergedValues] : [params.product.values ?? {}, params.hierarchy.mergedValues];
1521
1546
  const rawValue = readLayeredAkeneoValue(sourceLayers, fieldMapping.attributeCode, settings.locale, settings.channel ?? null);
1522
- const value = resolveCustomFieldValue(rawValue, attribute, kind);
1523
- if (value === null || value === void 0 || Array.isArray(value) && value.length === 0) continue;
1547
+ const resolved = resolveCustomFieldValue(rawValue, attribute, kind);
1548
+ const value = isEmptyCustomFieldValue(resolved) ? null : resolved;
1524
1549
  if (fieldMapping.target === "product") {
1525
1550
  productCustomFields[normalizeFieldKey(fieldMapping.fieldKey)] = value;
1526
1551
  } else {
1527
1552
  variantCustomFields[normalizeFieldKey(fieldMapping.fieldKey)] = value;
1528
1553
  }
1529
1554
  }
1530
- await Promise.all([
1531
- setCustomFieldsIfAny({
1532
- dataEngine,
1533
- entityId: PRODUCT_ENTITY_ID,
1534
- recordId: params.localProductId,
1535
- organizationId: scope.organizationId,
1536
- tenantId: scope.tenantId,
1537
- values: productCustomFields
1538
- }),
1539
- setCustomFieldsIfAny({
1540
- dataEngine,
1541
- entityId: VARIANT_ENTITY_ID,
1542
- recordId: params.localVariantId,
1543
- organizationId: scope.organizationId,
1544
- tenantId: scope.tenantId,
1545
- values: variantCustomFields
1546
- })
1547
- ]);
1555
+ const productValues = await omitClearsOfEmptyFields(PRODUCT_ENTITY_ID, params.localProductId, productCustomFields);
1556
+ await setCustomFieldsIfAny({
1557
+ dataEngine,
1558
+ entityId: PRODUCT_ENTITY_ID,
1559
+ recordId: params.localProductId,
1560
+ organizationId: scope.organizationId,
1561
+ tenantId: scope.tenantId,
1562
+ values: productValues
1563
+ });
1564
+ const variantValues = await omitClearsOfEmptyFields(VARIANT_ENTITY_ID, params.localVariantId, variantCustomFields);
1565
+ await setCustomFieldsIfAny({
1566
+ dataEngine,
1567
+ entityId: VARIANT_ENTITY_ID,
1568
+ recordId: params.localVariantId,
1569
+ organizationId: scope.organizationId,
1570
+ tenantId: scope.tenantId,
1571
+ values: variantValues
1572
+ });
1548
1573
  await Promise.all([
1549
1574
  params.fieldsetPlan?.product?.code ? executeCommand("catalog.products.update", {
1550
1575
  id: params.localProductId,
@@ -1555,7 +1580,7 @@ async function createAkeneoImporter(client, scope) {
1555
1580
  customFieldsetCode: params.fieldsetPlan.variant.code
1556
1581
  }) : Promise.resolve()
1557
1582
  ]);
1558
- if (Object.keys(productCustomFields).length > 0) {
1583
+ if (Object.keys(productValues).length > 0) {
1559
1584
  await emitCatalogQueryIndexEvent(buildCommandContext(), {
1560
1585
  entityType: PRODUCT_ENTITY_ID,
1561
1586
  recordId: params.localProductId,
@@ -1564,7 +1589,7 @@ async function createAkeneoImporter(client, scope) {
1564
1589
  action: "updated"
1565
1590
  });
1566
1591
  }
1567
- if (Object.keys(variantCustomFields).length > 0) {
1592
+ if (Object.keys(variantValues).length > 0) {
1568
1593
  await emitCatalogQueryIndexEvent(buildCommandContext(), {
1569
1594
  entityType: VARIANT_ENTITY_ID,
1570
1595
  recordId: params.localVariantId,
@@ -1748,40 +1773,61 @@ async function createAkeneoImporter(client, scope) {
1748
1773
  }
1749
1774
  }
1750
1775
  }
1776
+ async function recordRejectedMedia(asset, reason) {
1777
+ const integrationLogService = container.resolve("integrationLogService");
1778
+ await integrationLogService.write({
1779
+ integrationId: "sync_akeneo",
1780
+ level: "warn",
1781
+ code: "sync_akeneo.media_rejected",
1782
+ message: `Akeneo media ${asset.remote.codeOrUrl} was not imported: ${reason}`,
1783
+ scopeEntityType: asset.entityId,
1784
+ scopeEntityId: asset.recordId,
1785
+ payload: {
1786
+ externalId: asset.externalId,
1787
+ remoteCode: asset.remote.codeOrUrl,
1788
+ kind: asset.kind,
1789
+ reason
1790
+ }
1791
+ }, scope);
1792
+ }
1751
1793
  async function upsertAsset(asset) {
1752
1794
  const existingAttachmentId = await externalIdMappingService.lookupLocalId("sync_akeneo", "attachment", asset.externalId, scope);
1753
1795
  if (existingAttachmentId) return existingAttachmentId;
1754
- await ensureDefaultPartitions(em);
1755
- const binary = await client.downloadMediaFile(asset.remote.codeOrUrl);
1796
+ let binary;
1797
+ try {
1798
+ binary = await client.downloadMediaFile(asset.remote.codeOrUrl);
1799
+ } catch (error) {
1800
+ if (!isAkeneoResponseTooLargeError(error)) throw error;
1801
+ await recordRejectedMedia(asset, "max_upload_size");
1802
+ return null;
1803
+ }
1756
1804
  const fileName = asset.remote.fileNameHint ?? binary.fileName ?? `akeneo-${randomUUID().slice(0, 8)}`;
1757
- const partitionCode = resolveDefaultPartitionCode(asset.entityId);
1758
- const stored = await storePartitionFile({
1759
- partitionCode,
1760
- orgId: scope.organizationId,
1761
- tenantId: scope.tenantId,
1762
- fileName,
1763
- buffer: binary.buffer
1764
- });
1765
- const attachment = em.create(Attachment, {
1766
- entityId: asset.entityId,
1767
- recordId: asset.recordId,
1768
- organizationId: scope.organizationId,
1769
- tenantId: scope.tenantId,
1770
- partitionCode,
1771
- fileName,
1772
- mimeType: asset.remote.mimeTypeHint ?? binary.contentType ?? "application/octet-stream",
1773
- fileSize: binary.contentLength ?? binary.buffer.byteLength,
1774
- storageDriver: "local",
1775
- storagePath: stored.storagePath,
1776
- storageMetadata: mergeAttachmentMetadata(null, {
1777
- assignments: [{ type: asset.entityId, id: asset.recordId }]
1778
- }),
1779
- url: buildAttachmentFileUrl("pending"),
1780
- content: null
1781
- });
1782
- em.persist(attachment);
1783
- await em.flush();
1784
- attachment.url = asset.kind === "image" ? buildAttachmentImageUrl(attachment.id, { slug: slugifyAttachmentFileName(fileName) }) : buildAttachmentFileUrl(attachment.id);
1805
+ const uploadService = container.resolve("attachmentScopedUploadService");
1806
+ let attachment;
1807
+ try {
1808
+ attachment = await uploadService.upload({
1809
+ tenantId: scope.tenantId,
1810
+ organizationId: scope.organizationId,
1811
+ entityId: asset.entityId,
1812
+ recordId: asset.recordId,
1813
+ fileName,
1814
+ declaredMimeType: asset.remote.mimeTypeHint ?? binary.contentType,
1815
+ buffer: binary.buffer
1816
+ });
1817
+ } catch (error) {
1818
+ if (!isScopedAttachmentUploadError(error)) throw error;
1819
+ if (REJECTED_MEDIA_UPLOAD_CODES.has(error.code)) {
1820
+ await recordRejectedMedia(asset, error.code);
1821
+ return null;
1822
+ }
1823
+ const { translate } = await resolveTranslations();
1824
+ throw new Error(translate(
1825
+ "sync_akeneo.errors.mediaStorageRejected",
1826
+ "Akeneo media {code} was rejected by attachment storage ({reason}).",
1827
+ { code: asset.remote.codeOrUrl, reason: error.code }
1828
+ ));
1829
+ }
1830
+ attachment.url = asset.kind === "image" ? buildAttachmentImageUrl(attachment.id, { slug: slugifyAttachmentFileName(attachment.fileName) }) : buildAttachmentFileUrl(attachment.id);
1785
1831
  attachment.storageMetadata = {
1786
1832
  ...attachment.storageMetadata ?? {},
1787
1833
  source: "akeneo",
@@ -1790,16 +1836,37 @@ async function createAkeneoImporter(client, scope) {
1790
1836
  remoteCode: asset.remote.codeOrUrl
1791
1837
  };
1792
1838
  await em.flush();
1793
- await emitAttachmentCrudChange("created", attachment);
1839
+ await emitAttachmentCrudChange("updated", attachment);
1794
1840
  await externalIdMappingService.storeExternalIdMapping("sync_akeneo", "attachment", attachment.id, asset.externalId, scope);
1795
1841
  return attachment.id;
1796
1842
  }
1843
+ async function releaseImportedAttachment(attachment) {
1844
+ const attachmentService = container.resolve("attachmentService");
1845
+ if (!attachmentService.releaseScoped) {
1846
+ throw new Error("[internal] attachmentService.releaseScoped is not available");
1847
+ }
1848
+ try {
1849
+ await attachmentService.releaseScoped({
1850
+ attachmentId: attachment.id,
1851
+ tenantId: scope.tenantId,
1852
+ organizationId: scope.organizationId,
1853
+ expectedOwner: { entityId: attachment.entityId, recordId: attachment.recordId },
1854
+ expectedAssignment: { type: attachment.entityId, id: attachment.recordId },
1855
+ expectedPartitionCode: attachment.partitionCode
1856
+ });
1857
+ return true;
1858
+ } catch (error) {
1859
+ if (isCrudHttpError(error) && (error.status === 409 || error.status === 404)) return false;
1860
+ throw error;
1861
+ }
1862
+ }
1797
1863
  async function reconcileAttachments(params) {
1798
1864
  const desiredExternalIds = new Set(params.desiredAssets.map((asset) => asset.externalId));
1799
- const desiredImages = params.desiredAssets.filter((asset) => asset.kind === "image");
1800
- const desiredFiles = params.desiredAssets.filter((asset) => asset.kind === "file");
1801
- const desiredAttachmentIds = await Promise.all(params.desiredAssets.map((asset) => upsertAsset(asset)));
1802
- const heroAttachmentId = desiredImages.length > 0 ? desiredAttachmentIds[params.desiredAssets.findIndex((asset) => asset.externalId === desiredImages[0]?.externalId)] : null;
1865
+ let heroAttachmentId = null;
1866
+ for (const asset of params.desiredAssets) {
1867
+ const attachmentId = await upsertAsset(asset);
1868
+ if (!heroAttachmentId && attachmentId && asset.kind === "image") heroAttachmentId = attachmentId;
1869
+ }
1803
1870
  const heroAttachmentUrl = heroAttachmentId ? buildAttachmentImageUrl(heroAttachmentId) : null;
1804
1871
  const existing = await findWithDecryption(em, Attachment, {
1805
1872
  entityId: params.entityId,
@@ -1814,8 +1881,7 @@ async function createAkeneoImporter(client, scope) {
1814
1881
  if (!externalId || !kind) continue;
1815
1882
  const shouldDelete = kind === "image" ? params.reconciliation.deleteMissingMedia : params.reconciliation.deleteMissingAttachments;
1816
1883
  if (!shouldDelete || desiredExternalIds.has(externalId)) continue;
1817
- await deletePartitionFile(attachment.partitionCode, attachment.storagePath, attachment.storageDriver);
1818
- await em.remove(attachment).flush();
1884
+ if (!await releaseImportedAttachment(attachment)) continue;
1819
1885
  await emitAttachmentCrudChange("deleted", attachment);
1820
1886
  }
1821
1887
  return {