feat(prestashop): sync mapped statuses from Orbito in 1.1.11
This commit is contained in:
@@ -3,6 +3,23 @@
|
||||
Moduł podłącza się do sklepu podanego w konfiguracji i dodaje zamówienia za pomocą
|
||||
modułu `core/orders`
|
||||
|
||||
## Statusy zamówień
|
||||
|
||||
Orbito jest źródłem prawdy dla statusów zamówień. Przy ładowaniu zakładki
|
||||
„Mapowanie statusów” moduł pobiera aktualną listę i nazwy statusów z PrestaShop.
|
||||
Zapisane mapowanie jest używane wyłącznie w kierunku Orbito → PrestaShop:
|
||||
|
||||
- nowe zamówienie otrzymuje w Orbito status ustawiony w „Import zamówień”, bez
|
||||
odczytywania `current_state` jako statusu docelowego;
|
||||
- zmiana zmapowanego statusu w Orbito tworzy wpis `order_histories` w PrestaShop;
|
||||
- zmiany statusu wykonane w PrestaShop nigdy nie nadpisują statusu w Orbito;
|
||||
- status niezmapowany nie jest wysyłany do sklepu;
|
||||
- jeden status Orbito może wskazywać tylko jeden status PrestaShop.
|
||||
|
||||
Klucz Webservice wymaga co najmniej odczytu `order_states` i `orders` oraz prawa
|
||||
POST do `order_histories`. Synchronizacja nie używa `sendemail=1`, więc sama
|
||||
zmiana z Orbito nie zleca PrestaShop wysłania wiadomości statusowej do klienta.
|
||||
|
||||
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
|
||||
|
||||
@@ -4,12 +4,13 @@ const PsOrder = require('./src/models/PsOrder');
|
||||
const PrestashopApi = require('./src/PrestaApi');
|
||||
const { importFromPSOrder } = require('./src/OrderImporter');
|
||||
const { isLegacyApi } = require('./src/utils');
|
||||
const { loadEnabledConfigs, setLastOrderId } = require('./src/module-config');
|
||||
const { loadConfig, loadEnabledConfigs, setLastOrderId } = require('./src/module-config');
|
||||
const { registerPrestashopConfigBlocks } = require('./src/register-config');
|
||||
const { registerPrestashopPermissions } = require('./src/register-permissions');
|
||||
const { importOrdersForShop, syncPaymentsForShop } = require('./src/automation-jobs');
|
||||
const { createJobRuntime } = require('./src/job-runtime');
|
||||
const { ensureShopIcon } = require('./src/shop-icon');
|
||||
const { registerStatusSyncHook } = require('./src/status-sync');
|
||||
|
||||
const NEW_ORDERS_WINDOW_MS = 20 * 60 * 1000;
|
||||
// TTL locków cronowych w sekundach (jednostka oczekiwana przez Core.getLock/Core.extendLockTime).
|
||||
@@ -29,6 +30,10 @@ function apiFor(config) {
|
||||
return new PrestashopApi(config.apiUrl, config.apiKey, isLegacyApi(config.versionCode));
|
||||
}
|
||||
|
||||
registerStatusSyncHook({ Core, Log, PsOrder, loadConfig, apiFor }).catch(error => {
|
||||
Log.error('PrestaShop: nie udało się zarejestrować synchronizacji statusów', { error: error?.message });
|
||||
});
|
||||
|
||||
async function runOrdersPuller(isLockValid) {
|
||||
const configs = await loadEnabledConfigs();
|
||||
for (const config of configs) {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "core/prestashop",
|
||||
"version": "1.1.10",
|
||||
"version": "1.1.11",
|
||||
"singleton": false,
|
||||
"dependsOn": [
|
||||
"core/orders",
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "core.prestashop",
|
||||
"version": "1.1.10",
|
||||
"version": "1.1.11",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "core.prestashop",
|
||||
"version": "1.1.10",
|
||||
"version": "1.1.11",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@orbito/api-lib": "^3.3.3",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "core.prestashop",
|
||||
"version": "1.1.10",
|
||||
"version": "1.1.11",
|
||||
"description": "Integracja zamówień i płatności PrestaShop",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
const { Log, Core } = require("@orbito/api-lib");
|
||||
const PsOrder = require('./models/PsOrder');
|
||||
const { resolveStatusId, normalizeStatusId } = require('./status-mapper');
|
||||
const { normalizeStatusId } = require('./status-mapper');
|
||||
const { paymentTransactionId, parsePrestashopDate, upsertMapping } = require('./automation-jobs');
|
||||
const {
|
||||
buildProductSourceId,
|
||||
@@ -205,15 +205,13 @@ async function importFromPSOrder(orderId, api, config) {
|
||||
throw new Error(`Cannot import order ${orderId} — no valid order status configured`);
|
||||
}
|
||||
|
||||
const statusMapping = Array.isArray(config.statusMapping) ? config.statusMapping : [];
|
||||
const statusId = resolveStatusId(order.current_state, statusMapping, fallbackStatusId);
|
||||
if (!statusId) {
|
||||
throw new Error(`Cannot import order ${orderId} — could not resolve status for PS state ${order.current_state}`);
|
||||
}
|
||||
// Orbito jest właścicielem statusu. Stan PrestaShop nie może nadpisywać
|
||||
// statusu w Orbito, również przy imporcie nowego zamówienia. Mapowanie
|
||||
// statusów jest używane wyłącznie do synchronizacji Orbito -> PrestaShop.
|
||||
const statusId = fallbackStatusId;
|
||||
|
||||
Log.info( 'Resolved order status', {
|
||||
Log.info( 'Selected Orbito import status', {
|
||||
orderId,
|
||||
psStateId: order.current_state,
|
||||
orbitoStatusId: statusId
|
||||
});
|
||||
|
||||
|
||||
+24
-6
@@ -390,15 +390,33 @@ module.exports = class PrestashopApi {
|
||||
}
|
||||
|
||||
async setOrderState(orderId, stateId) {
|
||||
if (this.legacy) {
|
||||
return await this.updateOrderLegacy(orderId, {
|
||||
current_state: stateId
|
||||
});
|
||||
const normalizedOrderId = String(orderId ?? '').trim();
|
||||
const normalizedStateId = String(stateId ?? '').trim();
|
||||
if (!/^\d+$/.test(normalizedOrderId) || !/^\d+$/.test(normalizedStateId)) {
|
||||
throw new Error('Invalid PrestaShop order or state id');
|
||||
}
|
||||
|
||||
return await this.updateOrder(orderId, {
|
||||
current_state: stateId
|
||||
// Odczyt przed zapisem zapewnia idempotencję retry hooka. Status zmieniamy
|
||||
// przez order_histories (zamiast bezpośredniej edycji current_state), aby
|
||||
// PrestaShop wykonał standardowe skutki uboczne przejścia statusu.
|
||||
const current = await this.makeRequest(`orders/${normalizedOrderId}`, 'GET', {
|
||||
output_format: 'JSON'
|
||||
});
|
||||
if (!current?.order?.id) throw new Error(`PrestaShop order ${normalizedOrderId} not found`);
|
||||
if (String(current.order.current_state) === normalizedStateId) {
|
||||
return { order: current.order, unchanged: true };
|
||||
}
|
||||
|
||||
const response = await this.makeRequest('order_histories?output_format=JSON', 'POST', {
|
||||
order_history: {
|
||||
id_order_state: normalizedStateId,
|
||||
id_order: normalizedOrderId
|
||||
}
|
||||
});
|
||||
if (!response?.order_history?.id) {
|
||||
throw new Error('Failed to set PrestaShop order state');
|
||||
}
|
||||
return { orderHistory: response.order_history, unchanged: false };
|
||||
}
|
||||
|
||||
async updateOrder(orderId, data) {
|
||||
|
||||
@@ -25,7 +25,7 @@ async function loadStatusMapping(psStates) {
|
||||
}
|
||||
}));
|
||||
|
||||
return statusMapping;
|
||||
return statusMapping.sort((a, b) => a.psStateId - b.psStateId);
|
||||
}
|
||||
|
||||
// Shape kompatybilny z dotychczasowym użyciem (OrderImporter, CRON, PrestaApi).
|
||||
|
||||
+86
-11
@@ -2,7 +2,7 @@ const { Config, Log } = require('@orbito/api-lib');
|
||||
const { PropertyType, DisplayFormat } = Config;
|
||||
const PrestashopApi = require('./PrestaApi');
|
||||
const { isLegacyApi } = require('./utils');
|
||||
const { extractPsStateName } = require('./status-mapper');
|
||||
const { extractPsStateName, normalizeStatusId } = require('./status-mapper');
|
||||
const { setPsStates, loadPsStates } = require('./module-config');
|
||||
const { ensureShopIcon } = require('./shop-icon');
|
||||
|
||||
@@ -18,7 +18,7 @@ const ORBITO_STATUS_OPTIONS = {
|
||||
async function fetchPsStates(apiUrl, apiKey, versionCode) {
|
||||
const api = new PrestashopApi(apiUrl, apiKey, isLegacyApi(versionCode));
|
||||
const rawStates = await api.getStatuses();
|
||||
return (Array.isArray(rawStates) ? rawStates : [])
|
||||
const states = (Array.isArray(rawStates) ? rawStates : [])
|
||||
.filter(s => !s.deleted || s.deleted === '0' || s.deleted === 0)
|
||||
.map(s => ({
|
||||
id: parseInt(s.id, 10),
|
||||
@@ -26,6 +26,61 @@ async function fetchPsStates(apiUrl, apiKey, versionCode) {
|
||||
color: s.color || '#cccccc'
|
||||
}))
|
||||
.filter(s => !Number.isNaN(s.id));
|
||||
if (!states.length) throw new Error('PrestaShop nie zwrócił żadnych aktywnych statusów zamówień.');
|
||||
return states;
|
||||
}
|
||||
|
||||
async function refreshPsStatesForMapping() {
|
||||
const cachedStates = await loadPsStates();
|
||||
const [apiUrl, apiKey, versionCode] = await Promise.all([
|
||||
Config.get('connection.apiUrl', ''),
|
||||
Config.get('connection.apiKey', ''),
|
||||
Config.get('connection.versionCode', ''),
|
||||
]);
|
||||
|
||||
if (!apiUrl || !apiKey) {
|
||||
return {
|
||||
states: cachedStates,
|
||||
refreshError: 'Najpierw zapisz poprawne połączenie ze sklepem.',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const states = await fetchPsStates(apiUrl, apiKey, versionCode);
|
||||
await setPsStates(states);
|
||||
Log.info('PrestaShop mapping: odświeżono statusy przy otwarciu zakładki', { count: states.length });
|
||||
return { states, refreshError: null };
|
||||
} catch (error) {
|
||||
Log.warn('PrestaShop mapping: nie udało się odświeżyć statusów', { error: error?.message });
|
||||
return {
|
||||
states: cachedStates,
|
||||
refreshError: error?.message || 'Nie udało się pobrać statusów z PrestaShop.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function validateOutboundMapping(params, raport) {
|
||||
const assignments = Object.entries(params || {})
|
||||
.map(([field, value]) => ({
|
||||
field,
|
||||
psStateId: /^state_(\d+)$/.exec(field)?.[1] || null,
|
||||
orbitoStatusId: normalizeStatusId(value),
|
||||
}))
|
||||
.filter(entry => entry.psStateId && entry.orbitoStatusId);
|
||||
|
||||
const fieldsByOrbitoStatus = new Map();
|
||||
for (const assignment of assignments) {
|
||||
const fields = fieldsByOrbitoStatus.get(assignment.orbitoStatusId) || [];
|
||||
fields.push(assignment.field);
|
||||
fieldsByOrbitoStatus.set(assignment.orbitoStatusId, fields);
|
||||
}
|
||||
|
||||
for (const fields of fieldsByOrbitoStatus.values()) {
|
||||
if (fields.length < 2) continue;
|
||||
for (const field of fields) {
|
||||
raport.addError(field, 'Jeden status Orbito może wskazywać tylko jeden status PrestaShop.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function registerPrestashopConfigBlocks() {
|
||||
@@ -116,8 +171,8 @@ async function registerPrestashopConfigBlocks() {
|
||||
hint: {
|
||||
type: PropertyType.INFO,
|
||||
name: {
|
||||
pl: 'Domyślny status Orbito, gdy brak mapowania PS → Orbito. Lista pochodzi z modułu core/orders.',
|
||||
en: 'Default Orbito status when there is no PS → Orbito mapping. List comes from core/orders.'
|
||||
pl: 'Każde nowe zamówienie z PrestaShop otrzyma ten status. Status sklepu nigdy nie nadpisuje statusu w Orbito.',
|
||||
en: 'Every new PrestaShop order receives this status. The shop state never overwrites the Orbito status.'
|
||||
}
|
||||
},
|
||||
orderStatus: {
|
||||
@@ -132,15 +187,19 @@ async function registerPrestashopConfigBlocks() {
|
||||
title: { pl: 'Mapowanie statusów', en: 'Status mapping' },
|
||||
scope: 'global',
|
||||
schema: async () => {
|
||||
const psStates = await loadPsStates();
|
||||
const { states: psStates, refreshError } = await refreshPsStatesForMapping();
|
||||
|
||||
if (!psStates.length) {
|
||||
return {
|
||||
hint: {
|
||||
type: PropertyType.INFO,
|
||||
name: {
|
||||
pl: 'Brak statusów PrestaShop. Zapisz najpierw zakładkę „Połączenie ze sklepem” — statusy pobierzemy automatycznie przy zapisie.',
|
||||
en: 'No PrestaShop states yet. Save the “Shop connection” tab first — states are fetched automatically on save.'
|
||||
pl: refreshError
|
||||
? `Brak statusów PrestaShop. ${refreshError}`
|
||||
: 'PrestaShop nie zwrócił żadnych aktywnych statusów.',
|
||||
en: refreshError
|
||||
? `No PrestaShop states. ${refreshError}`
|
||||
: 'PrestaShop returned no active order states.'
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -150,12 +209,22 @@ async function registerPrestashopConfigBlocks() {
|
||||
hint: {
|
||||
type: PropertyType.INFO,
|
||||
name: {
|
||||
pl: 'Przypisz każdy status PrestaShop do odpowiednika w Orbito. Przy imporcie używane jest current_state z zamówienia PS.',
|
||||
en: 'Map each PrestaShop state to an Orbito status. Import uses current_state from the PS order.'
|
||||
pl: 'Mapowanie steruje wyłącznie wysyłką Orbito → PrestaShop. Zmiana z PrestaShop nigdy nie nadpisuje statusu Orbito.',
|
||||
en: 'Mapping controls Orbito → PrestaShop updates only. A PrestaShop change never overwrites the Orbito status.'
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (refreshError) {
|
||||
schema.refreshWarning = {
|
||||
type: PropertyType.INFO,
|
||||
name: {
|
||||
pl: `Nie udało się odświeżyć nazw statusów; pokazano ostatnio zapisane dane. ${refreshError}`,
|
||||
en: `Could not refresh state names; showing the last saved data. ${refreshError}`
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
for (const state of psStates) {
|
||||
const id = state.id;
|
||||
schema[`state_${id}`] = {
|
||||
@@ -169,11 +238,17 @@ async function registerPrestashopConfigBlocks() {
|
||||
}
|
||||
|
||||
return schema;
|
||||
}
|
||||
},
|
||||
validate: validateOutboundMapping,
|
||||
}
|
||||
});
|
||||
|
||||
Log.info('PrestaShop: zarejestrowano bloki konfiguracji Config');
|
||||
}
|
||||
|
||||
module.exports = { registerPrestashopConfigBlocks };
|
||||
module.exports = {
|
||||
fetchPsStates,
|
||||
refreshPsStatesForMapping,
|
||||
registerPrestashopConfigBlocks,
|
||||
validateOutboundMapping,
|
||||
};
|
||||
|
||||
@@ -34,6 +34,26 @@ function resolveStatusId(psStateId, statusMapping, fallbackStatusId) {
|
||||
return normalizeStatusId(match?.orbitoStatusId) ?? normalizeStatusId(fallbackStatusId);
|
||||
}
|
||||
|
||||
// Mapowanie jest konfigurowane w wierszach PrestaShop -> Orbito, ale po
|
||||
// zapisaniu służy wyłącznie do wysyłki statusu w przeciwnym kierunku.
|
||||
// Jeden status Orbito nie może wskazywać kilku statusów PrestaShop, bo wtedy
|
||||
// wynik synchronizacji zależałby od kolejności pól formularza.
|
||||
function resolvePsStateId(orbitoStatusId, statusMapping) {
|
||||
const normalizedStatusId = normalizeStatusId(orbitoStatusId);
|
||||
if (!normalizedStatusId || !Array.isArray(statusMapping)) return null;
|
||||
|
||||
const matches = statusMapping
|
||||
.filter(entry => normalizeStatusId(entry?.orbitoStatusId) === normalizedStatusId)
|
||||
.map(entry => parseInt(entry.psStateId, 10))
|
||||
.filter(stateId => !Number.isNaN(stateId));
|
||||
|
||||
const uniqueMatches = [...new Set(matches)];
|
||||
if (uniqueMatches.length > 1) {
|
||||
throw new Error(`Status Orbito ${normalizedStatusId} jest przypisany do kilku statusów PrestaShop`);
|
||||
}
|
||||
return uniqueMatches[0] ?? null;
|
||||
}
|
||||
|
||||
function formatPsStatesPreview(states) {
|
||||
if (!Array.isArray(states) || !states.length) {
|
||||
return 'Brak statusów PrestaShop — najpierw przetestuj połączenie.';
|
||||
@@ -59,6 +79,7 @@ module.exports = {
|
||||
normalizeStatusId,
|
||||
parseStatusMapping,
|
||||
resolveStatusId,
|
||||
resolvePsStateId,
|
||||
formatPsStatesPreview,
|
||||
extractPsStateName
|
||||
};
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
const { resolvePsStateId } = require('./status-mapper');
|
||||
|
||||
const STATUS_SYNC_LOCK_TTL_SECONDS = 120;
|
||||
|
||||
function asOrders(result) {
|
||||
if (Array.isArray(result)) return result;
|
||||
if (Array.isArray(result?.data)) return result.data;
|
||||
if (Array.isArray(result?.results)) return result.results;
|
||||
return [];
|
||||
}
|
||||
|
||||
function text(value) {
|
||||
return value == null ? '' : String(value).trim();
|
||||
}
|
||||
|
||||
function sourceOwnershipError(order, storedMapping, Core) {
|
||||
const ownModuleCode = text(Core.getModuleInfo?.().code) || 'core/prestashop';
|
||||
if (text(order?.source?.moduleCode) !== ownModuleCode) return 'different_source_module';
|
||||
|
||||
const ownInstanceId = text(Core.getInstanceId?.());
|
||||
const sourceInstanceId = text(order?.source?.moduleId);
|
||||
if (sourceInstanceId && ownInstanceId && sourceInstanceId !== ownInstanceId) {
|
||||
return 'different_source_instance';
|
||||
}
|
||||
// Dla starszych zamówień bez moduleId lokalny rekord mapowania jest
|
||||
// jedynym bezpiecznym dowodem, że zamówienie należy do tej instancji.
|
||||
if ((!sourceInstanceId || !ownInstanceId) && !storedMapping) {
|
||||
return 'source_instance_not_confirmed';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function syncOrderStatusToPrestashop(payload, dependencies) {
|
||||
const {
|
||||
Core,
|
||||
Log = console,
|
||||
PsOrder,
|
||||
loadConfig,
|
||||
apiFor,
|
||||
} = dependencies;
|
||||
const orderId = text(payload?.orderId);
|
||||
if (!/^[a-f0-9]{24}$/i.test(orderId)) {
|
||||
return { skipped: true, reason: 'invalid_order_id' };
|
||||
}
|
||||
|
||||
// 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([
|
||||
Core.callModule('core/orders', 'search', { _id: orderId }),
|
||||
PsOrder.findOne({ orbitoOrderId: orderId }),
|
||||
]);
|
||||
const initialOrder = asOrders(initialOrderResult)[0];
|
||||
if (!initialOrder) return { skipped: true, reason: 'order_not_found' };
|
||||
const ownershipError = sourceOwnershipError(initialOrder, storedMapping, Core);
|
||||
if (ownershipError) return { skipped: true, reason: ownershipError };
|
||||
|
||||
const lockName = `prestashop-status-sync:${orderId}`;
|
||||
const lockId = await Core.getLock(lockName, STATUS_SYNC_LOCK_TTL_SECONDS);
|
||||
if (!lockId) {
|
||||
// Równoległe zdarzenie zostaje w outboxie core/orders. Przy ponowieniu
|
||||
// odczyta najnowszy status Orbito, więc starszy event nie cofnie sklepu.
|
||||
throw new Error(`PrestaShop status sync is already running for order ${orderId}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const [orderResult, config] = await Promise.all([
|
||||
Core.callModule('core/orders', 'search', { _id: orderId }),
|
||||
loadConfig(),
|
||||
]);
|
||||
const order = asOrders(orderResult)[0];
|
||||
if (!order) return { skipped: true, reason: 'order_not_found' };
|
||||
const currentOwnershipError = sourceOwnershipError(order, storedMapping, Core);
|
||||
if (currentOwnershipError) return { skipped: true, reason: currentOwnershipError };
|
||||
|
||||
if (!config?.apiUrl || !config?.apiKey) {
|
||||
return { skipped: true, reason: 'shop_not_configured' };
|
||||
}
|
||||
|
||||
// Zawsze czytamy bieżący status zamówienia, a nie status ze zdarzenia.
|
||||
// Dzięki temu opóźniony retry może tylko doprowadzić sklep do aktualnego
|
||||
// stanu Orbito, nigdy cofnąć go do starszego statusu.
|
||||
const orbitoStatusId = text(order.statusId);
|
||||
const psStateId = resolvePsStateId(orbitoStatusId, config.statusMapping);
|
||||
if (psStateId == null) {
|
||||
return { skipped: true, reason: 'status_not_mapped' };
|
||||
}
|
||||
|
||||
const psOrderId = Number(storedMapping?.psOrderId ?? order.source?.sourceId);
|
||||
if (!Number.isSafeInteger(psOrderId) || psOrderId <= 0) {
|
||||
throw new Error(`Cannot resolve PrestaShop order id for Orbito order ${orderId}`);
|
||||
}
|
||||
|
||||
const result = await apiFor(config).setOrderState(psOrderId, psStateId);
|
||||
Log.info('PrestaShop order status synchronized from Orbito', {
|
||||
orderId,
|
||||
psOrderId,
|
||||
orbitoStatusId,
|
||||
psStateId,
|
||||
unchanged: result?.unchanged === true,
|
||||
});
|
||||
return {
|
||||
synced: true,
|
||||
unchanged: result?.unchanged === true,
|
||||
orderId,
|
||||
psOrderId,
|
||||
orbitoStatusId,
|
||||
psStateId,
|
||||
};
|
||||
} catch (error) {
|
||||
Log.error('PrestaShop order status synchronization failed', {
|
||||
orderId,
|
||||
error: error?.message,
|
||||
});
|
||||
throw error;
|
||||
} finally {
|
||||
await Core.releaseLock(lockId).catch(error => {
|
||||
Log.warn('PrestaShop status sync lock release failed', {
|
||||
orderId,
|
||||
lockId,
|
||||
error: error?.message,
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function registerStatusSyncHook(dependencies) {
|
||||
return dependencies.Core.registerHook('event:order:status_changed', payload => (
|
||||
syncOrderStatusToPrestashop(payload, dependencies)
|
||||
));
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
STATUS_SYNC_LOCK_TTL_SECONDS,
|
||||
asOrders,
|
||||
registerStatusSyncHook,
|
||||
sourceOwnershipError,
|
||||
syncOrderStatusToPrestashop,
|
||||
};
|
||||
@@ -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