fix(prestashop): import combinations as distinct products in 1.1.10

This commit is contained in:
fatequod
2026-09-18 15:11:06 +02:00
parent 519f8daeb0
commit af0dceaa1b
10 changed files with 269 additions and 61 deletions
+8
View File
@@ -3,6 +3,14 @@
Moduł podłącza się do sklepu podanego w konfiguracji i dodaje zamówienia za pomocą
modułu `core/orders`
Każda kombinacja PrestaShop jest zapisywana w `core/products` jako osobny
produkt. Tożsamość źródłowa ma postać
`product:<id produktu>:combination:<id kombinacji>`; dla produktu bez kombinacji
identyfikator kombinacji wynosi `0`. Przy kolejnym imporcie zgodny rekord ze
starszym, numerycznym `sourceId` jest bezpiecznie migrowany po SKU. Dane wariantu
obejmują jego referencję, EAN, lokalizację magazynową, zdjęcie i wagę produktu
powiększoną o wpływ wagi kombinacji.
Podczas importu zamówienia moduł zapisuje publiczne wiadomości klienta jako
`customer_message`. Obsługuje standardowe zasoby PrestaShop: `messages` po
`id_order` i `id_cart`, wątki `customer_threads` oraz ich `customer_messages`,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "core/prestashop",
"version": "1.1.9",
"version": "1.1.10",
"singleton": false,
"dependsOn": [
"core/orders",
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "core.prestashop",
"version": "1.1.9",
"version": "1.1.10",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "core.prestashop",
"version": "1.1.9",
"version": "1.1.10",
"license": "ISC",
"dependencies": {
"@orbito/api-lib": "^3.3.3",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "core.prestashop",
"version": "1.1.9",
"version": "1.1.10",
"description": "Integracja zamówień i płatności PrestaShop",
"main": "index.js",
"scripts": {
+84 -44
View File
@@ -2,7 +2,11 @@ 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');
const {
buildProductSourceId,
parseProductSourceId,
resolveProductMetadata,
} = require('./product-metadata');
function getPSMultiLangField(param, langId) {
if (Array.isArray(param)) {
@@ -19,6 +23,34 @@ function getPSMultiLangField(param, langId) {
return param;
}
function normalizeCombinationId(value) {
const id = String(value ?? '').trim();
return /^\d+$/.test(id) && id !== '0' ? id : '0';
}
function isCombinationForProduct(combination, productId) {
return combination
&& String(combination.id_product ?? '').trim() === String(productId ?? '').trim();
}
function resolveProductWeight(product, combination = null) {
const baseWeight = Number.parseFloat(product?.weight);
if (!combination) return Number.isFinite(baseWeight) ? baseWeight : undefined;
// In PrestaShop a combination's weight is an impact added to the base
// product weight, not the final weight of the variant.
const weightImpact = Number.parseFloat(combination.weight);
if (Number.isFinite(baseWeight) && Number.isFinite(weightImpact)) return baseWeight + weightImpact;
if (Number.isFinite(baseWeight)) return baseWeight;
return Number.isFinite(weightImpact) ? weightImpact : undefined;
}
function applyCombinationFields(target, combination) {
if (!combination) return;
if (String(combination.reference || '').trim()) target.sku = combination.reference;
if (Object.hasOwn(combination, 'ean13')) target.ean = combination.ean13 || '';
}
async function resolveImportStatusId(config) {
const statusResult = await Core.callModule( 'core/orders', 'status.search', {});
const statuses = statusResult?.results ?? [];
@@ -55,12 +87,14 @@ async function importFromPSOrder(orderId, api, config) {
let products = [];
for (let product of order.associations.order_rows) {
const productId = String(product.product_id);
const combinationId = normalizeCombinationId(product.product_attribute_id);
let unitPriceNet = parseFloat(product.unit_price_tax_excl); // jednak cen nie możemy zaokrąglać, bo presta pracuje w cenach brutto
let unitPriceGross = parseFloat(product.unit_price_tax_incl);
let taxRate = unitPriceNet ? (unitPriceGross - unitPriceNet) / unitPriceNet : 0;
const p = {
name: product.product_name,
sourceId: product.product_id,
sourceId: buildProductSourceId(productId, combinationId),
sku: product.product_reference,
ean: product.product_ean13,
unitPrice: unitPriceNet,
@@ -68,31 +102,31 @@ async function importFromPSOrder(orderId, api, config) {
qty: parseFloat(product.product_quantity)
};
const psProduct = await api.getProduct(product.product_id);
const psProduct = await api.getProduct(productId);
Log.debug( "Fetched product details: " + getPSMultiLangField(psProduct.name));
p.weight = parseFloat(psProduct.weight);
let productCombination = null;
if (combinationId !== '0') {
const combination = await api.getProductCombination(combinationId);
if (isCombinationForProduct(combination, productId)) {
productCombination = combination;
applyCombinationFields(p, combination);
}
}
const productWeight = resolveProductWeight(psProduct, productCombination);
if (productWeight !== undefined) p.weight = productWeight;
try {
const imgUrl = await api.getProductCoverImageUrl(product.product_id);
const imgUrl = await api.getProductCoverImageUrl(productId, productCombination);
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,
sourceId: productId,
sku: p.sku,
combination: productCombination,
requiresCombination: parseInt(product.product_attribute_id) > 0,
requiresCombination: combinationId !== '0',
}));
} catch (_) { /* optional product metadata must not block order import */ }
@@ -100,38 +134,39 @@ async function importFromPSOrder(orderId, api, config) {
p.isPack = true;
p.pack = [];
for (const packItem of psProduct.associations.product_bundle) {
const psItem = await api.getProduct(packItem.id);
const packProductId = String(packItem.id);
const packCombinationId = normalizeCombinationId(packItem.id_product_attribute);
const psItem = await api.getProduct(packProductId);
const pData = {
name: getPSMultiLangField(psItem.name),
sourceId: psItem.id,
sourceId: buildProductSourceId(packProductId, packCombinationId),
sku: psItem.reference,
ean: psItem.ean13,
weight: parseFloat(psItem.weight),
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) {
if (packCombinationId !== '0') {
const combination = await api.getProductCombination(packCombinationId);
if (isCombinationForProduct(combination, packProductId)) {
packCombination = combination;
const w = parseFloat(combination.weight);
if (!isNaN(w)) pData.weight = w;
pData.sku = combination.reference || pData.sku;
applyCombinationFields(pData, combination);
}
}
const packWeight = resolveProductWeight(psItem, packCombination);
if (packWeight !== undefined) pData.weight = packWeight;
try {
Object.assign(pData, await resolveProductMetadata(api, psItem, {
sourceId: pData.sourceId,
sourceId: packProductId,
sku: pData.sku,
combination: packCombination,
requiresCombination: parseInt(packItem.id_product_attribute) > 0,
requiresCombination: packCombinationId !== '0',
}));
} catch (_) { /* optional product metadata must not block order import */ }
try {
const imgUrl = await api.getProductCoverImageUrl(packItem.id);
const imgUrl = await api.getProductCoverImageUrl(packProductId, packCombination);
if (imgUrl) pData.coverImageUrl = imgUrl;
} catch (_) { /* no image */ }
@@ -143,22 +178,27 @@ async function importFromPSOrder(orderId, api, config) {
}
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(product.sourceId),
for (const product of productsForUpsert.filter(item => item.sourceId && item.name)) {
const sourceIdentity = parseProductSourceId(product.sourceId);
const upsert = {
// własny kod modułu bierzemy z core (po rejestracji), nie z hardcode'u
sourceModule: Core.getModuleInfo().code,
sourceId: String(product.sourceId),
previousSourceId: sourceIdentity?.productId || undefined,
sku: product.sku || '',
name: product.name,
};
for (const field of ['unitPrice', 'tax', 'weight', 'ean', 'coverImageUrl', 'brand', 'warehouseLocation']) {
if (Object.hasOwn(product, field) && product[field] !== undefined) upsert[field] = product[field];
}
await Core.callModule('core/products', 'upsert', upsert).catch(error => {
Log.warn('PrestaShop product catalog upsert failed', {
sourceId: 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(() => {});
})
);
error: error?.message,
});
});
}
const fallbackStatusId = await resolveImportStatusId(config);
if (!fallbackStatusId) {
+10 -1
View File
@@ -453,7 +453,16 @@ module.exports = class PrestashopApi {
return url + sep + 'ws_key=' + encodeURIComponent(this.apiKey);
}
async getProductCoverImageUrl(productId) {
async getProductCoverImageUrl(productId, combination = null) {
const combinationImages = combination?.associations?.images;
const combinationImage = Array.isArray(combinationImages)
? combinationImages[0]
: combinationImages;
const combinationImageId = combinationImage?.id;
if (combinationImageId && combinationImageId !== '0') {
return this.getProductImageUrl(productId, combinationImageId);
}
const product = await this.getProduct(productId);
const defaultImageId = product.id_default_image;
if (defaultImageId && defaultImageId !== '0' && defaultImageId !== '') {
+68 -6
View File
@@ -1,4 +1,39 @@
const MAX_METADATA_LENGTH = 200;
const PRODUCT_SOURCE_ID_PATTERN = /^product:(\d+):combination:(\d+)$/;
function normalizePrestashopId(value) {
const id = String(value ?? '').trim();
return /^\d+$/.test(id) ? id : '';
}
function buildProductSourceId(productId, combinationId = 0) {
const normalizedProductId = normalizePrestashopId(productId);
const normalizedCombinationId = normalizePrestashopId(combinationId);
if (!normalizedProductId || !normalizedCombinationId) {
throw new Error('Invalid PrestaShop product identity');
}
return `product:${normalizedProductId}:combination:${normalizedCombinationId}`;
}
function parseProductSourceId(value) {
const sourceId = String(value ?? '').trim();
const match = sourceId.match(PRODUCT_SOURCE_ID_PATTERN);
if (match) {
return {
sourceId,
productId: match[1],
combinationId: match[2],
legacy: false,
};
}
// Records imported before variant identities were introduced stored only
// the base PrestaShop product ID. Keep them refreshable during migration.
const productId = normalizePrestashopId(sourceId);
return productId
? { sourceId, productId, combinationId: null, legacy: true }
: null;
}
function normalizeSku(value) {
const sku = String(value ?? '').trim();
@@ -121,12 +156,33 @@ async function resolveProductMetadata(api, product, {
}
async function findMetadataBySourceAndSku(api, { sourceId, sku } = {}) {
const id = String(sourceId ?? '').trim();
const identity = parseProductSourceId(sourceId);
const normalizedSku = normalizeSku(sku);
if (!/^\d+$/.test(id) || !normalizedSku) return null;
if (!identity || !normalizedSku) return null;
const product = await api.getProduct(id);
if (!product || !sameId(product.id, id)) return null;
const product = await api.getProduct(identity.productId);
if (!product || !sameId(product.id, identity.productId)) return null;
if (!identity.legacy) {
if (identity.combinationId === '0') {
if (normalizeSku(product.reference) !== normalizedSku) return null;
const metadata = await resolveProductMetadata(api, product, {
sourceId: identity.productId,
sku,
});
return Object.keys(metadata).length > 0 ? metadata : null;
}
const combination = await api.getProductCombination(identity.combinationId);
if (!isMatchingCombination(product, combination, normalizedSku)) return null;
const metadata = await resolveProductMetadata(api, product, {
sourceId: identity.productId,
sku,
combination,
requiresCombination: true,
});
return Object.keys(metadata).length > 0 ? metadata : null;
}
const candidates = [];
if (normalizeSku(product.reference) === normalizedSku) {
@@ -136,19 +192,25 @@ async function findMetadataBySourceAndSku(api, { sourceId, sku } = {}) {
const knownCombinations = product.associations?.combinations;
const combinations = Array.isArray(knownCombinations) && knownCombinations.length === 0
? []
: await api.findProductCombinationsByReference(id, sku);
: await api.findProductCombinationsByReference(identity.productId, 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] });
const metadata = await resolveProductMetadata(api, product, {
sourceId: identity.productId,
sku,
combination: candidates[0],
});
return Object.keys(metadata).length > 0 ? metadata : null;
}
module.exports = {
MAX_METADATA_LENGTH,
buildProductSourceId,
parseProductSourceId,
normalizeSku,
chooseStockLocation,
resolveProductMetadata,
+37 -5
View File
@@ -43,6 +43,12 @@ test('order import upserts verified metadata for the ordered product and pack it
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',
}, {
product_id: '30', product_attribute_id: '300', product_name: 'Variant Blue', product_reference: 'OLD-BLUE',
product_ean13: '', unit_price_tax_excl: '20', unit_price_tax_incl: '24.6', product_quantity: '1',
}, {
product_id: '30', product_attribute_id: '301', product_name: 'Variant Red', product_reference: 'OLD-RED',
product_ean13: '', unit_price_tax_excl: '21', unit_price_tax_incl: '25.83', product_quantity: '1',
}],
},
};
@@ -55,10 +61,16 @@ test('order import upserts verified metadata for the ordered product and pack it
id: '20', name: 'Item', reference: 'ITEM-BASE', manufacturer_name: 'Item Brand', location: 'ITEM-BASE-BIN',
weight: '2', type: 'standard', associations: {},
},
'30': {
id: '30', name: 'Variant product', reference: 'VARIANT-BASE', manufacturer_name: 'Variant Brand',
location: 'VARIANT-BASE-BIN', weight: '1', 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' },
'300': { id: '300', id_product: '30', reference: 'VARIANT-BLUE', ean13: '5901234123457', weight: '0.1', location: 'BLUE-BIN' },
'301': { id: '301', id_product: '30', reference: 'VARIANT-RED', ean13: '5901234123464', weight: '0.2', location: 'RED-BIN' },
};
const api = {
isBLSupported: async () => false,
@@ -79,13 +91,33 @@ test('order import upserts verified metadata for the ordered product and pack it
};
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,
assert.equal(upserts.length, 4);
assert.deepEqual(upserts.find(product => product.sourceId === 'product:10:combination:100'), {
sourceModule: 'core/prestashop', sourceId: 'product:10:combination:100', previousSourceId: '10',
sku: 'PACK-V', name: 'Pack', unitPrice: 10, tax: 0.23, weight: 2.5,
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',
assert.deepEqual(upserts.find(product => product.sourceId === 'product:20:combination:200'), {
sourceModule: 'core/prestashop', sourceId: 'product:20:combination:200', previousSourceId: '20',
sku: 'ITEM-V', name: 'Item', weight: 4.5,
brand: 'Item Brand', warehouseLocation: 'ITEM-V-BIN',
});
assert.deepEqual(
upserts.filter(product => product.sourceId.startsWith('product:30:')).map(product => product.sourceId),
['product:30:combination:300', 'product:30:combination:301']
);
assert.deepEqual(
upserts.filter(product => product.sourceId.startsWith('product:30:')).map(product => product.sku),
['VARIANT-BLUE', 'VARIANT-RED']
);
assert.deepEqual(upserts.find(product => product.sourceId === 'product:30:combination:300'), {
sourceModule: 'core/prestashop', sourceId: 'product:30:combination:300', previousSourceId: '30',
sku: 'VARIANT-BLUE', name: 'Variant Blue', unitPrice: 20, tax: 0.23, weight: 1.1,
ean: '5901234123457', brand: 'Variant Brand', warehouseLocation: 'BLUE-BIN',
});
assert.deepEqual(upserts.find(product => product.sourceId === 'product:30:combination:301'), {
sourceModule: 'core/prestashop', sourceId: 'product:30:combination:301', previousSourceId: '30',
sku: 'VARIANT-RED', name: 'Variant Red', unitPrice: 21, tax: 0.23, weight: 1.2,
ean: '5901234123464', brand: 'Variant Brand', warehouseLocation: 'RED-BIN',
});
});
+12
View File
@@ -108,6 +108,18 @@ test('does not turn an unsafe reference filter into an empty combination match',
assert.equal(await api.findProductCombinationsByReference('1', 'SKU[1]'), null);
});
test('uses a combination image before the base product cover', async () => {
const api = new PrestashopApi('https://shop.example', 'secret', true, { maxGetAttempts: 1 });
api.getProduct = async () => assert.fail('base product must not be fetched when variant has an image');
const url = await api.getProductCoverImageUrl('1', {
associations: { images: [{ id: '55' }] },
});
assert.match(url, /images\/products\/1\/55\/home_default/);
assert.match(url, /ws_key=secret/);
});
test('collects public customer notes from order, cart and customer thread without cross-order leakage', async t => {
const originalFetch = Core.fetch;
t.after(() => { Core.fetch = originalFetch; });
+46 -1
View File
@@ -3,13 +3,14 @@ const assert = require('node:assert/strict');
const Module = require('node:module');
const path = require('node:path');
function loadMethod({ onGetProduct, onFindCombinations, onManufacturer, onStocks }) {
function loadMethod({ onGetProduct, onGetCombination, 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 getProductCombination(id) { return onGetCombination ? onGetCombination(id) : null; }
async findProductCombinationsByReference(id, sku) { return onFindCombinations(id, sku); }
async getManufacturer(id) { return onManufacturer(id); }
async getStockAvailabilities(id, attributeId) { return onStocks(id, attributeId); }
@@ -80,6 +81,50 @@ test('metadata lookup returns a variant only for exactly one verified reference
});
});
test('metadata lookup resolves a composite variant identity by exact combination ID', async () => {
const combinationCalls = [];
const method = loadMethod({
onGetProduct: async id => ({ id, reference: 'base', manufacturer_name: 'Brand', location: 'BASE' }),
onGetCombination: async id => {
combinationCalls.push(id);
return { id, id_product: '1', reference: 'variant', location: 'BIN-1' };
},
onFindCombinations: async () => assert.fail('composite identity must not search by reference'),
onManufacturer: async () => null,
onStocks: async () => [],
});
const result = await method({
products: [{ sourceId: 'product:1:combination:10', sku: ' VaRiAnT ' }],
}, {});
assert.deepEqual(combinationCalls, ['10']);
assert.deepEqual(result, {
results: [{
sourceId: 'product:1:combination:10',
sku: 'VaRiAnT',
brand: 'Brand',
warehouseLocation: 'BIN-1',
}],
});
});
test('product source identities distinguish base products and combinations', () => {
const { buildProductSourceId, parseProductSourceId } = require('../src/product-metadata');
assert.equal(buildProductSourceId('10', 0), 'product:10:combination:0');
assert.equal(buildProductSourceId('10', '101'), 'product:10:combination:101');
assert.deepEqual(parseProductSourceId('product:10:combination:101'), {
sourceId: 'product:10:combination:101',
productId: '10',
combinationId: '101',
legacy: false,
});
assert.deepEqual(parseProductSourceId('10'), {
sourceId: '10', productId: '10', combinationId: null, legacy: true,
});
});
test('metadata lookup omits synthetic SKUs and ambiguous variant matches', async () => {
let requestedCombinations = 0;
const method = loadMethod({