@open-mercato/sync-akeneo 0.11.1-develop.8378.1.e2099fcc8e → 0.11.1-develop.8385.1.e9d8a4b8f7

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.
@@ -257,7 +257,7 @@ function buildAkeneoMappingsFromPreset(input) {
257
257
  }
258
258
  async function loadLocalDiscoveryContext(em, scope) {
259
259
  const [channels, priceKinds] = await Promise.all([
260
- findWithDecryption(em, SalesChannel, {
260
+ em.getMetadata().has(SalesChannel) ? findWithDecryption(em, SalesChannel, {
261
261
  organizationId: scope.organizationId,
262
262
  tenantId: scope.tenantId,
263
263
  deletedAt: null,
@@ -265,7 +265,7 @@ async function loadLocalDiscoveryContext(em, scope) {
265
265
  }, {
266
266
  fields: ["code", "name"],
267
267
  orderBy: { name: "asc" }
268
- }, scope),
268
+ }, scope) : Promise.resolve([]),
269
269
  findWithDecryption(em, CatalogPriceKind, {
270
270
  tenantId: scope.tenantId,
271
271
  deletedAt: null,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/sync_akeneo/lib/preset.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CatalogPriceKind } from '@open-mercato/core/modules/catalog/data/entities'\nimport { SyncMapping } from '@open-mercato/core/modules/data_sync/data/entities'\nimport type { CredentialsService } from '@open-mercato/core/modules/integrations/lib/credentials-service'\nimport type { IntegrationLogService } from '@open-mercato/core/modules/integrations/lib/log-service'\nimport type { IntegrationStateService } from '@open-mercato/core/modules/integrations/lib/state-service'\nimport { SalesChannel } from '@open-mercato/core/modules/sales/data/entities'\nimport { createAkeneoClient } from './client'\nimport { inferAkeneoProductMapping } from './inference'\nimport {\n buildAkeneoFieldsetCode,\n buildDefaultAkeneoMapping,\n buildProductFieldMappings,\n normalizeAkeneoMapping,\n type AkeneoCredentialShape,\n} from './shared'\n\nconst AKENEO_INTEGRATION_ID = 'sync_akeneo'\n\ntype IntegrationScope = {\n organizationId: string\n tenantId: string\n}\n\ntype LocalChannelOption = {\n code: string\n name: string\n}\n\ntype PriceKindOption = {\n code: string\n title: string\n displayMode: string\n}\n\ntype DiscoverySnapshot = {\n locales: Array<{ code: string; label: string; enabled?: boolean }>\n channels: Array<{ code: string; label: string; locales: string[] }>\n attributes: Array<{\n code: string\n type: string\n label: string\n localizable: boolean\n scopable: boolean\n group?: string\n metricFamily?: string\n }>\n families: Array<{ code: string; label: string; attributeCount: number }>\n familyVariants: Array<{ familyCode: string; code: string; label: string; axes: string[]; attributes: string[] }>\n}\n\ntype AkeneoEnvPreset = {\n credentials: AkeneoCredentialShape\n force: boolean\n productLocale?: string\n categoryLocale?: string\n productChannel?: string | null\n productChannels?: string[]\n importAllChannels?: boolean\n createMissingChannels?: boolean\n syncAssociations?: boolean\n familyCodeFilter?: string[]\n productsSettingsOverride?: Record<string, unknown>\n categoriesSettingsOverride?: Record<string, unknown>\n attributesSettingsOverride?: Record<string, unknown>\n}\n\nexport type ApplyAkeneoPresetResult =\n | { status: 'skipped'; reason: string }\n | { status: 'configured'; discoveryApplied: true }\n\nfunction readEnvValue(env: NodeJS.ProcessEnv, keys: string[]): string | undefined {\n for (const key of keys) {\n const value = env[key]?.trim()\n if (value) return value\n }\n return undefined\n}\n\nfunction readCsvEnv(env: NodeJS.ProcessEnv, keys: string[]): string[] | undefined {\n const raw = readEnvValue(env, keys)\n if (!raw) return undefined\n const values = raw\n .split(',')\n .map((value) => value.trim())\n .filter((value) => value.length > 0)\n return values.length > 0 ? Array.from(new Set(values)) : undefined\n}\n\nfunction readBooleanEnv(env: NodeJS.ProcessEnv, keys: string[]): boolean | undefined {\n for (const key of keys) {\n const parsed = parseBooleanToken(env[key])\n if (parsed !== null) return parsed\n }\n return undefined\n}\n\nfunction readJsonEnv(env: NodeJS.ProcessEnv, keys: string[], label: string): Record<string, unknown> | undefined {\n const raw = readEnvValue(env, keys)\n if (!raw) return undefined\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Invalid JSON'\n throw new Error(`[sync_akeneo] ${label} is not valid JSON: ${message}`)\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(`[sync_akeneo] ${label} must be a JSON object.`)\n }\n return parsed as Record<string, unknown>\n}\n\nexport function readAkeneoEnvPreset(env: NodeJS.ProcessEnv = process.env): AkeneoEnvPreset | null {\n const credentialKeys = {\n apiUrl: ['OM_INTEGRATION_AKENEO_API_URL', 'OPENMERCATO_AKENEO_API_URL', 'AKENEO_API_URL'],\n clientId: ['OM_INTEGRATION_AKENEO_CLIENT_ID', 'OPENMERCATO_AKENEO_CLIENT_ID', 'AKENEO_CLIENT_ID'],\n clientSecret: ['OM_INTEGRATION_AKENEO_CLIENT_SECRET', 'OPENMERCATO_AKENEO_CLIENT_SECRET', 'AKENEO_CLIENT_SECRET'],\n username: ['OM_INTEGRATION_AKENEO_USERNAME', 'OPENMERCATO_AKENEO_USERNAME', 'AKENEO_USERNAME'],\n password: ['OM_INTEGRATION_AKENEO_PASSWORD', 'OPENMERCATO_AKENEO_PASSWORD', 'AKENEO_PASSWORD'],\n } as const\n\n const anyCredentialProvided = Object.values(credentialKeys).some((keys) => Boolean(readEnvValue(env, [...keys])))\n if (!anyCredentialProvided) {\n return null\n }\n\n const apiUrl = readEnvValue(env, [...credentialKeys.apiUrl])\n const clientId = readEnvValue(env, [...credentialKeys.clientId])\n const clientSecret = readEnvValue(env, [...credentialKeys.clientSecret])\n const username = readEnvValue(env, [...credentialKeys.username])\n const password = readEnvValue(env, [...credentialKeys.password])\n\n if (!apiUrl || !clientId || !clientSecret || !username || !password) {\n throw new Error(\n '[sync_akeneo] Incomplete Akeneo env preset. Set OM_INTEGRATION_AKENEO_API_URL, OM_INTEGRATION_AKENEO_CLIENT_ID, OM_INTEGRATION_AKENEO_CLIENT_SECRET, OM_INTEGRATION_AKENEO_USERNAME, and OM_INTEGRATION_AKENEO_PASSWORD.',\n )\n }\n\n return {\n credentials: {\n apiUrl,\n clientId,\n clientSecret,\n username,\n password,\n },\n force: readBooleanEnv(env, ['OM_INTEGRATION_AKENEO_FORCE_PRECONFIGURE', 'OPENMERCATO_AKENEO_FORCE_PRECONFIGURE', 'AKENEO_FORCE_PRECONFIGURE']) ?? false,\n productLocale: readEnvValue(env, ['OM_INTEGRATION_AKENEO_PRODUCT_LOCALE', 'OPENMERCATO_AKENEO_PRODUCT_LOCALE', 'AKENEO_PRODUCT_LOCALE']),\n categoryLocale: readEnvValue(env, ['OM_INTEGRATION_AKENEO_CATEGORY_LOCALE', 'OPENMERCATO_AKENEO_CATEGORY_LOCALE', 'AKENEO_CATEGORY_LOCALE']),\n productChannel: readEnvValue(env, ['OM_INTEGRATION_AKENEO_PRODUCT_CHANNEL', 'OPENMERCATO_AKENEO_PRODUCT_CHANNEL', 'AKENEO_PRODUCT_CHANNEL']) ?? undefined,\n productChannels: readCsvEnv(env, ['OM_INTEGRATION_AKENEO_IMPORT_CHANNELS', 'OPENMERCATO_AKENEO_IMPORT_CHANNELS', 'AKENEO_IMPORT_CHANNELS']),\n importAllChannels: readBooleanEnv(env, ['OM_INTEGRATION_AKENEO_IMPORT_ALL_CHANNELS', 'OPENMERCATO_AKENEO_IMPORT_ALL_CHANNELS', 'AKENEO_IMPORT_ALL_CHANNELS']),\n createMissingChannels: readBooleanEnv(env, ['OM_INTEGRATION_AKENEO_CREATE_MISSING_CHANNELS', 'OPENMERCATO_AKENEO_CREATE_MISSING_CHANNELS', 'AKENEO_CREATE_MISSING_CHANNELS']),\n syncAssociations: readBooleanEnv(env, ['OM_INTEGRATION_AKENEO_SYNC_ASSOCIATIONS', 'OPENMERCATO_AKENEO_SYNC_ASSOCIATIONS', 'AKENEO_SYNC_ASSOCIATIONS']),\n familyCodeFilter: readCsvEnv(env, ['OM_INTEGRATION_AKENEO_ATTRIBUTE_FAMILY_FILTER', 'OPENMERCATO_AKENEO_ATTRIBUTE_FAMILY_FILTER', 'AKENEO_ATTRIBUTE_FAMILY_FILTER']),\n productsSettingsOverride: readJsonEnv(\n env,\n ['OM_INTEGRATION_AKENEO_PRODUCTS_SETTINGS_JSON', 'OPENMERCATO_AKENEO_PRODUCTS_SETTINGS_JSON', 'AKENEO_PRODUCTS_SETTINGS_JSON'],\n 'OM_INTEGRATION_AKENEO_PRODUCTS_SETTINGS_JSON',\n ),\n categoriesSettingsOverride: readJsonEnv(\n env,\n ['OM_INTEGRATION_AKENEO_CATEGORIES_SETTINGS_JSON', 'OPENMERCATO_AKENEO_CATEGORIES_SETTINGS_JSON', 'AKENEO_CATEGORIES_SETTINGS_JSON'],\n 'OM_INTEGRATION_AKENEO_CATEGORIES_SETTINGS_JSON',\n ),\n attributesSettingsOverride: readJsonEnv(\n env,\n ['OM_INTEGRATION_AKENEO_ATTRIBUTES_SETTINGS_JSON', 'OPENMERCATO_AKENEO_ATTRIBUTES_SETTINGS_JSON', 'AKENEO_ATTRIBUTES_SETTINGS_JSON'],\n 'OM_INTEGRATION_AKENEO_ATTRIBUTES_SETTINGS_JSON',\n ),\n }\n}\n\nfunction inferPriceKindCode(attributeCode: string): string {\n const normalized = attributeCode.trim().toLowerCase()\n return normalized.includes('sale')\n || normalized.includes('promo')\n || normalized.includes('special')\n || normalized.includes('discount')\n ? 'sale'\n : 'regular'\n}\n\nfunction buildDiscoveredFieldsetMappings(discovery: DiscoverySnapshot): Array<{\n sourceType: 'family' | 'familyVariant'\n sourceCode: string\n target: 'product' | 'variant'\n fieldsetCode: string\n fieldsetLabel: string\n description: string\n}> {\n const familyRows = discovery.families.flatMap((family) => {\n const fieldsetCode = buildAkeneoFieldsetCode('product', family.code)\n if (!fieldsetCode) return []\n return [{\n sourceType: 'family' as const,\n sourceCode: family.code,\n target: 'product' as const,\n fieldsetCode,\n fieldsetLabel: family.label || family.code,\n description: `Akeneo family ${family.code}`,\n }]\n })\n\n const familyVariantRows = discovery.familyVariants.flatMap((familyVariant) => {\n const fieldsetCode = buildAkeneoFieldsetCode('variant', familyVariant.code)\n if (!fieldsetCode) return []\n return [{\n sourceType: 'familyVariant' as const,\n sourceCode: familyVariant.code,\n target: 'variant' as const,\n fieldsetCode,\n fieldsetLabel: familyVariant.label || familyVariant.code,\n description: `Akeneo family variant ${familyVariant.code} from family ${familyVariant.familyCode}`,\n }]\n })\n\n return [...familyRows, ...familyVariantRows]\n}\n\nexport function buildAkeneoMappingsFromPreset(input: {\n preset: AkeneoEnvPreset\n discovery: DiscoverySnapshot\n localChannels: LocalChannelOption[]\n priceKinds: PriceKindOption[]\n}): {\n productsMapping: ReturnType<typeof buildDefaultAkeneoMapping>\n categoriesMapping: ReturnType<typeof buildDefaultAkeneoMapping>\n attributesMapping: ReturnType<typeof buildDefaultAkeneoMapping>\n} {\n const { preset, discovery, localChannels, priceKinds } = input\n const baseProducts = buildDefaultAkeneoMapping('products')\n const productSettings = baseProducts.settings?.products\n if (!productSettings) {\n throw new Error('[sync_akeneo] Failed to resolve default product mapping settings.')\n }\n\n const discoveredFamilyVariant = discovery.familyVariants.length > 0\n ? {\n code: '__discovery__',\n variant_attribute_sets: discovery.familyVariants.map((familyVariant, index) => ({\n level: index + 1,\n axes: familyVariant.axes,\n attributes: familyVariant.attributes,\n })),\n }\n : null\n\n const inferred = inferAkeneoProductMapping({\n attributes: discovery.attributes.map((attribute) => ({\n code: attribute.code,\n type: attribute.type,\n labels: attribute.label ? { inferred: attribute.label } : undefined,\n localizable: attribute.localizable,\n scopable: attribute.scopable,\n group: attribute.group,\n metric_family: attribute.metricFamily,\n })),\n family: null,\n familyVariant: discoveredFamilyVariant,\n fieldMap: productSettings.fieldMap,\n explicitCustomFieldMappings: [],\n explicitMediaMappings: [],\n })\n\n const preferredLocale = preset.productLocale\n ?? productSettings.locale\n ?? discovery.locales.find((locale) => locale.enabled)?.code\n ?? discovery.locales[0]?.code\n const preferredAkeneoChannel = preset.productChannel\n ?? discovery.channels[0]?.code\n ?? productSettings.channel\n const preferredLocalChannel = localChannels.find((channel) => ['web', 'online', 'ecommerce', 'default'].includes(channel.code.trim().toLowerCase()))\n ?? localChannels[0]\n ?? null\n const selectedChannels = preset.productChannels\n ?? (preferredAkeneoChannel ? [preferredAkeneoChannel] : [])\n\n const discoveredPriceMappings = preferredLocalChannel\n ? inferred.autoPriceAttributeCodes.map((attributeCode) => {\n const inferredKind = inferPriceKindCode(attributeCode)\n const matchedPriceKind = priceKinds.find((priceKind) => priceKind.code === inferredKind)\n return {\n attributeCode,\n priceKindCode: matchedPriceKind?.code ?? inferredKind,\n akeneoChannel: preferredAkeneoChannel ?? null,\n localChannelCode: preferredLocalChannel.code,\n }\n })\n : []\n\n const productsOverride = preset.productsSettingsOverride ?? {}\n const overrideFieldMap = productsOverride.fieldMap && typeof productsOverride.fieldMap === 'object' && !Array.isArray(productsOverride.fieldMap)\n ? productsOverride.fieldMap as Record<string, unknown>\n : null\n const overrideReconciliation = productsOverride.reconciliation && typeof productsOverride.reconciliation === 'object' && !Array.isArray(productsOverride.reconciliation)\n ? productsOverride.reconciliation as Record<string, unknown>\n : null\n const {\n fieldMap: _ignoredFieldMap,\n reconciliation: _ignoredReconciliation,\n ...productsOverrideShallow\n } = productsOverride\n\n const rawProductsMapping = {\n ...baseProducts,\n settings: {\n products: {\n ...productSettings,\n locale: preferredLocale,\n channel: preferredAkeneoChannel ?? null,\n channels: selectedChannels,\n importAllChannels: preset.importAllChannels ?? productSettings.importAllChannels,\n customFieldMappings: inferred.autoCustomFieldMappings.map((mapping) => ({\n attributeCode: mapping.attributeCode,\n target: mapping.target,\n fieldKey: mapping.fieldKey,\n kind: mapping.kind ?? null,\n skip: mapping.skip ?? false,\n })),\n mediaMappings: inferred.autoMediaMappings.map((mapping) => ({\n attributeCode: mapping.attributeCode,\n target: mapping.target,\n kind: mapping.kind,\n })),\n priceMappings: discoveredPriceMappings,\n fieldsetMappings: buildDiscoveredFieldsetMappings(discovery),\n createMissingChannels: preset.createMissingChannels ?? productSettings.createMissingChannels,\n syncAssociations: preset.syncAssociations ?? productSettings.syncAssociations,\n ...productsOverrideShallow,\n fieldMap: {\n ...inferred.fieldMap,\n ...(overrideFieldMap ?? {}),\n },\n reconciliation: {\n ...productSettings.reconciliation,\n ...(overrideReconciliation ?? {}),\n },\n },\n },\n }\n const productsMapping = normalizeAkeneoMapping('products', rawProductsMapping as Record<string, unknown>)\n if (productsMapping.settings?.products) {\n productsMapping.fields = buildProductFieldMappings(productsMapping.settings.products)\n }\n\n const baseCategories = buildDefaultAkeneoMapping('categories')\n const categoriesMapping = normalizeAkeneoMapping('categories', {\n ...baseCategories,\n settings: {\n categories: {\n locale: preset.categoryLocale ?? preferredLocale,\n ...(preset.categoriesSettingsOverride ?? {}),\n },\n },\n })\n\n const baseAttributes = buildDefaultAkeneoMapping('attributes')\n const attributesMapping = normalizeAkeneoMapping('attributes', {\n ...baseAttributes,\n settings: {\n attributes: {\n ...baseAttributes.settings?.attributes,\n familyCodeFilter: preset.familyCodeFilter ?? baseAttributes.settings?.attributes?.familyCodeFilter ?? [],\n ...(preset.attributesSettingsOverride ?? {}),\n },\n },\n })\n\n return {\n productsMapping,\n categoriesMapping,\n attributesMapping,\n }\n}\n\nasync function loadLocalDiscoveryContext(em: EntityManager, scope: IntegrationScope): Promise<{\n localChannels: LocalChannelOption[]\n priceKinds: PriceKindOption[]\n}> {\n const [channels, priceKinds] = await Promise.all([\n findWithDecryption(em, SalesChannel, {\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n deletedAt: null,\n isActive: true,\n }, {\n fields: ['code', 'name'],\n orderBy: { name: 'asc' },\n }, scope),\n findWithDecryption(em, CatalogPriceKind, {\n tenantId: scope.tenantId,\n deletedAt: null,\n isActive: true,\n }, {\n fields: ['code', 'title', 'displayMode'],\n orderBy: { title: 'asc' },\n }, scope),\n ])\n\n return {\n localChannels: channels\n .filter((channel) => typeof channel.code === 'string' && channel.code.trim().length > 0)\n .map((channel) => ({ code: String(channel.code), name: channel.name })),\n priceKinds: priceKinds.map((priceKind) => ({\n code: priceKind.code,\n title: priceKind.title,\n displayMode: priceKind.displayMode,\n })),\n }\n}\n\nasync function upsertSyncMapping(\n em: EntityManager,\n entityType: 'products' | 'categories' | 'attributes',\n mapping: Record<string, unknown>,\n scope: IntegrationScope,\n): Promise<void> {\n const existing = await findOneWithDecryption(em, SyncMapping, {\n integrationId: AKENEO_INTEGRATION_ID,\n entityType,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n }, undefined, scope)\n\n if (existing) {\n existing.mapping = mapping\n await em.flush()\n return\n }\n\n const created = em.create(SyncMapping, {\n integrationId: AKENEO_INTEGRATION_ID,\n entityType,\n mapping,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n })\n await em.persist(created).flush()\n}\n\nasync function hasExistingAkeneoConfiguration(\n em: EntityManager,\n credentialsService: CredentialsService,\n scope: IntegrationScope,\n): Promise<boolean> {\n const [credentials, mappings] = await Promise.all([\n credentialsService.getRaw(AKENEO_INTEGRATION_ID, scope),\n findOneWithDecryption(em, SyncMapping, {\n integrationId: AKENEO_INTEGRATION_ID,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n }, {\n fields: ['id'],\n }, scope),\n ])\n return Boolean(credentials) || Boolean(mappings)\n}\n\nexport async function applyAkeneoEnvPreset(params: {\n em: EntityManager\n credentialsService: CredentialsService\n integrationStateService: IntegrationStateService\n integrationLogService?: IntegrationLogService\n scope: IntegrationScope\n force?: boolean\n env?: NodeJS.ProcessEnv\n}): Promise<ApplyAkeneoPresetResult> {\n const preset = readAkeneoEnvPreset(params.env)\n if (!preset) {\n return { status: 'skipped', reason: 'No Akeneo preset env variables were provided.' }\n }\n\n const force = params.force ?? preset.force\n if (!force && await hasExistingAkeneoConfiguration(params.em, params.credentialsService, params.scope)) {\n return { status: 'skipped', reason: 'Akeneo credentials or mappings already exist. Use force to overwrite them.' }\n }\n\n await params.credentialsService.save(AKENEO_INTEGRATION_ID, preset.credentials, params.scope)\n\n const client = createAkeneoClient(preset.credentials)\n const [discovery, localContext] = await Promise.all([\n client.collectDiscoveryData(),\n loadLocalDiscoveryContext(params.em, params.scope),\n ])\n\n const mappings = buildAkeneoMappingsFromPreset({\n preset,\n discovery,\n localChannels: localContext.localChannels,\n priceKinds: localContext.priceKinds,\n })\n\n await upsertSyncMapping(params.em, 'products', mappings.productsMapping as unknown as Record<string, unknown>, params.scope)\n await upsertSyncMapping(params.em, 'categories', mappings.categoriesMapping as unknown as Record<string, unknown>, params.scope)\n await upsertSyncMapping(params.em, 'attributes', mappings.attributesMapping as unknown as Record<string, unknown>, params.scope)\n await params.integrationStateService.upsert(AKENEO_INTEGRATION_ID, { isEnabled: true }, params.scope)\n\n if (params.integrationLogService) {\n await params.integrationLogService.scoped(AKENEO_INTEGRATION_ID, params.scope).info(\n 'Akeneo integration was preconfigured from environment variables.',\n {\n locale: mappings.productsMapping.settings?.products?.locale ?? null,\n channel: mappings.productsMapping.settings?.products?.channel ?? null,\n importAllChannels: mappings.productsMapping.settings?.products?.importAllChannels ?? null,\n },\n )\n }\n\n return { status: 'configured', discoveryApplied: true }\n}\n"],
5
- "mappings": "AACA,SAAS,yBAAyB;AAClC,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,wBAAwB;AACjC,SAAS,mBAAmB;AAI5B,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC,SAAS,iCAAiC;AAC1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAEP,MAAM,wBAAwB;AAsD9B,SAAS,aAAa,KAAwB,MAAoC;AAChF,aAAW,OAAO,MAAM;AACtB,UAAM,QAAQ,IAAI,GAAG,GAAG,KAAK;AAC7B,QAAI,MAAO,QAAO;AAAA,EACpB;AACA,SAAO;AACT;AAEA,SAAS,WAAW,KAAwB,MAAsC;AAChF,QAAM,MAAM,aAAa,KAAK,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,YAAY,SAAS,iBAAuD,OAAO,KAAK;AAC3H,QAAM,kBAAkB,OAAO,IAAI,cAAc,SAAS,mBAAyD,OAAO,KAAK;AAC/H,QAAM,kBAAkB,OAAO,IAAI,cAAc,SAAS,mBAAyD,OAAO,KAAK;AAC/H,QAAM,OAAO,wBAAwB,OAAO,uBAAuB,EAAE,WAAW,KAAK,GAAG,OAAO,KAAK;AAEpG,MAAI,OAAO,uBAAuB;AAChC,UAAM,OAAO,sBAAsB,OAAO,uBAAuB,OAAO,KAAK,EAAE;AAAA,MAC7E;AAAA,MACA;AAAA,QACE,QAAQ,SAAS,gBAAgB,UAAU,UAAU,UAAU;AAAA,QAC/D,SAAS,SAAS,gBAAgB,UAAU,UAAU,WAAW;AAAA,QACjE,mBAAmB,SAAS,gBAAgB,UAAU,UAAU,qBAAqB;AAAA,MACvF;AAAA,IACF;AAAA,EACF;AAEA,SAAO,EAAE,QAAQ,cAAc,kBAAkB,KAAK;AACxD;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CatalogPriceKind } from '@open-mercato/core/modules/catalog/data/entities'\nimport { SyncMapping } from '@open-mercato/core/modules/data_sync/data/entities'\nimport type { CredentialsService } from '@open-mercato/core/modules/integrations/lib/credentials-service'\nimport type { IntegrationLogService } from '@open-mercato/core/modules/integrations/lib/log-service'\nimport type { IntegrationStateService } from '@open-mercato/core/modules/integrations/lib/state-service'\nimport { SalesChannel } from '@open-mercato/core/modules/sales/data/entities'\nimport { createAkeneoClient } from './client'\nimport { inferAkeneoProductMapping } from './inference'\nimport {\n buildAkeneoFieldsetCode,\n buildDefaultAkeneoMapping,\n buildProductFieldMappings,\n normalizeAkeneoMapping,\n type AkeneoCredentialShape,\n} from './shared'\n\nconst AKENEO_INTEGRATION_ID = 'sync_akeneo'\n\ntype IntegrationScope = {\n organizationId: string\n tenantId: string\n}\n\ntype LocalChannelOption = {\n code: string\n name: string\n}\n\ntype PriceKindOption = {\n code: string\n title: string\n displayMode: string\n}\n\ntype DiscoverySnapshot = {\n locales: Array<{ code: string; label: string; enabled?: boolean }>\n channels: Array<{ code: string; label: string; locales: string[] }>\n attributes: Array<{\n code: string\n type: string\n label: string\n localizable: boolean\n scopable: boolean\n group?: string\n metricFamily?: string\n }>\n families: Array<{ code: string; label: string; attributeCount: number }>\n familyVariants: Array<{ familyCode: string; code: string; label: string; axes: string[]; attributes: string[] }>\n}\n\ntype AkeneoEnvPreset = {\n credentials: AkeneoCredentialShape\n force: boolean\n productLocale?: string\n categoryLocale?: string\n productChannel?: string | null\n productChannels?: string[]\n importAllChannels?: boolean\n createMissingChannels?: boolean\n syncAssociations?: boolean\n familyCodeFilter?: string[]\n productsSettingsOverride?: Record<string, unknown>\n categoriesSettingsOverride?: Record<string, unknown>\n attributesSettingsOverride?: Record<string, unknown>\n}\n\nexport type ApplyAkeneoPresetResult =\n | { status: 'skipped'; reason: string }\n | { status: 'configured'; discoveryApplied: true }\n\nfunction readEnvValue(env: NodeJS.ProcessEnv, keys: string[]): string | undefined {\n for (const key of keys) {\n const value = env[key]?.trim()\n if (value) return value\n }\n return undefined\n}\n\nfunction readCsvEnv(env: NodeJS.ProcessEnv, keys: string[]): string[] | undefined {\n const raw = readEnvValue(env, keys)\n if (!raw) return undefined\n const values = raw\n .split(',')\n .map((value) => value.trim())\n .filter((value) => value.length > 0)\n return values.length > 0 ? Array.from(new Set(values)) : undefined\n}\n\nfunction readBooleanEnv(env: NodeJS.ProcessEnv, keys: string[]): boolean | undefined {\n for (const key of keys) {\n const parsed = parseBooleanToken(env[key])\n if (parsed !== null) return parsed\n }\n return undefined\n}\n\nfunction readJsonEnv(env: NodeJS.ProcessEnv, keys: string[], label: string): Record<string, unknown> | undefined {\n const raw = readEnvValue(env, keys)\n if (!raw) return undefined\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Invalid JSON'\n throw new Error(`[sync_akeneo] ${label} is not valid JSON: ${message}`)\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(`[sync_akeneo] ${label} must be a JSON object.`)\n }\n return parsed as Record<string, unknown>\n}\n\nexport function readAkeneoEnvPreset(env: NodeJS.ProcessEnv = process.env): AkeneoEnvPreset | null {\n const credentialKeys = {\n apiUrl: ['OM_INTEGRATION_AKENEO_API_URL', 'OPENMERCATO_AKENEO_API_URL', 'AKENEO_API_URL'],\n clientId: ['OM_INTEGRATION_AKENEO_CLIENT_ID', 'OPENMERCATO_AKENEO_CLIENT_ID', 'AKENEO_CLIENT_ID'],\n clientSecret: ['OM_INTEGRATION_AKENEO_CLIENT_SECRET', 'OPENMERCATO_AKENEO_CLIENT_SECRET', 'AKENEO_CLIENT_SECRET'],\n username: ['OM_INTEGRATION_AKENEO_USERNAME', 'OPENMERCATO_AKENEO_USERNAME', 'AKENEO_USERNAME'],\n password: ['OM_INTEGRATION_AKENEO_PASSWORD', 'OPENMERCATO_AKENEO_PASSWORD', 'AKENEO_PASSWORD'],\n } as const\n\n const anyCredentialProvided = Object.values(credentialKeys).some((keys) => Boolean(readEnvValue(env, [...keys])))\n if (!anyCredentialProvided) {\n return null\n }\n\n const apiUrl = readEnvValue(env, [...credentialKeys.apiUrl])\n const clientId = readEnvValue(env, [...credentialKeys.clientId])\n const clientSecret = readEnvValue(env, [...credentialKeys.clientSecret])\n const username = readEnvValue(env, [...credentialKeys.username])\n const password = readEnvValue(env, [...credentialKeys.password])\n\n if (!apiUrl || !clientId || !clientSecret || !username || !password) {\n throw new Error(\n '[sync_akeneo] Incomplete Akeneo env preset. Set OM_INTEGRATION_AKENEO_API_URL, OM_INTEGRATION_AKENEO_CLIENT_ID, OM_INTEGRATION_AKENEO_CLIENT_SECRET, OM_INTEGRATION_AKENEO_USERNAME, and OM_INTEGRATION_AKENEO_PASSWORD.',\n )\n }\n\n return {\n credentials: {\n apiUrl,\n clientId,\n clientSecret,\n username,\n password,\n },\n force: readBooleanEnv(env, ['OM_INTEGRATION_AKENEO_FORCE_PRECONFIGURE', 'OPENMERCATO_AKENEO_FORCE_PRECONFIGURE', 'AKENEO_FORCE_PRECONFIGURE']) ?? false,\n productLocale: readEnvValue(env, ['OM_INTEGRATION_AKENEO_PRODUCT_LOCALE', 'OPENMERCATO_AKENEO_PRODUCT_LOCALE', 'AKENEO_PRODUCT_LOCALE']),\n categoryLocale: readEnvValue(env, ['OM_INTEGRATION_AKENEO_CATEGORY_LOCALE', 'OPENMERCATO_AKENEO_CATEGORY_LOCALE', 'AKENEO_CATEGORY_LOCALE']),\n productChannel: readEnvValue(env, ['OM_INTEGRATION_AKENEO_PRODUCT_CHANNEL', 'OPENMERCATO_AKENEO_PRODUCT_CHANNEL', 'AKENEO_PRODUCT_CHANNEL']) ?? undefined,\n productChannels: readCsvEnv(env, ['OM_INTEGRATION_AKENEO_IMPORT_CHANNELS', 'OPENMERCATO_AKENEO_IMPORT_CHANNELS', 'AKENEO_IMPORT_CHANNELS']),\n importAllChannels: readBooleanEnv(env, ['OM_INTEGRATION_AKENEO_IMPORT_ALL_CHANNELS', 'OPENMERCATO_AKENEO_IMPORT_ALL_CHANNELS', 'AKENEO_IMPORT_ALL_CHANNELS']),\n createMissingChannels: readBooleanEnv(env, ['OM_INTEGRATION_AKENEO_CREATE_MISSING_CHANNELS', 'OPENMERCATO_AKENEO_CREATE_MISSING_CHANNELS', 'AKENEO_CREATE_MISSING_CHANNELS']),\n syncAssociations: readBooleanEnv(env, ['OM_INTEGRATION_AKENEO_SYNC_ASSOCIATIONS', 'OPENMERCATO_AKENEO_SYNC_ASSOCIATIONS', 'AKENEO_SYNC_ASSOCIATIONS']),\n familyCodeFilter: readCsvEnv(env, ['OM_INTEGRATION_AKENEO_ATTRIBUTE_FAMILY_FILTER', 'OPENMERCATO_AKENEO_ATTRIBUTE_FAMILY_FILTER', 'AKENEO_ATTRIBUTE_FAMILY_FILTER']),\n productsSettingsOverride: readJsonEnv(\n env,\n ['OM_INTEGRATION_AKENEO_PRODUCTS_SETTINGS_JSON', 'OPENMERCATO_AKENEO_PRODUCTS_SETTINGS_JSON', 'AKENEO_PRODUCTS_SETTINGS_JSON'],\n 'OM_INTEGRATION_AKENEO_PRODUCTS_SETTINGS_JSON',\n ),\n categoriesSettingsOverride: readJsonEnv(\n env,\n ['OM_INTEGRATION_AKENEO_CATEGORIES_SETTINGS_JSON', 'OPENMERCATO_AKENEO_CATEGORIES_SETTINGS_JSON', 'AKENEO_CATEGORIES_SETTINGS_JSON'],\n 'OM_INTEGRATION_AKENEO_CATEGORIES_SETTINGS_JSON',\n ),\n attributesSettingsOverride: readJsonEnv(\n env,\n ['OM_INTEGRATION_AKENEO_ATTRIBUTES_SETTINGS_JSON', 'OPENMERCATO_AKENEO_ATTRIBUTES_SETTINGS_JSON', 'AKENEO_ATTRIBUTES_SETTINGS_JSON'],\n 'OM_INTEGRATION_AKENEO_ATTRIBUTES_SETTINGS_JSON',\n ),\n }\n}\n\nfunction inferPriceKindCode(attributeCode: string): string {\n const normalized = attributeCode.trim().toLowerCase()\n return normalized.includes('sale')\n || normalized.includes('promo')\n || normalized.includes('special')\n || normalized.includes('discount')\n ? 'sale'\n : 'regular'\n}\n\nfunction buildDiscoveredFieldsetMappings(discovery: DiscoverySnapshot): Array<{\n sourceType: 'family' | 'familyVariant'\n sourceCode: string\n target: 'product' | 'variant'\n fieldsetCode: string\n fieldsetLabel: string\n description: string\n}> {\n const familyRows = discovery.families.flatMap((family) => {\n const fieldsetCode = buildAkeneoFieldsetCode('product', family.code)\n if (!fieldsetCode) return []\n return [{\n sourceType: 'family' as const,\n sourceCode: family.code,\n target: 'product' as const,\n fieldsetCode,\n fieldsetLabel: family.label || family.code,\n description: `Akeneo family ${family.code}`,\n }]\n })\n\n const familyVariantRows = discovery.familyVariants.flatMap((familyVariant) => {\n const fieldsetCode = buildAkeneoFieldsetCode('variant', familyVariant.code)\n if (!fieldsetCode) return []\n return [{\n sourceType: 'familyVariant' as const,\n sourceCode: familyVariant.code,\n target: 'variant' as const,\n fieldsetCode,\n fieldsetLabel: familyVariant.label || familyVariant.code,\n description: `Akeneo family variant ${familyVariant.code} from family ${familyVariant.familyCode}`,\n }]\n })\n\n return [...familyRows, ...familyVariantRows]\n}\n\nexport function buildAkeneoMappingsFromPreset(input: {\n preset: AkeneoEnvPreset\n discovery: DiscoverySnapshot\n localChannels: LocalChannelOption[]\n priceKinds: PriceKindOption[]\n}): {\n productsMapping: ReturnType<typeof buildDefaultAkeneoMapping>\n categoriesMapping: ReturnType<typeof buildDefaultAkeneoMapping>\n attributesMapping: ReturnType<typeof buildDefaultAkeneoMapping>\n} {\n const { preset, discovery, localChannels, priceKinds } = input\n const baseProducts = buildDefaultAkeneoMapping('products')\n const productSettings = baseProducts.settings?.products\n if (!productSettings) {\n throw new Error('[sync_akeneo] Failed to resolve default product mapping settings.')\n }\n\n const discoveredFamilyVariant = discovery.familyVariants.length > 0\n ? {\n code: '__discovery__',\n variant_attribute_sets: discovery.familyVariants.map((familyVariant, index) => ({\n level: index + 1,\n axes: familyVariant.axes,\n attributes: familyVariant.attributes,\n })),\n }\n : null\n\n const inferred = inferAkeneoProductMapping({\n attributes: discovery.attributes.map((attribute) => ({\n code: attribute.code,\n type: attribute.type,\n labels: attribute.label ? { inferred: attribute.label } : undefined,\n localizable: attribute.localizable,\n scopable: attribute.scopable,\n group: attribute.group,\n metric_family: attribute.metricFamily,\n })),\n family: null,\n familyVariant: discoveredFamilyVariant,\n fieldMap: productSettings.fieldMap,\n explicitCustomFieldMappings: [],\n explicitMediaMappings: [],\n })\n\n const preferredLocale = preset.productLocale\n ?? productSettings.locale\n ?? discovery.locales.find((locale) => locale.enabled)?.code\n ?? discovery.locales[0]?.code\n const preferredAkeneoChannel = preset.productChannel\n ?? discovery.channels[0]?.code\n ?? productSettings.channel\n const preferredLocalChannel = localChannels.find((channel) => ['web', 'online', 'ecommerce', 'default'].includes(channel.code.trim().toLowerCase()))\n ?? localChannels[0]\n ?? null\n const selectedChannels = preset.productChannels\n ?? (preferredAkeneoChannel ? [preferredAkeneoChannel] : [])\n\n const discoveredPriceMappings = preferredLocalChannel\n ? inferred.autoPriceAttributeCodes.map((attributeCode) => {\n const inferredKind = inferPriceKindCode(attributeCode)\n const matchedPriceKind = priceKinds.find((priceKind) => priceKind.code === inferredKind)\n return {\n attributeCode,\n priceKindCode: matchedPriceKind?.code ?? inferredKind,\n akeneoChannel: preferredAkeneoChannel ?? null,\n localChannelCode: preferredLocalChannel.code,\n }\n })\n : []\n\n const productsOverride = preset.productsSettingsOverride ?? {}\n const overrideFieldMap = productsOverride.fieldMap && typeof productsOverride.fieldMap === 'object' && !Array.isArray(productsOverride.fieldMap)\n ? productsOverride.fieldMap as Record<string, unknown>\n : null\n const overrideReconciliation = productsOverride.reconciliation && typeof productsOverride.reconciliation === 'object' && !Array.isArray(productsOverride.reconciliation)\n ? productsOverride.reconciliation as Record<string, unknown>\n : null\n const {\n fieldMap: _ignoredFieldMap,\n reconciliation: _ignoredReconciliation,\n ...productsOverrideShallow\n } = productsOverride\n\n const rawProductsMapping = {\n ...baseProducts,\n settings: {\n products: {\n ...productSettings,\n locale: preferredLocale,\n channel: preferredAkeneoChannel ?? null,\n channels: selectedChannels,\n importAllChannels: preset.importAllChannels ?? productSettings.importAllChannels,\n customFieldMappings: inferred.autoCustomFieldMappings.map((mapping) => ({\n attributeCode: mapping.attributeCode,\n target: mapping.target,\n fieldKey: mapping.fieldKey,\n kind: mapping.kind ?? null,\n skip: mapping.skip ?? false,\n })),\n mediaMappings: inferred.autoMediaMappings.map((mapping) => ({\n attributeCode: mapping.attributeCode,\n target: mapping.target,\n kind: mapping.kind,\n })),\n priceMappings: discoveredPriceMappings,\n fieldsetMappings: buildDiscoveredFieldsetMappings(discovery),\n createMissingChannels: preset.createMissingChannels ?? productSettings.createMissingChannels,\n syncAssociations: preset.syncAssociations ?? productSettings.syncAssociations,\n ...productsOverrideShallow,\n fieldMap: {\n ...inferred.fieldMap,\n ...(overrideFieldMap ?? {}),\n },\n reconciliation: {\n ...productSettings.reconciliation,\n ...(overrideReconciliation ?? {}),\n },\n },\n },\n }\n const productsMapping = normalizeAkeneoMapping('products', rawProductsMapping as Record<string, unknown>)\n if (productsMapping.settings?.products) {\n productsMapping.fields = buildProductFieldMappings(productsMapping.settings.products)\n }\n\n const baseCategories = buildDefaultAkeneoMapping('categories')\n const categoriesMapping = normalizeAkeneoMapping('categories', {\n ...baseCategories,\n settings: {\n categories: {\n locale: preset.categoryLocale ?? preferredLocale,\n ...(preset.categoriesSettingsOverride ?? {}),\n },\n },\n })\n\n const baseAttributes = buildDefaultAkeneoMapping('attributes')\n const attributesMapping = normalizeAkeneoMapping('attributes', {\n ...baseAttributes,\n settings: {\n attributes: {\n ...baseAttributes.settings?.attributes,\n familyCodeFilter: preset.familyCodeFilter ?? baseAttributes.settings?.attributes?.familyCodeFilter ?? [],\n ...(preset.attributesSettingsOverride ?? {}),\n },\n },\n })\n\n return {\n productsMapping,\n categoriesMapping,\n attributesMapping,\n }\n}\n\nasync function loadLocalDiscoveryContext(em: EntityManager, scope: IntegrationScope): Promise<{\n localChannels: LocalChannelOption[]\n priceKinds: PriceKindOption[]\n}> {\n const [channels, priceKinds] = await Promise.all([\n em.getMetadata().has(SalesChannel)\n ? findWithDecryption(em, SalesChannel, {\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n deletedAt: null,\n isActive: true,\n }, {\n fields: ['code', 'name'],\n orderBy: { name: 'asc' },\n }, scope)\n : Promise.resolve<SalesChannel[]>([]),\n findWithDecryption(em, CatalogPriceKind, {\n tenantId: scope.tenantId,\n deletedAt: null,\n isActive: true,\n }, {\n fields: ['code', 'title', 'displayMode'],\n orderBy: { title: 'asc' },\n }, scope),\n ])\n\n return {\n localChannels: channels\n .filter((channel) => typeof channel.code === 'string' && channel.code.trim().length > 0)\n .map((channel) => ({ code: String(channel.code), name: channel.name })),\n priceKinds: priceKinds.map((priceKind) => ({\n code: priceKind.code,\n title: priceKind.title,\n displayMode: priceKind.displayMode,\n })),\n }\n}\n\nasync function upsertSyncMapping(\n em: EntityManager,\n entityType: 'products' | 'categories' | 'attributes',\n mapping: Record<string, unknown>,\n scope: IntegrationScope,\n): Promise<void> {\n const existing = await findOneWithDecryption(em, SyncMapping, {\n integrationId: AKENEO_INTEGRATION_ID,\n entityType,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n }, undefined, scope)\n\n if (existing) {\n existing.mapping = mapping\n await em.flush()\n return\n }\n\n const created = em.create(SyncMapping, {\n integrationId: AKENEO_INTEGRATION_ID,\n entityType,\n mapping,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n })\n await em.persist(created).flush()\n}\n\nasync function hasExistingAkeneoConfiguration(\n em: EntityManager,\n credentialsService: CredentialsService,\n scope: IntegrationScope,\n): Promise<boolean> {\n const [credentials, mappings] = await Promise.all([\n credentialsService.getRaw(AKENEO_INTEGRATION_ID, scope),\n findOneWithDecryption(em, SyncMapping, {\n integrationId: AKENEO_INTEGRATION_ID,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n }, {\n fields: ['id'],\n }, scope),\n ])\n return Boolean(credentials) || Boolean(mappings)\n}\n\nexport async function applyAkeneoEnvPreset(params: {\n em: EntityManager\n credentialsService: CredentialsService\n integrationStateService: IntegrationStateService\n integrationLogService?: IntegrationLogService\n scope: IntegrationScope\n force?: boolean\n env?: NodeJS.ProcessEnv\n}): Promise<ApplyAkeneoPresetResult> {\n const preset = readAkeneoEnvPreset(params.env)\n if (!preset) {\n return { status: 'skipped', reason: 'No Akeneo preset env variables were provided.' }\n }\n\n const force = params.force ?? preset.force\n if (!force && await hasExistingAkeneoConfiguration(params.em, params.credentialsService, params.scope)) {\n return { status: 'skipped', reason: 'Akeneo credentials or mappings already exist. Use force to overwrite them.' }\n }\n\n await params.credentialsService.save(AKENEO_INTEGRATION_ID, preset.credentials, params.scope)\n\n const client = createAkeneoClient(preset.credentials)\n const [discovery, localContext] = await Promise.all([\n client.collectDiscoveryData(),\n loadLocalDiscoveryContext(params.em, params.scope),\n ])\n\n const mappings = buildAkeneoMappingsFromPreset({\n preset,\n discovery,\n localChannels: localContext.localChannels,\n priceKinds: localContext.priceKinds,\n })\n\n await upsertSyncMapping(params.em, 'products', mappings.productsMapping as unknown as Record<string, unknown>, params.scope)\n await upsertSyncMapping(params.em, 'categories', mappings.categoriesMapping as unknown as Record<string, unknown>, params.scope)\n await upsertSyncMapping(params.em, 'attributes', mappings.attributesMapping as unknown as Record<string, unknown>, params.scope)\n await params.integrationStateService.upsert(AKENEO_INTEGRATION_ID, { isEnabled: true }, params.scope)\n\n if (params.integrationLogService) {\n await params.integrationLogService.scoped(AKENEO_INTEGRATION_ID, params.scope).info(\n 'Akeneo integration was preconfigured from environment variables.',\n {\n locale: mappings.productsMapping.settings?.products?.locale ?? null,\n channel: mappings.productsMapping.settings?.products?.channel ?? null,\n importAllChannels: mappings.productsMapping.settings?.products?.importAllChannels ?? null,\n },\n )\n }\n\n return { status: 'configured', discoveryApplied: true }\n}\n"],
5
+ "mappings": "AACA,SAAS,yBAAyB;AAClC,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,wBAAwB;AACjC,SAAS,mBAAmB;AAI5B,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC,SAAS,iCAAiC;AAC1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAEP,MAAM,wBAAwB;AAsD9B,SAAS,aAAa,KAAwB,MAAoC;AAChF,aAAW,OAAO,MAAM;AACtB,UAAM,QAAQ,IAAI,GAAG,GAAG,KAAK;AAC7B,QAAI,MAAO,QAAO;AAAA,EACpB;AACA,SAAO;AACT;AAEA,SAAS,WAAW,KAAwB,MAAsC;AAChF,QAAM,MAAM,aAAa,KAAK,IAAI;AAClC,MAAI,CAAC,IAAK,QAAO;AACjB,QAAM,SAAS,IACZ,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AAO,IAAI,YAAY,SAAS,iBAAuD,OAAO,KAAK;AAC3H,QAAM,kBAAkB,OAAO,IAAI,cAAc,SAAS,mBAAyD,OAAO,KAAK;AAC/H,QAAM,kBAAkB,OAAO,IAAI,cAAc,SAAS,mBAAyD,OAAO,KAAK;AAC/H,QAAM,OAAO,wBAAwB,OAAO,uBAAuB,EAAE,WAAW,KAAK,GAAG,OAAO,KAAK;AAEpG,MAAI,OAAO,uBAAuB;AAChC,UAAM,OAAO,sBAAsB,OAAO,uBAAuB,OAAO,KAAK,EAAE;AAAA,MAC7E;AAAA,MACA;AAAA,QACE,QAAQ,SAAS,gBAAgB,UAAU,UAAU,UAAU;AAAA,QAC/D,SAAS,SAAS,gBAAgB,UAAU,UAAU,WAAW;AAAA,QACjE,mBAAmB,SAAS,gBAAgB,UAAU,UAAU,qBAAqB;AAAA,MACvF;AAAA,IACF;AAAA,EACF;AAEA,SAAO,EAAE,QAAQ,cAAc,kBAAkB,KAAK;AACxD;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/sync-akeneo",
3
- "version": "0.11.1-develop.8378.1.e2099fcc8e",
3
+ "version": "0.11.1-develop.8385.1.e9d8a4b8f7",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -53,21 +53,21 @@
53
53
  }
54
54
  },
55
55
  "dependencies": {
56
- "@open-mercato/core": "0.11.1-develop.8378.1.e2099fcc8e",
57
- "@open-mercato/ui": "0.11.1-develop.8378.1.e2099fcc8e",
56
+ "@open-mercato/core": "0.11.1-develop.8385.1.e9d8a4b8f7",
57
+ "@open-mercato/ui": "0.11.1-develop.8385.1.e9d8a4b8f7",
58
58
  "node-html-markdown": "^2.0.0"
59
59
  },
60
60
  "peerDependencies": {
61
61
  "@mikro-orm/postgresql": "^7.0.14",
62
- "@open-mercato/ai-assistant": "0.11.1-develop.8378.1.e2099fcc8e",
63
- "@open-mercato/shared": "0.11.1-develop.8378.1.e2099fcc8e",
62
+ "@open-mercato/ai-assistant": "0.11.1-develop.8385.1.e9d8a4b8f7",
63
+ "@open-mercato/shared": "0.11.1-develop.8385.1.e9d8a4b8f7",
64
64
  "react": "^19.0.0",
65
65
  "react-dom": "^19.0.0",
66
66
  "react-is": ">=18.0.0"
67
67
  },
68
68
  "devDependencies": {
69
- "@open-mercato/ai-assistant": "0.11.1-develop.8378.1.e2099fcc8e",
70
- "@open-mercato/shared": "0.11.1-develop.8378.1.e2099fcc8e",
69
+ "@open-mercato/ai-assistant": "0.11.1-develop.8385.1.e9d8a4b8f7",
70
+ "@open-mercato/shared": "0.11.1-develop.8385.1.e9d8a4b8f7",
71
71
  "@types/jest": "^30.0.0",
72
72
  "@types/react": "^19.2.18",
73
73
  "@types/react-dom": "^19.2.5",
@@ -131,6 +131,7 @@ function createWorld(extraAttributeCodes: string[] = []) {
131
131
  available: true,
132
132
  }
133
133
  const em = {
134
+ getMetadata: () => ({ has: () => true }),
134
135
  clear: jest.fn(),
135
136
  create: jest.fn((_entity: unknown, data: Record<string, unknown>) => ({ ...data })),
136
137
  persist: jest.fn(),
@@ -116,6 +116,7 @@ function createMediaWorld(download: (code: string) => Promise<MediaBinary>) {
116
116
 
117
117
  const removed: Array<{ id: string }> = []
118
118
  const em = {
119
+ getMetadata: () => ({ has: () => true }),
119
120
  create: jest.fn((_entity: unknown, data: Record<string, unknown>) => ({ ...data, id: nextId('raw-attachment') })),
120
121
  persist: jest.fn(),
121
122
  remove: jest.fn((entity: { id: string }) => {
@@ -81,7 +81,7 @@ function createMediaWorld(attachments: Attachment[]) {
81
81
  const dataEngine = { flushOrmEntityChanges: jest.fn(async () => undefined) }
82
82
 
83
83
  mockContainerResolve.mockImplementation((key: string) => {
84
- if (key === 'em') return { remove: () => ({ flush: async () => undefined }) }
84
+ if (key === 'em') return { getMetadata: () => ({ has: () => true }), remove: () => ({ flush: async () => undefined }) }
85
85
  if (key === 'attachmentService') return { releaseScoped: mockReleaseScoped }
86
86
  if (key === 'commandBus') return commandBus
87
87
  if (key === 'dataEngine') return dataEngine
@@ -97,6 +97,7 @@ function createImporterWorld(attributes: AkeneoAttribute[], seededMappings: Mapp
97
97
  }
98
98
 
99
99
  const em = {
100
+ getMetadata: () => ({ has: () => true }),
100
101
  getConnection: () => ({ execute: async () => [] }),
101
102
  flush: jest.fn(async () => undefined),
102
103
  persist: jest.fn(),
@@ -63,6 +63,8 @@ function createCatalogWorld() {
63
63
  const mappings: MappingRow[] = []
64
64
  const deletedPriceIds: string[] = []
65
65
  const deletedOfferIds: string[] = []
66
+ const integrationLogWrites: Array<Record<string, unknown>> = []
67
+ const salesModule = { enabled: true }
66
68
  let sequence = 0
67
69
  const nextId = (prefix: string) => {
68
70
  sequence += 1
@@ -168,7 +170,10 @@ function createCatalogWorld() {
168
170
  }
169
171
 
170
172
  mockContainerResolve.mockImplementation((key: string) => {
171
- if (key === 'em') return {}
173
+ if (key === 'em') return { getMetadata: () => ({ has: (entity: unknown) => salesModule.enabled || entity !== SalesChannel }) }
174
+ if (key === 'integrationLogService') {
175
+ return { write: jest.fn(async (entry: Record<string, unknown>) => { integrationLogWrites.push(entry) }) }
176
+ }
172
177
  if (key === 'commandBus') return commandBus
173
178
  if (key === 'dataEngine') return {}
174
179
  if (key === 'externalIdMappingService') return externalIdMappingService
@@ -177,6 +182,7 @@ function createCatalogWorld() {
177
182
  })
178
183
 
179
184
  mockFindOneWithDecryption.mockImplementation(async (_em: unknown, entity: unknown, where: Record<string, unknown>) => {
185
+ if (entity === SalesChannel && !salesModule.enabled) throw new Error('Metadata for entity SalesChannel not found')
180
186
  if (entity === SalesChannel) return CHANNELS.find((channel) => channel.code === where.code) ?? null
181
187
  if (entity === CatalogPriceKind) {
182
188
  return where.code === 'regular' || where.code === 'sale'
@@ -196,6 +202,7 @@ function createCatalogWorld() {
196
202
  })
197
203
 
198
204
  mockFindWithDecryption.mockImplementation(async (_em: unknown, entity: unknown, where: Record<string, unknown>) => {
205
+ if (entity === SalesChannel && !salesModule.enabled) throw new Error('Metadata for entity SalesChannel not found')
199
206
  if (entity === CatalogOffer) return offers.filter((offer) => offer.product === where.product)
200
207
  if (entity === CatalogProductPrice) {
201
208
  return prices.filter((price) => (
@@ -209,7 +216,7 @@ function createCatalogWorld() {
209
216
  const client = {
210
217
  getFamily: jest.fn(async () => null),
211
218
  getFamilyVariant: jest.fn(async () => null),
212
- getAttribute: jest.fn(async () => null),
219
+ getAttribute: jest.fn(async (_code: string): Promise<unknown> => null),
213
220
  getProductModel: jest.fn(async (code: string) => (
214
221
  code === MODEL_CODE
215
222
  ? { code: MODEL_CODE, values: { name: [{ locale: 'en_US', scope: null, data: 'Tee' }] }, categories: [] }
@@ -269,6 +276,8 @@ function createCatalogWorld() {
269
276
  mappings,
270
277
  deletedPriceIds,
271
278
  deletedOfferIds,
279
+ integrationLogWrites,
280
+ salesModule,
272
281
  pricesOf,
273
282
  seedManualPrice,
274
283
  dropPriceRow,
@@ -756,4 +765,90 @@ describe('akeneo catalog importer offer and price reconciliation', () => {
756
765
  expect(priceLookups.filter((where) => where.variant !== undefined).every((where) => where.variant === variantId)).toBe(true)
757
766
  expect(priceLookups.some((where) => where.variant === variantId)).toBe(true)
758
767
  })
768
+
769
+ describe('when the sales module is disabled', () => {
770
+ const PRODUCT_COMMANDS = ['catalog.products.create', 'catalog.variants.create']
771
+
772
+ function executedCommands(world: ReturnType<typeof createCatalogWorld>): string[] {
773
+ return world.commandBus.execute.mock.calls.map(([commandId]) => commandId)
774
+ }
775
+
776
+ it('imports the product and skips mapped channel-bound offers and prices without throwing', async () => {
777
+ const world = createCatalogWorld()
778
+ world.salesModule.enabled = false
779
+ const importer = await createAkeneoImporter(world.client as never, scope)
780
+ const mapping = buildMapping([WEB_REGULAR, B2B_SALE])
781
+
782
+ await importer.upsertProduct(buildSimpleProduct('uuid-mug', 'MUG', {
783
+ price: [{ scope: 'ecommerce', amount: '5.00' }, { scope: 'b2b', amount: '4.00' }],
784
+ }), mapping)
785
+ await importer.upsertProduct(buildSimpleProduct('uuid-cup', 'CUP', {
786
+ price: [{ scope: 'ecommerce', amount: '3.00' }],
787
+ }), mapping)
788
+
789
+ expect(executedCommands(world)).toEqual(expect.arrayContaining(PRODUCT_COMMANDS))
790
+ expect(executedCommands(world).filter((commandId) => commandId === 'catalog.products.create')).toHaveLength(2)
791
+ expect(executedCommands(world).some((commandId) => commandId.startsWith('catalog.offers.') || commandId.startsWith('catalog.prices.'))).toBe(false)
792
+ expect(world.offers).toEqual([])
793
+ expect(world.prices).toEqual([])
794
+ expect(world.integrationLogWrites).toEqual([
795
+ expect.objectContaining({ integrationId: 'sync_akeneo', level: 'warn', code: 'sync_akeneo.sales_channels_unavailable' }),
796
+ ])
797
+ })
798
+
799
+ it('never auto-creates a sales channel for inferred price attributes', async () => {
800
+ const world = createCatalogWorld()
801
+ world.salesModule.enabled = false
802
+ world.client.getAttribute.mockImplementation(async (code: string) => (
803
+ code === 'price'
804
+ ? { code: 'price', type: 'pim_catalog_price_collection', labels: {}, localizable: false, scopable: true }
805
+ : null
806
+ ))
807
+ const importer = await createAkeneoImporter(world.client as never, scope)
808
+ const base = buildMapping([])
809
+ const products = base.settings?.products
810
+ if (!products) throw new Error('[internal] product mapping settings are missing')
811
+ const mapping: AkeneoDataMapping = {
812
+ ...base,
813
+ settings: { ...base.settings, products: { ...products, createMissingChannels: true } },
814
+ }
815
+
816
+ await importer.upsertProduct(buildSimpleProduct('uuid-mug', 'MUG', {
817
+ price: [{ scope: 'ecommerce', amount: '5.00' }],
818
+ }), mapping)
819
+
820
+ expect(executedCommands(world)).toEqual(expect.arrayContaining(PRODUCT_COMMANDS))
821
+ expect(executedCommands(world)).not.toContain('sales.channels.create')
822
+ expect(world.offers).toEqual([])
823
+ expect(world.integrationLogWrites).toHaveLength(1)
824
+ })
825
+
826
+ it('keeps offers and prices imported while sales was enabled', async () => {
827
+ const world = createCatalogWorld()
828
+ const mapping = buildMapping([WEB_REGULAR])
829
+ const product = buildSimpleProduct('uuid-mug', 'MUG', { price: [{ scope: 'ecommerce', amount: '5.00' }] })
830
+ const enabledImporter = await createAkeneoImporter(world.client as never, scope)
831
+ await enabledImporter.upsertProduct(product, mapping)
832
+ expect(world.pricesOf('MUG')).toEqual(['regular:channel-web:USD:5'])
833
+
834
+ world.salesModule.enabled = false
835
+ const disabledImporter = await createAkeneoImporter(world.client as never, scope)
836
+ await disabledImporter.upsertProduct(product, mapping)
837
+
838
+ expect(world.deletedOfferIds).toEqual([])
839
+ expect(world.deletedPriceIds).toEqual([])
840
+ expect(world.pricesOf('MUG')).toEqual(['regular:channel-web:USD:5'])
841
+ })
842
+
843
+ it('does not warn when the product carries no price mappings', async () => {
844
+ const world = createCatalogWorld()
845
+ world.salesModule.enabled = false
846
+ const importer = await createAkeneoImporter(world.client as never, scope)
847
+
848
+ await importer.upsertProduct(buildSimpleProduct('uuid-mug', 'MUG', {}), buildMapping([]))
849
+
850
+ expect(executedCommands(world)).toEqual(expect.arrayContaining(PRODUCT_COMMANDS))
851
+ expect(world.integrationLogWrites).toEqual([])
852
+ })
853
+ })
759
854
  })
@@ -240,7 +240,7 @@ describe('akeneo catalog importer option schemas', () => {
240
240
  }
241
241
 
242
242
  mockContainerResolve.mockImplementation((key: string) => {
243
- if (key === 'em') return {}
243
+ if (key === 'em') return { getMetadata: () => ({ has: () => true }) }
244
244
  if (key === 'commandBus') return commandBus
245
245
  if (key === 'dataEngine') return {}
246
246
  if (key === 'externalIdMappingService') return externalIdMappingService
@@ -12,7 +12,7 @@ type FindWithDecryptionArgs = [unknown, unknown, unknown, Record<string, unknown
12
12
  const findWithDecryptionMock = jest.fn<Promise<unknown[]>, FindWithDecryptionArgs>(async () => [])
13
13
 
14
14
  jest.mock('@open-mercato/shared/lib/encryption/find', () => ({
15
- findWithDecryption: (...args: unknown[]) => findWithDecryptionMock(...args),
15
+ findWithDecryption: (...args: unknown[]) => findWithDecryptionMock(...(args as FindWithDecryptionArgs)),
16
16
  }))
17
17
 
18
18
  jest.mock('@open-mercato/shared/lib/auth/server', () => ({
@@ -22,7 +22,7 @@ jest.mock('@open-mercato/shared/lib/auth/server', () => ({
22
22
  jest.mock('@open-mercato/shared/lib/di/container', () => ({
23
23
  createRequestContainer: async () => ({
24
24
  resolve: (token: string) => {
25
- if (token === 'em') return {}
25
+ if (token === 'em') return { getMetadata: () => ({ has: () => true }) }
26
26
  if (token === 'integrationCredentialsService') {
27
27
  return {
28
28
  resolve: async () => null,
@@ -0,0 +1,176 @@
1
+ /** @jest-environment node */
2
+
3
+ const tenantId = '11111111-1111-4111-8111-111111111111'
4
+ const orgId = '22222222-2222-4222-8222-222222222222'
5
+
6
+ let mockSalesChannelsAvailable = true
7
+ let mockCredentials: Record<string, unknown> | null = null
8
+
9
+ const mockFindWithDecryption = jest.fn()
10
+ const mockFindOneWithDecryption = jest.fn()
11
+ const mockCollectDiscoveryData = jest.fn()
12
+
13
+ const mockEm = {
14
+ getMetadata: () => ({
15
+ has: (entity: unknown) => mockSalesChannelsAvailable || entity !== SalesChannel,
16
+ }),
17
+ create: jest.fn((_entity: unknown, data: Record<string, unknown>) => ({ ...data })),
18
+ persist: jest.fn(() => ({ flush: async () => undefined })),
19
+ flush: jest.fn(async () => undefined),
20
+ }
21
+
22
+ jest.mock('@open-mercato/shared/lib/encryption/find', () => ({
23
+ findWithDecryption: (...args: unknown[]) => mockFindWithDecryption(...args),
24
+ findOneWithDecryption: (...args: unknown[]) => mockFindOneWithDecryption(...args),
25
+ }))
26
+
27
+ jest.mock('@open-mercato/shared/lib/auth/server', () => ({
28
+ getAuthFromRequest: async () => ({ tenantId, orgId, sub: null }),
29
+ }))
30
+
31
+ jest.mock('@open-mercato/shared/lib/di/container', () => ({
32
+ createRequestContainer: async () => ({
33
+ resolve: (token: string) => {
34
+ if (token === 'em') return mockEm
35
+ if (token === 'integrationCredentialsService') return { resolve: async () => mockCredentials }
36
+ return undefined
37
+ },
38
+ }),
39
+ }))
40
+
41
+ jest.mock('../lib/client', () => ({
42
+ ...jest.requireActual('../lib/client'),
43
+ createAkeneoClient: () => ({ collectDiscoveryData: mockCollectDiscoveryData }),
44
+ }))
45
+
46
+ import type { EntityManager } from '@mikro-orm/postgresql'
47
+ import type { CredentialsService } from '@open-mercato/core/modules/integrations/lib/credentials-service'
48
+ import type { IntegrationStateService } from '@open-mercato/core/modules/integrations/lib/state-service'
49
+ import { SalesChannel } from '@open-mercato/core/modules/sales/data/entities'
50
+ import { CatalogPriceKind } from '@open-mercato/core/modules/catalog/data/entities'
51
+ import { SyncMapping } from '@open-mercato/core/modules/data_sync/data/entities'
52
+ import { GET } from '../api/discovery/route'
53
+ import { applyAkeneoEnvPreset } from '../lib/preset'
54
+ import { metadata } from '../index'
55
+
56
+ const DISCOVERY = {
57
+ locales: [{ code: 'en_US', label: 'English', enabled: true }],
58
+ channels: [{ code: 'ecommerce', label: 'Ecommerce', locales: ['en_US'] }],
59
+ attributes: [
60
+ { code: 'name', type: 'pim_catalog_text', label: 'Name', localizable: true, scopable: false },
61
+ { code: 'price', type: 'pim_catalog_price_collection', label: 'Price', localizable: false, scopable: true },
62
+ ],
63
+ families: [{ code: 'clothing', label: 'Clothing', attributeCount: 2 }],
64
+ familyVariants: [],
65
+ version: '7.0',
66
+ }
67
+
68
+ const PRESET_ENV = {
69
+ OM_INTEGRATION_AKENEO_API_URL: 'https://example.akeneo.com',
70
+ OM_INTEGRATION_AKENEO_CLIENT_ID: 'client-id',
71
+ OM_INTEGRATION_AKENEO_CLIENT_SECRET: 'client-secret',
72
+ OM_INTEGRATION_AKENEO_USERNAME: 'api-user',
73
+ OM_INTEGRATION_AKENEO_PASSWORD: 'api-pass',
74
+ OM_INTEGRATION_AKENEO_PRODUCT_CHANNEL: 'ecommerce',
75
+ } as NodeJS.ProcessEnv
76
+
77
+ function salesChannelLookups(): unknown[][] {
78
+ return [...mockFindWithDecryption.mock.calls, ...mockFindOneWithDecryption.mock.calls]
79
+ .filter(([, entity]) => entity === SalesChannel)
80
+ }
81
+
82
+ beforeEach(() => {
83
+ mockSalesChannelsAvailable = true
84
+ mockCredentials = null
85
+ mockFindWithDecryption.mockReset()
86
+ mockFindOneWithDecryption.mockReset()
87
+ mockCollectDiscoveryData.mockReset()
88
+ mockCollectDiscoveryData.mockResolvedValue(DISCOVERY)
89
+ mockFindWithDecryption.mockImplementation(async (_em: unknown, entity: unknown) => {
90
+ if (entity === SalesChannel) {
91
+ if (!mockSalesChannelsAvailable) throw new Error('Metadata for entity SalesChannel not found')
92
+ return [{ code: 'web', name: 'Web' }]
93
+ }
94
+ if (entity === CatalogPriceKind) return [{ code: 'regular', title: 'Regular', displayMode: 'excluding-tax' }]
95
+ return []
96
+ })
97
+ mockFindOneWithDecryption.mockImplementation(async (_em: unknown, entity: unknown) => {
98
+ if (entity === SalesChannel && !mockSalesChannelsAvailable) {
99
+ throw new Error('Metadata for entity SalesChannel not found')
100
+ }
101
+ return null
102
+ })
103
+ })
104
+
105
+ describe('sync_akeneo with the sales module disabled', () => {
106
+ it('no longer requires sales and declares progress explicitly', () => {
107
+ expect(metadata.requires).not.toContain('sales')
108
+ expect(metadata.requires).toEqual(expect.arrayContaining(['integrations', 'data_sync', 'catalog', 'progress']))
109
+ })
110
+
111
+ it('discovery returns an empty local channel list and keeps the rest of the payload', async () => {
112
+ mockSalesChannelsAvailable = false
113
+ mockCredentials = { apiUrl: 'https://example.akeneo.com' }
114
+
115
+ const res = await GET(new Request('http://localhost/api/sync_akeneo/discovery'))
116
+
117
+ expect(res.status).toBe(200)
118
+ const body = await res.json()
119
+ expect(body.ok).toBe(true)
120
+ expect(body.localChannels).toEqual([])
121
+ expect(body.priceKinds).toEqual([{ code: 'regular', title: 'Regular', displayMode: 'excluding-tax' }])
122
+ expect(body.locales).toEqual(DISCOVERY.locales)
123
+ expect(body.channels).toEqual(DISCOVERY.channels)
124
+ expect(body.attributes.map((attribute: { code: string }) => attribute.code)).toEqual(['name', 'price'])
125
+ expect(body.families).toEqual(DISCOVERY.families)
126
+ expect(salesChannelLookups()).toEqual([])
127
+ })
128
+
129
+ it('discovery without credentials still lists price kinds and no local channels', async () => {
130
+ mockSalesChannelsAvailable = false
131
+
132
+ const res = await GET(new Request('http://localhost/api/sync_akeneo/discovery'))
133
+
134
+ expect(res.status).toBe(200)
135
+ const body = await res.json()
136
+ expect(body.ok).toBe(false)
137
+ expect(body.localChannels).toEqual([])
138
+ expect(body.priceKinds).toHaveLength(1)
139
+ })
140
+
141
+ it('discovery still lists local sales channels when sales is enabled', async () => {
142
+ mockCredentials = { apiUrl: 'https://example.akeneo.com' }
143
+
144
+ const res = await GET(new Request('http://localhost/api/sync_akeneo/discovery'))
145
+
146
+ const body = await res.json()
147
+ expect(body.ok).toBe(true)
148
+ expect(body.localChannels).toEqual([{ code: 'web', name: 'Web' }])
149
+ })
150
+
151
+ it('env preset applies credentials and mappings without channel-bound prices', async () => {
152
+ mockSalesChannelsAvailable = false
153
+ const credentialsService = { save: jest.fn(async () => undefined), resolve: jest.fn(async () => null) }
154
+ const integrationStateService = { upsert: jest.fn(async () => undefined) }
155
+
156
+ const result = await applyAkeneoEnvPreset({
157
+ em: mockEm as unknown as EntityManager,
158
+ credentialsService: credentialsService as unknown as CredentialsService,
159
+ integrationStateService: integrationStateService as unknown as IntegrationStateService,
160
+ scope: { organizationId: orgId, tenantId },
161
+ force: true,
162
+ env: PRESET_ENV,
163
+ })
164
+
165
+ expect(result).toEqual({ status: 'configured', discoveryApplied: true })
166
+ expect(credentialsService.save).toHaveBeenCalledTimes(1)
167
+ expect(integrationStateService.upsert).toHaveBeenCalledWith('sync_akeneo', { isEnabled: true }, { organizationId: orgId, tenantId })
168
+ const createdMappings = mockEm.create.mock.calls
169
+ .filter(([entity]) => entity === SyncMapping)
170
+ .map(([, data]) => data as { entityType: string; mapping: { settings?: { products?: { priceMappings?: Array<{ localChannelCode: string }> } } } })
171
+ expect(createdMappings.map((entry) => entry.entityType)).toEqual(['products', 'categories', 'attributes'])
172
+ const productsMapping = createdMappings.find((entry) => entry.entityType === 'products')
173
+ expect(productsMapping?.mapping.settings?.products?.priceMappings ?? []).toEqual([])
174
+ expect(salesChannelLookups()).toEqual([])
175
+ })
176
+ })
@@ -40,19 +40,22 @@ export async function GET(req: Request) {
40
40
  // encryption map at all. This is a discovery endpoint with no pagination,
41
41
  // so the #3278 two-phase encrypted-sort does not apply. Covered by
42
42
  // __tests__/discovery-route.test.ts.
43
+ const salesChannelsAvailable = em.getMetadata().has(SalesChannel)
43
44
  const [localChannels, priceKinds] = await Promise.all([
44
- findWithDecryption(em, SalesChannel, {
45
- organizationId: auth.orgId,
46
- tenantId: auth.tenantId,
47
- deletedAt: null,
48
- isActive: true,
49
- }, {
50
- fields: ['code', 'name'],
51
- orderBy: { name: 'asc' },
52
- }, {
53
- organizationId: auth.orgId as string,
54
- tenantId: auth.tenantId,
55
- }),
45
+ salesChannelsAvailable
46
+ ? findWithDecryption(em, SalesChannel, {
47
+ organizationId: auth.orgId,
48
+ tenantId: auth.tenantId,
49
+ deletedAt: null,
50
+ isActive: true,
51
+ }, {
52
+ fields: ['code', 'name'],
53
+ orderBy: { name: 'asc' },
54
+ }, {
55
+ organizationId: auth.orgId as string,
56
+ tenantId: auth.tenantId,
57
+ })
58
+ : Promise.resolve<SalesChannel[]>([]),
56
59
  findWithDecryption(em, CatalogPriceKind, {
57
60
  tenantId: auth.tenantId,
58
61
  deletedAt: null,
@@ -2,5 +2,5 @@ export const metadata = {
2
2
  id: 'sync_akeneo',
3
3
  title: 'Akeneo Product Sync',
4
4
  description: 'Import Akeneo PIM categories, product attributes, and products into the Open Mercato catalog.',
5
- requires: ['integrations', 'data_sync', 'catalog', 'sales'],
5
+ requires: ['integrations', 'data_sync', 'catalog', 'progress'],
6
6
  }