Compare commits

...
11 Commits
Author SHA1 Message Date
fatequod ff011e7e28 Fix free sample orders with delivery discounts 2026-10-20 10:34:31 +02:00
wiktorandClaude Opus 5.5 cdd761535a Release 1.3.1: SDK 4.4.3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01684guZqmdZzks6zgEQrFHs
2026-10-17 11:38:58 +02:00
wiktorandClaude Opus 5.5 6ffbd2effa Release 1.3.0: configurable start order ID for import
Saving a new "start order ID" in the import block moves the import
cursor to X-1, so the next run imports from order X inclusive.
The block also shows the current cursor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EDD4j8Y2gTf72v7dMgSHz8
2026-10-15 14:46:57 +02:00
wiktorandClaude Fable 5.1 cc3ab1fd4a Release 1.2.6: restore dependsOn in manifest
Wydanie drugiego autora usunęło z module.json pole dependsOn przywrócone wcześniej
(dpd 2c682e5 / inpost f6b7cf0 / prestashop 234adde); bez niego instalacja modułu
nie dociąga zależnych modułów.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Qf35mEHqL5L7cx3Cpo4qeK
2026-10-15 14:19:26 +02:00
wiktorandClaude Opus 5.5 84c2b2087a Release 1.2.5: SDK 4.4.1 for TLS RPC
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Qf35mEHqL5L7cx3Cpo4qeK
2026-10-15 14:17:57 +02:00
fatequod 8df9f36bb0 Release 1.2.4: correct discount VAT using product rates 2026-10-15 14:08:53 +02:00
wiktorandClaude Fable 5.1 234addeadc fix: przywrócenie dependsOn w manifeście
Rdzeń instaluje zależności z dependsOn obrazu (plan instalacji, marketplace,
asystent AI). Pole zniknęło z module.json przy ostatnich wydaniach, przez co
moduł instalował się bez wymaganych modułów bazowych.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AQUzPg6Zuw11UnaQgqngCM
2026-10-09 14:52:02 +02:00
fatequod 1d40a05989 Release 1.2.3: fix PrestaShop status mapping lookup for string order IDs 2026-10-08 12:04:08 +02:00
fatequod d140625ba0 Release 1.2.2: recover missed PrestaShop status changes 2026-10-08 10:57:21 +02:00
fatequod 86cf1a232f Release 1.2.1 2026-09-30 11:51:45 +02:00
fatequod 1f79463f51 Use hook-backed outbound status mapping 2026-09-30 11:49:04 +02:00
22 changed files with 1381 additions and 214 deletions
+68
View File
@@ -3,6 +3,25 @@
Moduł podłącza się do sklepu podanego w konfiguracji i dodaje zamówienia za pomocą
modułu `core/orders`
## VAT rabatów
Importer zachowuje kwotę brutto rabatu ze sklepu. Przy jednej stawce VAT
produktów (również składowych zestawów) stosuje tę stawkę i wylicza netto
z brutto. Niespójne sumy netto/brutto ze źródła nie tworzą nowej stawki VAT.
Przykład: 75,35 zł brutto przy VAT 23% daje 61,26 zł netto, nawet gdy sklep
przekazał 63,51 zł netto. Pozycje bezpłatne nie wyznaczają VAT rabatu.
Zamówienia z bezpłatnymi produktami i darmową dostawą są importowane z cenami
0 zł. Gdy zerowe sumy zamówienia i produktów oraz rabat netto/brutto równy
kosztowi dostawy potwierdzają ten przypadek, rabat ma typ `delivery` i VAT
z `carrier_tax_rate`. Koszt dostawy otrzymuje tę samą stawkę. Późniejsza
edycja ceny produktu, np. na 0,01 zł, nie jest pomniejszana rabatem dostawy.
Przy kilku stawkach VAT albo brakujących danych importer zgłasza
`DISCOUNT_TAX_AMBIGUOUS` przed utworzeniem zamówienia. W takim przypadku
potrzebne jest potwierdzone rozbicie rabatu według stawek; importer nie
wybiera pierwszej stawki ani stawki uśrednionej.
## Daty zamówień i płatności
Daty PrestaShop bez oznaczenia strefy (`date_add`, `date_upd`) są odczytywane
@@ -17,6 +36,17 @@ zapisanych zamówień ani istniejących płatności. Niepoprawne daty korzystaj
z czasu importu; powtórzona godzina przy zmianie czasu oznacza jej pierwsze
wystąpienie, ponieważ data PrestaShop nie rozróżnia obu wystąpień.
## ID startowe importu
Pierwszy import ustawia kursor na najnowszym zamówieniu w sklepie i nie
pobiera zamówień historycznych. W bloku „Import zamówień” widać ostatnio
przetworzone zamówienie PrestaShop. Zapis nowej wartości „ID startowe
zamówienia PrestaShop” przesuwa kursor tak, by następny import zaczął od tego
zamówienia włącznie — do przodu lub wstecz, także na działającej instancji.
Zapis tej samej wartości ani wyczyszczenie pola nie zmieniają kursora.
Zamówienia już obecne w Orbito nie są duplikowane, ale cofnięcie kursora może
ponownie zaimportować zamówienia usunięte w Orbito.
## Statusy zamówień
Orbito jest źródłem prawdy dla statusów zamówień. Przy ładowaniu zakładki
@@ -30,10 +60,48 @@ Zapisane mapowanie jest używane wyłącznie w kierunku Orbito → PrestaShop:
- status niezmapowany nie jest wysyłany do sklepu;
- jeden status Orbito może wskazywać tylko jeden status PrestaShop.
Formularz ma wiersz dla każdego statusu Orbito i listę statusów PrestaShop do
wyboru. Kilka statusów Orbito może wskazywać ten sam status PrestaShop.
Lista Orbito pochodzi z kontraktu `orders.status.search`; brak dostawcy,
niejednoznaczny dostawca lub błąd pobierania są widoczne w formularzu.
Przed udostępnieniem formularza moduł uzupełnia nowe pola na podstawie starych
przypisań. Migracja jest addytywna: można ją wznowić po przerwaniu, a kolejne
uruchomienia nie nadpisują zapisanych wyborów ani celowo wyczyszczonych pól.
Stare klucze `mapping.state_<PS ID>` pozostają bez zmian. Nowe pola
`mapping.orbito_<Orbito ID>` mają pierwszeństwo tylko dla danego statusu Orbito;
dopóki pole nie zostało zapisane, synchronizacja odczytuje stare przypisanie.
Zapisanie pustego pola wyłącza wysyłkę, bez przywracania starego
przypisania. Odczyt obejmuje również statusy nieobecne już na listach — formularz
pokazuje ich zapisane ID. Konflikt starych przypisań nie wybiera celu automatycznie:
pokazuje wszystkie cele i wymaga wybrania jednego lub wyczyszczenia pola.
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.
Oprócz hooka zmiany statusu integracja co minutę sprawdza maksymalnie 50
najdawniej sprawdzanych mapowań z własnej bazy. Odczytuje aktualny status przez
kontrakt `orders.search` i uzupełnia zgubione zdarzenia. Po przejściu partii
sprawdza kolejne zamówienia; pełny obieg może trwać kilka minut. Kontrola
okresowa obejmuje zamówienia z `previousStatusId`, czyli po zmianie statusu,
aby nie wysyłać do sklepu początkowego statusu importu.
Potwierdzony status, jego datę i docelowy status PrestaShop zapisuje lokalnie.
Przed POST utrwala osobny znacznik próby. Jeśli odpowiedź zginie albo kontener
zostanie przerwany, przy następnym sprawdzeniu wykonuje wyłącznie GET. Zgodny
stan sklepu potwierdza poprzednią próbę; niezgodny blokuje dalsze zapisy i
generuje ostrzeżenie `previous write outcome is uncertain`. Taki przypadek
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
+5 -1
View File
@@ -10,7 +10,7 @@ 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 { registerStatusSyncHook, reconcileOrderStatuses } = 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).
@@ -82,6 +82,10 @@ async function syncShopIcon() {
}
const jobs = [
new CronJob('15 * * * * *', () => runtime.track(() =>
runtime.withRenewedLock('prestashop-status-reconciliation', JOB_LOCK_TTL_SECONDS, valid =>
reconcileOrderStatuses({ Core, Log, PsOrder, loadConfig, apiFor }, valid))
).catch(error => Log.error('PrestaShop status reconciliation worker failed', { error: error?.message }))),
new CronJob('0 * * * * *', () => runtime.track(() =>
runtime.withRenewedLock('prestashop-orders-puller', JOB_LOCK_TTL_SECONDS, runOrdersPuller)
)),
+10 -2
View File
@@ -1,5 +1,13 @@
{
"name": "core/prestashop",
"version": "1.2.0",
"singleton": false
"version": "1.3.2",
"singleton": false,
"files": [
"index.js",
"package.json",
"package-lock.json",
"src/",
"methods/",
"README.md"
]
}
+8 -8
View File
@@ -1,29 +1,29 @@
{
"name": "core.prestashop",
"version": "1.2.0",
"version": "1.3.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "core.prestashop",
"version": "1.2.0",
"version": "1.3.2",
"license": "ISC",
"dependencies": {
"@orbito/api-lib": "^3.10.0",
"@orbito/api-lib": "^4.4.3",
"cron": "^4.4.0",
"dotenv": "^17.2.3",
"ejs": "^4.0.1",
"fastest-validator": "^1.19.1",
"js2xmlparser": "^5.0.0",
"nanoid": "^5.1.6",
"node-cache": "^5.1.2",
"uuid": "^11.1.0",
"fastest-validator": "^1.19.1"
"uuid": "^11.1.0"
}
},
"node_modules/@orbito/api-lib": {
"version": "3.10.0",
"resolved": "https://git.kozminski.net.pl/api/packages/orbito/npm/%40orbito%2Fapi-lib/-/3.10.0/api-lib-3.10.0.tgz",
"integrity": "sha512-isA8AhISPW8NRRKuco4MByqnevpiiGZRcHP/CBuYg+XSUgbpF1gwqdThi3PzzT1pAtNhZVhQH2ti2RvLJjN3Yg==",
"version": "4.4.3",
"resolved": "https://git.kozminski.net.pl/api/packages/orbito/npm/%40orbito%2Fapi-lib/-/4.4.3/api-lib-4.4.3.tgz",
"integrity": "sha512-/Fg2kMyHIbj9yIw3vPz0kJUmsxfHwShUiSsJXquICFCYfkAGPSNq4mQwpxYQPJ8TE1RKtdWJOmAA0azWqb/ktA==",
"license": "ISC",
"dependencies": {
"bson": "^6.10.4",
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "core.prestashop",
"version": "1.2.0",
"version": "1.3.2",
"description": "Integracja zamówień i płatności PrestaShop",
"main": "index.js",
"scripts": {
@@ -10,7 +10,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"@orbito/api-lib": "^3.10.0",
"@orbito/api-lib": "^4.4.3",
"cron": "^4.4.0",
"dotenv": "^17.2.3",
"ejs": "^4.0.1",
+4 -12
View File
@@ -3,6 +3,7 @@ const { Log, Core } = require("@orbito/api-lib");
const PsOrder = require('./models/PsOrder');
const { normalizeStatusId } = require('./status-mapper');
const { paymentTransactionId, parsePrestashopDate, upsertMapping } = require('./automation-jobs');
const { mapOrderDiscounts } = require('./order-discounts');
const {
buildProductSourceId,
resolveProductMetadata,
@@ -312,18 +313,8 @@ async function importFromPSOrder(orderId, api, config) {
pickupPoint.address = { street, zipCode, city };
}
const discounts = [];
if (parseFloat(order.total_discounts)) {
let net = parseFloat(order.total_discounts_tax_excl);
let gross = parseFloat(order.total_discounts_tax_incl);
let tax = net ? (gross - net) / net : 0;
discounts.push({
name: "Rabat",
amount: Math.round(net * 100) / 100,
gross: Math.round(gross * 100) / 100,
tax: Math.round(tax * 100) / 100
});
}
const discounts = mapOrderDiscounts(order, products);
const deliveryDiscount = discounts.find(discount => discount.type === 'delivery');
const totalPaidReal = parseFloat(order.total_paid_real) || 0;
const createdAt = parsePrestashopDate(order.date_add, new Date(), config.timeZone);
@@ -378,6 +369,7 @@ async function importFromPSOrder(orderId, api, config) {
cost: {
amount: parseFloat(order.total_shipping_tax_excl),
...(deliveryDiscount ? { tax: deliveryDiscount.tax } : {}),
},
isCod: (order.payment + "").toLowerCase().includes("pobranie")
+26 -4
View File
@@ -14,6 +14,10 @@ module.exports = class PrestashopApi {
this.retryBaseMs = requestOptions.retryBaseMs || 250;
}
close() {
this.cache.close();
}
getUrl(endpoint = "") {
if (endpoint.startsWith('/')) {
endpoint = endpoint.slice(1);
@@ -431,31 +435,49 @@ module.exports = class PrestashopApi {
return messages;
}
async setOrderState(orderId, stateId) {
async getOrderState(orderId) {
const id = String(orderId ?? '').trim();
if (!/^\d+$/.test(id)) throw new Error('Invalid PrestaShop order id');
const current = await this.makeRequest(`orders/${id}`, 'GET', { output_format: 'JSON' });
if (String(current?.order?.id) !== id || !/^\d+$/.test(String(current.order.current_state))) {
throw new Error(`Invalid PrestaShop order state response for ${id}`);
}
return Number(current.order.current_state);
}
async setOrderState(orderId, stateId, { beforeWrite } = {}) {
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');
}
// Odczyt przed zapisem zapewnia idempotencję retry hooka. Status zmieniamy
// Odczyt przed zapisem pomija zbędny wpis historii. 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?.id) !== normalizedOrderId
|| !/^\d+$/.test(String(current?.order?.current_state))) {
throw new Error(`Invalid PrestaShop order state response for ${normalizedOrderId}`);
}
if (String(current.order.current_state) === normalizedStateId) {
return { order: current.order, unchanged: true };
}
// Konsument utrwala próbę PRZED efektem. Awaria zapisu lokalnego
// blokuje POST, a utrata odpowiedzi po POST nie pozwala go ponowić.
if (beforeWrite) await beforeWrite();
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) {
if (!response?.order_history?.id
|| String(response.order_history.id_order) !== normalizedOrderId
|| String(response.order_history.id_order_state) !== normalizedStateId) {
throw new Error('Failed to set PrestaShop order state');
}
return { orderHistory: response.order_history, unchanged: false };
+4
View File
@@ -11,6 +11,9 @@ const schema = new DB.Schema('ps_orders', {
// Ostatnia kumulatywna kwota total_paid_real potwierdzona w core/orders.
paymentTotalSynced: { type: 'number', optional: true },
paymentCheckedAt: { type: 'date', optional: true },
statusSyncCheckedAt: { type: 'date', optional: true },
statusSyncAttempt: { type: 'object', optional: true },
statusSyncConfirmed: { type: 'object', optional: true },
nextPaymentCheckAt: { type: 'date', optional: true },
});
@@ -21,5 +24,6 @@ DB.createIndex('ps_orders', { psOrderId: 1, shopConfigId: 1 }, { unique: true })
DB.createIndex('ps_orders', { orbitoOrderId: 1 });
DB.createIndex('ps_orders', { syncedAt: -1 });
DB.createIndex('ps_orders', { shopConfigId: 1, nextPaymentCheckAt: 1, syncedAt: 1 });
DB.createIndex('ps_orders', { statusSyncCheckedAt: 1, _id: 1 });
module.exports = schema;
+31 -15
View File
@@ -1,5 +1,6 @@
const { Config } = require('@orbito/api-lib');
const { DEFAULT_SHOP_TIME_ZONE } = require('./prestashop-date');
const { readStatusMapping, LEGACY_CONFLICT } = require('./status-mapper');
/** Stały identyfikator sklepu (jeden sklep na firmę) — używany w PsOrder.shopConfigId. */
const SHOP_ID = 'default';
@@ -13,20 +14,32 @@ async function loadPsStates() {
return Array.isArray(states) ? states : [];
}
async function loadStatusMapping(psStates) {
const states = Array.isArray(psStates) ? psStates : await loadPsStates();
const statusMapping = [];
async function loadLastOrderId() {
const lastOrderId = await Config.get('runtime.lastOrderId', null);
return lastOrderId == null ? null : Number(lastOrderId);
}
await Promise.all(states.map(async (state) => {
const id = parseInt(state.id ?? state.psStateId, 10);
if (Number.isNaN(id)) return;
const orbitoStatusId = await Config.get(`mapping.state_${id}`, '');
if (orbitoStatusId) {
statusMapping.push({ psStateId: id, orbitoStatusId: String(orbitoStatusId) });
async function loadStatusMapping() {
return readStatusMapping(await Config.getAll());
}
// Additive, restart-safe migration before exposing the new form. The generic
// form renders saved values, not schema defaults. Never rewrite legacy keys or
// an existing outbound choice (including an explicitly cleared field).
async function initializeOutboundMapping() {
const config = await Config.getAll();
const grouped = new Map();
for (const entry of readStatusMapping(config)) {
const ids = grouped.get(entry.orbitoStatusId) || new Set();
ids.add(String(entry.psStateId));
grouped.set(entry.orbitoStatusId, ids);
}
for (const [id, targets] of grouped) {
const key = `mapping.orbito_${id}`;
if (!Object.hasOwn(config, key)) {
await Config.set(key, targets.size === 1 ? [...targets][0] : LEGACY_CONFLICT);
}
}));
return statusMapping.sort((a, b) => a.psStateId - b.psStateId);
}
}
// Shape kompatybilny z dotychczasowym użyciem (OrderImporter, CRON, PrestaApi).
@@ -49,11 +62,11 @@ async function loadConfig() {
Config.get('connection.versionCode', ''),
Config.get('connection.timeZone', DEFAULT_SHOP_TIME_ZONE),
Config.get('import.orderStatus', ''),
Config.get('runtime.lastOrderId', null),
loadLastOrderId(),
loadPsStates()
]);
const statusMapping = await loadStatusMapping(psStates);
const statusMapping = await loadStatusMapping();
return {
_id: SHOP_ID,
@@ -64,7 +77,7 @@ async function loadConfig() {
versionCode: versionCode || '',
timeZone: String(timeZone || DEFAULT_SHOP_TIME_ZONE).trim() || DEFAULT_SHOP_TIME_ZONE,
orderStatus: orderStatus || '',
lastOrderId: lastOrderId == null ? null : Number(lastOrderId),
lastOrderId,
psStates,
statusMapping
};
@@ -88,7 +101,10 @@ module.exports = {
isConfigured,
loadConfig,
loadEnabledConfigs,
loadLastOrderId,
loadPsStates,
loadStatusMapping,
initializeOutboundMapping,
setLastOrderId,
setPsStates
};
+70
View File
@@ -0,0 +1,70 @@
function discountTaxError(message) {
const error = new Error(message);
error.code = 'DISCOUNT_TAX_AMBIGUOUS';
return error;
}
function sourceNumber(value) {
if (value === undefined || value === null || String(value).trim() === '') return NaN;
return Number(value);
}
function cents(value) {
return Math.round(value * 100);
}
function freeSampleDeliveryDiscount(order, products, gross) {
// With free goods and a zero order total, a discount equal to shipping
// cancels delivery only. Keep that benefit separate from editable goods.
if (!products.length || !products.every(product =>
Number.isFinite(product.qty) && product.qty > 0 && product.unitPrice === 0)) return null;
if (!['total_products', 'total_products_wt', 'total_paid_tax_excl', 'total_paid_tax_incl']
.every(field => sourceNumber(order[field]) === 0)) return null;
if (!['total_wrapping_tax_excl', 'total_wrapping_tax_incl']
.every(field => order[field] === undefined || sourceNumber(order[field]) === 0)) return null;
const amount = sourceNumber(order.total_shipping_tax_excl);
const shippingGross = sourceNumber(order.total_shipping_tax_incl);
const discountNet = sourceNumber(order.total_discounts_tax_excl);
const tax = sourceNumber(order.carrier_tax_rate) / 100;
if (!(Number.isFinite(amount) && amount > 0 && Number.isFinite(shippingGross) && shippingGross > 0
&& Number.isFinite(discountNet) && discountNet >= 0
&& Number.isFinite(tax) && tax >= 0 && tax <= 1)) return null;
if (cents(amount) !== cents(discountNet) || cents(shippingGross) !== cents(gross)
|| cents(amount * (1 + tax)) !== cents(shippingGross)) return null;
return { name: 'Darmowa dostawa', type: 'delivery', amount, gross: cents(gross) / 100, tax };
}
// A total discount's net/gross ratio is not a VAT rate. In particular, source
// totals can be inconsistent or combine several rates. Use the taxed goods.
function mapOrderDiscounts(order, products) {
if (!(Number.parseFloat(order.total_discounts) > 0)) return [];
const gross = Number.parseFloat(order.total_discounts_tax_incl);
if (!Number.isFinite(gross) || gross < 0) {
throw discountTaxError('Nieprawidłowa kwota brutto rabatu PrestaShop.');
}
if (gross === 0) return [];
const deliveryDiscount = freeSampleDeliveryDiscount(order, products, gross);
if (deliveryDiscount) return [deliveryDiscount];
const taxes = new Set();
for (const product of products) {
if (!(product.qty > 0 && product.unitPrice > 0)) continue;
const lines = product.isPack && product.pack?.length ? product.pack : [product];
for (const line of lines) {
if (!(line.qty > 0)) continue;
if (!Number.isFinite(line.tax) || line.tax < 0 || line.tax > 1) {
throw discountTaxError('Brak jednoznacznej stawki VAT produktów objętych rabatem.');
}
taxes.add(line.tax);
}
}
if (taxes.size !== 1) {
throw discountTaxError('Rabat wymaga rozbicia według stawek VAT produktów; nie można utworzyć stawki z sum netto i brutto.');
}
const [tax] = taxes;
return [{ name: 'Rabat', type: 'product', gross: Math.round(gross * 100) / 100,
amount: Math.round(gross / (1 + tax) * 100) / 100, tax }];
}
module.exports = { mapOrderDiscounts };
+7 -102
View File
@@ -2,20 +2,12 @@ const { Config, Log } = require('@orbito/api-lib');
const { PropertyType, DisplayFormat } = Config;
const PrestashopApi = require('./PrestaApi');
const { isLegacyApi } = require('./utils');
const { extractPsStateName, normalizeStatusId } = require('./status-mapper');
const { setPsStates, loadPsStates } = require('./module-config');
const { extractPsStateName } = require('./status-mapper');
const { importStatusSchema, validateImportBlock, outboundMappingSchema, validateOutboundMapping } = require('./status-config');
const { setPsStates, loadPsStates, initializeOutboundMapping } = require('./module-config');
const { ensureShopIcon } = require('./shop-icon');
const { DEFAULT_SHOP_TIME_ZONE, validateTimeZone } = require('./prestashop-date');
const ORBITO_STATUS_OPTIONS = {
module: 'core/prestashop',
method: 'status.search',
params: {},
responsePath: 'results',
idKey: '_id',
labelKey: 'name'
};
async function fetchPsStates(apiUrl, apiKey, versionCode) {
const api = new PrestashopApi(apiUrl, apiKey, isLegacyApi(versionCode));
const rawStates = await api.getStatuses();
@@ -60,31 +52,8 @@ async function refreshPsStatesForMapping() {
}
}
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() {
await initializeOutboundMapping();
await Config.registerConfigBlocks({
connection: {
title: { pl: 'Połączenie ze sklepem', en: 'Shop connection' },
@@ -184,78 +153,14 @@ async function registerPrestashopConfigBlocks() {
import: {
title: { pl: 'Import zamówień', en: 'Order import' },
scope: 'global',
schema: {
hint: {
type: PropertyType.INFO,
name: {
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: {
type: PropertyType.STRING,
name: { pl: 'Domyślny status po imporcie', en: 'Default status after import' },
options: ORBITO_STATUS_OPTIONS
}
}
schema: importStatusSchema,
validate: validateImportBlock,
},
mapping: {
title: { pl: 'Mapowanie statusów', en: 'Status mapping' },
scope: 'global',
schema: async () => {
const { states: psStates, refreshError } = await refreshPsStatesForMapping();
if (!psStates.length) {
return {
hint: {
type: PropertyType.INFO,
name: {
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.'
}
}
};
}
const schema = {
hint: {
type: PropertyType.INFO,
name: {
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}`] = {
type: PropertyType.STRING,
name: {
pl: `${state.name || `Status ${id}`} (PS #${id})`,
en: `${state.name || `State ${id}`} (PS #${id})`
},
options: ORBITO_STATUS_OPTIONS
};
}
return schema;
},
schema: () => outboundMappingSchema(refreshPsStatesForMapping),
validate: validateOutboundMapping,
}
});
+131
View File
@@ -0,0 +1,131 @@
const { Config, Core } = require('@orbito/api-lib');
const { requestHook } = require('./hook-contract');
const { normalizeStatusId, readStatusMapping, isPsStateId, LEGACY_CONFLICT } = require('./status-mapper');
const { loadLastOrderId, setLastOrderId } = require('./module-config');
function info(pl, en = pl) {
return { type: Config.PropertyType.INFO, name: { pl, en } };
}
async function loadOrbitoStatuses() {
try {
const response = await requestHook(Core, 'orders.status.search', {});
if (!Array.isArray(response?.results)) throw new Error('Niepoprawna odpowiedź listy statusów.');
return { statuses: response.results, error: null };
} catch (error) {
return { statuses: [], error: `Nie udało się pobrać statusów Orbito. ${error.message}` };
}
}
function importCursorInfo(lastOrderId) {
if (!Number.isFinite(lastOrderId)) {
return info(
'Pierwszy import zacznie od najnowszego zamówienia w sklepie, chyba że podasz ID startowe.',
'The first import starts from the newest order in the shop unless you set a start order ID.',
);
}
return info(
`Ostatnio przetworzone zamówienie PrestaShop: #${lastOrderId} — następny import zacznie od #${lastOrderId + 1}.`,
`Last processed PrestaShop order: #${lastOrderId} — the next import starts from #${lastOrderId + 1}.`,
);
}
async function importStatusSchema() {
const [{ statuses, error }, savedId, lastOrderId] = await Promise.all([
loadOrbitoStatuses(), Config.get('import.orderStatus', ''), loadLastOrderId(),
]);
const values = statuses.map(status => ({ id: String(status._id), label: status.name }));
if (savedId && !values.some(value => value.id === String(savedId))) {
values.push({ id: String(savedId), label: `Zapisany status Orbito (${savedId}) — niedostępny na liście` });
}
return {
hint: info(
'Każde nowe zamówienie z PrestaShop otrzyma ten status. Status sklepu nigdy nie nadpisuje statusu w Orbito.',
'Every new PrestaShop order receives this status. The shop state never overwrites the Orbito status.',
),
...(error ? { statusWarning: info(error) } : {}),
orderStatus: {
type: Config.PropertyType.STRING,
name: { pl: 'Domyślny status po imporcie', en: 'Default status after import' },
options: { values },
},
cursor: importCursorInfo(lastOrderId),
startOrderId: {
type: Config.PropertyType.NUMBER,
name: { pl: 'ID startowe zamówienia PrestaShop', en: 'PrestaShop start order ID' },
description: {
pl: 'Opcjonalnie. Po zapisie nowej wartości import zacznie od tego zamówienia (włącznie), także wstecz. Cofnięcie może ponownie zaimportować zamówienia usunięte w Orbito.',
en: 'Optional. After saving a new value the import starts from this order (inclusive), also backwards. Moving back may re-import orders deleted in Orbito.',
},
},
};
}
// Runs right before the core saves the block; moves the import cursor only when the start ID changes.
async function validateImportBlock(params, report) {
const value = params?.startOrderId;
if (value == null || value === '') return;
const startOrderId = Number(value);
if (!Number.isInteger(startOrderId) || startOrderId < 1) {
report.addError('startOrderId', 'Podaj dodatnią liczbę całkowitą (ID zamówienia PrestaShop) albo zostaw pole puste.');
return;
}
if (Number(await Config.get('import.startOrderId', null)) === startOrderId) return;
await setLastOrderId(startOrderId - 1);
}
async function outboundMappingSchema(refreshPsStates) {
const [config, { statuses, error }, { states, refreshError }] = await Promise.all([
Config.getAll(), loadOrbitoStatuses(), refreshPsStates(),
]);
const mapping = readStatusMapping(config);
const schema = {
hint: info(
'Dla każdego statusu Orbito wybierz status PrestaShop. Kilka statusów Orbito może wskazywać ten sam status PrestaShop. Puste pole wyłącza wysyłkę tego statusu. Zmiany w sklepie nie nadpisują statusów Orbito.',
'Choose a PrestaShop state for each Orbito status. Multiple Orbito statuses may use the same PrestaShop state. An empty field disables synchronization for that status. Shop changes never overwrite Orbito statuses.',
),
};
if (error) schema.statusWarning = info(error);
if (refreshError) schema.refreshWarning = info(`Nie udało się odświeżyć statusów PrestaShop; pokazano ostatnio zapisane dane. ${refreshError}`);
const rows = new Map(statuses
.filter(status => normalizeStatusId(status._id))
.map(status => [String(status._id), status.name || String(status._id)]));
const values = states.map(state => ({ id: String(state.id), label: `${state.name || 'Status'} (PS #${state.id})` }));
for (const entry of mapping) {
if (!rows.has(entry.orbitoStatusId)) rows.set(entry.orbitoStatusId, `Status Orbito ${entry.orbitoStatusId} — niedostępny na liście`);
if (!values.some(value => value.id === String(entry.psStateId))) {
values.push({ id: String(entry.psStateId), label: `Status PrestaShop #${entry.psStateId} — niedostępny na liście` });
}
}
// Also keep explicitly cleared rows visible when their Orbito status disappears.
for (const key of Object.keys(config)) {
const id = /^mapping\.orbito_([a-f0-9]{24})$/i.exec(key)?.[1];
if (id && !rows.has(id)) rows.set(id, `Status Orbito ${id} — niedostępny na liście`);
}
for (const [id, name] of rows) {
const matches = [...new Set(mapping.filter(entry => entry.orbitoStatusId === id).map(entry => String(entry.psStateId)))];
const conflict = matches.length > 1;
schema[`orbito_${id}`] = {
type: Config.PropertyType.STRING,
name: { pl: name, en: name },
options: { values: conflict
? [{ id: LEGACY_CONFLICT, label: `Konflikt zapisanych przypisań: PS #${matches.join(', #')} — wybierz jeden status lub wyczyść` }, ...values]
: values },
};
}
return schema;
}
function validateOutboundMapping(params, report) {
for (const [field, value] of Object.entries(params || {})) {
if (!/^orbito_[a-f0-9]{24}$/i.test(field) || value == null || value === '') continue;
if (value === LEGACY_CONFLICT) {
report.addError(field, 'Zachowano wszystkie stare przypisania. Wybierz jeden status PrestaShop lub wyczyść pole, aby wyłączyć wysyłkę.');
} else if (!isPsStateId(value)) {
report.addError(field, 'Wybierz poprawny status PrestaShop.');
}
}
}
module.exports = { importStatusSchema, validateImportBlock, outboundMappingSchema, validateOutboundMapping };
+33 -2
View File
@@ -1,3 +1,5 @@
const LEGACY_CONFLICT = 'legacy_conflict';
function normalizeStatusId(value) {
if (value == null || value === '') return null;
if (typeof value === 'object' && value._id != null) {
@@ -34,8 +36,7 @@ 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.
// Kilka statusów Orbito może wskazywać ten sam status PrestaShop.
// 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) {
@@ -54,6 +55,33 @@ function resolvePsStateId(orbitoStatusId, statusMapping) {
return uniqueMatches[0] ?? null;
}
// Legacy keys remain untouched. An explicitly saved empty outbound field
// disables its legacy assignment; a missing field inherits it. Read all keys,
// including states no longer returned by the shop, to avoid losing mappings.
function readStatusMapping(config) {
const legacy = [];
const outbound = new Map();
for (const [key, value] of Object.entries(config)) {
const oldMatch = /^mapping\.state_(\d+)$/.exec(key);
const newMatch = /^mapping\.orbito_([a-f0-9]{24})$/i.exec(key);
if (oldMatch && normalizeStatusId(value)) {
legacy.push({ psStateId: Number(oldMatch[1]), orbitoStatusId: normalizeStatusId(value) });
}
if (newMatch && value !== LEGACY_CONFLICT) outbound.set(newMatch[1], value);
}
const result = legacy.filter(entry => !outbound.has(entry.orbitoStatusId));
for (const [orbitoStatusId, value] of outbound) {
if (value == null || value === '') continue;
if (!isPsStateId(value)) throw new Error(`Niepoprawny status PrestaShop dla statusu Orbito ${orbitoStatusId}`);
result.push({ orbitoStatusId, psStateId: Number(value) });
}
return result.sort((a, b) => a.psStateId - b.psStateId);
}
function isPsStateId(value) {
return /^\d+$/.test(String(value)) && Number.isSafeInteger(Number(value)) && Number(value) > 0;
}
function formatPsStatesPreview(states) {
if (!Array.isArray(states) || !states.length) {
return 'Brak statusów PrestaShop — najpierw przetestuj połączenie.';
@@ -76,6 +104,9 @@ function extractPsStateName(name) {
}
module.exports = {
LEGACY_CONFLICT,
readStatusMapping,
isPsStateId,
normalizeStatusId,
parseStatusMapping,
resolveStatusId,
+143 -12
View File
@@ -14,6 +14,36 @@ function text(value) {
return value == null ? '' : String(value).trim();
}
function statusVersion(order, psStateId) {
const date = order.statusDate ? new Date(order.statusDate) : null;
return {
orbitoStatusId: text(order.statusId),
statusDate: date && Number.isFinite(date.getTime()) ? date.toISOString() : '',
psStateId,
};
}
function sameVersion(left, right) {
return left?.orbitoStatusId === right.orbitoStatusId
&& 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';
@@ -46,23 +76,26 @@ 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 };
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.
// Kontrola okresowa wróci do zamówienia. SDK hooków może przechwycić
// wyjątek, więc nie polegamy na ponowieniu po stronie nadawcy.
throw new Error(`PrestaShop status sync is already running for order ${orderId}`);
}
let api;
try {
const [orderResult, config] = await Promise.all([
requestHook(Core, 'orders.search', { _id: orderId }),
@@ -70,13 +103,24 @@ async function syncOrderStatusToPrestashop(payload, dependencies) {
]);
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) {
return { skipped: true, reason: 'shop_not_configured' };
}
// Polling uzupełnia zmiany statusów, nie wysyła początkowego statusu
// importu. Rzeczywiste zdarzenie zawsze może uruchomić synchronizację.
if (payload.reconcile && !order.previousStatusId) {
return { skipped: true, reason: 'status_not_changed' };
}
// 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.
@@ -86,12 +130,65 @@ async function syncOrderStatusToPrestashop(payload, dependencies) {
return { skipped: true, reason: 'status_not_mapped' };
}
const psOrderId = Number(storedMapping?.psOrderId ?? order.source?.sourceId);
const psOrderId = Number(currentMapping?.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);
let mapping = currentMapping;
if (!mapping) {
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 };
const version = statusVersion(order, psStateId);
if (!mapping.statusSyncAttempt && sameVersion(mapping.statusSyncConfirmed, version)) {
return { synced: true, unchanged: true, orderId, psOrderId, orbitoStatusId, psStateId };
}
api = apiFor(config);
if (mapping.statusSyncAttempt) {
// Po timeoutcie lub restarcie wyłącznie odczyt. Niezgodny stan
// wymaga weryfikacji operatora, nigdy automatycznego drugiego POST.
const actualStateId = await api.getOrderState(psOrderId);
if (actualStateId !== mapping.statusSyncAttempt.psStateId) {
Log.warn('PrestaShop status sync requires verification; previous write outcome is uncertain', {
orderId, psOrderId, actualStateId, expectedStateId: mapping.statusSyncAttempt.psStateId,
});
return { skipped: true, reason: 'outcome_uncertain', orderId, psOrderId };
}
mapping.statusSyncConfirmed = mapping.statusSyncAttempt;
await PsOrder.update(mappingKey, {
$set: { statusSyncConfirmed: mapping.statusSyncConfirmed },
$unset: { statusSyncAttempt: '' },
});
}
if (sameVersion(mapping.statusSyncConfirmed, version)) {
return { synced: true, unchanged: true, orderId, psOrderId, orbitoStatusId, psStateId };
}
const result = await api.setOrderState(psOrderId, psStateId, {
beforeWrite: async () => {
const saved = await PsOrder.update(mappingKey, {
$set: { statusSyncAttempt: { ...version, attemptedAt: new Date() } },
});
if (saved?.matchedCount !== 1) throw new Error('Cannot persist PrestaShop status write attempt');
},
});
await PsOrder.update(mappingKey, {
$set: { statusSyncConfirmed: version },
$unset: { statusSyncAttempt: '' },
});
Log.info('PrestaShop order status synchronized from Orbito', {
orderId,
psOrderId,
@@ -114,6 +211,7 @@ async function syncOrderStatusToPrestashop(payload, dependencies) {
});
throw error;
} finally {
api?.close?.();
await Core.releaseLock(lockId).catch(error => {
Log.warn('PrestaShop status sync lock release failed', {
orderId,
@@ -125,15 +223,48 @@ async function syncOrderStatusToPrestashop(payload, dependencies) {
}
function registerStatusSyncHook(dependencies) {
return dependencies.Core.registerHook('event:order:status_changed', payload => (
syncOrderStatusToPrestashop(payload, dependencies)
));
return dependencies.Core.registerHook('event:order:status_changed', async payload => {
try {
const result = await syncOrderStatusToPrestashop(payload, dependencies);
if (result.skipped) dependencies.Log?.info('PrestaShop status event skipped', {
orderId: text(payload?.orderId), reason: result.reason,
});
return result;
} catch (error) {
// Obejmuje też błędy wyszukania dostawcy przed uzyskaniem locka.
dependencies.Log?.error('PrestaShop status event failed', {
orderId: text(payload?.orderId), error: error?.message,
});
throw error;
}
});
}
async function reconcileOrderStatuses(dependencies, isLockValid = () => true) {
const { PsOrder, Log = console } = dependencies;
// Najdawniej sprawdzane rekordy pierwsze; znacznik zapewnia rotację,
// także gdy kilka starych zamówień usunięto lub wymaga ręcznej weryfikacji.
const mappings = await PsOrder.find({ orbitoOrderId: { $exists: true, $ne: null } },
50, 0, { statusSyncCheckedAt: 1, _id: 1 });
for (const mapping of mappings) {
if (!isLockValid()) break;
try {
await syncOrderStatusToPrestashop({ orderId: text(mapping.orbitoOrderId), reconcile: true }, dependencies);
} catch (error) {
Log.warn('PrestaShop status reconciliation failed', {
orderId: text(mapping.orbitoOrderId), psOrderId: mapping.psOrderId, error: error?.message,
});
} finally {
await PsOrder.update({ _id: mapping._id }, { $set: { statusSyncCheckedAt: new Date() } });
}
}
}
module.exports = {
STATUS_SYNC_LOCK_TTL_SECONDS,
asOrders,
registerStatusSyncHook,
reconcileOrderStatuses,
sourceOwnershipError,
syncOrderStatusToPrestashop,
};
+151
View File
@@ -0,0 +1,151 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { mapOrderDiscounts } = require('../src/order-discounts');
const Module = require('node:module');
const path = require('node:path');
const source = { total_discounts: '75.35', total_discounts_tax_excl: '63.51', total_discounts_tax_incl: '75.35' };
const product = { qty: 3, unitPrice: 62.03, tax: 0.23 };
const sampleOrder = {
id: '4888', reference: 'MCBPBQOGI', payment: 'Próbki',
total_products: '0.000000', total_products_wt: '0.000000',
total_paid_tax_excl: '0.000000', total_paid_tax_incl: '0.000000', total_paid_real: '0.000000',
total_wrapping_tax_excl: '0.000000', total_wrapping_tax_incl: '0.000000',
total_discounts: '14.760000', total_discounts_tax_excl: '12.000000', total_discounts_tax_incl: '14.760000',
total_shipping_tax_excl: '12.000000', total_shipping_tax_incl: '14.760000', carrier_tax_rate: '23.000',
associations: { order_rows: [{ product_id: '784', product_attribute_id: '0',
product_name: 'MULTICOLOR', product_reference: 'NS.40.H.7016',
product_quantity: '2', unit_price_tax_excl: '0.000000', unit_price_tax_incl: '0.000000' }] },
};
test('6Q3-M9R: inconsistent source totals cannot manufacture 19% VAT', () => {
assert.deepEqual(mapOrderDiscounts(source, [product]), [
{ name: 'Rabat', type: 'product', amount: 61.26, gross: 75.35, tax: 0.23 },
]);
});
test('discounts follow actual VAT, including exempt and fractional rates', () => {
for (const tax of [0, 0.08, 0.19, 0.077]) {
const [discount] = mapOrderDiscounts(source, [{ ...product, tax }]);
assert.equal(discount.tax, tax);
assert.equal(discount.amount, Math.round(75.35 / (1 + tax) * 100) / 100);
assert.equal(discount.gross, 75.35);
}
assert.equal(mapOrderDiscounts(source, [product, { ...product, unitPrice: 0, tax: 0.08 }])[0].tax, 0.23);
assert.deepEqual(mapOrderDiscounts({ total_discounts: '0' }, []), []);
});
test('mixed or missing VAT requires a verified breakdown instead of a synthetic rate', () => {
for (const products of [[], [{ ...product, tax: undefined }], [product, { ...product, tax: 0.08 }],
[{ ...product, isPack: true, pack: [{ qty: 1, tax: 0.23 }, { qty: 1, tax: 0.08 }] }]]) {
assert.throws(() => mapOrderDiscounts(source, products), { code: 'DISCOUNT_TAX_AMBIGUOUS' });
}
assert.throws(() => mapOrderDiscounts({ ...source, total_discounts_tax_incl: 'invalid' }, [product]), /brutto/);
});
test('4888: zero-price samples retain a delivery discount using the source carrier VAT', () => {
for (const tax of [0, 0.08, 0.23, 0.077]) {
const gross = Math.round(12 * (1 + tax) * 100) / 100;
const order = { ...sampleOrder, carrier_tax_rate: String(tax * 100),
total_shipping_tax_incl: String(gross), total_discounts_tax_incl: String(gross), total_discounts: String(gross) };
assert.deepEqual(mapOrderDiscounts(order, [{ ...product, unitPrice: 0, qty: 2 }]), [
{ name: 'Darmowa dostawa', type: 'delivery', amount: 12, gross, tax },
]);
}
});
test('zero-price orders require matching source totals and an explicit delivery VAT', () => {
for (const overrides of [
{ total_products: '1' }, { total_products_wt: '1' },
{ total_paid_tax_excl: '1' }, { total_paid_tax_incl: '1' },
{ total_wrapping_tax_excl: '1' }, { total_wrapping_tax_incl: '1' },
{ total_products: undefined }, { total_paid_tax_incl: undefined },
{ total_discounts_tax_excl: '11' }, { total_shipping_tax_incl: '15' },
{ carrier_tax_rate: undefined }, { carrier_tax_rate: '' }, { carrier_tax_rate: '19' },
{ carrier_tax_rate: '-1' }, { carrier_tax_rate: 'invalid' }, { carrier_tax_rate: '101' },
]) {
assert.throws(() => mapOrderDiscounts({ ...sampleOrder, ...overrides }, [{ ...product, unitPrice: 0 }]),
{ code: 'DISCOUNT_TAX_AMBIGUOUS' }, JSON.stringify(overrides));
}
assert.throws(() => mapOrderDiscounts(sampleOrder, []), { code: 'DISCOUNT_TAX_AMBIGUOUS' });
assert.throws(() => mapOrderDiscounts(sampleOrder, [{ ...product, unitPrice: 0, qty: NaN }]),
{ code: 'DISCOUNT_TAX_AMBIGUOUS' });
});
async function importThroughHooks(providers, overrides = {}) {
const created = [];
const original = Module._load;
const Core = {
getModuleInfo: () => ({ code: 'core/prestashop' }),
async execHook(name, envelope) {
if (name.endsWith('.providers')) return providers.map(instanceId => ({ protocol: 'orbito.contract/1', moduleCode: 'alternative/orders', instanceId }));
let data;
if (name === 'orders.status.search') data = { results: [{ _id: '000000000000000000000001' }] };
else if (name === 'orders.create') { created.push(envelope.params); data = { _id: 'created-1' }; }
else throw new Error(name);
return [{ protocol: 'orbito.contract/1', instanceId: envelope.targetInstanceId, ok: true, data }];
},
};
Module._load = function(request, ...args) {
if (request === '@orbito/api-lib') return { Core, Log: { debug() {}, info() {}, warn() {}, error() {} } };
if (request === './models/PsOrder') return { update: async () => {}, findOne: async () => null };
return original.call(this, request, ...args);
};
const filename = path.resolve(__dirname, '../src/OrderImporter');
delete require.cache[require.resolve(filename)];
let importer;
try { importer = require(filename); } finally { Module._load = original; }
const order = { ...source, id: '4858', reference: 'MWSKTWLNP', id_address_delivery: '1', id_customer: '1',
id_currency: '1', total_shipping_tax_excl: '12', payment: 'B2B', date_add: '2026-10-08 11:40:00',
associations: { order_rows: [{ product_id: '1', product_name: 'PAVING', product_reference: 'NS.02.J',
product_attribute_id: '0', product_quantity: '3', unit_price_tax_excl: '62.03', unit_price_tax_incl: '76.30' }] },
...overrides,
};
const api = { isBLSupported: async () => false,
makeRequest: async endpoint => {
if (endpoint === `orders/${order.id}`) return { order };
if (endpoint === 'addresses/1') return { address: { id_country: '1', address1: 'Street', postcode: '00-001' } };
if (endpoint === 'customers/1') return { customer: { firstname: 'Test', lastname: 'Test', email: 'test@example.com' } };
throw new Error(endpoint);
},
getProduct: async () => ({ name: 'PAVING', type: 'standard' }),
getProductCoverImageUrl: async () => null,
getCurrency: async () => ({ iso_code: 'PLN' }), getCountry: async () => ({ iso_code: 'PL' }),
getCustomerNotes: async () => [],
};
try {
await importer.importFromPSOrder(order.id, api, { _id: 'shop-1', orderStatus: '000000000000000000000001' });
return { created };
} catch (error) { return { created, error }; }
}
test('real hook import delivers corrected discount to an alternative orders provider once', async () => {
const { created, error } = await importThroughHooks(['orders-account-1']);
assert.equal(error, undefined);
assert.equal(created.length, 1);
assert.deepEqual(created[0].discounts, [{ name: 'Rabat', type: 'product', amount: 61.26, gross: 75.35, tax: 0.23 }]);
});
test('4888 imports once through hooks with unchanged zero prices and matching delivery VAT', async () => {
const { created, error } = await importThroughHooks(['orders-account-1'], sampleOrder);
assert.equal(error, undefined);
assert.equal(created.length, 1);
assert.equal(created[0].source.uniqueId, 'MCBPBQOGI:4888');
assert.equal(created[0].products[0].unitPrice, 0);
assert.equal(created[0].products[0].qty, 2);
assert.deepEqual(created[0].delivery.cost, { amount: 12, tax: 0.23 });
assert.deepEqual(created[0].discounts, [
{ name: 'Darmowa dostawa', type: 'delivery', amount: 12, gross: 14.76, tax: 0.23 },
]);
assert.deepEqual(created[0].payments, []);
});
test('absent or multiple orders accounts do not create an order', async () => {
for (const providers of [[], ['orders-account-1', 'orders-account-2']]) {
for (const order of [{}, sampleOrder]) {
const result = await importThroughHooks(providers, order);
assert.equal(result.created.length, 0);
assert.match(result.error.code, /^HOOK_PROVIDER_(UNAVAILABLE|AMBIGUOUS)$/);
}
}
});
+33
View File
@@ -82,6 +82,39 @@ test('does not create a duplicate order history when PrestaShop already has the
assert.equal(calls, 1);
});
test('persists an attempt only before POST, and a persistence failure prevents POST', async t => {
const originalFetch = Core.fetch;
t.after(() => { Core.fetch = originalFetch; });
const steps = [];
Core.fetch = async (url, options) => {
steps.push(options.method);
return options.method === 'GET'
? response(200, { order: { id: '21', current_state: '2' } })
: response(201, { order_history: { id: '99', id_order: '21', id_order_state: '7' } });
};
const api = new PrestashopApi('https://shop.example', 'secret', true);
await api.setOrderState(21, 7, { beforeWrite: async () => steps.push('persist') });
assert.deepEqual(steps, ['GET', 'persist', 'POST']);
steps.length = 0;
await assert.rejects(api.setOrderState(21, 7, {
beforeWrite: async () => { throw new Error('database unavailable'); },
}), /database unavailable/);
assert.deepEqual(steps, ['GET']);
Core.fetch = async () => response(200, { order: { id: '21', current_state: '7' } });
await api.setOrderState(21, 7, { beforeWrite: async () => assert.fail('unnecessary attempt') });
});
test('uncertain status verification rejects a response for another order', async t => {
const originalFetch = Core.fetch;
t.after(() => { Core.fetch = originalFetch; });
Core.fetch = async () => response(200, { order: { id: '22', current_state: '7' } });
const api = new PrestashopApi('https://shop.example', 'secret', true);
await assert.rejects(api.getOrderState(21), /Invalid PrestaShop order state/);
await assert.rejects(api.setOrderState(21, 7, {
beforeWrite: async () => assert.fail('wrong order must not reach POST'),
}), /Invalid PrestaShop order state/);
});
test('rejects non-retryable 4xx and invalid JSON', async t => {
const originalFetch = Core.fetch;
t.after(() => { Core.fetch = originalFetch; });
+1
View File
@@ -32,6 +32,7 @@ test('saving a valid shop connection refreshes the persisted source icon', async
if (request === './status-mapper') return { extractPsStateName: value => value };
if (request === './module-config') {
return {
initializeOutboundMapping: async () => {},
setPsStates: async value => { savedStates = value; },
loadPsStates: async () => [],
};
+205 -51
View File
@@ -5,86 +5,157 @@ const test = require('node:test');
const registerConfigPath = path.resolve(__dirname, '../src/register-config.js');
function loadConfigModule({ states, cachedStates = [] }) {
const { registerContract } = require('../src/hook-contract');
const { readStatusMapping, resolvePsStateId } = require('../src/status-mapper');
const STATUS_A = '507f191e810c19729de860ea';
const STATUS_B = '507f191e810c19729de860eb';
function loadConfigModule({ states = [], cachedStates = [], saved = {}, providers = 1, failPs = false, failOrbito = false } = {}) {
let blocks;
let savedStates;
const store = {
'connection.apiUrl': 'https://shop.test',
'connection.apiKey': 'secret',
'connection.versionCode': '8',
'runtime.psStates': cachedStates,
...saved,
};
const hooks = new Map();
const requests = [];
for (let i = 0; i < providers; i++) {
registerContract({
getInstanceId: () => `order-provider-${i}`,
getModuleInfo: () => ({ code: 'alternative/orders' }),
registerHook: (name, handler) => hooks.set(name, [...(hooks.get(name) || []), handler]),
}, 'orders.status.search', async () => {
if (failOrbito) throw new Error('Status service offline');
return { results: [{ _id: STATUS_A, name: 'Do nadania' }, { _id: STATUS_B, name: 'Wysłane' }] };
});
}
const Config = {
PropertyType: { INFO: 'info', STRING: 'string', NUMBER: 'number' },
DisplayFormat: { URL: 'url', SECRET: 'secret' },
registerConfigBlocks: async value => { blocks = value; },
get: async (key, fallback) => Object.hasOwn(store, key) ? store[key] : fallback,
getAll: async () => ({ ...store }),
set: async (key, value) => { store[key] = value; },
};
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 === '@orbito/api-lib') return {
Config,
Core: { execHook: async (name, request) => {
requests.push({ name, request });
return Promise.all((hooks.get(name) || []).map(handler => handler.call({
caller: { moduleCode: 'core/prestashop', instanceId: 'shop-instance' },
}, request)));
} },
Log: { info() {}, warn() {} },
};
if (request === './PrestaApi') return class PrestashopApi {
async getStatuses() {
if (failPs) throw new Error('Shop offline');
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;
for (const file of ['../src/register-config', '../src/status-config', '../src/module-config']) {
delete require.cache[require.resolve(file)];
}
let loaded, loadConfig, initializeOutboundMapping;
try {
loaded = require(registerConfigPath);
} finally {
Module._load = originalLoad;
}
({ loadConfig, initializeOutboundMapping } = require('../src/module-config'));
} finally { Module._load = originalLoad; }
return {
...loaded,
...loaded, store, requests, loadConfig, initializeOutboundMapping, Config,
register: async () => {
await loaded.registerPrestashopConfigBlocks();
return blocks;
},
getSavedStates: () => savedStates,
};
}
test('opening the mapping block fetches and persists current PrestaShop state names', async () => {
test('mapping rows are Orbito statuses, with fresh local PrestaShop options obtained through the selected hook provider', async () => {
const module = loadConfigModule({
cachedStates: [{ id: 2, name: 'Stara nazwa', color: '#000000' }],
states: [{ id: '2', name: 'Nowa nazwa', color: '#00ff00', deleted: '0' }],
saved: { 'mapping.state_2': STATUS_A },
});
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' }]);
assert.equal(schema[`orbito_${STATUS_A}`].name.pl, 'Do nadania');
assert.equal(module.store[`mapping.orbito_${STATUS_A}`], '2');
assert.deepEqual(schema[`orbito_${STATUS_A}`].options, { values: [{ id: '2', label: 'Nowa nazwa (PS #2)' }] });
assert.equal(schema.state_2, undefined);
assert.deepEqual(module.store['runtime.psStates'], [{ id: 2, name: 'Nowa nazwa', color: '#00ff00' }]);
assert.equal(module.requests[1].request.targetInstanceId, 'order-provider-0');
assert.equal(module.store['mapping.state_2'], STATUS_A);
assert.equal(module.store[`mapping.orbito_${STATUS_A}`], '2');
});
test('mapping validation prevents two PrestaShop states from sharing one Orbito status', async () => {
const module = loadConfigModule({ states: [] });
const statusId = '507f191e810c19729de860ea';
test('two Orbito statuses can be saved and loaded with the same PrestaShop target without changing legacy data', async () => {
const module = loadConfigModule({ saved: { 'mapping.state_2': STATUS_A } });
const params = { [`orbito_${STATUS_A}`]: '2', [`orbito_${STATUS_B}`]: '2' };
const errors = [];
module.validateOutboundMapping(params, { addError: (...args) => errors.push(args) });
assert.deepEqual(errors, []);
for (const [field, value] of Object.entries(params)) module.store[`mapping.${field}`] = value;
const config = await module.loadConfig();
assert.equal(resolvePsStateId(STATUS_A, config.statusMapping), 2);
assert.equal(resolvePsStateId(STATUS_B, config.statusMapping), 2);
assert.equal(module.store['mapping.state_2'], STATUS_A);
});
module.validateOutboundMapping({
state_2: statusId,
state_3: statusId,
state_4: '507f191e810c19729de860eb',
}, {
addError: (field, message) => errors.push({ field, message }),
test('missing shop statuses and missing Orbito statuses retain their assignments and visible IDs', async () => {
const missingId = '507f191e810c19729de860ec';
const module = loadConfigModule({ saved: { 'mapping.state_99': missingId } });
const schema = await (await module.register()).mapping.schema();
assert.match(schema[`orbito_${missingId}`].name.pl, new RegExp(missingId));
assert.equal(module.store[`mapping.orbito_${missingId}`], '99');
assert.ok(schema[`orbito_${missingId}`].options.values.some(option => option.id === '99'));
assert.equal(resolvePsStateId(missingId, (await module.loadConfig()).statusMapping), 99);
});
for (const options of [{ providers: 0 }, { providers: 2 }, { failOrbito: true }]) {
test(`unavailable or ambiguous status provider is visible and preserves mapping: ${JSON.stringify(options)}`, async () => {
const module = loadConfigModule({ ...options, saved: { 'mapping.state_2': STATUS_A, 'import.orderStatus': STATUS_A } });
const blocks = await module.register();
const schema = await blocks.mapping.schema();
assert.match(schema.statusWarning.name.pl, /Nie udało się pobrać/);
assert.equal(module.store[`mapping.orbito_${STATUS_A}`], '2');
if (options.providers !== undefined) assert.ok(module.requests.every(request => request.name.endsWith('.providers')));
const importSchema = await blocks.import.schema();
assert.match(importSchema.statusWarning.name.pl, /Nie udało się pobrać/);
assert.equal(importSchema.orderStatus.options.values[0].id, STATUS_A);
assert.equal(module.store['mapping.state_2'], STATUS_A);
});
}
assert.deepEqual(errors.map(error => error.field), ['state_2', 'state_3']);
test('a shop outage shows cached names and never clears the mapping', async () => {
const module = loadConfigModule({ failPs: true, cachedStates: [{ id: 2, name: 'Oczekujące' }], saved: { 'mapping.state_2': STATUS_A } });
const schema = await (await module.register()).mapping.schema();
assert.match(schema.refreshWarning.name.pl, /Shop offline/);
assert.equal(module.store[`mapping.orbito_${STATUS_A}`], '2');
assert.equal(schema[`orbito_${STATUS_A}`].options.values[0].label, 'Oczekujące (PS #2)');
});
test('legacy conflicts keep every target and require an explicit choice before save', async () => {
const module = loadConfigModule({ saved: { 'mapping.state_2': STATUS_A, 'mapping.state_3': STATUS_A } });
const schema = await (await module.register()).mapping.schema();
const field = `orbito_${STATUS_A}`;
assert.equal(module.store[`mapping.${field}`], 'legacy_conflict');
assert.match(schema[field].options.values[0].label, /#2, #3/);
const errors = [];
module.validateOutboundMapping({ [field]: module.store[`mapping.${field}`] }, { addError: (...args) => errors.push(args) });
assert.equal(errors[0][0], field);
assert.throws(() => resolvePsStateId(STATUS_A, readStatusMapping(module.store)), /kilku statusów/);
module.store[`mapping.${field}`] = '3';
assert.equal(resolvePsStateId(STATUS_A, (await module.loadConfig()).statusMapping), 3);
assert.equal(module.store['mapping.state_2'], STATUS_A);
assert.equal(module.store['mapping.state_3'], STATUS_A);
});
test('connection validates the shop time zone and defaults to Europe/Warsaw', async () => {
@@ -108,6 +179,7 @@ test('config loading applies Warsaw to existing installations and passes a saved
const originalLoad = Module._load;
Module._load = function(request, parent, isMain) {
if (request === '@orbito/api-lib') return { Config: {
getAll: async () => ({}),
get: async (key, fallback) => key === 'connection.timeZone' ? savedTimeZone ?? fallback : fallback,
} };
return originalLoad.call(this, request, parent, isMain);
@@ -123,3 +195,85 @@ test('config loading applies Warsaw to existing installations and passes a saved
savedTimeZone = ' Europe/London ';
assert.equal((await loadConfig()).timeZone, 'Europe/London');
});
test('additive migration resumes after a failed write, preserves empty overrides and is idempotent', async () => {
const module = loadConfigModule({ saved: { 'mapping.state_2': STATUS_A, 'mapping.state_7': STATUS_B } });
const originalSet = module.Config.set;
let writes = 0;
module.Config.set = async (key, value) => {
if (++writes === 2) throw new Error('Interrupted write');
return originalSet(key, value);
};
await assert.rejects(module.initializeOutboundMapping, /Interrupted write/);
assert.equal(module.store[`mapping.orbito_${STATUS_A}`], '2');
assert.equal(Object.hasOwn(module.store, `mapping.orbito_${STATUS_B}`), false);
module.store[`mapping.orbito_${STATUS_A}`] = '';
module.Config.set = originalSet;
await module.initializeOutboundMapping();
assert.equal(module.store[`mapping.orbito_${STATUS_A}`], '');
assert.equal(module.store[`mapping.orbito_${STATUS_B}`], '7');
const saved = structuredClone(module.store);
await module.initializeOutboundMapping();
assert.deepEqual(module.store, saved);
const schema = await (await module.register()).mapping.schema();
assert.equal(schema[`orbito_${STATUS_A}`].default, undefined);
assert.equal(resolvePsStateId(STATUS_A, (await module.loadConfig()).statusMapping), null);
});
test('separate shop instances keep their own target IDs and options', async () => {
const a = loadConfigModule({ states: [{ id: 2, name: 'Sklep A' }], saved: { 'mapping.state_2': STATUS_A } });
const blocksA = await a.register();
const b = loadConfigModule({ states: [{ id: 7, name: 'Sklep B' }], saved: { 'mapping.state_7': STATUS_A } });
const blocksB = await b.register();
const schemaA = await blocksA.mapping.schema();
const schemaB = await blocksB.mapping.schema();
assert.deepEqual(schemaA[`orbito_${STATUS_A}`].options.values, [{ id: '2', label: 'Sklep A (PS #2)' }]);
assert.deepEqual(schemaB[`orbito_${STATUS_A}`].options.values, [{ id: '7', label: 'Sklep B (PS #7)' }]);
assert.equal(a.store[`mapping.orbito_${STATUS_A}`], '2');
assert.equal(b.store[`mapping.orbito_${STATUS_A}`], '7');
});
test('import block shows the import cursor or the first-import hint', async () => {
const withCursor = await (await loadConfigModule({ saved: { 'runtime.lastOrderId': 100 } }).register()).import.schema();
assert.match(withCursor.cursor.name.pl, /#100 — następny import zacznie od #101/);
assert.match(withCursor.cursor.name.en, /#100 — the next import starts from #101/);
assert.equal(withCursor.startOrderId.type, 'number');
const withoutCursor = await (await loadConfigModule().register()).import.schema();
assert.match(withoutCursor.cursor.name.pl, /Pierwszy import zacznie od najnowszego zamówienia/);
});
test('a changed start order ID moves the import cursor to the previous order, forwards and backwards', async () => {
const module = loadConfigModule({ saved: { 'runtime.lastOrderId': 100, 'import.startOrderId': 50 } });
const blocks = await module.register();
const errors = [];
const report = { addError: (...args) => errors.push(args) };
await blocks.import.validate({ orderStatus: STATUS_A, startOrderId: 150 }, report);
assert.equal(module.store['runtime.lastOrderId'], 149);
module.store['import.startOrderId'] = 150;
await blocks.import.validate({ orderStatus: STATUS_A, startOrderId: '20' }, report);
assert.equal(module.store['runtime.lastOrderId'], 19);
assert.deepEqual(errors, []);
});
test('an unchanged or cleared start order ID keeps the import cursor', async () => {
const module = loadConfigModule({ saved: { 'runtime.lastOrderId': 100, 'import.startOrderId': 50 } });
const blocks = await module.register();
const errors = [];
for (const startOrderId of [50, '50', '', null, undefined]) {
await blocks.import.validate({ orderStatus: STATUS_B, startOrderId }, { addError: (...args) => errors.push(args) });
}
assert.equal(module.store['runtime.lastOrderId'], 100);
assert.deepEqual(errors, []);
});
test('an invalid start order ID is reported and keeps the import cursor', async () => {
const module = loadConfigModule({ saved: { 'runtime.lastOrderId': 100 } });
const blocks = await module.register();
for (const startOrderId of [0, -5, 1.5, 'abc']) {
const errors = [];
await blocks.import.validate({ startOrderId }, { addError: (...args) => errors.push(args) });
assert.deepEqual(errors.map(([field]) => field), ['startOrderId']);
}
assert.equal(module.store['runtime.lastOrderId'], 100);
});
+27 -1
View File
@@ -1,7 +1,7 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { resolvePsStateId } = require('../src/status-mapper');
const { resolvePsStateId, readStatusMapping } = require('../src/status-mapper');
const STATUS_A = '507f191e810c19729de860ea';
const STATUS_B = '507f191e810c19729de860eb';
@@ -22,3 +22,29 @@ test('rejects an ambiguous outbound status mapping', () => {
{ psStateId: 3, orbitoStatusId: STATUS_A },
]), /kilku statusów PrestaShop/);
});
test('an outbound override affects only its Orbito status and preserves all other legacy assignments', () => {
const config = { 'mapping.state_2': STATUS_A, 'mapping.state_7': STATUS_B, [`mapping.orbito_${STATUS_A}`]: '7' };
const mapping = readStatusMapping(config);
assert.equal(resolvePsStateId(STATUS_A, mapping), 7);
assert.equal(resolvePsStateId(STATUS_B, mapping), 7);
assert.equal(config['mapping.state_2'], STATUS_A);
});
test('clearing an outbound field never resurrects its legacy mapping', () => {
for (const empty of ['', null]) {
const mapping = readStatusMapping({
'mapping.state_2': STATUS_A,
'mapping.state_7': STATUS_B,
[`mapping.orbito_${STATUS_A}`]: empty,
});
assert.equal(resolvePsStateId(STATUS_A, mapping), null);
assert.equal(resolvePsStateId(STATUS_B, mapping), 7);
}
});
test('invalid saved outbound state fails safely instead of sending a truncated state ID', () => {
for (const value of ['2foo', '-2', '0', '2.5']) {
assert.throws(() => readStatusMapping({ [`mapping.orbito_${STATUS_A}`]: value }), /Niepoprawny status/);
}
});
+187
View File
@@ -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');
});
+199
View File
@@ -0,0 +1,199 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { registerContract } = require('../src/hook-contract');
const { reconcileOrderStatuses, registerStatusSyncHook, syncOrderStatusToPrestashop } = require('../src/status-sync');
const ORDER_ID = '6ac74c9146601f810995d104';
const STATUS_ID = '6a706a2a51bb5be41a1b43c0';
const SHOP_INSTANCE = 'aaaaaaaaaaaaaaaaaaaaaaaa';
function fixture() {
const hooks = new Map();
const order = {
_id: ORDER_ID, statusId: STATUS_ID, previousStatusId: '6a706a2a51bb5be41a1b43be',
statusDate: '2026-10-08T08:18:57.788Z',
source: { moduleCode: 'core/prestashop', moduleId: SHOP_INSTANCE, sourceId: '4856' },
};
const mapping = { _id: 'bbbbbbbbbbbbbbbbbbbbbbbb', orbitoOrderId: ORDER_ID, psOrderId: 4856 };
const calls = { posts: 0, reads: 0, logs: [], locks: new Set() };
registerContract({
getInstanceId: () => 'other-author-orders',
getModuleInfo: () => ({ code: 'other-author/orders' }),
registerHook: (name, handler) => hooks.set(name, handler),
}, 'orders.search', async params => ({ data: params._id === ORDER_ID ? [order] : [] }));
const deps = {
Core: {
getInstanceId: () => SHOP_INSTANCE,
getModuleInfo: () => ({ code: 'core/prestashop' }),
registerHook: async (name, handler) => hooks.set(name, handler),
execHook: async (name, request) => {
const handler = hooks.get(name);
return handler ? [await handler.call({
caller: { instanceId: SHOP_INSTANCE, moduleCode: 'core/prestashop' },
}, request)] : [];
},
getLock: async name => {
if (calls.locks.has(name)) return null;
calls.locks.add(name);
return name;
},
releaseLock: async name => calls.locks.delete(name),
},
PsOrder: {
find: async () => [structuredClone(mapping)],
findOne: async () => structuredClone(mapping),
update: async (key, update) => {
Object.assign(mapping, structuredClone(update.$set || {}));
for (const field of Object.keys(update.$unset || {})) delete mapping[field];
return { matchedCount: 1 };
},
},
Log: Object.fromEntries(['info', 'warn', 'error'].map(level => [level,
(...args) => calls.logs.push([level, ...args])])),
loadConfig: async () => ({ apiUrl: 'https://shop.test', apiKey: 'test-key',
statusMapping: [{ orbitoStatusId: STATUS_ID, psStateId: 16 }] }),
apiFor: () => api,
};
const api = {
state: 12, loseResponse: false,
getOrderState: async () => { calls.reads++; return api.state; },
setOrderState: async (id, state, { beforeWrite }) => {
assert.equal(id, 4856);
if (api.state === state) return { unchanged: true };
await beforeWrite();
assert.equal(mapping.statusSyncAttempt.psStateId, state);
calls.posts++;
if (api.loseResponse) throw new Error('lost POST response');
api.state = state;
return { unchanged: false };
},
};
return { deps, order, mapping, calls, api, hooks };
}
test('recovers a missed status event through a real alternative-provider hook and persists confirmation', async () => {
const { deps, mapping, calls, api } = fixture();
await reconcileOrderStatuses(deps);
assert.equal(api.state, 16);
assert.equal(calls.posts, 1);
assert.equal(mapping.statusSyncConfirmed.orbitoStatusId, STATUS_ID);
assert.ok(mapping.statusSyncCheckedAt instanceof Date);
await reconcileOrderStatuses(deps);
assert.equal(calls.posts, 1);
});
test('lost POST response survives another run and blocks a second write until an external read confirms it', async () => {
const { deps, mapping, calls, api } = fixture();
api.loseResponse = true;
await reconcileOrderStatuses(deps);
assert.equal(calls.posts, 1);
assert.ok(mapping.statusSyncAttempt);
await reconcileOrderStatuses(deps);
assert.equal(calls.posts, 1);
assert.equal(calls.reads, 1);
assert.equal(mapping.statusSyncConfirmed, undefined);
assert.ok(calls.logs.some(row => /requires verification/.test(row[1])));
// PrestaShop did commit the earlier request. Read confirmation requires no POST.
api.state = 16;
await reconcileOrderStatuses(deps);
assert.equal(calls.posts, 1);
assert.equal(mapping.statusSyncAttempt, undefined);
assert.equal(mapping.statusSyncConfirmed.psStateId, 16);
});
test('failure before POST can be checked again without recording an uncertain mutation', async () => {
const { deps, mapping, calls, api } = fixture();
const write = api.setOrderState;
api.setOrderState = async () => { throw new Error('GET unavailable'); };
await reconcileOrderStatuses(deps);
assert.equal(mapping.statusSyncAttempt, undefined);
api.setOrderState = write;
await reconcileOrderStatuses(deps);
assert.equal(calls.posts, 1);
});
test('a crash while saving success is recovered by GET without a second history', async () => {
const { deps, mapping, calls } = fixture();
const save = deps.PsOrder.update;
let failConfirmation = true;
deps.PsOrder.update = async (key, update) => {
if (update.$set?.statusSyncConfirmed && failConfirmation) {
failConfirmation = false;
throw new Error('confirmation storage unavailable');
}
return save(key, update);
};
await reconcileOrderStatuses(deps);
assert.equal(calls.posts, 1);
assert.ok(mapping.statusSyncAttempt);
await reconcileOrderStatuses(deps);
assert.equal(calls.reads, 1);
assert.equal(calls.posts, 1);
assert.equal(mapping.statusSyncAttempt, undefined);
assert.equal(mapping.statusSyncConfirmed.psStateId, 16);
});
test('does not synchronize another installation or an initial import through polling', async () => {
const { deps, order, calls } = fixture();
order.source.moduleId = 'cccccccccccccccccccccccc';
await reconcileOrderStatuses(deps);
assert.equal(calls.posts, 0);
order.source.moduleId = SHOP_INSTANCE;
delete order.previousStatusId;
await reconcileOrderStatuses(deps);
assert.equal(calls.posts, 0);
// An explicit event still works without a historical previousStatusId field.
await syncOrderStatusToPrestashop({ orderId: ORDER_ID }, deps);
assert.equal(calls.posts, 1);
});
test('logs silent skip reasons and provider failures from the registered event handler', async () => {
const { deps, calls, hooks } = fixture();
await registerStatusSyncHook(deps);
const handler = hooks.get('event:order:status_changed');
await handler({ orderId: 'bad-id' });
assert.ok(calls.logs.some(row => row[2]?.reason === 'invalid_order_id'));
hooks.delete('orders.search.providers');
await assert.rejects(handler({ orderId: ORDER_ID }), /HOOK_PROVIDER_UNAVAILABLE/);
assert.ok(calls.logs.some(row => /status event failed/.test(row[1])));
assert.equal(calls.posts, 0);
});
test('lost attempt record prevents POST and a subsequent status change creates one new history', async () => {
const { deps, order, calls } = fixture();
const save = deps.PsOrder.update;
deps.PsOrder.update = async (key, update) => update.$set?.statusSyncAttempt
? { matchedCount: 0 } : save(key, update);
await assert.rejects(syncOrderStatusToPrestashop({ orderId: ORDER_ID }, deps), /Cannot persist/);
assert.equal(calls.posts, 0);
deps.PsOrder.update = save;
await reconcileOrderStatuses(deps);
order.statusDate = '2026-10-08T09:00:00Z';
const config = await deps.loadConfig();
config.statusMapping[0].psStateId = 4;
deps.loadConfig = async () => config;
await reconcileOrderStatuses(deps);
assert.equal(calls.posts, 2);
});
test('an unavailable or ambiguous provider cannot cause writes and still advances the scan', async () => {
const { deps, hooks, calls, mapping } = fixture();
hooks.delete('orders.search.providers');
await reconcileOrderStatuses(deps);
assert.equal(calls.posts, 0);
assert.ok(mapping.statusSyncCheckedAt);
deps.Core.execHook = async () => [
{ protocol: 'orbito.contract/1', instanceId: 'first-instance' },
{ protocol: 'orbito.contract/1', instanceId: 'second-instance' },
];
await reconcileOrderStatuses(deps);
assert.equal(calls.posts, 0);
assert.ok(calls.logs.some(row => /HOOK_PROVIDER_AMBIGUOUS/.test(row[2]?.error)));
});
test('reconciliation stops before reading any order when the worker loses its lock', async () => {
const { deps, calls, mapping } = fixture();
await reconcileOrderStatuses(deps, () => false);
assert.equal(calls.posts, 0);
assert.equal(mapping.statusSyncCheckedAt, undefined);
});
+36 -2
View File
@@ -36,7 +36,10 @@ function dependencies(overrides = {}) {
const deps = {
Core,
Log: { info() {}, warn() {}, error() {} },
PsOrder: { findOne: async () => ({ psOrderId: 21, orbitoOrderId: ORDER_ID }) },
PsOrder: {
findOne: async () => ({ psOrderId: 21, orbitoOrderId: ORDER_ID }),
update: async () => ({ matchedCount: 1 }),
},
loadConfig: async () => ({
apiUrl: 'https://shop.test',
apiKey: 'secret',
@@ -44,7 +47,8 @@ function dependencies(overrides = {}) {
}),
apiFor: () => ({
setOrderState: async (...args) => {
calls.setOrderState.push(args);
calls.setOrderState.push(args.slice(0, 2));
await args[2]?.beforeWrite();
return { unchanged: false };
},
}),
@@ -68,6 +72,36 @@ test('syncs the current Orbito status to the mapped PrestaShop state', async ()
assert.equal(result.synced, true);
});
test('different Orbito statuses both synchronize to their shared PrestaShop state', async () => {
const { registerContract } = require('../src/hook-contract');
const { readStatusMapping } = require('../src/status-mapper');
const { deps, calls } = dependencies();
let statusId = OLD_STATUS;
const hooks = new Map();
registerContract({
getInstanceId: () => 'alternative-orders-instance',
getModuleInfo: () => ({ code: 'alternative/orders' }),
registerHook: (name, handler) => hooks.set(name, handler),
}, 'orders.search', async () => ({ data: [{
_id: ORDER_ID, statusId,
source: { moduleCode: 'core/prestashop', moduleId: deps.Core.getInstanceId(), sourceId: '21' },
}] }));
deps.Core.execHook = async (name, request) => [await hooks.get(name).call({
caller: { moduleCode: 'core/prestashop', instanceId: deps.Core.getInstanceId() },
}, request)];
deps.loadConfig = async () => ({
apiUrl: 'https://shop.test', apiKey: 'secret',
statusMapping: readStatusMapping({
[`mapping.orbito_${OLD_STATUS}`]: '7',
[`mapping.orbito_${CURRENT_STATUS}`]: '7',
}),
});
await syncOrderStatusToPrestashop({ orderId: ORDER_ID }, deps);
statusId = CURRENT_STATUS;
await syncOrderStatusToPrestashop({ orderId: ORDER_ID }, deps);
assert.deepEqual(calls.setOrderState, [[21, 7], [21, 7]]);
});
test('ignores status events for an order owned by another PrestaShop instance', async () => {
const { deps, calls } = dependencies();
deps.Core.callModule = async () => ({ data: [{