188 lines
9.0 KiB
JavaScript
188 lines
9.0 KiB
JavaScript
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');
|
|
});
|