diff --git a/index.js b/index.js index 5b0f3e6..14ff9aa 100644 --- a/index.js +++ b/index.js @@ -76,7 +76,7 @@ async function syncShopIcon() { } const jobs = [ - new CronJob('0 */5 * * * *', () => runtime.track(() => + new CronJob('0 * * * * *', () => runtime.track(() => runtime.withRenewedLock('prestashop-orders-puller', JOB_LOCK_TTL_SECONDS, runOrdersPuller) )), new CronJob('0 */3 * * * *', () => runtime.track(() => diff --git a/methods/product/get_metadata.js b/methods/product/get_metadata.js new file mode 100644 index 0000000..2dda44c --- /dev/null +++ b/methods/product/get_metadata.js @@ -0,0 +1,64 @@ +const PrestashopApi = require('../../src/PrestaApi'); +const { isLegacyApi } = require('../../src/utils'); +const { loadConfig, isConfigured } = require('../../src/module-config'); +const { PERMISSIONS, requirePermission } = require('../../src/register-permissions'); +const { findMetadataBySourceAndSku } = require('../../src/product-metadata'); + +const MAX_PRODUCTS = 100; +const METADATA_CONCURRENCY = 5; + +function normalizeRequestProduct(value) { + const sourceId = String(value?.sourceId ?? '').trim(); + const sku = String(value?.sku ?? '').trim(); + if (!sourceId || !sku) return null; + return { sourceId, sku }; +} + +function uniqueProducts(products) { + const seen = new Set(); + const result = []; + for (const value of Array.isArray(products) ? products : []) { + const product = normalizeRequestProduct(value); + if (!product) continue; + const key = `${product.sourceId}\u0000${product.sku.toUpperCase()}`; + if (seen.has(key)) continue; + seen.add(key); + result.push(product); + } + return result; +} + +async function mapWithConcurrency(values, concurrency, worker) { + let nextIndex = 0; + const runners = Array.from({ length: Math.min(concurrency, values.length) }, async () => { + while (nextIndex < values.length) { + const index = nextIndex++; + await worker(values[index], index); + } + }); + await Promise.all(runners); +} + +module.exports = async function(params, ctx) { + requirePermission(PERMISSIONS.ORDERS_VIEW, ctx); + + const products = uniqueProducts(params?.products); + if (products.length === 0) return { results: [] }; + if (products.length > MAX_PRODUCTS) throw new Error('products exceeds the 100 item limit'); + + const config = await loadConfig(); + if (!isConfigured(config)) return { results: [] }; + + const api = new PrestashopApi(config.apiUrl, config.apiKey, isLegacyApi(config.versionCode)); + const results = new Array(products.length); + await mapWithConcurrency(products, METADATA_CONCURRENCY, async (product, index) => { + try { + const metadata = await findMetadataBySourceAndSku(api, product); + if (metadata) results[index] = { ...product, ...metadata }; + } catch (_) { /* one product must not block the remaining metadata batch */ } + }); + + return { results: results.filter(Boolean) }; +}; + +module.exports._private = { MAX_PRODUCTS, METADATA_CONCURRENCY, uniqueProducts, mapWithConcurrency }; diff --git a/module.json b/module.json index 4b4c3c2..37df32f 100644 --- a/module.json +++ b/module.json @@ -1,6 +1,6 @@ { "name": "core/prestashop", - "version": "1.1.5", + "version": "1.1.7", "singleton": false, "dependsOn": [ "core/orders", diff --git a/package-lock.json b/package-lock.json index c27a01e..b892c1a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "core.prestashop", - "version": "1.1.5", + "version": "1.1.7", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "core.prestashop", - "version": "1.1.5", + "version": "1.1.7", "license": "ISC", "dependencies": { "@orbito/api-lib": "^3.3.3", diff --git a/package.json b/package.json index 9d12733..99df7ee 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "core.prestashop", - "version": "1.1.5", + "version": "1.1.7", "description": "Integracja zamówień i płatności PrestaShop", "main": "index.js", "scripts": { diff --git a/src/OrderImporter.js b/src/OrderImporter.js index 7ab12ca..4352257 100644 --- a/src/OrderImporter.js +++ b/src/OrderImporter.js @@ -2,6 +2,7 @@ const { Log, Core } = require("@orbito/api-lib"); const PsOrder = require('./models/PsOrder'); const { resolveStatusId, normalizeStatusId } = require('./status-mapper'); const { paymentTransactionId, parsePrestashopDate, upsertMapping } = require('./automation-jobs'); +const { resolveProductMetadata } = require('./product-metadata'); function getPSMultiLangField(param, langId) { if (Array.isArray(param)) { @@ -76,14 +77,25 @@ async function importFromPSOrder(orderId, api, config) { if (imgUrl) p.coverImageUrl = imgUrl; } catch (_) { /* no image available */ } + let productCombination = null; if (parseInt(product.product_attribute_id) > 0) { const combination = await api.getProductCombination(product.product_attribute_id); if (combination) { + productCombination = combination; const w = parseFloat(combination.weight); if (!isNaN(w)) p.weight = w; } } + try { + Object.assign(p, await resolveProductMetadata(api, psProduct, { + sourceId: p.sourceId, + sku: p.sku, + combination: productCombination, + requiresCombination: parseInt(product.product_attribute_id) > 0, + })); + } catch (_) { /* optional product metadata must not block order import */ } + if (psProduct.type == "pack" && psProduct.associations.product_bundle) { p.isPack = true; p.pack = []; @@ -98,15 +110,26 @@ async function importFromPSOrder(orderId, api, config) { qty: parseFloat(packItem.quantity) }; + let packCombination = null; if (parseInt(packItem.id_product_attribute) > 0) { const combination = await api.getProductCombination(packItem.id_product_attribute); if (combination) { + packCombination = combination; const w = parseFloat(combination.weight); if (!isNaN(w)) pData.weight = w; pData.sku = combination.reference || pData.sku; } } + try { + Object.assign(pData, await resolveProductMetadata(api, psItem, { + sourceId: pData.sourceId, + sku: pData.sku, + combination: packCombination, + requiresCombination: parseInt(packItem.id_product_attribute) > 0, + })); + } catch (_) { /* optional product metadata must not block order import */ } + try { const imgUrl = await api.getProductCoverImageUrl(packItem.id); if (imgUrl) pData.coverImageUrl = imgUrl; @@ -119,19 +142,22 @@ async function importFromPSOrder(orderId, api, config) { products.push(p); } - await Promise.all( - products - .filter(p => p.sourceId && p.name) - .map(p => Core.callModule( 'core/products', 'upsert', { + const productsForUpsert = products.flatMap(product => [product, ...(Array.isArray(product.pack) ? product.pack : [])]); + await Promise.all(productsForUpsert + .filter(product => product.sourceId && product.name) + .map(product => { + const upsert = { // własny kod modułu bierzemy z core (po rejestracji), nie z hardcode'u sourceModule: Core.getModuleInfo().code, - sourceId: String(p.sourceId), - sku: p.sku || '', - name: p.name, - unitPrice: p.unitPrice, - ean: p.ean, - coverImageUrl: p.coverImageUrl || undefined, - }).catch(() => {})) + sourceId: String(product.sourceId), + sku: product.sku || '', + name: product.name, + }; + for (const field of ['unitPrice', 'ean', 'coverImageUrl', 'brand', 'warehouseLocation']) { + if (Object.hasOwn(product, field) && product[field] !== undefined) upsert[field] = product[field]; + } + return Core.callModule('core/products', 'upsert', upsert).catch(() => {}); + }) ); const fallbackStatusId = await resolveImportStatusId(config); diff --git a/src/PrestaApi.js b/src/PrestaApi.js index 0f1afb3..a9cd0af 100644 --- a/src/PrestaApi.js +++ b/src/PrestaApi.js @@ -199,6 +199,61 @@ module.exports = class PrestashopApi { return combination; } + async getManufacturer(manufacturerId) { + const id = String(manufacturerId || '').trim(); + if (!id) return null; + + const cacheKey = "manufacturer_" + id; + let manufacturer = this.cache.get(cacheKey); + if (!manufacturer) { + const res = await this.makeRequest('manufacturers/' + id, 'GET', { output_format: "JSON" }); + manufacturer = res.manufacturer || null; + if (manufacturer) this.cache.set(cacheKey, manufacturer); + } + + return manufacturer; + } + + async findProductCombinationsByReference(productId, reference) { + const id = String(productId || '').trim(); + const sku = String(reference || '').trim(); + if (!/^\d+$/.test(id) || !sku || /[\[\],|%]/.test(sku)) return null; + + const cacheKey = `product_combinations_${id}_${sku}`; + const cached = this.cache.get(cacheKey); + if (cached) return cached; + + const res = await this.makeRequest('combinations', 'GET', { + output_format: "JSON", + display: 'full', + 'filter[id_product]': `[${id}]`, + 'filter[reference]': `[${sku}]`, + }); + const combinations = Array.isArray(res.combinations) ? res.combinations : []; + this.cache.set(cacheKey, combinations); + return combinations; + } + + async getStockAvailabilities(productId, productAttributeId = 0) { + const id = String(productId || '').trim(); + const attributeId = String(productAttributeId || '0').trim(); + if (!/^\d+$/.test(id) || !/^\d+$/.test(attributeId)) return []; + + const cacheKey = `stock_availabilities_${id}_${attributeId}`; + const cached = this.cache.get(cacheKey); + if (cached) return cached; + + const res = await this.makeRequest('stock_availables', 'GET', { + output_format: "JSON", + display: 'full', + 'filter[id_product]': `[${id}]`, + 'filter[id_product_attribute]': `[${attributeId}]`, + }); + const stockAvailabilities = Array.isArray(res.stock_availables) ? res.stock_availables : []; + this.cache.set(cacheKey, stockAvailabilities); + return stockAvailabilities; + } + async getStatuses() { let cacheKey = "statuses"; let statuses = this.cache.get(cacheKey); diff --git a/src/product-metadata.js b/src/product-metadata.js new file mode 100644 index 0000000..7543ec1 --- /dev/null +++ b/src/product-metadata.js @@ -0,0 +1,156 @@ +const MAX_METADATA_LENGTH = 200; + +function normalizeSku(value) { + const sku = String(value ?? '').trim(); + if (!sku || sku.startsWith('~:')) return ''; + return sku.toUpperCase(); +} + +function sameId(left, right) { + return String(left ?? '').trim() === String(right ?? '').trim(); +} + +function metadataText(value) { + if (typeof value !== 'string' || value.length > MAX_METADATA_LENGTH) return undefined; + return value; +} + +function ownMetadataField(record, field) { + if (!record || !Object.hasOwn(record, field)) return undefined; + return metadataText(record[field]); +} + +async function resolveBrand(api, product) { + const inlineName = ownMetadataField(product, 'manufacturer_name'); + if (inlineName !== undefined) return inlineName; + + const manufacturerId = String(product?.id_manufacturer ?? '').trim(); + if (!manufacturerId) return undefined; + if (!/^\d+$/.test(manufacturerId)) return undefined; + if (manufacturerId === '0') return ''; + + const manufacturer = await api.getManufacturer(manufacturerId); + return ownMetadataField(manufacturer, 'name'); +} + +function chooseStockLocation(stockAvailabilities, product, productAttributeId) { + const expectedProductId = String(product?.id ?? '').trim(); + const expectedAttributeId = String(productAttributeId ?? '0').trim(); + const candidates = (Array.isArray(stockAvailabilities) ? stockAvailabilities : []) + .filter(stock => sameId(stock.id_product, expectedProductId) + && sameId(stock.id_product_attribute, expectedAttributeId)) + .map(stock => ({ stock, location: ownMetadataField(stock, 'location') })) + .filter(candidate => candidate.location !== undefined); + + if (candidates.length === 0) return { status: 'missing' }; + + const defaultShopId = String(product?.id_shop_default ?? '').trim(); + if (defaultShopId) { + const forDefaultShop = candidates.filter(({ stock }) => sameId(stock.id_shop, defaultShopId)); + if (forDefaultShop.length === 1) return { status: 'found', location: forDefaultShop[0].location }; + if (forDefaultShop.length > 1) return { status: 'ambiguous' }; + } + + return candidates.length === 1 + ? { status: 'found', location: candidates[0].location } + : { status: 'ambiguous' }; +} + +async function resolveStockLocation(api, product, productAttributeId) { + try { + const stocks = await api.getStockAvailabilities(product.id, productAttributeId); + return chooseStockLocation(stocks, product, productAttributeId); + } catch (_) { + return { status: 'unavailable' }; + } +} + +function legacyLocationFallback(record, stockResult) { + const location = ownMetadataField(record, 'location'); + if (location !== '') return location; + return ['unavailable', 'ambiguous'].includes(stockResult.status) ? undefined : location; +} + +async function resolveWarehouseLocation(api, product, combination) { + if (combination) { + const combinationStockLocation = await resolveStockLocation(api, product, combination.id); + if (combinationStockLocation.status === 'found') return combinationStockLocation.location; + + const combinationLocation = legacyLocationFallback(combination, combinationStockLocation); + if (combinationLocation !== undefined) return combinationLocation; + + if (['unavailable', 'ambiguous'].includes(combinationStockLocation.status)) return undefined; + } + + const productStockLocation = await resolveStockLocation(api, product, 0); + if (productStockLocation.status === 'found') return productStockLocation.location; + + return legacyLocationFallback(product, productStockLocation); +} + +function isMatchingCombination(product, combination, normalizedSku) { + return !!combination + && sameId(combination.id_product, product?.id) + && normalizeSku(combination.reference) === normalizedSku; +} + +async function resolveProductMetadata(api, product, { + sourceId = null, sku, combination = null, requiresCombination = false, +} = {}) { + const normalizedSku = normalizeSku(sku); + if (!product || !normalizedSku) return {}; + if (sourceId != null && !sameId(product.id, sourceId)) return {}; + + if (combination) { + if (!isMatchingCombination(product, combination, normalizedSku)) return {}; + } else if (requiresCombination) { + return {}; + } else if (normalizeSku(product.reference) !== normalizedSku) { + return {}; + } + + const metadata = {}; + try { + const brand = await resolveBrand(api, product); + if (brand !== undefined) metadata.brand = brand; + } catch (_) { /* optional manufacturer data must not block metadata sync */ } + + const warehouseLocation = await resolveWarehouseLocation(api, product, combination); + if (warehouseLocation !== undefined) metadata.warehouseLocation = warehouseLocation; + return metadata; +} + +async function findMetadataBySourceAndSku(api, { sourceId, sku } = {}) { + const id = String(sourceId ?? '').trim(); + const normalizedSku = normalizeSku(sku); + if (!/^\d+$/.test(id) || !normalizedSku) return null; + + const product = await api.getProduct(id); + if (!product || !sameId(product.id, id)) return null; + + const candidates = []; + if (normalizeSku(product.reference) === normalizedSku) { + candidates.push(null); + } + + const knownCombinations = product.associations?.combinations; + const combinations = Array.isArray(knownCombinations) && knownCombinations.length === 0 + ? [] + : await api.findProductCombinationsByReference(id, sku); + if (combinations === null) return null; + for (const combination of combinations) { + if (isMatchingCombination(product, combination, normalizedSku)) candidates.push(combination); + } + + if (candidates.length !== 1) return null; + const metadata = await resolveProductMetadata(api, product, { sourceId: id, sku, combination: candidates[0] }); + return Object.keys(metadata).length > 0 ? metadata : null; +} + +module.exports = { + MAX_METADATA_LENGTH, + normalizeSku, + chooseStockLocation, + resolveProductMetadata, + findMetadataBySourceAndSku, +}; diff --git a/test/order-importer-metadata.test.js b/test/order-importer-metadata.test.js new file mode 100644 index 0000000..cd3bb1f --- /dev/null +++ b/test/order-importer-metadata.test.js @@ -0,0 +1,90 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const Module = require('node:module'); +const path = require('node:path'); + +function loadImporter(Core, PsOrder) { + const importerPath = path.resolve(__dirname, '../src/OrderImporter.js'); + const originalLoad = Module._load; + Module._load = function(request, parent, isMain) { + if (request === '@orbito/api-lib') return { Core, Log: { debug() {}, info() {}, warn() {}, error() {} } }; + if (request === './models/PsOrder') return PsOrder; + return originalLoad.call(this, request, parent, isMain); + }; + delete require.cache[importerPath]; + try { + return require(importerPath); + } finally { + Module._load = originalLoad; + } +} + +test('order import upserts verified metadata for the ordered product and pack items', async () => { + const upserts = []; + const Core = { + getModuleInfo: () => ({ code: 'core/prestashop' }), + callModule: async (module, method, params) => { + if (module === 'core/orders' && method === 'status.search') return { results: [{ _id: '000000000000000000000001', positionInGroup: 1 }] }; + if (module === 'core/products' && method === 'upsert') { + upserts.push(params); + return {}; + } + if (module === 'core/orders' && method === 'create') return { _id: 'order-1' }; + throw new Error(`Unexpected core call: ${module}.${method}`); + }, + }; + const PsOrder = { findOne: async () => null, update: async () => {} }; + const { importFromPSOrder } = loadImporter(Core, PsOrder); + const order = { + id: '1', reference: 'PS-1', current_state: '1', id_customer: '5', id_address_delivery: '6', + id_currency: '1', id_carrier: '0', payment: 'Card', date_add: '2026-01-01 10:00:00', + total_discounts: '0', total_paid_real: '0', total_shipping_tax_excl: '0', + associations: { + order_rows: [{ + product_id: '10', product_attribute_id: '100', product_name: 'Pack', product_reference: 'PACK-V', + product_ean13: '', unit_price_tax_excl: '10', unit_price_tax_incl: '12.3', product_quantity: '1', + }], + }, + }; + const products = { + '10': { + id: '10', name: 'Pack', reference: 'PACK-BASE', manufacturer_name: 'Pack Brand', location: 'BASE-BIN', + weight: '1', type: 'pack', associations: { product_bundle: [{ id: '20', id_product_attribute: '200', quantity: '2' }] }, + }, + '20': { + id: '20', name: 'Item', reference: 'ITEM-BASE', manufacturer_name: 'Item Brand', location: 'ITEM-BASE-BIN', + weight: '2', type: 'standard', associations: {}, + }, + }; + const combinations = { + '100': { id: '100', id_product: '10', reference: 'PACK-V', weight: '1.5', location: 'PACK-V-BIN' }, + '200': { id: '200', id_product: '20', reference: 'ITEM-V', weight: '2.5', location: 'ITEM-V-BIN' }, + }; + const api = { + isBLSupported: async () => false, + makeRequest: async endpoint => { + if (endpoint === 'orders/1') return { order }; + if (endpoint === 'customers/5') return { customer: { firstname: 'Ada', lastname: 'Lovelace', email: 'ada@test' } }; + if (endpoint === 'addresses/6') return { address: { firstname: 'Ada', lastname: 'Lovelace', address1: 'Street 1', city: 'Warsaw', postcode: '00-001', id_country: '1' } }; + throw new Error(`Unexpected API request: ${endpoint}`); + }, + getProduct: async id => products[id], + getProductCombination: async id => combinations[id], + getProductCoverImageUrl: async () => null, + getCurrency: async () => ({ iso_code: 'PLN' }), + getCountry: async () => ({ iso_code: 'PL' }), + getStockAvailabilities: async () => [], + getManufacturer: async () => null, + }; + await importFromPSOrder('1', api, { _id: 'default', orderStatus: '000000000000000000000001', statusMapping: [] }); + + assert.equal(upserts.length, 2); + assert.deepEqual(upserts.find(product => product.sourceId === '10'), { + sourceModule: 'core/prestashop', sourceId: '10', sku: 'PACK-V', name: 'Pack', unitPrice: 10, + ean: '', brand: 'Pack Brand', warehouseLocation: 'PACK-V-BIN', + }); + assert.deepEqual(upserts.find(product => product.sourceId === '20'), { + sourceModule: 'core/prestashop', sourceId: '20', sku: 'ITEM-V', name: 'Item', + brand: 'Item Brand', warehouseLocation: 'ITEM-V-BIN', + }); +}); diff --git a/test/presta-api.test.js b/test/presta-api.test.js index fbb4404..a260bdf 100644 --- a/test/presta-api.test.js +++ b/test/presta-api.test.js @@ -80,3 +80,30 @@ test('preserves the explicitly allowed product partial-success compatibility pat assert.deepEqual(await api.makeRequest('products/1', 'GET', null, true), { product: { id: 1 } }); }); + +test('looks up combinations and stock locations with exact product filters', async t => { + const originalFetch = Core.fetch; + t.after(() => { Core.fetch = originalFetch; }); + const urls = []; + Core.fetch = async url => { + urls.push(url); + if (url.includes('combinations')) return response(200, { combinations: [{ id: '10' }] }); + return response(200, { stock_availables: [{ id: '20' }] }); + }; + const api = new PrestashopApi('https://shop.example', 'secret', true, { maxGetAttempts: 1 }); + + assert.deepEqual(await api.findProductCombinationsByReference('1', 'SKU-1'), [{ id: '10' }]); + assert.deepEqual(await api.getStockAvailabilities('1', '10'), [{ id: '20' }]); + assert.match(urls[0], /filter%5Bid_product%5D=%5B1%5D/); + assert.match(urls[0], /filter%5Breference%5D=%5BSKU-1%5D/); + assert.match(urls[1], /filter%5Bid_product_attribute%5D=%5B10%5D/); +}); + +test('does not turn an unsafe reference filter into an empty combination match', async t => { + const originalFetch = Core.fetch; + t.after(() => { Core.fetch = originalFetch; }); + Core.fetch = async () => assert.fail('must not issue a broadened combination lookup'); + const api = new PrestashopApi('https://shop.example', 'secret', true, { maxGetAttempts: 1 }); + + assert.equal(await api.findProductCombinationsByReference('1', 'SKU[1]'), null); +}); diff --git a/test/product-metadata.test.js b/test/product-metadata.test.js new file mode 100644 index 0000000..d2806f5 --- /dev/null +++ b/test/product-metadata.test.js @@ -0,0 +1,209 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const Module = require('node:module'); +const path = require('node:path'); + +function loadMethod({ onGetProduct, onFindCombinations, onManufacturer, onStocks }) { + const methodPath = path.resolve(__dirname, '../methods/product/get_metadata.js'); + const originalLoad = Module._load; + Module._load = function(request, parent, isMain) { + if (request === '../../src/PrestaApi') { + return class PrestashopApi { + async getProduct(id) { return onGetProduct(id); } + async findProductCombinationsByReference(id, sku) { return onFindCombinations(id, sku); } + async getManufacturer(id) { return onManufacturer(id); } + async getStockAvailabilities(id, attributeId) { return onStocks(id, attributeId); } + }; + } + if (request === '../../src/utils') return { isLegacyApi: () => false }; + if (request === '../../src/module-config') { + return { loadConfig: async () => ({ apiUrl: 'https://shop.test', apiKey: 'key' }), isConfigured: () => true }; + } + if (request === '../../src/register-permissions') { + return { PERMISSIONS: { ORDERS_VIEW: 'orders.view' }, requirePermission() {} }; + } + return originalLoad.call(this, request, parent, isMain); + }; + delete require.cache[methodPath]; + delete require.cache[path.resolve(__dirname, '../src/product-metadata.js')]; + try { + return require(methodPath); + } finally { + Module._load = originalLoad; + } +} + +test('metadata lookup deduplicates source/SKU pairs and preserves confirmed empty values', async () => { + const calls = []; + const method = loadMethod({ + onGetProduct: async id => ({ + id, + reference: id === '1' ? 'base-1' : 'base-2', + id_manufacturer: id === '1' ? '8' : '0', + location: id === '1' ? 'A-01' : '', + }), + onFindCombinations: async () => [], + onManufacturer: async id => ({ id, name: 'Acme' }), + onStocks: async () => [], + }); + + const result = await method({ products: [ + { sourceId: '1', sku: 'base-1' }, + { sourceId: '1', sku: 'base-1' }, + { sourceId: '1', sku: 'BASE-1' }, + { sourceId: '2', sku: 'base-2' }, + ] }, {}); + + assert.equal(result.results.length, 2); + assert.deepEqual(result.results.find(item => item.sourceId === '1'), { + sourceId: '1', sku: 'base-1', brand: 'Acme', warehouseLocation: 'A-01', + }); + assert.deepEqual(result.results.find(item => item.sourceId === '2'), { + sourceId: '2', sku: 'base-2', brand: '', warehouseLocation: '', + }); + assert.equal(calls.length, 0); +}); + +test('metadata lookup returns a variant only for exactly one verified reference match', async () => { + const method = loadMethod({ + onGetProduct: async id => ({ id, reference: 'base', manufacturer_name: 'Brand', location: 'BASE' }), + onFindCombinations: async () => [ + { id: '10', id_product: '1', reference: 'variant', location: 'BIN-1' }, + ], + onManufacturer: async () => null, + onStocks: async () => [], + }); + + const result = await method({ products: [{ sourceId: '1', sku: ' VaRiAnT ' }] }, {}); + assert.deepEqual(result, { + results: [{ sourceId: '1', sku: 'VaRiAnT', brand: 'Brand', warehouseLocation: 'BIN-1' }], + }); +}); + +test('metadata lookup omits synthetic SKUs and ambiguous variant matches', async () => { + let requestedCombinations = 0; + const method = loadMethod({ + onGetProduct: async id => ({ id, reference: 'base', manufacturer_name: 'Brand', location: 'BASE' }), + onFindCombinations: async () => { + requestedCombinations += 1; + return [ + { id: '10', id_product: '1', reference: 'variant', location: 'BIN-1' }, + { id: '11', id_product: '1', reference: 'VARIANT', location: 'BIN-2' }, + ]; + }, + onManufacturer: async () => null, + onStocks: async () => [], + }); + + const result = await method({ products: [ + { sourceId: '1', sku: '~:core/prestashop:1' }, + { sourceId: '1', sku: 'variant' }, + ] }, {}); + + assert.deepEqual(result, { results: [] }); + assert.equal(requestedCombinations, 1); +}); + +test('stock fallback only accepts a unique or default-shop record', async () => { + const { chooseStockLocation } = require('../src/product-metadata'); + const product = { id: '1', id_shop_default: '2' }; + + assert.equal(chooseStockLocation([ + { id_product: '1', id_product_attribute: '0', id_shop: '1', location: 'OTHER' }, + { id_product: '1', id_product_attribute: '0', id_shop: '2', location: 'DEFAULT' }, + ], product, 0).location, 'DEFAULT'); + assert.equal(chooseStockLocation([ + { id_product: '1', id_product_attribute: '0', id_shop: '1', location: 'A' }, + { id_product: '1', id_product_attribute: '0', id_shop: '3', location: 'B' }, + ], product, 0).status, 'ambiguous'); +}); + +test('stock availability is authoritative over stale legacy product location, including a confirmed empty value', async () => { + const { resolveProductMetadata } = require('../src/product-metadata'); + const api = { + getManufacturer: async () => null, + getStockAvailabilities: async () => [{ + id_product: '1', id_product_attribute: '0', id_shop: '1', location: 'A2', + }], + }; + const product = { id: '1', id_shop_default: '1', reference: 'sku', manufacturer_name: 'Brand', location: 'STALE' }; + + assert.deepEqual(await resolveProductMetadata(api, product, { sku: 'SKU' }), { + brand: 'Brand', warehouseLocation: 'A2', + }); + + api.getStockAvailabilities = async () => [{ + id_product: '1', id_product_attribute: '0', id_shop: '1', location: '', + }]; + assert.deepEqual(await resolveProductMetadata(api, product, { sku: 'SKU' }), { + brand: 'Brand', warehouseLocation: '', + }); +}); + +test('a missing ordered combination never falls back to the base product metadata', async () => { + const { resolveProductMetadata } = require('../src/product-metadata'); + const api = { + getManufacturer: async () => null, + getStockAvailabilities: async () => [{ id_product: '1', id_product_attribute: '0', location: 'BASE' }], + }; + const product = { id: '1', reference: 'SKU', manufacturer_name: 'Brand', location: 'LEGACY' }; + + assert.deepEqual(await resolveProductMetadata(api, product, { + sku: 'SKU', requiresCombination: true, + }), {}); +}); + +test('failed or ambiguous stock lookups do not clear metadata through an empty legacy location', async () => { + const { resolveProductMetadata } = require('../src/product-metadata'); + const product = { id: '1', reference: 'SKU', manufacturer_name: 'Brand', location: '' }; + const failedStockApi = { + getManufacturer: async () => null, + getStockAvailabilities: async () => { throw new Error('forbidden'); }, + }; + + const baseResult = await resolveProductMetadata(failedStockApi, product, { sku: 'SKU' }); + assert.deepEqual(baseResult, { brand: 'Brand' }); + assert.equal(Object.hasOwn(baseResult, 'warehouseLocation'), false); + + const variantResult = await resolveProductMetadata(failedStockApi, product, { + sku: 'VARIANT', + combination: { id: '10', id_product: '1', reference: 'VARIANT', location: '' }, + }); + assert.deepEqual(variantResult, { brand: 'Brand' }); + assert.equal(Object.hasOwn(variantResult, 'warehouseLocation'), false); + + const ambiguousStockApi = { + getManufacturer: async () => null, + getStockAvailabilities: async () => [ + { id_product: '1', id_product_attribute: '0', id_shop: '2', location: 'A' }, + { id_product: '1', id_product_attribute: '0', id_shop: '3', location: 'B' }, + ], + }; + const ambiguousResult = await resolveProductMetadata(ambiguousStockApi, product, { sku: 'SKU' }); + assert.equal(Object.hasOwn(ambiguousResult, 'warehouseLocation'), false); +}); + +test('metadata lookup skips a base match when the variation reference cannot be filtered safely', async () => { + const { findMetadataBySourceAndSku } = require('../src/product-metadata'); + const api = { + getProduct: async id => ({ id, reference: 'SKU[1]', manufacturer_name: 'Brand' }), + findProductCombinationsByReference: async () => null, + }; + + assert.equal(await findMetadataBySourceAndSku(api, { sourceId: '1', sku: 'SKU[1]' }), null); +}); + +test('metadata lookup skips combination API when product declares no combinations', async () => { + const method = loadMethod({ + onGetProduct: async id => ({ + id, reference: 'base', manufacturer_name: 'Brand', location: 'LEGACY', associations: { combinations: [] }, + }), + onFindCombinations: async () => assert.fail('must not request combinations for a known empty association'), + onManufacturer: async () => null, + onStocks: async () => [], + }); + + assert.deepEqual(await method({ products: [{ sourceId: '1', sku: 'base' }] }, {}), { + results: [{ sourceId: '1', sku: 'base', brand: 'Brand', warehouseLocation: 'LEGACY' }], + }); +});