@open-mercato/sync-akeneo 0.9.1-develop.7574.1.837288eec1 → 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.
- package/dist/modules/sync_akeneo/cli.js +2 -19
- package/dist/modules/sync_akeneo/cli.js.map +2 -2
- package/dist/modules/sync_akeneo/lib/catalog-importer.js +42 -25
- package/dist/modules/sync_akeneo/lib/catalog-importer.js.map +2 -2
- package/dist/modules/sync_akeneo/lib/first-import.js +1 -2
- package/dist/modules/sync_akeneo/lib/first-import.js.map +2 -2
- package/jest.config.cjs +1 -1
- package/package.json +12 -9
- package/src/modules/sync_akeneo/__tests__/catalog-importer.custom-fields.test.ts +419 -0
- package/src/modules/sync_akeneo/__tests__/catalog-importer.media.test.ts +193 -0
- package/src/modules/sync_akeneo/__tests__/catalog-importer.numeric-values.test.ts +292 -0
- package/src/modules/sync_akeneo/__tests__/catalog-importer.prices.test.ts +47 -0
- package/src/modules/sync_akeneo/__tests__/first-import.test.ts +82 -0
- package/src/modules/sync_akeneo/cli.ts +2 -24
- package/src/modules/sync_akeneo/i18n/de.json +10 -0
- package/src/modules/sync_akeneo/i18n/en.json +10 -0
- package/src/modules/sync_akeneo/i18n/es.json +10 -0
- package/src/modules/sync_akeneo/i18n/ko.json +10 -0
- package/src/modules/sync_akeneo/i18n/pl.json +10 -0
- package/src/modules/sync_akeneo/lib/catalog-importer.ts +51 -28
- package/src/modules/sync_akeneo/lib/first-import.ts +0 -1
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { Attachment } from '@open-mercato/core/modules/attachments/data/entities'
|
|
2
|
+
import { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'
|
|
3
|
+
import { CatalogProduct, CatalogProductVariant } from '@open-mercato/core/modules/catalog/data/entities'
|
|
4
|
+
import { createAkeneoImporter } from '../lib/catalog-importer'
|
|
5
|
+
import { buildDefaultAkeneoMapping, type AkeneoDataMapping, type AkeneoProduct } from '../lib/shared'
|
|
6
|
+
|
|
7
|
+
const mockContainerResolve = jest.fn()
|
|
8
|
+
const mockFindOneWithDecryption = jest.fn()
|
|
9
|
+
const mockFindWithDecryption = jest.fn()
|
|
10
|
+
const mockReleaseScoped = jest.fn()
|
|
11
|
+
const mockDeletePartitionFile = jest.fn()
|
|
12
|
+
const mockEmitCrudSideEffects = jest.fn()
|
|
13
|
+
|
|
14
|
+
jest.mock('@open-mercato/shared/lib/di/container', () => ({
|
|
15
|
+
createRequestContainer: jest.fn(async () => ({
|
|
16
|
+
resolve: mockContainerResolve,
|
|
17
|
+
})),
|
|
18
|
+
}))
|
|
19
|
+
|
|
20
|
+
jest.mock('@open-mercato/shared/lib/encryption/find', () => ({
|
|
21
|
+
findOneWithDecryption: (...args: unknown[]) => mockFindOneWithDecryption(...args),
|
|
22
|
+
findWithDecryption: (...args: unknown[]) => mockFindWithDecryption(...args),
|
|
23
|
+
}))
|
|
24
|
+
|
|
25
|
+
jest.mock('@open-mercato/core/modules/attachments/lib/storage', () => ({
|
|
26
|
+
deletePartitionFile: (...args: unknown[]) => mockDeletePartitionFile(...args),
|
|
27
|
+
storePartitionFile: jest.fn(async () => {
|
|
28
|
+
throw new Error('[internal] no upload expected in test')
|
|
29
|
+
}),
|
|
30
|
+
}))
|
|
31
|
+
|
|
32
|
+
jest.mock('@open-mercato/shared/lib/commands/helpers', () => ({
|
|
33
|
+
...jest.requireActual('@open-mercato/shared/lib/commands/helpers'),
|
|
34
|
+
emitCrudSideEffects: (...args: unknown[]) => mockEmitCrudSideEffects(...args),
|
|
35
|
+
}))
|
|
36
|
+
|
|
37
|
+
const scope = { organizationId: 'org-1', tenantId: 'tenant-1' }
|
|
38
|
+
const PRODUCT_ID = 'product-1'
|
|
39
|
+
const KEPT_EXTERNAL_ID = 'product:image:main_image:kept.png:0'
|
|
40
|
+
|
|
41
|
+
const SHARED_STORAGE_PATH = 'org-1/tenant-1/shared.png'
|
|
42
|
+
|
|
43
|
+
function storedAttachment(id: string, externalId: string): Attachment {
|
|
44
|
+
return {
|
|
45
|
+
id,
|
|
46
|
+
entityId: 'catalog:catalog_product',
|
|
47
|
+
recordId: PRODUCT_ID,
|
|
48
|
+
organizationId: scope.organizationId,
|
|
49
|
+
tenantId: scope.tenantId,
|
|
50
|
+
partitionCode: 'productsMedia',
|
|
51
|
+
storageDriver: 'local',
|
|
52
|
+
storagePath: SHARED_STORAGE_PATH,
|
|
53
|
+
storageMetadata: { source: 'akeneo', externalId, kind: 'image' },
|
|
54
|
+
} as unknown as Attachment
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function createMediaWorld(attachments: Attachment[]) {
|
|
58
|
+
const commandBus = {
|
|
59
|
+
execute: jest.fn(async (commandId: string, { input }: { input: Record<string, unknown> }) => {
|
|
60
|
+
switch (commandId) {
|
|
61
|
+
case 'catalog.products.create':
|
|
62
|
+
return { result: { productId: PRODUCT_ID } }
|
|
63
|
+
case 'catalog.products.update':
|
|
64
|
+
return { result: { productId: input.id } }
|
|
65
|
+
case 'catalog.variants.create':
|
|
66
|
+
return { result: { variantId: 'variant-1' } }
|
|
67
|
+
case 'catalog.variants.update':
|
|
68
|
+
return { result: { variantId: input.id } }
|
|
69
|
+
default:
|
|
70
|
+
throw new Error(`[internal] unexpected command: ${commandId}`)
|
|
71
|
+
}
|
|
72
|
+
}),
|
|
73
|
+
}
|
|
74
|
+
const externalIdMappingService = {
|
|
75
|
+
lookupLocalId: jest.fn(async (_integrationId: string, entityType: string, externalId: string) => (
|
|
76
|
+
entityType === 'attachment' && externalId === KEPT_EXTERNAL_ID ? 'attachment-kept' : null
|
|
77
|
+
)),
|
|
78
|
+
lookupExternalId: jest.fn(async () => null),
|
|
79
|
+
storeExternalIdMapping: jest.fn(async () => undefined),
|
|
80
|
+
}
|
|
81
|
+
const dataEngine = { flushOrmEntityChanges: jest.fn(async () => undefined) }
|
|
82
|
+
|
|
83
|
+
mockContainerResolve.mockImplementation((key: string) => {
|
|
84
|
+
if (key === 'em') return { remove: () => ({ flush: async () => undefined }) }
|
|
85
|
+
if (key === 'attachmentService') return { releaseScoped: mockReleaseScoped }
|
|
86
|
+
if (key === 'commandBus') return commandBus
|
|
87
|
+
if (key === 'dataEngine') return dataEngine
|
|
88
|
+
if (key === 'externalIdMappingService') return externalIdMappingService
|
|
89
|
+
if (key === 'cache') throw new Error('[internal] no cache in test')
|
|
90
|
+
throw new Error(`[internal] unexpected dependency: ${key}`)
|
|
91
|
+
})
|
|
92
|
+
mockFindOneWithDecryption.mockImplementation(async (_em: unknown, entity: unknown, where: Record<string, unknown>) => {
|
|
93
|
+
if (entity === CatalogProduct && where.id === PRODUCT_ID) return { id: PRODUCT_ID, deletedAt: null }
|
|
94
|
+
if (entity === CatalogProductVariant && where.product === PRODUCT_ID) return { id: 'variant-1', product: PRODUCT_ID }
|
|
95
|
+
return null
|
|
96
|
+
})
|
|
97
|
+
mockFindWithDecryption.mockImplementation(async (_em: unknown, entity: unknown, where: Record<string, unknown>) => {
|
|
98
|
+
if (entity === Attachment) return attachments.filter((attachment) => attachment.recordId === where.recordId)
|
|
99
|
+
return []
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
const client = {
|
|
103
|
+
getFamily: jest.fn(async () => null),
|
|
104
|
+
getFamilyVariant: jest.fn(async () => null),
|
|
105
|
+
getAttribute: jest.fn(async (code: string) => (
|
|
106
|
+
code === 'main_image'
|
|
107
|
+
? { code, type: 'pim_catalog_image', localizable: false, scopable: false, labels: {} }
|
|
108
|
+
: null
|
|
109
|
+
)),
|
|
110
|
+
getProductModel: jest.fn(async () => null),
|
|
111
|
+
downloadMediaFile: jest.fn(async () => {
|
|
112
|
+
throw new Error('[internal] no download expected in test')
|
|
113
|
+
}),
|
|
114
|
+
}
|
|
115
|
+
return { client }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function buildMediaMapping(): AkeneoDataMapping {
|
|
119
|
+
const base = buildDefaultAkeneoMapping('products')
|
|
120
|
+
const products = base.settings?.products
|
|
121
|
+
if (!products) throw new Error('[internal] default Akeneo product mapping is missing')
|
|
122
|
+
return {
|
|
123
|
+
...base,
|
|
124
|
+
settings: {
|
|
125
|
+
...base.settings,
|
|
126
|
+
products: {
|
|
127
|
+
...products,
|
|
128
|
+
priceMappings: [],
|
|
129
|
+
mediaMappings: [{ attributeCode: 'main_image', target: 'product', kind: 'image' }],
|
|
130
|
+
customFieldMappings: [],
|
|
131
|
+
syncAssociations: false,
|
|
132
|
+
createMissingChannels: false,
|
|
133
|
+
reconciliation: { ...products.reconciliation, deleteMissingMedia: true },
|
|
134
|
+
},
|
|
135
|
+
},
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const product: AkeneoProduct = {
|
|
140
|
+
uuid: 'uuid-mug',
|
|
141
|
+
identifier: 'MUG',
|
|
142
|
+
parent: null,
|
|
143
|
+
enabled: true,
|
|
144
|
+
values: {
|
|
145
|
+
sku: [{ locale: null, scope: null, data: 'MUG' }],
|
|
146
|
+
main_image: [{ locale: null, scope: null, data: 'kept.png' }],
|
|
147
|
+
},
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
describe('akeneo catalog importer media reconciliation', () => {
|
|
151
|
+
beforeEach(() => {
|
|
152
|
+
mockContainerResolve.mockReset()
|
|
153
|
+
mockFindOneWithDecryption.mockReset()
|
|
154
|
+
mockFindWithDecryption.mockReset()
|
|
155
|
+
mockReleaseScoped.mockReset()
|
|
156
|
+
mockDeletePartitionFile.mockReset()
|
|
157
|
+
mockEmitCrudSideEffects.mockReset()
|
|
158
|
+
})
|
|
159
|
+
|
|
160
|
+
it('releases a stale media row through the attachment service and leaves the stored file to it', async () => {
|
|
161
|
+
const stale = storedAttachment('attachment-stale', 'product:image:main_image:old.png:0')
|
|
162
|
+
const world = createMediaWorld([storedAttachment('attachment-kept', KEPT_EXTERNAL_ID), stale])
|
|
163
|
+
mockReleaseScoped.mockResolvedValue(undefined)
|
|
164
|
+
const importer = await createAkeneoImporter(world.client as never, scope)
|
|
165
|
+
|
|
166
|
+
await importer.upsertProduct(product, buildMediaMapping())
|
|
167
|
+
|
|
168
|
+
expect(mockReleaseScoped).toHaveBeenCalledTimes(1)
|
|
169
|
+
expect(mockReleaseScoped).toHaveBeenCalledWith({
|
|
170
|
+
attachmentId: 'attachment-stale',
|
|
171
|
+
tenantId: scope.tenantId,
|
|
172
|
+
organizationId: scope.organizationId,
|
|
173
|
+
expectedOwner: { entityId: 'catalog:catalog_product', recordId: PRODUCT_ID },
|
|
174
|
+
expectedAssignment: { type: 'catalog:catalog_product', id: PRODUCT_ID },
|
|
175
|
+
expectedPartitionCode: 'productsMedia',
|
|
176
|
+
})
|
|
177
|
+
expect(mockDeletePartitionFile).not.toHaveBeenCalled()
|
|
178
|
+
expect(mockEmitCrudSideEffects).toHaveBeenCalledWith(expect.objectContaining({ action: 'deleted', entity: stale }))
|
|
179
|
+
})
|
|
180
|
+
|
|
181
|
+
it('skips the deleted event without failing the product when a concurrent delete already removed the row', async () => {
|
|
182
|
+
const stale = storedAttachment('attachment-stale', 'product:image:main_image:old.png:0')
|
|
183
|
+
const world = createMediaWorld([stale])
|
|
184
|
+
mockReleaseScoped.mockRejectedValue(new CrudHttpError(404, { error: 'Attachment not found' }))
|
|
185
|
+
const importer = await createAkeneoImporter(world.client as never, scope)
|
|
186
|
+
|
|
187
|
+
await expect(importer.upsertProduct(product, buildMediaMapping())).resolves.toBeDefined()
|
|
188
|
+
|
|
189
|
+
expect(mockReleaseScoped).toHaveBeenCalledTimes(1)
|
|
190
|
+
expect(mockDeletePartitionFile).not.toHaveBeenCalled()
|
|
191
|
+
expect(mockEmitCrudSideEffects).not.toHaveBeenCalledWith(expect.objectContaining({ action: 'deleted' }))
|
|
192
|
+
})
|
|
193
|
+
})
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CatalogProduct,
|
|
3
|
+
CatalogProductVariant,
|
|
4
|
+
CatalogProductVariantRelation,
|
|
5
|
+
} from '@open-mercato/core/modules/catalog/data/entities'
|
|
6
|
+
import type { CustomFieldDefinition } from '@open-mercato/shared/modules/entities'
|
|
7
|
+
import { createAkeneoImporter } from '../lib/catalog-importer'
|
|
8
|
+
import {
|
|
9
|
+
buildDefaultAkeneoMapping,
|
|
10
|
+
type AkeneoAttribute,
|
|
11
|
+
type AkeneoCustomFieldMapping,
|
|
12
|
+
type AkeneoDataMapping,
|
|
13
|
+
type AkeneoProduct,
|
|
14
|
+
} from '../lib/shared'
|
|
15
|
+
|
|
16
|
+
const mockContainerResolve = jest.fn()
|
|
17
|
+
const mockFindOneWithDecryption = jest.fn()
|
|
18
|
+
const mockFindWithDecryption = jest.fn()
|
|
19
|
+
const mockEnsureCustomFieldDefinitions = jest.fn()
|
|
20
|
+
|
|
21
|
+
jest.mock('@open-mercato/shared/lib/commands/customFieldSnapshots', () => ({
|
|
22
|
+
loadCustomFieldSnapshot: jest.fn(async () => ({})),
|
|
23
|
+
}))
|
|
24
|
+
|
|
25
|
+
jest.mock('@open-mercato/shared/lib/di/container', () => ({
|
|
26
|
+
createRequestContainer: jest.fn(async () => ({
|
|
27
|
+
resolve: mockContainerResolve,
|
|
28
|
+
})),
|
|
29
|
+
}))
|
|
30
|
+
|
|
31
|
+
jest.mock('@open-mercato/shared/lib/encryption/find', () => ({
|
|
32
|
+
findOneWithDecryption: (...args: unknown[]) => mockFindOneWithDecryption(...args),
|
|
33
|
+
findWithDecryption: (...args: unknown[]) => mockFindWithDecryption(...args),
|
|
34
|
+
}))
|
|
35
|
+
|
|
36
|
+
jest.mock('@open-mercato/core/modules/entities/lib/field-definitions', () => ({
|
|
37
|
+
ensureCustomFieldDefinitions: (...args: unknown[]) => mockEnsureCustomFieldDefinitions(...args),
|
|
38
|
+
}))
|
|
39
|
+
|
|
40
|
+
type DefinitionSet = { entity: string; fields: CustomFieldDefinition[]; source?: string }
|
|
41
|
+
type CustomFieldWrite = { entityId: string; recordId: string; values: Record<string, unknown> }
|
|
42
|
+
type MappingRow = { entityType: string; localId: string; externalId: string }
|
|
43
|
+
type RecordRow = { id: string; product?: string; sku?: string; isDefault?: boolean }
|
|
44
|
+
|
|
45
|
+
const scope = { organizationId: 'org-1', tenantId: 'tenant-1' }
|
|
46
|
+
const PRODUCT_ENTITY_ID = 'catalog:catalog_product'
|
|
47
|
+
const VARIANT_ENTITY_ID = 'catalog:catalog_product_variant'
|
|
48
|
+
|
|
49
|
+
function createImporterWorld(attributes: AkeneoAttribute[], seededMappings: MappingRow[] = []) {
|
|
50
|
+
const products: RecordRow[] = []
|
|
51
|
+
const variants: RecordRow[] = []
|
|
52
|
+
const mappings: MappingRow[] = [...seededMappings]
|
|
53
|
+
const customFieldWrites: CustomFieldWrite[] = []
|
|
54
|
+
const createdRelations: Array<Record<string, unknown>> = []
|
|
55
|
+
let sequence = 0
|
|
56
|
+
const nextId = (prefix: string) => {
|
|
57
|
+
sequence += 1
|
|
58
|
+
return `${prefix}-${sequence}`
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const commandBus = {
|
|
62
|
+
execute: jest.fn(async (commandId: string, { input }: { input: Record<string, unknown> }) => {
|
|
63
|
+
switch (commandId) {
|
|
64
|
+
case 'catalog.products.create': {
|
|
65
|
+
const id = nextId('product')
|
|
66
|
+
products.push({ id })
|
|
67
|
+
return { result: { productId: id } }
|
|
68
|
+
}
|
|
69
|
+
case 'catalog.products.update':
|
|
70
|
+
return { result: { productId: input.id } }
|
|
71
|
+
case 'catalog.variants.create': {
|
|
72
|
+
const id = nextId('variant')
|
|
73
|
+
variants.push({ id, product: String(input.productId), sku: String(input.sku), isDefault: input.isDefault === true })
|
|
74
|
+
return { result: { variantId: id } }
|
|
75
|
+
}
|
|
76
|
+
case 'catalog.variants.update':
|
|
77
|
+
return { result: { variantId: input.id } }
|
|
78
|
+
default:
|
|
79
|
+
throw new Error(`[internal] unexpected command: ${commandId}`)
|
|
80
|
+
}
|
|
81
|
+
}),
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const externalIdMappingService = {
|
|
85
|
+
lookupLocalId: jest.fn(async (_integrationId: string, entityType: string, externalId: string) => (
|
|
86
|
+
mappings.find((row) => row.entityType === entityType && row.externalId === externalId)?.localId ?? null
|
|
87
|
+
)),
|
|
88
|
+
storeExternalIdMapping: jest.fn(async (_integrationId: string, entityType: string, localId: string, externalId: string) => {
|
|
89
|
+
mappings.push({ entityType, localId, externalId })
|
|
90
|
+
}),
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const dataEngine = {
|
|
94
|
+
setCustomFields: jest.fn(async (payload: CustomFieldWrite) => {
|
|
95
|
+
customFieldWrites.push({ entityId: payload.entityId, recordId: payload.recordId, values: payload.values })
|
|
96
|
+
}),
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const em = {
|
|
100
|
+
getConnection: () => ({ execute: async () => [] }),
|
|
101
|
+
flush: jest.fn(async () => undefined),
|
|
102
|
+
persist: jest.fn(),
|
|
103
|
+
remove: jest.fn(),
|
|
104
|
+
isInTransaction: () => true,
|
|
105
|
+
getReference: (_entity: unknown, id: string) => ({ id }),
|
|
106
|
+
create: (entity: unknown, data: Record<string, unknown>) => {
|
|
107
|
+
if (entity === CatalogProductVariantRelation) createdRelations.push(data)
|
|
108
|
+
return data
|
|
109
|
+
},
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
mockContainerResolve.mockImplementation((key: string) => {
|
|
113
|
+
if (key === 'em') return em
|
|
114
|
+
if (key === 'commandBus') return commandBus
|
|
115
|
+
if (key === 'dataEngine') return dataEngine
|
|
116
|
+
if (key === 'externalIdMappingService') return externalIdMappingService
|
|
117
|
+
if (key === 'cache') throw new Error('[internal] no cache in test')
|
|
118
|
+
throw new Error(`[internal] unexpected dependency: ${key}`)
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
mockFindOneWithDecryption.mockImplementation(async (_em: unknown, entity: unknown, where: Record<string, unknown>) => {
|
|
122
|
+
if (entity === CatalogProduct) return products.find((product) => product.id === where.id) ?? null
|
|
123
|
+
if (entity === CatalogProductVariant) {
|
|
124
|
+
return variants.find((variant) => (
|
|
125
|
+
(where.id === undefined || variant.id === where.id)
|
|
126
|
+
&& (where.product === undefined || variant.product === where.product)
|
|
127
|
+
&& (where.sku === undefined || variant.sku === where.sku)
|
|
128
|
+
&& (where.isDefault === undefined || variant.isDefault === where.isDefault)
|
|
129
|
+
)) ?? null
|
|
130
|
+
}
|
|
131
|
+
return null
|
|
132
|
+
})
|
|
133
|
+
mockFindWithDecryption.mockResolvedValue([])
|
|
134
|
+
|
|
135
|
+
mockEnsureCustomFieldDefinitions.mockResolvedValue(undefined)
|
|
136
|
+
|
|
137
|
+
const client = {
|
|
138
|
+
getFamily: jest.fn(async () => null),
|
|
139
|
+
getFamilyVariant: jest.fn(async () => null),
|
|
140
|
+
getProductModel: jest.fn(async () => null),
|
|
141
|
+
getAttribute: jest.fn(async (code: string) => attributes.find((attribute) => attribute.code === code) ?? null),
|
|
142
|
+
listAttributeOptions: jest.fn(async () => []),
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const definedFields = (entityId: string): CustomFieldDefinition[] => (
|
|
146
|
+
mockEnsureCustomFieldDefinitions.mock.calls
|
|
147
|
+
.flatMap(([, sets]) => sets as DefinitionSet[])
|
|
148
|
+
.filter((set) => set.entity === entityId)
|
|
149
|
+
.flatMap((set) => set.fields)
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
return { client, customFieldWrites, createdRelations, definedFields }
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function buildMapping(overrides: { customFieldMappings?: AkeneoCustomFieldMapping[]; syncAssociations?: boolean }): AkeneoDataMapping {
|
|
156
|
+
const base = buildDefaultAkeneoMapping('products')
|
|
157
|
+
const products = base.settings?.products
|
|
158
|
+
if (!products) throw new Error('[internal] default Akeneo product mapping is missing')
|
|
159
|
+
return {
|
|
160
|
+
...base,
|
|
161
|
+
settings: {
|
|
162
|
+
...base.settings,
|
|
163
|
+
products: {
|
|
164
|
+
...products,
|
|
165
|
+
priceMappings: [],
|
|
166
|
+
mediaMappings: [],
|
|
167
|
+
customFieldMappings: overrides.customFieldMappings ?? [],
|
|
168
|
+
syncAssociations: overrides.syncAssociations ?? false,
|
|
169
|
+
createMissingChannels: false,
|
|
170
|
+
},
|
|
171
|
+
},
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function buildSimpleProduct(uuid: string, sku: string, values: Record<string, unknown>): AkeneoProduct {
|
|
176
|
+
const attributeValues = Object.fromEntries(
|
|
177
|
+
Object.entries(values).map(([code, data]) => [code, [{ locale: null, scope: null, data }]]),
|
|
178
|
+
)
|
|
179
|
+
return {
|
|
180
|
+
uuid,
|
|
181
|
+
identifier: sku,
|
|
182
|
+
parent: null,
|
|
183
|
+
enabled: true,
|
|
184
|
+
values: {
|
|
185
|
+
sku: [{ locale: null, scope: null, data: sku }],
|
|
186
|
+
...attributeValues,
|
|
187
|
+
},
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
describe('akeneo catalog importer numeric attribute handling', () => {
|
|
192
|
+
beforeEach(() => {
|
|
193
|
+
mockContainerResolve.mockReset()
|
|
194
|
+
mockFindOneWithDecryption.mockReset()
|
|
195
|
+
mockFindWithDecryption.mockReset()
|
|
196
|
+
mockEnsureCustomFieldDefinitions.mockReset()
|
|
197
|
+
})
|
|
198
|
+
|
|
199
|
+
it('turns numeric minimum and maximum values into min and max validation rules and ignores non-numeric bounds', async () => {
|
|
200
|
+
const world = createImporterWorld([
|
|
201
|
+
{ code: 'load_limit', type: 'pim_catalog_number', decimals_allowed: false, minimum_value: 0, maximum_value: 250 },
|
|
202
|
+
{ code: 'thickness', type: 'pim_catalog_number', decimals_allowed: true, minimum_value: '0.5', maximum_value: ' 12.75 ' },
|
|
203
|
+
{ code: 'rating', type: 'pim_catalog_number', decimals_allowed: true, minimum_value: 'none', maximum_value: ' ' },
|
|
204
|
+
{ code: 'stock_hint', type: 'pim_catalog_number', decimals_allowed: true, minimum_value: '-5', maximum_value: null },
|
|
205
|
+
])
|
|
206
|
+
const importer = await createAkeneoImporter(world.client as never, scope)
|
|
207
|
+
|
|
208
|
+
await importer.syncMappedCustomFields(buildMapping({
|
|
209
|
+
customFieldMappings: [
|
|
210
|
+
{ attributeCode: 'load_limit', fieldKey: 'load_limit', target: 'product' },
|
|
211
|
+
{ attributeCode: 'thickness', fieldKey: 'thickness', target: 'product' },
|
|
212
|
+
{ attributeCode: 'rating', fieldKey: 'rating', target: 'variant' },
|
|
213
|
+
{ attributeCode: 'stock_hint', fieldKey: 'stock_hint', target: 'variant' },
|
|
214
|
+
],
|
|
215
|
+
}), 'en_US')
|
|
216
|
+
|
|
217
|
+
const validationByKey = Object.fromEntries(
|
|
218
|
+
[...world.definedFields(PRODUCT_ENTITY_ID), ...world.definedFields(VARIANT_ENTITY_ID)]
|
|
219
|
+
.map((field) => [field.key, { kind: field.kind, validation: field.validation }]),
|
|
220
|
+
)
|
|
221
|
+
expect(validationByKey).toEqual({
|
|
222
|
+
load_limit: { kind: 'integer', validation: [{ rule: 'min', param: 0 }, { rule: 'max', param: 250 }] },
|
|
223
|
+
thickness: { kind: 'float', validation: [{ rule: 'min', param: 0.5 }, { rule: 'max', param: 12.75 }] },
|
|
224
|
+
rating: { kind: 'float', validation: [] },
|
|
225
|
+
stock_hint: { kind: 'float', validation: [{ rule: 'min', param: -5 }] },
|
|
226
|
+
})
|
|
227
|
+
})
|
|
228
|
+
|
|
229
|
+
it.each([
|
|
230
|
+
{ label: 'numbers', packSize: 7.9, ratio: 1.25, expected: { pack_size: 7, ratio: 1.25 } },
|
|
231
|
+
{ label: 'numeric strings', packSize: '-12.6', ratio: ' 0.375 ', expected: { pack_size: -12, ratio: 0.375 } },
|
|
232
|
+
{ label: 'blank strings', packSize: ' ', ratio: '', expected: {} },
|
|
233
|
+
{ label: 'garbage strings', packSize: 'twelve', ratio: '1,5', expected: {} },
|
|
234
|
+
])('writes integer and float custom field values given as $label', async ({ packSize, ratio, expected }) => {
|
|
235
|
+
const world = createImporterWorld([
|
|
236
|
+
{ code: 'pack_size', type: 'pim_catalog_number', decimals_allowed: false },
|
|
237
|
+
{ code: 'ratio', type: 'pim_catalog_number', decimals_allowed: true },
|
|
238
|
+
])
|
|
239
|
+
const importer = await createAkeneoImporter(world.client as never, scope)
|
|
240
|
+
const mapping = buildMapping({
|
|
241
|
+
customFieldMappings: [
|
|
242
|
+
{ attributeCode: 'pack_size', fieldKey: 'pack_size', target: 'product' },
|
|
243
|
+
{ attributeCode: 'ratio', fieldKey: 'ratio', target: 'product' },
|
|
244
|
+
],
|
|
245
|
+
})
|
|
246
|
+
|
|
247
|
+
await importer.upsertProduct(buildSimpleProduct('uuid-box', 'BOX', { pack_size: packSize, ratio }), mapping)
|
|
248
|
+
|
|
249
|
+
const productValues = world.customFieldWrites
|
|
250
|
+
.filter((write) => write.entityId === PRODUCT_ENTITY_ID)
|
|
251
|
+
.reduce<Record<string, unknown>>((merged, write) => ({ ...merged, ...write.values }), {})
|
|
252
|
+
expect(productValues).toEqual(expected)
|
|
253
|
+
})
|
|
254
|
+
|
|
255
|
+
it('stores quantified association quantities given as numbers or numeric strings and drops unreadable ones', async () => {
|
|
256
|
+
const world = createImporterWorld([], [
|
|
257
|
+
{ entityType: 'catalog_product_variant', externalId: 'child-uuid-1', localId: 'child-variant-1' },
|
|
258
|
+
{ entityType: 'catalog_product_variant', externalId: 'CHILD-2:default', localId: 'child-variant-2' },
|
|
259
|
+
{ entityType: 'catalog_product_variant', externalId: 'child-uuid-3', localId: 'child-variant-3' },
|
|
260
|
+
{ entityType: 'catalog_product', externalId: 'model-a', localId: 'child-product-a' },
|
|
261
|
+
])
|
|
262
|
+
const importer = await createAkeneoImporter(world.client as never, scope)
|
|
263
|
+
const product: AkeneoProduct = {
|
|
264
|
+
...buildSimpleProduct('uuid-kit', 'KIT', {}),
|
|
265
|
+
quantified_associations: {
|
|
266
|
+
PACK: {
|
|
267
|
+
products: [
|
|
268
|
+
{ uuid: 'child-uuid-1', quantity: '3' },
|
|
269
|
+
{ identifier: 'CHILD-2', quantity: 2 },
|
|
270
|
+
{ uuid: 'child-uuid-3', quantity: 'several' },
|
|
271
|
+
],
|
|
272
|
+
product_models: [{ code: 'model-a', quantity: ' 4 ' }],
|
|
273
|
+
},
|
|
274
|
+
},
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
await importer.upsertProduct(product, buildMapping({ syncAssociations: true }))
|
|
278
|
+
|
|
279
|
+
const relations = world.createdRelations.map((relation) => ({
|
|
280
|
+
relationType: relation.relationType,
|
|
281
|
+
childVariant: relation.childVariant,
|
|
282
|
+
childProduct: relation.childProduct,
|
|
283
|
+
minQuantity: relation.minQuantity,
|
|
284
|
+
}))
|
|
285
|
+
expect(relations).toEqual([
|
|
286
|
+
{ relationType: 'bundle', childVariant: { id: 'child-variant-1' }, childProduct: null, minQuantity: 3 },
|
|
287
|
+
{ relationType: 'bundle', childVariant: { id: 'child-variant-2' }, childProduct: null, minQuantity: 2 },
|
|
288
|
+
{ relationType: 'bundle', childVariant: { id: 'child-variant-3' }, childProduct: null, minQuantity: null },
|
|
289
|
+
{ relationType: 'bundle', childVariant: null, childProduct: { id: 'child-product-a' }, minQuantity: 4 },
|
|
290
|
+
])
|
|
291
|
+
})
|
|
292
|
+
})
|
|
@@ -352,6 +352,28 @@ describe('akeneo catalog importer offer and price reconciliation', () => {
|
|
|
352
352
|
mockFindWithDecryption.mockReset()
|
|
353
353
|
})
|
|
354
354
|
|
|
355
|
+
it('passes every decimal digit to catalog price create and update commands', async () => {
|
|
356
|
+
const world = createCatalogWorld()
|
|
357
|
+
const importer = await createAkeneoImporter(world.client as never, scope)
|
|
358
|
+
const mapping = buildMapping([WEB_REGULAR])
|
|
359
|
+
const originalAmount = '1.123456789012345678'
|
|
360
|
+
const updatedAmount = '1.123456789012345679'
|
|
361
|
+
|
|
362
|
+
await importer.upsertProduct(buildVariant('uuid-exact', 'TEE-EXACT', {
|
|
363
|
+
price: [{ scope: 'ecommerce', amount: originalAmount }],
|
|
364
|
+
}), mapping)
|
|
365
|
+
expect(world.commandBus.execute).toHaveBeenCalledWith('catalog.prices.create', expect.objectContaining({
|
|
366
|
+
input: expect.objectContaining({ unitPriceNet: originalAmount, unitPriceGross: originalAmount }),
|
|
367
|
+
}))
|
|
368
|
+
|
|
369
|
+
await importer.upsertProduct(buildVariant('uuid-exact', 'TEE-EXACT', {
|
|
370
|
+
price: [{ scope: 'ecommerce', amount: updatedAmount }],
|
|
371
|
+
}), mapping)
|
|
372
|
+
expect(world.commandBus.execute).toHaveBeenCalledWith('catalog.prices.update', expect.objectContaining({
|
|
373
|
+
input: expect.objectContaining({ unitPriceNet: updatedAmount, unitPriceGross: updatedAmount }),
|
|
374
|
+
}))
|
|
375
|
+
})
|
|
376
|
+
|
|
355
377
|
it('keeps the prices of sibling variants that share a product-level offer', async () => {
|
|
356
378
|
const world = createCatalogWorld()
|
|
357
379
|
const importer = await createAkeneoImporter(world.client as never, scope)
|
|
@@ -484,6 +506,31 @@ describe('akeneo catalog importer offer and price reconciliation', () => {
|
|
|
484
506
|
expect(world.pricesOf('TEE-M')).toEqual(['regular:channel-web:USD:10'])
|
|
485
507
|
})
|
|
486
508
|
|
|
509
|
+
it('passes the exact Akeneo price strings to the create and update commands', async () => {
|
|
510
|
+
const world = createCatalogWorld()
|
|
511
|
+
const importer = await createAkeneoImporter(world.client as never, scope)
|
|
512
|
+
const mapping = buildMapping([WEB_REGULAR])
|
|
513
|
+
|
|
514
|
+
await importer.upsertProduct(buildSimpleProduct('uuid-gem', 'GEM', {
|
|
515
|
+
price: [{ scope: 'ecommerce', amount: '1.123456789012345678' }],
|
|
516
|
+
}), mapping)
|
|
517
|
+
await importer.upsertProduct(buildSimpleProduct('uuid-gem', 'GEM', {
|
|
518
|
+
price: [{ scope: 'ecommerce', amount: '1.123456789012345679' }],
|
|
519
|
+
}), mapping)
|
|
520
|
+
|
|
521
|
+
const priceCommands = world.commandBus.execute.mock.calls
|
|
522
|
+
.filter(([commandId]) => commandId === 'catalog.prices.create' || commandId === 'catalog.prices.update')
|
|
523
|
+
.map(([commandId, { input }]) => ({
|
|
524
|
+
commandId,
|
|
525
|
+
unitPriceNet: input.unitPriceNet,
|
|
526
|
+
unitPriceGross: input.unitPriceGross,
|
|
527
|
+
}))
|
|
528
|
+
expect(priceCommands).toEqual([
|
|
529
|
+
{ commandId: 'catalog.prices.create', unitPriceNet: '1.123456789012345678', unitPriceGross: '1.123456789012345678' },
|
|
530
|
+
{ commandId: 'catalog.prices.update', unitPriceNet: '1.123456789012345679', unitPriceGross: '1.123456789012345679' },
|
|
531
|
+
])
|
|
532
|
+
})
|
|
533
|
+
|
|
487
534
|
it('deletes the offer of a simple product whose channel price was removed', async () => {
|
|
488
535
|
const world = createCatalogWorld()
|
|
489
536
|
const importer = await createAkeneoImporter(world.client as never, scope)
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { AwilixContainer } from 'awilix'
|
|
2
|
+
import type { startDataSyncRun } from '@open-mercato/core/modules/data_sync/lib/start-run'
|
|
3
|
+
import { runAkeneoFirstImportSequence } from '../lib/first-import'
|
|
4
|
+
|
|
5
|
+
const mockStartDataSyncRun = jest.fn()
|
|
6
|
+
const mockEnqueue = jest.fn()
|
|
7
|
+
|
|
8
|
+
jest.mock('@open-mercato/core/modules/data_sync/lib/queue', () => ({
|
|
9
|
+
getSyncQueue: jest.fn(() => ({ enqueue: mockEnqueue })),
|
|
10
|
+
}))
|
|
11
|
+
|
|
12
|
+
jest.mock('@open-mercato/core/modules/data_sync/lib/start-run', () => {
|
|
13
|
+
const actual = jest.requireActual<typeof import('@open-mercato/core/modules/data_sync/lib/start-run')>(
|
|
14
|
+
'@open-mercato/core/modules/data_sync/lib/start-run',
|
|
15
|
+
)
|
|
16
|
+
return {
|
|
17
|
+
...actual,
|
|
18
|
+
startDataSyncRun: (params: Parameters<typeof startDataSyncRun>[0]) => {
|
|
19
|
+
mockStartDataSyncRun(params)
|
|
20
|
+
return actual.startDataSyncRun(params)
|
|
21
|
+
},
|
|
22
|
+
}
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
const scope = { organizationId: 'org-1', tenantId: 'tenant-1', userId: 'user-1' }
|
|
26
|
+
|
|
27
|
+
function buildHarness() {
|
|
28
|
+
const progressService = {
|
|
29
|
+
startJob: jest.fn(async () => undefined),
|
|
30
|
+
createJob: jest.fn(async () => ({ id: 'run-job-1' })),
|
|
31
|
+
updateProgress: jest.fn(async () => undefined),
|
|
32
|
+
completeJob: jest.fn(async () => undefined),
|
|
33
|
+
getJob: jest.fn(async () => ({ totalCount: 1, processedCount: 1, progressPercent: 100 })),
|
|
34
|
+
}
|
|
35
|
+
const syncRunService = {
|
|
36
|
+
findRunningOverlap: jest.fn(async () => null),
|
|
37
|
+
createRun: jest.fn(async (input: { entityType: string; progressJobId: string | null }) => ({
|
|
38
|
+
id: `run-${input.entityType}`,
|
|
39
|
+
status: 'pending',
|
|
40
|
+
progressJobId: input.progressJobId,
|
|
41
|
+
})),
|
|
42
|
+
getRun: jest.fn(async (runId: string) => ({ id: runId, status: 'completed', progressJobId: 'run-job-1' })),
|
|
43
|
+
}
|
|
44
|
+
const services: Record<string, unknown> = {
|
|
45
|
+
em: { clear: jest.fn() },
|
|
46
|
+
progressService,
|
|
47
|
+
dataSyncRunService: syncRunService,
|
|
48
|
+
}
|
|
49
|
+
const container = { resolve: (token: string) => services[token] } as unknown as AwilixContainer
|
|
50
|
+
return { container, progressService, syncRunService }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
describe('Akeneo first import batch size', () => {
|
|
54
|
+
beforeEach(() => {
|
|
55
|
+
jest.clearAllMocks()
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it('delegates batch size resolution to the shared helper for every step', async () => {
|
|
59
|
+
const { container, progressService, syncRunService } = buildHarness()
|
|
60
|
+
|
|
61
|
+
await runAkeneoFirstImportSequence({ container, progressJobId: 'sequence-job-1', scope })
|
|
62
|
+
|
|
63
|
+
expect(mockStartDataSyncRun).toHaveBeenCalledTimes(3)
|
|
64
|
+
for (const [stepIndex, entityType] of ['categories', 'attributes', 'products'].entries()) {
|
|
65
|
+
const [params] = mockStartDataSyncRun.mock.calls[stepIndex] as [Parameters<typeof startDataSyncRun>[0]]
|
|
66
|
+
expect(params.input).toEqual({
|
|
67
|
+
integrationId: 'sync_akeneo',
|
|
68
|
+
entityType,
|
|
69
|
+
direction: 'import',
|
|
70
|
+
triggeredBy: scope.userId,
|
|
71
|
+
})
|
|
72
|
+
expect(params.scope).toEqual(scope)
|
|
73
|
+
expect(syncRunService.findRunningOverlap).toHaveBeenNthCalledWith(stepIndex + 1, 'sync_akeneo', entityType, 'import', scope)
|
|
74
|
+
expect(mockEnqueue).toHaveBeenNthCalledWith(stepIndex + 1, {
|
|
75
|
+
runId: `run-${entityType}`,
|
|
76
|
+
batchSize: 100,
|
|
77
|
+
scope,
|
|
78
|
+
})
|
|
79
|
+
}
|
|
80
|
+
expect(progressService.completeJob).toHaveBeenCalledWith('sequence-job-1', expect.any(Object), scope)
|
|
81
|
+
})
|
|
82
|
+
})
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { parseModuleCliOptions } from '@open-mercato/shared/lib/cli/parseModuleCliOptions'
|
|
1
2
|
import type { ModuleCli } from '@open-mercato/shared/modules/registry'
|
|
2
3
|
import type { EntityManager } from '@mikro-orm/postgresql'
|
|
3
4
|
import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
|
|
@@ -7,30 +8,7 @@ import type { IntegrationLogService } from '@open-mercato/core/modules/integrati
|
|
|
7
8
|
import { applyAkeneoEnvPreset, readAkeneoEnvPreset } from './lib/preset'
|
|
8
9
|
|
|
9
10
|
function parseArgs(args: string[]): Record<string, string | boolean> {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
for (let i = 0; i < args.length; i++) {
|
|
13
|
-
const arg = args[i]
|
|
14
|
-
if (!arg.startsWith('--')) continue
|
|
15
|
-
|
|
16
|
-
const key = arg.slice(2)
|
|
17
|
-
if (key.includes('=')) {
|
|
18
|
-
const [name, value] = key.split('=')
|
|
19
|
-
result[name] = value
|
|
20
|
-
continue
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
const next = args[i + 1]
|
|
24
|
-
if (next && !next.startsWith('--')) {
|
|
25
|
-
result[key] = next
|
|
26
|
-
i += 1
|
|
27
|
-
continue
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
result[key] = true
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
return result
|
|
11
|
+
return parseModuleCliOptions(args)
|
|
34
12
|
}
|
|
35
13
|
|
|
36
14
|
function printHelp(): void {
|
|
@@ -1,4 +1,14 @@
|
|
|
1
1
|
{
|
|
2
|
+
"sync_akeneo.credentials.apiUrl.helpText": "Use the base Akeneo PIM URL, without a trailing slash.",
|
|
3
|
+
"sync_akeneo.credentials.apiUrl.label": "Akeneo URL",
|
|
4
|
+
"sync_akeneo.credentials.clientId.helpText": "Create a connected app or API client in Akeneo and copy its client id.",
|
|
5
|
+
"sync_akeneo.credentials.clientId.label": "Client ID",
|
|
6
|
+
"sync_akeneo.credentials.clientSecret.helpText": "Use the client secret generated for the Akeneo API connection.",
|
|
7
|
+
"sync_akeneo.credentials.clientSecret.label": "Client Secret",
|
|
8
|
+
"sync_akeneo.credentials.password.helpText": "Use the password for the dedicated Akeneo API user.",
|
|
9
|
+
"sync_akeneo.credentials.password.label": "API Password",
|
|
10
|
+
"sync_akeneo.credentials.username.helpText": "Create a dedicated Akeneo user for synchronization and grant only the product/catalog permissions it needs.",
|
|
11
|
+
"sync_akeneo.credentials.username.label": "API Username",
|
|
2
12
|
"sync_akeneo.customFields.actions.add": "Zeile hinzufügen",
|
|
3
13
|
"sync_akeneo.customFields.actions.createMissing": "Fehlende Felder jetzt erstellen",
|
|
4
14
|
"sync_akeneo.customFields.actions.creating": "Wird erstellt...",
|