Release 1.2.3: fix PrestaShop status mapping lookup for string order IDs
This commit is contained in:
@@ -66,6 +66,12 @@ wymaga ręcznej weryfikacji historii i stanu zamówienia przed wznowieniem;
|
||||
integracja nie ponawia samodzielnie niepewnego POST. Błąd przed utrwaleniem
|
||||
próby można sprawdzić ponownie. Pominięcia i błędy obsługi zdarzeń są logowane.
|
||||
|
||||
Powiązania zamówień przy synchronizacji statusów są odczytywane po unikalnym
|
||||
kluczu `shopConfigId + psOrderId`, z weryfikacją zgodności ID Orbito. Obsługiwane
|
||||
są zarówno tekstowe `orbitoOrderId` zapisane podczas importu przez `$set`, jak
|
||||
i BSON `ObjectId`. Nie jest potrzebna migracja ani ponowny import zamówień;
|
||||
zachowane pozostają potwierdzenia i niepewne próby wcześniejszych zapisów.
|
||||
|
||||
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
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "core/prestashop",
|
||||
"version": "1.2.2",
|
||||
"version": "1.2.3",
|
||||
"singleton": false
|
||||
}
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "core.prestashop",
|
||||
"version": "1.2.2",
|
||||
"version": "1.2.3",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "core.prestashop",
|
||||
"version": "1.2.2",
|
||||
"version": "1.2.3",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@orbito/api-lib": "^3.10.0",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "core.prestashop",
|
||||
"version": "1.2.2",
|
||||
"version": "1.2.3",
|
||||
"description": "Integracja zamówień i płatności PrestaShop",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
|
||||
+40
-9
@@ -28,6 +28,22 @@ function sameVersion(left, right) {
|
||||
&& left.statusDate === right.statusDate && left.psStateId === right.psStateId;
|
||||
}
|
||||
|
||||
async function findStatusMapping(PsOrder, order, config) {
|
||||
const orderId = text(order._id);
|
||||
const psOrderId = Number(order.source?.sourceId);
|
||||
// Import zapisuje orbitoOrderId przez $set. SDK nie rzutuje wartości
|
||||
// wewnątrz $set, ale rzutuje filtr findOne na ObjectId. Starsze rekordy
|
||||
// z tekstowym ID są więc niewidoczne dla filtra po orbitoOrderId.
|
||||
// Klucz unikalny sklepu działa dla obu reprezentacji bez migracji danych.
|
||||
const mapping = await PsOrder.findOne(Number.isSafeInteger(psOrderId) && psOrderId > 0
|
||||
? { shopConfigId: String(config?._id || 'default'), psOrderId }
|
||||
: { orbitoOrderId: orderId });
|
||||
if (mapping && text(mapping.orbitoOrderId) !== orderId) {
|
||||
throw new Error(`PrestaShop order mapping does not belong to Orbito order ${orderId}`);
|
||||
}
|
||||
return mapping;
|
||||
}
|
||||
|
||||
function sourceOwnershipError(order, storedMapping, Core) {
|
||||
const ownModuleCode = text(Core.getModuleInfo?.().code) || 'core/prestashop';
|
||||
if (text(order?.source?.moduleCode) !== ownModuleCode) return 'different_source_module';
|
||||
@@ -60,12 +76,14 @@ async function syncOrderStatusToPrestashop(payload, dependencies) {
|
||||
|
||||
// Hook trafia do każdej instancji modułu w firmie. Odfiltrowujemy obce
|
||||
// sklepy przed lockiem, aby nie blokowały instancji będącej właścicielem.
|
||||
const [initialOrderResult, storedMapping] = await Promise.all([
|
||||
requestHook(Core, 'orders.search', { _id: orderId }),
|
||||
PsOrder.findOne({ orbitoOrderId: orderId }),
|
||||
]);
|
||||
const initialOrderResult = await requestHook(Core, 'orders.search', { _id: orderId });
|
||||
const initialOrder = asOrders(initialOrderResult)[0];
|
||||
if (!initialOrder) return { skipped: true, reason: 'order_not_found' };
|
||||
const initialOwnershipError = sourceOwnershipError(initialOrder, null, Core);
|
||||
if (initialOwnershipError && initialOwnershipError !== 'source_instance_not_confirmed') {
|
||||
return { skipped: true, reason: initialOwnershipError };
|
||||
}
|
||||
const storedMapping = await findStatusMapping(PsOrder, initialOrder, await loadConfig());
|
||||
const ownershipError = sourceOwnershipError(initialOrder, storedMapping, Core);
|
||||
if (ownershipError) return { skipped: true, reason: ownershipError };
|
||||
|
||||
@@ -79,14 +97,18 @@ async function syncOrderStatusToPrestashop(payload, dependencies) {
|
||||
|
||||
let api;
|
||||
try {
|
||||
const [orderResult, config, currentMapping] = await Promise.all([
|
||||
const [orderResult, config] = await Promise.all([
|
||||
requestHook(Core, 'orders.search', { _id: orderId }),
|
||||
loadConfig(),
|
||||
PsOrder.findOne({ orbitoOrderId: orderId }),
|
||||
]);
|
||||
const order = asOrders(orderResult)[0];
|
||||
if (!order) return { skipped: true, reason: 'order_not_found' };
|
||||
const currentOwnershipError = sourceOwnershipError(order, storedMapping, Core);
|
||||
const sourceError = sourceOwnershipError(order, null, Core);
|
||||
if (sourceError && sourceError !== 'source_instance_not_confirmed') {
|
||||
return { skipped: true, reason: sourceError };
|
||||
}
|
||||
const currentMapping = await findStatusMapping(PsOrder, order, config);
|
||||
const currentOwnershipError = sourceOwnershipError(order, currentMapping, Core);
|
||||
if (currentOwnershipError) return { skipped: true, reason: currentOwnershipError };
|
||||
|
||||
if (!config?.apiUrl || !config?.apiKey) {
|
||||
@@ -115,8 +137,17 @@ async function syncOrderStatusToPrestashop(payload, dependencies) {
|
||||
|
||||
let mapping = currentMapping;
|
||||
if (!mapping) {
|
||||
await PsOrder.create({ shopConfigId: String(config._id || 'default'), psOrderId, orbitoOrderId: orderId });
|
||||
mapping = await PsOrder.findOne({ orbitoOrderId: orderId });
|
||||
try {
|
||||
await PsOrder.create({ shopConfigId: String(config._id || 'default'), psOrderId, orbitoOrderId: orderId });
|
||||
} catch (error) {
|
||||
// Import może utrwalić powiązanie równolegle. Odczytujemy je
|
||||
// ponownie i weryfikujemy właściciela; nie nadpisujemy danych
|
||||
// ani zapamiętanego wyniku wcześniejszej próby wysyłki.
|
||||
if (!/E11000|duplicate key/i.test(error?.message || '')) throw error;
|
||||
mapping = await findStatusMapping(PsOrder, order, config);
|
||||
if (!mapping) throw error;
|
||||
}
|
||||
mapping ||= await findStatusMapping(PsOrder, order, config);
|
||||
if (!mapping) throw new Error(`Cannot persist PrestaShop status mapping for ${orderId}`);
|
||||
}
|
||||
const mappingKey = mapping._id ? { _id: mapping._id } : { orbitoOrderId: orderId };
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const Module = require('node:module');
|
||||
const { registerContract } = require('../src/hook-contract');
|
||||
const { upsertMapping } = require('../src/automation-jobs');
|
||||
const { syncOrderStatusToPrestashop, reconcileOrderStatuses } = require('../src/status-sync');
|
||||
const sdkRoot = require('node:path').dirname(require.resolve('@orbito/api-lib/package.json'));
|
||||
const BSON = require(require.resolve('bson', { paths: [sdkRoot] }));
|
||||
const { CLIENT2SERVER_COMMANDS: codes } = require(`${sdkRoot}/codes`);
|
||||
|
||||
// Exercise the installed SDK and the production schema, including BSON wire
|
||||
// types. Plain findOne stubs hide the string/ObjectId mismatch seen on B2B.
|
||||
let database;
|
||||
const originalLoad = Module._load;
|
||||
Module._load = function(request, parent, isMain) {
|
||||
if (request === '../ClientConnection' && parent.filename === `${sdkRoot}/api/db.js`) {
|
||||
return { client: { call: (...args) => database(...args) } };
|
||||
}
|
||||
if (request === './log' && parent.filename === `${sdkRoot}/api/db.js`) return {};
|
||||
return originalLoad.call(this, request, parent, isMain);
|
||||
};
|
||||
let DB;
|
||||
try { DB = require(`${sdkRoot}/api/db`); } finally { Module._load = originalLoad; }
|
||||
Module._load = function(request, parent, isMain) {
|
||||
if (request === '@orbito/api-lib') return { DB: { ...DB, createIndex() {} } };
|
||||
return originalLoad.call(this, request, parent, isMain);
|
||||
};
|
||||
let PsOrder;
|
||||
try { PsOrder = require('../src/models/PsOrder'); } finally { Module._load = originalLoad; }
|
||||
|
||||
const ORDER_ID = '6ac768b046601f810995d108';
|
||||
const STATUS_ID = '6a706a2a51bb5be41a1b43be';
|
||||
const INSTANCE_ID = '6a633bfa4bfff2cf55660004';
|
||||
const equal = (left, right) => BSON.serialize({ value: left }).equals(BSON.serialize({ value: right }));
|
||||
|
||||
async function fixture({ objectId = false, missing = false, legacy = false } = {}) {
|
||||
const rows = [], calls = { inserts: 0, posts: 0, reads: 0 };
|
||||
database = async (command, collection, filterBytes, updateBytes, options) => {
|
||||
assert.equal(collection, 'ps_orders');
|
||||
const query = BSON.deserialize(filterBytes);
|
||||
const matches = row => Object.entries(query).every(([key, value]) => {
|
||||
if (value && typeof value === 'object' && '$exists' in value) return row[key] != null;
|
||||
return equal(row[key], value);
|
||||
});
|
||||
if (command === codes.DB_FIND) return [true, ...rows.filter(matches).map(row => BSON.serialize(row))];
|
||||
if (command === codes.DB_INSERT) {
|
||||
calls.inserts++;
|
||||
if (rows.some(row => row.psOrderId === query.psOrderId && row.shopConfigId === query.shopConfigId)) {
|
||||
return [false, 'E11000 duplicate key'];
|
||||
}
|
||||
const row = { _id: new BSON.ObjectId(), ...query };
|
||||
rows.push(row);
|
||||
return [true, BSON.serialize({ insertedId: row._id })];
|
||||
}
|
||||
assert.equal(command, codes.DB_UPDATE);
|
||||
const update = BSON.deserialize(updateBytes);
|
||||
let row = rows.find(matches);
|
||||
const matchedCount = row ? 1 : 0;
|
||||
if (!row && options?.upsert) {
|
||||
row = { _id: new BSON.ObjectId(), ...query };
|
||||
rows.push(row);
|
||||
}
|
||||
if (row) {
|
||||
Object.assign(row, update.$set || {});
|
||||
for (const key of Object.keys(update.$unset || {})) delete row[key];
|
||||
}
|
||||
return [true, BSON.serialize({ matchedCount })];
|
||||
};
|
||||
if (!missing) await upsertMapping(PsOrder, {
|
||||
shopConfigId: 'default', psOrderId: 4860,
|
||||
orbitoOrderId: objectId ? new BSON.ObjectId(ORDER_ID) : ORDER_ID,
|
||||
});
|
||||
const hooks = new Map();
|
||||
const order = { _id: ORDER_ID, statusId: STATUS_ID, previousStatusId: 'previous-status',
|
||||
statusDate: '2026-10-08T09:56:00Z',
|
||||
source: { moduleCode: 'core/prestashop', moduleId: legacy ? undefined : INSTANCE_ID, sourceId: '4860' } };
|
||||
registerContract({
|
||||
getInstanceId: () => 'alternative-orders', getModuleInfo: () => ({ code: 'alternative/orders' }),
|
||||
registerHook: (name, handler) => hooks.set(name, handler),
|
||||
}, 'orders.search', async () => ({ data: [order] }));
|
||||
const api = {
|
||||
state: 2, loseResponse: false,
|
||||
getOrderState: async () => { calls.reads++; return api.state; },
|
||||
setOrderState: async (id, state, { beforeWrite }) => {
|
||||
assert.equal(id, 4860);
|
||||
if (api.state === state) return { unchanged: true };
|
||||
await beforeWrite();
|
||||
assert.equal(rows[0].statusSyncAttempt.psStateId, state);
|
||||
calls.posts++;
|
||||
if (api.loseResponse) throw new Error('lost response');
|
||||
api.state = state;
|
||||
return { unchanged: false };
|
||||
},
|
||||
};
|
||||
const deps = {
|
||||
PsOrder, Log: { info() {}, warn() {}, error() {} },
|
||||
Core: {
|
||||
getInstanceId: () => INSTANCE_ID, getModuleInfo: () => ({ code: 'core/prestashop' }),
|
||||
execHook: async (name, request) => [await hooks.get(name).call({
|
||||
caller: { instanceId: INSTANCE_ID, moduleCode: 'core/prestashop' },
|
||||
}, request)],
|
||||
getLock: async () => 'lock', releaseLock: async () => {},
|
||||
},
|
||||
loadConfig: async () => ({ _id: 'default', apiUrl: 'https://shop.test', apiKey: 'test',
|
||||
statusMapping: [{ orbitoStatusId: STATUS_ID, psStateId: 7 }] }),
|
||||
apiFor: () => api,
|
||||
};
|
||||
return { deps, rows, calls, api, order };
|
||||
}
|
||||
|
||||
for (const objectId of [false, true]) test(`SDK: reuse ${objectId ? 'ObjectId' : 'string'} import mapping without duplicate insertion`, async () => {
|
||||
const { deps, rows, calls } = await fixture({ objectId });
|
||||
const originalId = rows[0]._id.toHexString();
|
||||
assert.equal(Boolean(await PsOrder.findOne({ orbitoOrderId: ORDER_ID })), objectId);
|
||||
await reconcileOrderStatuses(deps);
|
||||
assert.equal(calls.posts, 1);
|
||||
assert.equal(calls.inserts, 0);
|
||||
assert.equal(rows.length, 1);
|
||||
assert.equal(rows[0]._id.toHexString(), originalId);
|
||||
assert.equal(rows[0].statusSyncConfirmed.psStateId, 7);
|
||||
await syncOrderStatusToPrestashop({ orderId: ORDER_ID }, deps);
|
||||
assert.equal(calls.posts, 1);
|
||||
});
|
||||
|
||||
test('SDK: an uncertain write in a string mapping still blocks another POST', async () => {
|
||||
const { deps, rows, calls, api } = await fixture();
|
||||
api.loseResponse = true;
|
||||
await assert.rejects(syncOrderStatusToPrestashop({ orderId: ORDER_ID }, deps), /lost response/);
|
||||
await reconcileOrderStatuses(deps);
|
||||
assert.equal(calls.posts, 1);
|
||||
assert.equal(calls.reads, 1);
|
||||
assert.ok(rows[0].statusSyncAttempt);
|
||||
api.state = 7;
|
||||
await reconcileOrderStatuses(deps);
|
||||
assert.equal(calls.posts, 1);
|
||||
assert.equal(rows[0].statusSyncAttempt, undefined);
|
||||
assert.equal(rows[0].statusSyncConfirmed.psStateId, 7);
|
||||
});
|
||||
|
||||
test('SDK: legacy source ownership is proven by the matching string mapping', async () => {
|
||||
const { deps, calls } = await fixture({ legacy: true });
|
||||
assert.equal((await syncOrderStatusToPrestashop({ orderId: ORDER_ID }, deps)).synced, true);
|
||||
assert.equal(calls.posts, 1);
|
||||
});
|
||||
|
||||
test('SDK: a legacy order without a mapping is not assigned to this shop', async () => {
|
||||
const { deps, calls } = await fixture({ legacy: true, missing: true });
|
||||
assert.equal((await syncOrderStatusToPrestashop({ orderId: ORDER_ID }, deps)).reason, 'source_instance_not_confirmed');
|
||||
assert.equal(calls.posts, 0);
|
||||
assert.equal(calls.inserts, 0);
|
||||
});
|
||||
|
||||
test('SDK: conflicting mapping or another source instance cannot cause a write', async () => {
|
||||
const { deps, rows, calls, order } = await fixture();
|
||||
rows[0].orbitoOrderId = 'aaaaaaaaaaaaaaaaaaaaaaaa';
|
||||
await assert.rejects(syncOrderStatusToPrestashop({ orderId: ORDER_ID }, deps), /does not belong/);
|
||||
order.source.moduleId = 'bbbbbbbbbbbbbbbbbbbbbbbb';
|
||||
assert.equal((await syncOrderStatusToPrestashop({ orderId: ORDER_ID }, deps)).reason, 'different_source_instance');
|
||||
assert.equal(calls.posts, 0);
|
||||
assert.equal(calls.inserts, 0);
|
||||
});
|
||||
|
||||
test('SDK: a missing mapping is created once and then reused', async () => {
|
||||
const { deps, calls, rows } = await fixture({ missing: true });
|
||||
await syncOrderStatusToPrestashop({ orderId: ORDER_ID }, deps);
|
||||
await syncOrderStatusToPrestashop({ orderId: ORDER_ID }, deps);
|
||||
assert.equal(calls.inserts, 1);
|
||||
assert.equal(calls.posts, 1);
|
||||
assert.equal(rows.length, 1);
|
||||
});
|
||||
|
||||
test('SDK: an import racing with mapping creation is reread without losing its attempt', async () => {
|
||||
const { deps, calls, rows } = await fixture({ missing: true });
|
||||
const create = PsOrder.create.bind(PsOrder);
|
||||
deps.PsOrder = Object.create(PsOrder);
|
||||
deps.PsOrder.create = async data => {
|
||||
await upsertMapping(PsOrder, { ...data, reference: 'from-import' });
|
||||
rows[0].statusSyncAttempt = { psStateId: 7 };
|
||||
return create(data);
|
||||
};
|
||||
const result = await syncOrderStatusToPrestashop({ orderId: ORDER_ID }, deps);
|
||||
assert.equal(result.reason, 'outcome_uncertain');
|
||||
assert.equal(calls.posts, 0);
|
||||
assert.equal(calls.reads, 1);
|
||||
assert.equal(rows.length, 1);
|
||||
assert.equal(rows[0].reference, 'from-import');
|
||||
});
|
||||
Reference in New Issue
Block a user