@open-mercato/sync-akeneo 0.8.1-develop.7296.1.2111d779db → 0.9.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.
@@ -0,0 +1,712 @@
1
+ import {
2
+ CatalogOffer,
3
+ CatalogPriceKind,
4
+ CatalogProduct,
5
+ CatalogProductPrice,
6
+ CatalogProductVariant,
7
+ } from '@open-mercato/core/modules/catalog/data/entities'
8
+ import { SalesChannel } from '@open-mercato/core/modules/sales/data/entities'
9
+ import { createAkeneoImporter } from '../lib/catalog-importer'
10
+ import {
11
+ buildDefaultAkeneoMapping,
12
+ type AkeneoDataMapping,
13
+ type AkeneoPriceMapping,
14
+ type AkeneoProduct,
15
+ type AkeneoReconciliationSettings,
16
+ type AkeneoValues,
17
+ } from '../lib/shared'
18
+
19
+ const mockContainerResolve = jest.fn()
20
+ const mockFindOneWithDecryption = jest.fn()
21
+ const mockFindWithDecryption = jest.fn()
22
+
23
+ jest.mock('@open-mercato/shared/lib/di/container', () => ({
24
+ createRequestContainer: jest.fn(async () => ({
25
+ resolve: mockContainerResolve,
26
+ })),
27
+ }))
28
+
29
+ jest.mock('@open-mercato/shared/lib/encryption/find', () => ({
30
+ findOneWithDecryption: (...args: unknown[]) => mockFindOneWithDecryption(...args),
31
+ findWithDecryption: (...args: unknown[]) => mockFindWithDecryption(...args),
32
+ }))
33
+
34
+ type ProductRow = { id: string; deletedAt: null }
35
+ type VariantRow = { id: string; product: string; sku: string; isDefault: boolean; deletedAt: null }
36
+ type OfferRow = { id: string; product: string; channelId: string; deletedAt: null }
37
+ type PriceRow = {
38
+ id: string
39
+ offer: string
40
+ variant: { id: string } | null
41
+ channelId: string
42
+ currencyCode: string
43
+ kind: string
44
+ minQuantity: number
45
+ unitPriceNet: number
46
+ }
47
+ type MappingRow = { entityType: string; localId: string; externalId: string }
48
+
49
+ const scope = { organizationId: 'org-1', tenantId: 'tenant-1' }
50
+
51
+ const CHANNELS = [
52
+ { id: 'channel-web', code: 'web' },
53
+ { id: 'channel-b2b', code: 'b2b' },
54
+ ]
55
+
56
+ const MODEL_CODE = 'tee'
57
+
58
+ function createCatalogWorld() {
59
+ const products: ProductRow[] = []
60
+ const variants: VariantRow[] = []
61
+ const offers: OfferRow[] = []
62
+ const prices: PriceRow[] = []
63
+ const mappings: MappingRow[] = []
64
+ const deletedPriceIds: string[] = []
65
+ const deletedOfferIds: string[] = []
66
+ let sequence = 0
67
+ const nextId = (prefix: string) => {
68
+ sequence += 1
69
+ return `${prefix}-${sequence}`
70
+ }
71
+
72
+ const commandBus = {
73
+ execute: jest.fn(async (commandId: string, { input }: { input: Record<string, unknown> }) => {
74
+ switch (commandId) {
75
+ case 'catalog.products.create': {
76
+ const id = nextId('product')
77
+ products.push({ id, deletedAt: null })
78
+ return { result: { productId: id } }
79
+ }
80
+ case 'catalog.products.update':
81
+ return { result: { productId: input.id } }
82
+ case 'catalog.variants.create': {
83
+ const id = nextId('variant')
84
+ variants.push({
85
+ id,
86
+ product: String(input.productId),
87
+ sku: String(input.sku),
88
+ isDefault: input.isDefault === true,
89
+ deletedAt: null,
90
+ })
91
+ return { result: { variantId: id } }
92
+ }
93
+ case 'catalog.variants.update':
94
+ return { result: { variantId: input.id } }
95
+ case 'catalog.offers.create': {
96
+ const id = nextId('offer')
97
+ offers.push({ id, product: String(input.productId), channelId: String(input.channelId), deletedAt: null })
98
+ return { result: { offerId: id } }
99
+ }
100
+ case 'catalog.offers.update':
101
+ return { result: { offerId: input.id } }
102
+ case 'catalog.offers.delete': {
103
+ const index = offers.findIndex((offer) => offer.id === input.id)
104
+ if (index < 0) throw new Error('[internal] offer not found')
105
+ offers.splice(index, 1)
106
+ deletedOfferIds.push(String(input.id))
107
+ return { result: { offerId: input.id } }
108
+ }
109
+ case 'catalog.prices.create': {
110
+ const id = nextId('price')
111
+ const kind = input.priceKindId === 'kind-sale' ? 'sale' : 'regular'
112
+ const violatesUniqueKey = prices.some((entry) => (
113
+ entry.variant?.id === input.variantId
114
+ && entry.currencyCode === input.currencyCode
115
+ && entry.kind === kind
116
+ && entry.minQuantity === Number(input.minQuantity)
117
+ ))
118
+ if (violatesUniqueKey) throw new Error('[internal] catalog_product_variant_prices_unique violated')
119
+ prices.push({
120
+ id,
121
+ offer: String(input.offerId),
122
+ variant: { id: String(input.variantId) },
123
+ channelId: String(input.channelId),
124
+ currencyCode: String(input.currencyCode),
125
+ kind,
126
+ minQuantity: Number(input.minQuantity),
127
+ unitPriceNet: Number(input.unitPriceNet),
128
+ })
129
+ return { result: { priceId: id } }
130
+ }
131
+ case 'catalog.prices.update': {
132
+ const price = prices.find((entry) => entry.id === input.id)
133
+ if (!price) throw new Error('[internal] price not found')
134
+ price.unitPriceNet = Number(input.unitPriceNet)
135
+ price.minQuantity = Number(input.minQuantity)
136
+ return { result: { priceId: price.id } }
137
+ }
138
+ case 'catalog.prices.delete': {
139
+ const index = prices.findIndex((entry) => entry.id === input.id)
140
+ if (index < 0) throw new Error('[internal] price not found')
141
+ prices.splice(index, 1)
142
+ deletedPriceIds.push(String(input.id))
143
+ return { result: { priceId: input.id } }
144
+ }
145
+ default:
146
+ throw new Error(`[internal] unexpected command: ${commandId}`)
147
+ }
148
+ }),
149
+ }
150
+
151
+ const externalIdMappingService = {
152
+ lookupLocalId: jest.fn(async (_integrationId: string, entityType: string, externalId: string) => (
153
+ mappings.find((row) => row.entityType === entityType && row.externalId === externalId)?.localId ?? null
154
+ )),
155
+ lookupExternalId: jest.fn(async (_integrationId: string, entityType: string, localId: string) => (
156
+ mappings.find((row) => row.entityType === entityType && row.localId === localId)?.externalId ?? null
157
+ )),
158
+ storeExternalIdMapping: jest.fn(async (_integrationId: string, entityType: string, localId: string, externalId: string) => {
159
+ const existing = mappings.find((row) => row.entityType === entityType && row.externalId === externalId)
160
+ ?? mappings.find((row) => row.entityType === entityType && row.localId === localId)
161
+ if (existing) {
162
+ existing.localId = localId
163
+ existing.externalId = externalId
164
+ return
165
+ }
166
+ mappings.push({ entityType, localId, externalId })
167
+ }),
168
+ }
169
+
170
+ mockContainerResolve.mockImplementation((key: string) => {
171
+ if (key === 'em') return {}
172
+ if (key === 'commandBus') return commandBus
173
+ if (key === 'dataEngine') return {}
174
+ if (key === 'externalIdMappingService') return externalIdMappingService
175
+ if (key === 'cache') throw new Error('[internal] no cache in test')
176
+ throw new Error(`[internal] unexpected dependency: ${key}`)
177
+ })
178
+
179
+ mockFindOneWithDecryption.mockImplementation(async (_em: unknown, entity: unknown, where: Record<string, unknown>) => {
180
+ if (entity === SalesChannel) return CHANNELS.find((channel) => channel.code === where.code) ?? null
181
+ if (entity === CatalogPriceKind) {
182
+ return where.code === 'regular' || where.code === 'sale'
183
+ ? { id: `kind-${String(where.code)}`, code: where.code, displayMode: 'excluding-tax' }
184
+ : null
185
+ }
186
+ if (entity === CatalogProduct) return products.find((product) => product.id === where.id) ?? null
187
+ if (entity === CatalogProductVariant) {
188
+ return variants.find((variant) => (
189
+ (where.id === undefined || variant.id === where.id)
190
+ && (where.product === undefined || variant.product === where.product)
191
+ && (where.sku === undefined || variant.sku === where.sku)
192
+ && (where.isDefault === undefined || variant.isDefault === where.isDefault)
193
+ )) ?? null
194
+ }
195
+ return null
196
+ })
197
+
198
+ mockFindWithDecryption.mockImplementation(async (_em: unknown, entity: unknown, where: Record<string, unknown>) => {
199
+ if (entity === CatalogOffer) return offers.filter((offer) => offer.product === where.product)
200
+ if (entity === CatalogProductPrice) {
201
+ return prices.filter((price) => (
202
+ (where.offer === undefined || price.offer === where.offer)
203
+ && (where.variant === undefined || price.variant?.id === where.variant)
204
+ ))
205
+ }
206
+ return []
207
+ })
208
+
209
+ const client = {
210
+ getFamily: jest.fn(async () => null),
211
+ getFamilyVariant: jest.fn(async () => null),
212
+ getAttribute: jest.fn(async () => null),
213
+ getProductModel: jest.fn(async (code: string) => (
214
+ code === MODEL_CODE
215
+ ? { code: MODEL_CODE, values: { name: [{ locale: 'en_US', scope: null, data: 'Tee' }] }, categories: [] }
216
+ : null
217
+ )),
218
+ }
219
+
220
+ const variantIdBySku = (sku: string): string => {
221
+ const variant = variants.find((entry) => entry.sku === sku)
222
+ if (!variant) throw new Error(`[internal] no variant with sku ${sku}`)
223
+ return variant.id
224
+ }
225
+
226
+ const pricesOf = (sku: string) => prices
227
+ .filter((price) => price.variant?.id === variantIdBySku(sku))
228
+ .map((price) => `${price.kind}:${price.channelId}:${price.currencyCode}:${price.unitPriceNet}`)
229
+ .sort()
230
+
231
+ const offerIdByChannel = (channelId: string): string => {
232
+ const offer = offers.find((entry) => entry.channelId === channelId)
233
+ if (!offer) throw new Error(`[internal] no offer on channel ${channelId}`)
234
+ return offer.id
235
+ }
236
+
237
+ const seedManualPrice = (params: {
238
+ channelId: string
239
+ sku: string | null
240
+ amount: number
241
+ kind?: string
242
+ minQuantity?: number
243
+ }): string => {
244
+ const id = nextId('manual-price')
245
+ prices.push({
246
+ id,
247
+ offer: offerIdByChannel(params.channelId),
248
+ variant: params.sku ? { id: variantIdBySku(params.sku) } : null,
249
+ channelId: params.channelId,
250
+ currencyCode: 'USD',
251
+ kind: params.kind ?? 'manual',
252
+ minQuantity: params.minQuantity ?? 1,
253
+ unitPriceNet: params.amount,
254
+ })
255
+ return id
256
+ }
257
+
258
+ const dropPriceRow = (sku: string): void => {
259
+ const index = prices.findIndex((price) => price.variant?.id === variantIdBySku(sku))
260
+ if (index < 0) throw new Error(`[internal] no price for sku ${sku}`)
261
+ prices.splice(index, 1)
262
+ }
263
+
264
+ return {
265
+ client,
266
+ commandBus,
267
+ offers,
268
+ prices,
269
+ mappings,
270
+ deletedPriceIds,
271
+ deletedOfferIds,
272
+ pricesOf,
273
+ seedManualPrice,
274
+ dropPriceRow,
275
+ }
276
+ }
277
+
278
+ function buildMapping(
279
+ priceMappings: AkeneoPriceMapping[],
280
+ reconciliation?: Partial<AkeneoReconciliationSettings>,
281
+ ): AkeneoDataMapping {
282
+ const base = buildDefaultAkeneoMapping('products')
283
+ const products = base.settings?.products
284
+ if (!products) throw new Error('[internal] default Akeneo product mapping is missing')
285
+ return {
286
+ ...base,
287
+ settings: {
288
+ ...base.settings,
289
+ products: {
290
+ ...products,
291
+ priceMappings,
292
+ mediaMappings: [],
293
+ customFieldMappings: [],
294
+ syncAssociations: false,
295
+ createMissingChannels: false,
296
+ reconciliation: { ...products.reconciliation, ...reconciliation },
297
+ },
298
+ },
299
+ }
300
+ }
301
+
302
+ type PriceValue = { scope: string; amount: string; currency?: string }
303
+
304
+ function buildVariant(uuid: string, sku: string, values: Record<string, PriceValue[]>): AkeneoProduct {
305
+ const priceValues: AkeneoValues = {}
306
+ for (const [attributeCode, entries] of Object.entries(values)) {
307
+ priceValues[attributeCode] = entries.map((entry) => ({
308
+ locale: null,
309
+ scope: entry.scope,
310
+ data: [{ amount: entry.amount, currency: entry.currency ?? 'USD' }],
311
+ }))
312
+ }
313
+ return {
314
+ uuid,
315
+ identifier: sku,
316
+ parent: MODEL_CODE,
317
+ enabled: true,
318
+ values: {
319
+ sku: [{ locale: null, scope: null, data: sku }],
320
+ ...priceValues,
321
+ },
322
+ }
323
+ }
324
+
325
+ function buildSimpleProduct(uuid: string, sku: string, values: Record<string, PriceValue[]>): AkeneoProduct {
326
+ return { ...buildVariant(uuid, sku, values), parent: null }
327
+ }
328
+
329
+ const WEB_REGULAR: AkeneoPriceMapping = {
330
+ attributeCode: 'price',
331
+ priceKindCode: 'regular',
332
+ akeneoChannel: 'ecommerce',
333
+ localChannelCode: 'web',
334
+ }
335
+ const WEB_SALE: AkeneoPriceMapping = {
336
+ attributeCode: 'sale_price',
337
+ priceKindCode: 'sale',
338
+ akeneoChannel: 'ecommerce',
339
+ localChannelCode: 'web',
340
+ }
341
+ const B2B_SALE: AkeneoPriceMapping = {
342
+ attributeCode: 'price',
343
+ priceKindCode: 'sale',
344
+ akeneoChannel: 'b2b',
345
+ localChannelCode: 'b2b',
346
+ }
347
+
348
+ describe('akeneo catalog importer offer and price reconciliation', () => {
349
+ beforeEach(() => {
350
+ mockContainerResolve.mockReset()
351
+ mockFindOneWithDecryption.mockReset()
352
+ mockFindWithDecryption.mockReset()
353
+ })
354
+
355
+ it('keeps the prices of sibling variants that share a product-level offer', async () => {
356
+ const world = createCatalogWorld()
357
+ const importer = await createAkeneoImporter(world.client as never, scope)
358
+ const mapping = buildMapping([WEB_REGULAR])
359
+ const small = buildVariant('uuid-s', 'TEE-S', { price: [{ scope: 'ecommerce', amount: '10.00' }] })
360
+ const medium = buildVariant('uuid-m', 'TEE-M', { price: [{ scope: 'ecommerce', amount: '12.00' }] })
361
+ const large = buildVariant('uuid-l', 'TEE-L', { price: [{ scope: 'ecommerce', amount: '14.00' }] })
362
+
363
+ await importer.upsertProduct(small, mapping)
364
+ await importer.upsertProduct(medium, mapping)
365
+ await importer.upsertProduct(large, mapping)
366
+
367
+ expect(world.deletedPriceIds).toEqual([])
368
+ expect(world.offers).toHaveLength(1)
369
+ expect(world.pricesOf('TEE-S')).toEqual(['regular:channel-web:USD:10'])
370
+ expect(world.pricesOf('TEE-M')).toEqual(['regular:channel-web:USD:12'])
371
+ expect(world.pricesOf('TEE-L')).toEqual(['regular:channel-web:USD:14'])
372
+ })
373
+
374
+ it('is idempotent when the same variants are imported again', async () => {
375
+ const world = createCatalogWorld()
376
+ const importer = await createAkeneoImporter(world.client as never, scope)
377
+ const mapping = buildMapping([WEB_REGULAR])
378
+ const small = buildVariant('uuid-s', 'TEE-S', { price: [{ scope: 'ecommerce', amount: '10.00' }] })
379
+ const medium = buildVariant('uuid-m', 'TEE-M', { price: [{ scope: 'ecommerce', amount: '12.00' }] })
380
+
381
+ for (let round = 0; round < 3; round += 1) {
382
+ await importer.upsertProduct(small, mapping)
383
+ await importer.upsertProduct(medium, mapping)
384
+ }
385
+
386
+ const createdPrices = world.commandBus.execute.mock.calls.filter(([commandId]) => commandId === 'catalog.prices.create')
387
+ expect(createdPrices).toHaveLength(2)
388
+ expect(world.deletedPriceIds).toEqual([])
389
+ expect(world.prices).toHaveLength(2)
390
+ expect(world.mappings.filter((row) => row.entityType === 'catalog_product_price')).toHaveLength(2)
391
+ })
392
+
393
+ it('leaves sibling prices alone when one variant is re-imported on its own', async () => {
394
+ const world = createCatalogWorld()
395
+ const importer = await createAkeneoImporter(world.client as never, scope)
396
+ const mapping = buildMapping([WEB_REGULAR])
397
+ await importer.upsertProduct(buildVariant('uuid-s', 'TEE-S', { price: [{ scope: 'ecommerce', amount: '10.00' }] }), mapping)
398
+ await importer.upsertProduct(buildVariant('uuid-m', 'TEE-M', { price: [{ scope: 'ecommerce', amount: '12.00' }] }), mapping)
399
+
400
+ await importer.upsertProduct(buildVariant('uuid-s', 'TEE-S', { price: [{ scope: 'ecommerce', amount: '11.00' }] }), mapping)
401
+
402
+ expect(world.deletedPriceIds).toEqual([])
403
+ expect(world.pricesOf('TEE-S')).toEqual(['regular:channel-web:USD:11'])
404
+ expect(world.pricesOf('TEE-M')).toEqual(['regular:channel-web:USD:12'])
405
+ })
406
+
407
+ it('still deletes a price the mapping no longer produces for the imported variant', async () => {
408
+ const world = createCatalogWorld()
409
+ const importer = await createAkeneoImporter(world.client as never, scope)
410
+ const mapping = buildMapping([WEB_REGULAR, WEB_SALE])
411
+ await importer.upsertProduct(buildVariant('uuid-s', 'TEE-S', {
412
+ price: [{ scope: 'ecommerce', amount: '10.00' }],
413
+ sale_price: [{ scope: 'ecommerce', amount: '8.00' }],
414
+ }), mapping)
415
+ await importer.upsertProduct(buildVariant('uuid-m', 'TEE-M', {
416
+ price: [{ scope: 'ecommerce', amount: '12.00' }],
417
+ sale_price: [{ scope: 'ecommerce', amount: '9.00' }],
418
+ }), mapping)
419
+
420
+ await importer.upsertProduct(buildVariant('uuid-s', 'TEE-S', {
421
+ price: [{ scope: 'ecommerce', amount: '10.00' }],
422
+ }), mapping)
423
+
424
+ expect(world.deletedPriceIds).toHaveLength(1)
425
+ expect(world.pricesOf('TEE-S')).toEqual(['regular:channel-web:USD:10'])
426
+ expect(world.pricesOf('TEE-M')).toEqual(['regular:channel-web:USD:12', 'sale:channel-web:USD:9'])
427
+ })
428
+
429
+ it('keeps an offer and its sibling prices when the imported variant has no price on that channel', async () => {
430
+ const world = createCatalogWorld()
431
+ const importer = await createAkeneoImporter(world.client as never, scope)
432
+ const mapping = buildMapping([WEB_REGULAR, B2B_SALE])
433
+ await importer.upsertProduct(buildVariant('uuid-s', 'TEE-S', {
434
+ price: [{ scope: 'ecommerce', amount: '10.00' }, { scope: 'b2b', amount: '7.00' }],
435
+ }), mapping)
436
+
437
+ await importer.upsertProduct(buildVariant('uuid-m', 'TEE-M', {
438
+ price: [{ scope: 'ecommerce', amount: '12.00' }],
439
+ }), mapping)
440
+
441
+ expect(world.deletedOfferIds).toEqual([])
442
+ expect(world.deletedPriceIds).toEqual([])
443
+ expect(world.offers).toHaveLength(2)
444
+ expect(world.pricesOf('TEE-S')).toEqual(['regular:channel-web:USD:10', 'sale:channel-b2b:USD:7'])
445
+ expect(world.pricesOf('TEE-M')).toEqual(['regular:channel-web:USD:12'])
446
+ })
447
+
448
+ it('removes the imported variant prices from an offer it left and keeps the offer for its siblings', async () => {
449
+ const world = createCatalogWorld()
450
+ const importer = await createAkeneoImporter(world.client as never, scope)
451
+ const mapping = buildMapping([WEB_REGULAR, B2B_SALE])
452
+ const bothChannels = { price: [{ scope: 'ecommerce', amount: '10.00' }, { scope: 'b2b', amount: '7.00' }] }
453
+ await importer.upsertProduct(buildVariant('uuid-s', 'TEE-S', bothChannels), mapping)
454
+ await importer.upsertProduct(buildVariant('uuid-m', 'TEE-M', bothChannels), mapping)
455
+
456
+ await importer.upsertProduct(buildVariant('uuid-s', 'TEE-S', {
457
+ price: [{ scope: 'ecommerce', amount: '10.00' }],
458
+ }), mapping)
459
+
460
+ expect(world.deletedOfferIds).toEqual([])
461
+ expect(world.deletedPriceIds).toHaveLength(1)
462
+ expect(world.offers).toHaveLength(2)
463
+ expect(world.pricesOf('TEE-S')).toEqual(['regular:channel-web:USD:10'])
464
+ expect(world.pricesOf('TEE-M')).toEqual(['regular:channel-web:USD:10', 'sale:channel-b2b:USD:7'])
465
+ })
466
+
467
+ it('deletes an offer once no variant has a price on it', async () => {
468
+ const world = createCatalogWorld()
469
+ const importer = await createAkeneoImporter(world.client as never, scope)
470
+ const mapping = buildMapping([WEB_REGULAR, B2B_SALE])
471
+ const bothChannels = { price: [{ scope: 'ecommerce', amount: '10.00' }, { scope: 'b2b', amount: '7.00' }] }
472
+ const webOnly = { price: [{ scope: 'ecommerce', amount: '10.00' }] }
473
+ await importer.upsertProduct(buildVariant('uuid-s', 'TEE-S', bothChannels), mapping)
474
+ await importer.upsertProduct(buildVariant('uuid-m', 'TEE-M', bothChannels), mapping)
475
+
476
+ await importer.upsertProduct(buildVariant('uuid-s', 'TEE-S', webOnly), mapping)
477
+ expect(world.deletedOfferIds).toEqual([])
478
+ await importer.upsertProduct(buildVariant('uuid-m', 'TEE-M', webOnly), mapping)
479
+
480
+ expect(world.deletedOfferIds).toHaveLength(1)
481
+ expect(world.offers).toHaveLength(1)
482
+ expect(world.offers[0]?.channelId).toBe('channel-web')
483
+ expect(world.pricesOf('TEE-S')).toEqual(['regular:channel-web:USD:10'])
484
+ expect(world.pricesOf('TEE-M')).toEqual(['regular:channel-web:USD:10'])
485
+ })
486
+
487
+ it('deletes the offer of a simple product whose channel price was removed', async () => {
488
+ const world = createCatalogWorld()
489
+ const importer = await createAkeneoImporter(world.client as never, scope)
490
+ const mapping = buildMapping([WEB_REGULAR, B2B_SALE])
491
+ await importer.upsertProduct(buildSimpleProduct('uuid-mug', 'MUG', {
492
+ price: [{ scope: 'ecommerce', amount: '5.00' }, { scope: 'b2b', amount: '4.00' }],
493
+ }), mapping)
494
+
495
+ await importer.upsertProduct(buildSimpleProduct('uuid-mug', 'MUG', {
496
+ price: [{ scope: 'ecommerce', amount: '5.00' }],
497
+ }), mapping)
498
+
499
+ expect(world.deletedOfferIds).toHaveLength(1)
500
+ expect(world.deletedPriceIds).toHaveLength(1)
501
+ expect(world.offers).toHaveLength(1)
502
+ expect(world.pricesOf('MUG')).toEqual(['regular:channel-web:USD:5'])
503
+ })
504
+
505
+ it('keeps stale prices and offers when price and offer reconciliation are switched off', async () => {
506
+ const world = createCatalogWorld()
507
+ const importer = await createAkeneoImporter(world.client as never, scope)
508
+ const mapping = buildMapping([WEB_REGULAR, B2B_SALE], { deleteMissingPrices: false, deleteMissingOffers: false })
509
+ await importer.upsertProduct(buildSimpleProduct('uuid-mug', 'MUG', {
510
+ price: [{ scope: 'ecommerce', amount: '5.00' }, { scope: 'b2b', amount: '4.00' }],
511
+ }), mapping)
512
+
513
+ await importer.upsertProduct(buildSimpleProduct('uuid-mug', 'MUG', {
514
+ price: [{ scope: 'ecommerce', amount: '5.00' }],
515
+ }), mapping)
516
+
517
+ expect(world.deletedOfferIds).toEqual([])
518
+ expect(world.deletedPriceIds).toEqual([])
519
+ expect(world.offers).toHaveLength(2)
520
+ })
521
+
522
+ it('keeps stale prices and offers of a variant product when price and offer reconciliation are switched off', async () => {
523
+ const world = createCatalogWorld()
524
+ const importer = await createAkeneoImporter(world.client as never, scope)
525
+ const mapping = buildMapping([WEB_REGULAR, B2B_SALE], { deleteMissingPrices: false, deleteMissingOffers: false })
526
+ const bothChannels = { price: [{ scope: 'ecommerce', amount: '10.00' }, { scope: 'b2b', amount: '7.00' }] }
527
+ await importer.upsertProduct(buildVariant('uuid-s', 'TEE-S', bothChannels), mapping)
528
+ await importer.upsertProduct(buildVariant('uuid-m', 'TEE-M', bothChannels), mapping)
529
+
530
+ await importer.upsertProduct(buildVariant('uuid-s', 'TEE-S', { price: [{ scope: 'ecommerce', amount: '10.00' }] }), mapping)
531
+
532
+ expect(world.deletedOfferIds).toEqual([])
533
+ expect(world.deletedPriceIds).toEqual([])
534
+ expect(world.prices).toHaveLength(4)
535
+ })
536
+
537
+ it('removes the leaving variant price under the offer switch alone and keeps it under the price switch alone', async () => {
538
+ const bothChannels = { price: [{ scope: 'ecommerce', amount: '10.00' }, { scope: 'b2b', amount: '7.00' }] }
539
+ const webOnly = { price: [{ scope: 'ecommerce', amount: '10.00' }] }
540
+
541
+ const offersOnly = createCatalogWorld()
542
+ const offersOnlyImporter = await createAkeneoImporter(offersOnly.client as never, scope)
543
+ const offersOnlyMapping = buildMapping([WEB_REGULAR, B2B_SALE], { deleteMissingPrices: false, deleteMissingOffers: true })
544
+ await offersOnlyImporter.upsertProduct(buildVariant('uuid-s', 'TEE-S', bothChannels), offersOnlyMapping)
545
+ await offersOnlyImporter.upsertProduct(buildVariant('uuid-m', 'TEE-M', bothChannels), offersOnlyMapping)
546
+ await offersOnlyImporter.upsertProduct(buildVariant('uuid-s', 'TEE-S', webOnly), offersOnlyMapping)
547
+
548
+ expect(offersOnly.deletedOfferIds).toEqual([])
549
+ expect(offersOnly.pricesOf('TEE-S')).toEqual(['regular:channel-web:USD:10'])
550
+ expect(offersOnly.pricesOf('TEE-M')).toEqual(['regular:channel-web:USD:10', 'sale:channel-b2b:USD:7'])
551
+
552
+ const pricesOnly = createCatalogWorld()
553
+ const pricesOnlyImporter = await createAkeneoImporter(pricesOnly.client as never, scope)
554
+ const pricesOnlyMapping = buildMapping([WEB_REGULAR, B2B_SALE], { deleteMissingPrices: true, deleteMissingOffers: false })
555
+ await pricesOnlyImporter.upsertProduct(buildVariant('uuid-s', 'TEE-S', bothChannels), pricesOnlyMapping)
556
+ await pricesOnlyImporter.upsertProduct(buildVariant('uuid-m', 'TEE-M', bothChannels), pricesOnlyMapping)
557
+ await pricesOnlyImporter.upsertProduct(buildVariant('uuid-s', 'TEE-S', webOnly), pricesOnlyMapping)
558
+
559
+ expect(pricesOnly.deletedOfferIds).toEqual([])
560
+ expect(pricesOnly.deletedPriceIds).toEqual([])
561
+ expect(pricesOnly.pricesOf('TEE-S')).toEqual(['regular:channel-web:USD:10', 'sale:channel-b2b:USD:7'])
562
+ })
563
+
564
+ it('reconciles each currency of the imported variant without touching the sibling', async () => {
565
+ const world = createCatalogWorld()
566
+ const importer = await createAkeneoImporter(world.client as never, scope)
567
+ const mapping = buildMapping([WEB_REGULAR])
568
+ const twoCurrencies = (uuid: string, sku: string): AkeneoProduct => ({
569
+ ...buildVariant(uuid, sku, {}),
570
+ values: {
571
+ sku: [{ locale: null, scope: null, data: sku }],
572
+ price: [{
573
+ locale: null,
574
+ scope: 'ecommerce',
575
+ data: [{ amount: '10.00', currency: 'USD' }, { amount: '9.00', currency: 'EUR' }],
576
+ }],
577
+ },
578
+ })
579
+ await importer.upsertProduct(twoCurrencies('uuid-s', 'TEE-S'), mapping)
580
+ await importer.upsertProduct(twoCurrencies('uuid-m', 'TEE-M'), mapping)
581
+
582
+ await importer.upsertProduct(buildVariant('uuid-s', 'TEE-S', { price: [{ scope: 'ecommerce', amount: '10.00' }] }), mapping)
583
+
584
+ expect(world.deletedPriceIds).toHaveLength(1)
585
+ expect(world.pricesOf('TEE-S')).toEqual(['regular:channel-web:USD:10'])
586
+ expect(world.pricesOf('TEE-M')).toEqual(['regular:channel-web:EUR:9', 'regular:channel-web:USD:10'])
587
+ })
588
+
589
+ it('never deletes prices the importer did not create while another variant keeps the offer', async () => {
590
+ const world = createCatalogWorld()
591
+ const importer = await createAkeneoImporter(world.client as never, scope)
592
+ const mapping = buildMapping([WEB_REGULAR, B2B_SALE])
593
+ const bothChannels = { price: [{ scope: 'ecommerce', amount: '10.00' }, { scope: 'b2b', amount: '7.00' }] }
594
+ await importer.upsertProduct(buildVariant('uuid-s', 'TEE-S', bothChannels), mapping)
595
+ await importer.upsertProduct(buildVariant('uuid-m', 'TEE-M', { price: [{ scope: 'ecommerce', amount: '12.00' }] }), mapping)
596
+ expect(world.deletedOfferIds).toEqual([])
597
+ const siblingManualPriceId = world.seedManualPrice({ channelId: 'channel-b2b', sku: 'TEE-M', amount: 6 })
598
+ const ownManualPriceId = world.seedManualPrice({ channelId: 'channel-b2b', sku: 'TEE-S', amount: 5 })
599
+ const ownWebManualPriceId = world.seedManualPrice({ channelId: 'channel-web', sku: 'TEE-S', amount: 4 })
600
+
601
+ await importer.upsertProduct(buildVariant('uuid-s', 'TEE-S', { price: [{ scope: 'ecommerce', amount: '10.00' }] }), mapping)
602
+
603
+ expect(world.deletedOfferIds).toEqual([])
604
+ expect(world.deletedPriceIds).toHaveLength(1)
605
+ expect(world.prices.map((price) => price.id)).toEqual(
606
+ expect.arrayContaining([siblingManualPriceId, ownManualPriceId, ownWebManualPriceId]),
607
+ )
608
+ expect(world.pricesOf('TEE-S')).toEqual(['manual:channel-b2b:USD:5', 'manual:channel-web:USD:4', 'regular:channel-web:USD:10'])
609
+ })
610
+
611
+ it('does not let a product-level price keep an offer no variant is priced on', async () => {
612
+ const world = createCatalogWorld()
613
+ const importer = await createAkeneoImporter(world.client as never, scope)
614
+ const mapping = buildMapping([WEB_REGULAR, B2B_SALE])
615
+ await importer.upsertProduct(buildVariant('uuid-s', 'TEE-S', {
616
+ price: [{ scope: 'ecommerce', amount: '10.00' }, { scope: 'b2b', amount: '7.00' }],
617
+ }), mapping)
618
+ await importer.upsertProduct(buildVariant('uuid-m', 'TEE-M', { price: [{ scope: 'ecommerce', amount: '12.00' }] }), mapping)
619
+ expect(world.deletedOfferIds).toEqual([])
620
+ world.seedManualPrice({ channelId: 'channel-b2b', sku: null, amount: 6 })
621
+
622
+ await importer.upsertProduct(buildVariant('uuid-s', 'TEE-S', { price: [{ scope: 'ecommerce', amount: '10.00' }] }), mapping)
623
+
624
+ expect(world.deletedOfferIds).toHaveLength(1)
625
+ expect(world.offers).toHaveLength(1)
626
+ expect(world.prices.every((price) => price.channelId === 'channel-web')).toBe(true)
627
+ })
628
+
629
+ it('recreates a price whose mapping points at a deleted row and re-points the mapping', async () => {
630
+ const world = createCatalogWorld()
631
+ const importer = await createAkeneoImporter(world.client as never, scope)
632
+ const mapping = buildMapping([WEB_REGULAR])
633
+ const small = buildVariant('uuid-s', 'TEE-S', { price: [{ scope: 'ecommerce', amount: '10.00' }] })
634
+ await importer.upsertProduct(small, mapping)
635
+ await importer.upsertProduct(buildVariant('uuid-m', 'TEE-M', { price: [{ scope: 'ecommerce', amount: '12.00' }] }), mapping)
636
+ expect(world.deletedPriceIds).toEqual([])
637
+ world.dropPriceRow('TEE-S')
638
+
639
+ await importer.upsertProduct(small, mapping)
640
+
641
+ expect(world.pricesOf('TEE-S')).toEqual(['regular:channel-web:USD:10'])
642
+ expect(world.pricesOf('TEE-M')).toEqual(['regular:channel-web:USD:12'])
643
+ const priceMappings = world.mappings.filter((row) => row.entityType === 'catalog_product_price')
644
+ expect(priceMappings).toHaveLength(2)
645
+ expect(priceMappings.every((row) => world.prices.some((price) => price.id === row.localId))).toBe(true)
646
+ })
647
+
648
+ it('adopts an unmapped price left by an interrupted import instead of creating a twin', async () => {
649
+ const world = createCatalogWorld()
650
+ const importer = await createAkeneoImporter(world.client as never, scope)
651
+ const mapping = buildMapping([WEB_REGULAR])
652
+ const small = buildVariant('uuid-s', 'TEE-S', { price: [{ scope: 'ecommerce', amount: '10.00' }] })
653
+ await importer.upsertProduct(small, mapping)
654
+ const stalePriceMapping = world.mappings.find((row) => row.entityType === 'catalog_product_price')
655
+ if (!stalePriceMapping) throw new Error('[internal] price mapping was not stored')
656
+ const livePriceId = stalePriceMapping.localId
657
+ stalePriceMapping.localId = 'price-deleted-earlier'
658
+
659
+ await importer.upsertProduct(small, mapping)
660
+
661
+ const createdPrices = world.commandBus.execute.mock.calls.filter(([commandId]) => commandId === 'catalog.prices.create')
662
+ expect(createdPrices).toHaveLength(1)
663
+ expect(world.prices.map((price) => price.id)).toEqual([livePriceId])
664
+ expect(stalePriceMapping.localId).toBe(livePriceId)
665
+ })
666
+
667
+ it('leaves a manual tier price alone when the mapped price row is gone', async () => {
668
+ const world = createCatalogWorld()
669
+ const importer = await createAkeneoImporter(world.client as never, scope)
670
+ const mapping = buildMapping([WEB_REGULAR])
671
+ const small = buildVariant('uuid-s', 'TEE-S', { price: [{ scope: 'ecommerce', amount: '10.00' }] })
672
+ await importer.upsertProduct(small, mapping)
673
+ world.dropPriceRow('TEE-S')
674
+ const tierPriceId = world.seedManualPrice({
675
+ channelId: 'channel-web',
676
+ sku: 'TEE-S',
677
+ amount: 8,
678
+ kind: 'regular',
679
+ minQuantity: 10,
680
+ })
681
+
682
+ await importer.upsertProduct(small, mapping)
683
+
684
+ const tierPrice = world.prices.find((price) => price.id === tierPriceId)
685
+ expect(tierPrice).toMatchObject({ minQuantity: 10, unitPriceNet: 8 })
686
+ expect(world.prices).toHaveLength(2)
687
+ const priceMapping = world.mappings.find((row) => row.entityType === 'catalog_product_price')
688
+ expect(priceMapping?.localId).not.toBe(tierPriceId)
689
+ })
690
+
691
+ it('scopes every price lookup to the tenant and organization and the upsert lookup to the imported variant', async () => {
692
+ const world = createCatalogWorld()
693
+ const importer = await createAkeneoImporter(world.client as never, scope)
694
+ const mapping = buildMapping([WEB_REGULAR, B2B_SALE])
695
+ await importer.upsertProduct(buildVariant('uuid-s', 'TEE-S', {
696
+ price: [{ scope: 'ecommerce', amount: '10.00' }, { scope: 'b2b', amount: '7.00' }],
697
+ }), mapping)
698
+ await importer.upsertProduct(buildVariant('uuid-s', 'TEE-S', { price: [{ scope: 'ecommerce', amount: '10.00' }] }), mapping)
699
+
700
+ const priceLookups = mockFindWithDecryption.mock.calls
701
+ .filter(([, entity]) => entity === CatalogProductPrice)
702
+ .map(([, , where]) => where as Record<string, unknown>)
703
+ expect(priceLookups.length).toBeGreaterThan(0)
704
+ for (const where of priceLookups) {
705
+ expect(where).toMatchObject({ organizationId: 'org-1', tenantId: 'tenant-1' })
706
+ expect(typeof where.offer).toBe('string')
707
+ }
708
+ const variantId = world.prices[0]?.variant?.id
709
+ expect(priceLookups.filter((where) => where.variant !== undefined).every((where) => where.variant === variantId)).toBe(true)
710
+ expect(priceLookups.some((where) => where.variant === variantId)).toBe(true)
711
+ })
712
+ })