feat(prestashop): sync mapped statuses from Orbito in 1.1.11
This commit is contained in:
@@ -65,8 +65,15 @@ test('imports only public PrestaShop customer messages as customer_message notes
|
||||
getManufacturer: async () => null,
|
||||
};
|
||||
|
||||
await importFromPSOrder('1', api, { _id: 'default', orderStatus: '000000000000000000000001', statusMapping: [] });
|
||||
await importFromPSOrder('1', api, {
|
||||
_id: 'default',
|
||||
orderStatus: '000000000000000000000001',
|
||||
// To mapowanie służy tylko do wysyłki Orbito -> PrestaShop. Import nie
|
||||
// może ustawić statusu Orbito na podstawie current_state sklepu.
|
||||
statusMapping: [{ psStateId: 1, orbitoStatusId: '000000000000000000000002' }],
|
||||
});
|
||||
|
||||
assert.equal(createPayload.statusId, '000000000000000000000001');
|
||||
assert.deepEqual(createPayload.notes, [
|
||||
{ text: 'Proszę zadzwonić przed dostawą', type: 'customer_message' },
|
||||
{ text: 'Tekst z checkoutu', type: 'customer_message' },
|
||||
|
||||
@@ -41,6 +41,46 @@ test('does not retry mutating requests', async t => {
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
test('changes an order state by creating an idempotent PrestaShop order history', async t => {
|
||||
const originalFetch = Core.fetch;
|
||||
t.after(() => { Core.fetch = originalFetch; });
|
||||
const requests = [];
|
||||
Core.fetch = async (url, options) => {
|
||||
requests.push({ url, options });
|
||||
if (options.method === 'GET') {
|
||||
return response(200, { order: { id: '21', current_state: '2' } });
|
||||
}
|
||||
return response(201, { order_history: { id: '99', id_order: '21', id_order_state: '7' } });
|
||||
};
|
||||
const api = new PrestashopApi('https://shop.example', 'secret', false, { maxGetAttempts: 1 });
|
||||
|
||||
const result = await api.setOrderState(21, 7);
|
||||
|
||||
assert.equal(result.unchanged, false);
|
||||
assert.equal(requests.length, 2);
|
||||
assert.match(requests[0].url, /\/api\/orders\/21\?/);
|
||||
assert.equal(requests[1].options.method, 'POST');
|
||||
assert.match(requests[1].url, /\/api\/order_histories\?output_format=JSON$/);
|
||||
assert.match(requests[1].options.body, /<id_order_state>7<\/id_order_state>/);
|
||||
assert.match(requests[1].options.body, /<id_order>21<\/id_order>/);
|
||||
});
|
||||
|
||||
test('does not create a duplicate order history when PrestaShop already has the target state', async t => {
|
||||
const originalFetch = Core.fetch;
|
||||
t.after(() => { Core.fetch = originalFetch; });
|
||||
let calls = 0;
|
||||
Core.fetch = async () => {
|
||||
calls += 1;
|
||||
return response(200, { order: { id: '21', current_state: '7' } });
|
||||
};
|
||||
const api = new PrestashopApi('https://shop.example', 'secret', true, { maxGetAttempts: 1 });
|
||||
|
||||
const result = await api.setOrderState('21', '7');
|
||||
|
||||
assert.equal(result.unchanged, true);
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
test('rejects non-retryable 4xx and invalid JSON', async t => {
|
||||
const originalFetch = Core.fetch;
|
||||
t.after(() => { Core.fetch = originalFetch; });
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
const assert = require('node:assert/strict');
|
||||
const Module = require('node:module');
|
||||
const path = require('node:path');
|
||||
const test = require('node:test');
|
||||
|
||||
const registerConfigPath = path.resolve(__dirname, '../src/register-config.js');
|
||||
|
||||
function loadConfigModule({ states, cachedStates = [] }) {
|
||||
let blocks;
|
||||
let savedStates;
|
||||
const originalLoad = Module._load;
|
||||
Module._load = function(request, parent, isMain) {
|
||||
if (request === '@orbito/api-lib') {
|
||||
return {
|
||||
Config: {
|
||||
PropertyType: { INFO: 'info', STRING: 'string' },
|
||||
DisplayFormat: { URL: 'url', SECRET: 'secret' },
|
||||
registerConfigBlocks: async value => { blocks = value; },
|
||||
get: async (key, fallback) => ({
|
||||
'connection.apiUrl': 'https://shop.test',
|
||||
'connection.apiKey': 'secret',
|
||||
'connection.versionCode': '8',
|
||||
}[key] ?? fallback),
|
||||
},
|
||||
Log: { info() {}, warn() {} },
|
||||
};
|
||||
}
|
||||
if (request === './PrestaApi') {
|
||||
return class PrestashopApi {
|
||||
async getStatuses() { return states; }
|
||||
};
|
||||
}
|
||||
if (request === './utils') return { isLegacyApi: () => false };
|
||||
if (request === './module-config') {
|
||||
return {
|
||||
setPsStates: async value => { savedStates = value; },
|
||||
loadPsStates: async () => cachedStates,
|
||||
};
|
||||
}
|
||||
if (request === './shop-icon') return { ensureShopIcon: async () => {} };
|
||||
return originalLoad.call(this, request, parent, isMain);
|
||||
};
|
||||
|
||||
delete require.cache[registerConfigPath];
|
||||
let loaded;
|
||||
try {
|
||||
loaded = require(registerConfigPath);
|
||||
} finally {
|
||||
Module._load = originalLoad;
|
||||
}
|
||||
return {
|
||||
...loaded,
|
||||
register: async () => {
|
||||
await loaded.registerPrestashopConfigBlocks();
|
||||
return blocks;
|
||||
},
|
||||
getSavedStates: () => savedStates,
|
||||
};
|
||||
}
|
||||
|
||||
test('opening the mapping block fetches and persists current PrestaShop state names', async () => {
|
||||
const module = loadConfigModule({
|
||||
cachedStates: [{ id: 2, name: 'Stara nazwa', color: '#000000' }],
|
||||
states: [{ id: '2', name: 'Nowa nazwa', color: '#00ff00', deleted: '0' }],
|
||||
});
|
||||
const blocks = await module.register();
|
||||
|
||||
const schema = await blocks.mapping.schema();
|
||||
|
||||
assert.equal(schema.state_2.name.pl, 'Nowa nazwa (PS #2)');
|
||||
assert.deepEqual(module.getSavedStates(), [{ id: 2, name: 'Nowa nazwa', color: '#00ff00' }]);
|
||||
});
|
||||
|
||||
test('mapping validation prevents two PrestaShop states from sharing one Orbito status', async () => {
|
||||
const module = loadConfigModule({ states: [] });
|
||||
const statusId = '507f191e810c19729de860ea';
|
||||
const errors = [];
|
||||
|
||||
module.validateOutboundMapping({
|
||||
state_2: statusId,
|
||||
state_3: statusId,
|
||||
state_4: '507f191e810c19729de860eb',
|
||||
}, {
|
||||
addError: (field, message) => errors.push({ field, message }),
|
||||
});
|
||||
|
||||
assert.deepEqual(errors.map(error => error.field), ['state_2', 'state_3']);
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
const { resolvePsStateId } = require('../src/status-mapper');
|
||||
|
||||
const STATUS_A = '507f191e810c19729de860ea';
|
||||
const STATUS_B = '507f191e810c19729de860eb';
|
||||
|
||||
test('resolves a saved mapping in the outbound Orbito to PrestaShop direction', () => {
|
||||
assert.equal(resolvePsStateId(STATUS_B, [
|
||||
{ psStateId: 2, orbitoStatusId: STATUS_A },
|
||||
{ psStateId: 7, orbitoStatusId: STATUS_B },
|
||||
]), 7);
|
||||
assert.equal(resolvePsStateId('507f191e810c19729de860ec', [
|
||||
{ psStateId: 7, orbitoStatusId: STATUS_B },
|
||||
]), null);
|
||||
});
|
||||
|
||||
test('rejects an ambiguous outbound status mapping', () => {
|
||||
assert.throws(() => resolvePsStateId(STATUS_A, [
|
||||
{ psStateId: 2, orbitoStatusId: STATUS_A },
|
||||
{ psStateId: 3, orbitoStatusId: STATUS_A },
|
||||
]), /kilku statusów PrestaShop/);
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
const {
|
||||
STATUS_SYNC_LOCK_TTL_SECONDS,
|
||||
registerStatusSyncHook,
|
||||
syncOrderStatusToPrestashop,
|
||||
} = require('../src/status-sync');
|
||||
|
||||
const ORDER_ID = '507f191e810c19729de860e1';
|
||||
const OLD_STATUS = '507f191e810c19729de860e2';
|
||||
const CURRENT_STATUS = '507f191e810c19729de860e3';
|
||||
|
||||
function dependencies(overrides = {}) {
|
||||
const calls = { setOrderState: [], released: [], locks: [] };
|
||||
const Core = {
|
||||
getLock: async (name, ttl) => {
|
||||
calls.locks.push([name, ttl]);
|
||||
return 'status-lock';
|
||||
},
|
||||
releaseLock: async id => { calls.released.push(id); },
|
||||
getModuleInfo: () => ({ code: 'core/prestashop' }),
|
||||
getInstanceId: () => 'aaaaaaaaaaaaaaaaaaaaaaaa',
|
||||
callModule: async () => ({ data: [{
|
||||
_id: ORDER_ID,
|
||||
statusId: CURRENT_STATUS,
|
||||
source: {
|
||||
moduleCode: 'core/prestashop',
|
||||
moduleId: 'aaaaaaaaaaaaaaaaaaaaaaaa',
|
||||
sourceId: '21',
|
||||
},
|
||||
}] }),
|
||||
registerHook: async () => true,
|
||||
};
|
||||
const deps = {
|
||||
Core,
|
||||
Log: { info() {}, warn() {}, error() {} },
|
||||
PsOrder: { findOne: async () => ({ psOrderId: 21, orbitoOrderId: ORDER_ID }) },
|
||||
loadConfig: async () => ({
|
||||
apiUrl: 'https://shop.test',
|
||||
apiKey: 'secret',
|
||||
statusMapping: [{ psStateId: 7, orbitoStatusId: CURRENT_STATUS }],
|
||||
}),
|
||||
apiFor: () => ({
|
||||
setOrderState: async (...args) => {
|
||||
calls.setOrderState.push(args);
|
||||
return { unchanged: false };
|
||||
},
|
||||
}),
|
||||
...overrides,
|
||||
};
|
||||
return { deps, calls };
|
||||
}
|
||||
|
||||
test('syncs the current Orbito status to the mapped PrestaShop state', async () => {
|
||||
const { deps, calls } = dependencies();
|
||||
|
||||
const result = await syncOrderStatusToPrestashop({
|
||||
orderId: ORDER_ID,
|
||||
statusId: OLD_STATUS,
|
||||
}, deps);
|
||||
|
||||
assert.deepEqual(calls.setOrderState, [[21, 7]]);
|
||||
assert.deepEqual(calls.locks, [[`prestashop-status-sync:${ORDER_ID}`, STATUS_SYNC_LOCK_TTL_SECONDS]]);
|
||||
assert.deepEqual(calls.released, ['status-lock']);
|
||||
assert.equal(result.orbitoStatusId, CURRENT_STATUS);
|
||||
assert.equal(result.synced, true);
|
||||
});
|
||||
|
||||
test('ignores status events for an order owned by another PrestaShop instance', async () => {
|
||||
const { deps, calls } = dependencies();
|
||||
deps.Core.callModule = async () => ({ data: [{
|
||||
_id: ORDER_ID,
|
||||
statusId: CURRENT_STATUS,
|
||||
source: {
|
||||
moduleCode: 'core/prestashop',
|
||||
moduleId: 'bbbbbbbbbbbbbbbbbbbbbbbb',
|
||||
sourceId: '21',
|
||||
},
|
||||
}] });
|
||||
|
||||
const result = await syncOrderStatusToPrestashop({ orderId: ORDER_ID }, deps);
|
||||
|
||||
assert.deepEqual(calls.setOrderState, []);
|
||||
assert.equal(result.reason, 'different_source_instance');
|
||||
assert.deepEqual(calls.locks, []);
|
||||
assert.deepEqual(calls.released, []);
|
||||
});
|
||||
|
||||
test('does not write an unmapped Orbito status to PrestaShop', async () => {
|
||||
const { deps, calls } = dependencies({
|
||||
loadConfig: async () => ({
|
||||
apiUrl: 'https://shop.test',
|
||||
apiKey: 'secret',
|
||||
statusMapping: [{ psStateId: 2, orbitoStatusId: OLD_STATUS }],
|
||||
}),
|
||||
});
|
||||
|
||||
const result = await syncOrderStatusToPrestashop({ orderId: ORDER_ID }, deps);
|
||||
|
||||
assert.deepEqual(calls.setOrderState, []);
|
||||
assert.equal(result.reason, 'status_not_mapped');
|
||||
});
|
||||
|
||||
test('keeps a concurrent event retryable when the per-order lock is occupied', async () => {
|
||||
const { deps } = dependencies();
|
||||
deps.Core.getLock = async () => null;
|
||||
|
||||
await assert.rejects(
|
||||
() => syncOrderStatusToPrestashop({ orderId: ORDER_ID }, deps),
|
||||
/already running/
|
||||
);
|
||||
});
|
||||
|
||||
test('registers the Orbito order status change hook', async () => {
|
||||
const { deps } = dependencies();
|
||||
let registration;
|
||||
deps.Core.registerHook = async (name, handler) => { registration = { name, handler }; };
|
||||
|
||||
await registerStatusSyncHook(deps);
|
||||
|
||||
assert.equal(registration.name, 'event:order:status_changed');
|
||||
assert.equal(typeof registration.handler, 'function');
|
||||
});
|
||||
Reference in New Issue
Block a user