Compare commits
24
Commits
ac64072f1b
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ff011e7e28 | ||
|
|
cdd761535a | ||
|
|
6ffbd2effa | ||
|
|
cc3ab1fd4a | ||
|
|
84c2b2087a | ||
|
|
8df9f36bb0 | ||
|
|
234addeadc | ||
|
|
1d40a05989 | ||
|
|
d140625ba0 | ||
|
|
86cf1a232f | ||
|
|
1f79463f51 | ||
|
|
599a7b9863 | ||
|
|
6b5e03246e | ||
|
|
93ebfe728d | ||
|
|
be4284bdd6 | ||
|
|
3030e9439c | ||
|
|
aa5297c5d8 | ||
|
|
11f1c99e2b | ||
|
|
af0dceaa1b | ||
|
|
519f8daeb0 | ||
|
|
8230135a2e | ||
|
|
7c917d7a59 | ||
|
|
57c95fa83d | ||
|
|
7e84524714 |
@@ -0,0 +1,16 @@
|
||||
# Orbito — zasady modułu dla agentów AI
|
||||
|
||||
Jeśli pracujesz w pełnym workspace Orbito, przed zmianami przeczytaj [../codex.md](../codex.md). W osobnym klonie repozytorium nadal obowiązują wszystkie poniższe reguły.
|
||||
|
||||
1. **Komunikacja między modułami wyłącznie przez hooki. Jedyny wyjątek: `core/orders → core/products`.** Wyjątek jest jednostronny i nieprzechodni.
|
||||
2. Nie dodawaj bezpośredniego RPC/HTTP do innego modułu, importów jego kodu lub danych, innych zależności `dependsOn` ani stałych obcych celów w UI. Wrapper, proxy lub dynamiczna nazwa nie stanowią obejścia tej reguły.
|
||||
3. Nie wpisuj na sztywno konkretnego dostawcy ani klienta API. Zakazane jest np. zaufanie tylko do `core/packing` w orders. Sprawdzaj uwierzytelniony kontekst i uprawnienia. Własne identyfikatory, lokalne funkcje i SDK platformy są dozwolone.
|
||||
4. Używaj istniejącego `src/hook-contract.js` i jawnych kontraktów domenowych. Brak kontraktu rozwiąż przez jego dodanie lub rozszerzenie, bez awaryjnego powrotu do RPC. Każda paczka ma działać samodzielnie.
|
||||
5. Obsłuż zero, jednego i wielu dostawców oraz kilka kont jednego modułu. Komenda ma wskazywać jedną instancję przed efektem; nie wybieraj pierwszej odpowiedzi i nie ponawiaj automatycznie niepewnego efektu. Nie zgaduj właściciela danych historycznych.
|
||||
6. Listy konfiguracji pobieraj hookiem w bieżącej instancji, np. jako `options.values` z `{ id, label }`. Nie zakładaj, że `options.module` adresuje właściwe konto. Zachowuj zapisane ID i pokazuj błąd niedostępnej listy.
|
||||
7. Przy zmianach integracji uruchom testy modułu oraz, z katalogu pełnego workspace, `node --test --test-concurrency=1 --test-force-exit module-contracts/*.test.js`. Dodaj odpowiedni test regresji prawdziwej ścieżki hooków. Nie osłabiaj kontroli architektury. Jeżeli workspace lub testy są niedostępne, podaj ograniczenie zamiast deklarować pełną weryfikację.
|
||||
8. **Nie modyfikuj `ordershub-backend` ani `ordershub-frontend`**, także przez zbiorcze polecenia. Zachowuj istniejące zmiany użytkownika. Ogólne polecenie naprawy lub publikacji nie zezwala na wyjątki od architektury.
|
||||
|
||||
## Code Review Rules
|
||||
|
||||
Zgłaszaj bezpośrednie powiązania między modułami także poza manifestem: zaszytego klienta API, obcy cel formularza, import modelu, fallback RPC i arbitralny wybór dostawcy. Sprawdź kontrakt, wybór instancji i test z alternatywnym dostawcą.
|
||||
@@ -1,4 +1,127 @@
|
||||
# Moduł do integracji Prestashop
|
||||
|
||||
Moduł podłącza się do sklepu podanego w konfiguracji i dodaje zamówienia za pomocą
|
||||
modułu `core/orders`
|
||||
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
|
||||
w strefie sklepu ustawionej w „Połączenie ze sklepem → Strefa czasowa sklepu”.
|
||||
Domyślnie jest to `Europe/Warsaw`, również dla istniejących konfiguracji bez
|
||||
tego pola. Dla sklepu w innej strefie ustaw jej nazwę IANA, np. `Europe/London`.
|
||||
Przeliczenie uwzględnia czas letni i zimowy, niezależnie od strefy serwera.
|
||||
Daty zawierające już `Z` lub offset zachowują wskazany moment.
|
||||
|
||||
Poprawka dotyczy nowych importów zamówień i płatności. Nie zmienia dat już
|
||||
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
|
||||
„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.
|
||||
|
||||
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
|
||||
identyfikator kombinacji wynosi `0`. Przy kolejnym imporcie zgodny rekord ze
|
||||
starszym, numerycznym `sourceId` jest bezpiecznie migrowany po SKU. Dane wariantu
|
||||
obejmują jego referencję, EAN, lokalizację magazynową, zdjęcie i wagę produktu
|
||||
powiększoną o wpływ wagi kombinacji. Cena bazowa netto katalogu jest pobierana
|
||||
z ceny produktu PrestaShop powiększonej o wpływ ceny kombinacji; cena pozycji
|
||||
zamówienia pozostaje niezależną ceną transakcyjną i nie nadpisuje katalogu.
|
||||
|
||||
Podczas importu zamówienia moduł zapisuje publiczne wiadomości klienta jako
|
||||
`customer_message`. Obsługuje standardowe zasoby PrestaShop: `messages` po
|
||||
`id_order` i `id_cart`, wątki `customer_threads` oraz ich `customer_messages`,
|
||||
a także standardowe `gift_message`. Dotyczy to też `DeliveryMessage` / pola
|
||||
`delivery_message` z checkoutu, które PrestaShop zapisuje w standardowym
|
||||
`messages` po `id_cart`. Klucz Webservice musi mieć uprawnienie GET
|
||||
do tych zasobów. Niedostępny endpoint powoduje ostrzeżenie bez logowania treści
|
||||
wiadomości i nie blokuje importu zamówienia.
|
||||
|
||||
Wiadomości prywatne i wpisy pracowników są pomijane, a kopie tej samej treści
|
||||
z checkoutu i wątku klienta są deduplikowane. Moduł nie odczytuje prywatnych
|
||||
tabel ani niestandardowych pól checkoutów. Zmiana działa dla nowo importowanych
|
||||
zamówień; nie wykonuje automatycznego backfillu istniejących zamówień.
|
||||
|
||||
@@ -4,17 +4,21 @@ 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, 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).
|
||||
const JOB_LOCK_TTL_SECONDS = 5 * 60;
|
||||
const runtime = createJobRuntime(Core, Log);
|
||||
|
||||
Utils.loadMethods(__dirname + '/methods');
|
||||
require('./src/register-contracts').registerContracts();
|
||||
|
||||
registerPrestashopConfigBlocks().catch(error => {
|
||||
Log.error('PrestaShop: nie udało się zarejestrować bloków Config', { error: error?.message });
|
||||
@@ -27,6 +31,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) {
|
||||
@@ -74,14 +82,18 @@ async function syncShopIcon() {
|
||||
}
|
||||
|
||||
const jobs = [
|
||||
new CronJob('0 */5 * * * *', () => runtime.track(() =>
|
||||
runtime.withRenewedLock('prestashop-orders-puller', 5 * 60 * 1000, runOrdersPuller)
|
||||
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)
|
||||
)),
|
||||
new CronJob('0 */3 * * * *', () => runtime.track(() =>
|
||||
runtime.withRenewedLock('prestashop-payments-sync', 5 * 60 * 1000, valid => runPaymentSync('recent', valid))
|
||||
runtime.withRenewedLock('prestashop-payments-sync', JOB_LOCK_TTL_SECONDS, valid => runPaymentSync('recent', valid))
|
||||
)),
|
||||
new CronJob('30 */30 * * * *', () => runtime.track(() =>
|
||||
runtime.withRenewedLock('prestashop-payments-sync', 5 * 60 * 1000, valid => runPaymentSync('older', valid))
|
||||
runtime.withRenewedLock('prestashop-payments-sync', JOB_LOCK_TTL_SECONDS, valid => runPaymentSync('older', valid))
|
||||
)),
|
||||
];
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
const PrestashopApi = require('../../src/PrestaApi');
|
||||
const { isLegacyApi } = require('../../src/utils');
|
||||
const { loadConfig, isConfigured } = require('../../src/module-config');
|
||||
const { PERMISSIONS, requirePermission } = require('../../src/register-permissions');
|
||||
const { findMetadataBySourceAndSku } = require('../../src/product-metadata');
|
||||
|
||||
const MAX_PRODUCTS = 100;
|
||||
const METADATA_CONCURRENCY = 5;
|
||||
|
||||
function normalizeRequestProduct(value) {
|
||||
const sourceId = String(value?.sourceId ?? '').trim();
|
||||
const sku = String(value?.sku ?? '').trim();
|
||||
if (!sourceId || !sku) return null;
|
||||
return { sourceId, sku };
|
||||
}
|
||||
|
||||
function uniqueProducts(products) {
|
||||
const seen = new Set();
|
||||
const result = [];
|
||||
for (const value of Array.isArray(products) ? products : []) {
|
||||
const product = normalizeRequestProduct(value);
|
||||
if (!product) continue;
|
||||
const key = `${product.sourceId}\u0000${product.sku.toUpperCase()}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
result.push(product);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function mapWithConcurrency(values, concurrency, worker) {
|
||||
let nextIndex = 0;
|
||||
const runners = Array.from({ length: Math.min(concurrency, values.length) }, async () => {
|
||||
while (nextIndex < values.length) {
|
||||
const index = nextIndex++;
|
||||
await worker(values[index], index);
|
||||
}
|
||||
});
|
||||
await Promise.all(runners);
|
||||
}
|
||||
|
||||
module.exports = async function(params, ctx) {
|
||||
requirePermission(PERMISSIONS.ORDERS_VIEW, ctx);
|
||||
|
||||
const products = uniqueProducts(params?.products);
|
||||
if (products.length === 0) return { results: [] };
|
||||
if (products.length > MAX_PRODUCTS) throw new Error('products exceeds the 100 item limit');
|
||||
|
||||
const config = await loadConfig();
|
||||
if (!isConfigured(config)) return { results: [] };
|
||||
|
||||
const api = new PrestashopApi(config.apiUrl, config.apiKey, isLegacyApi(config.versionCode));
|
||||
const results = new Array(products.length);
|
||||
await mapWithConcurrency(products, METADATA_CONCURRENCY, async (product, index) => {
|
||||
try {
|
||||
const metadata = await findMetadataBySourceAndSku(api, product);
|
||||
if (metadata) results[index] = { ...product, ...metadata };
|
||||
} catch (_) { /* one product must not block the remaining metadata batch */ }
|
||||
});
|
||||
|
||||
return { results: results.filter(Boolean) };
|
||||
};
|
||||
|
||||
module.exports._private = { MAX_PRODUCTS, METADATA_CONCURRENCY, uniqueProducts, mapWithConcurrency };
|
||||
@@ -1,8 +1,9 @@
|
||||
const { requestHook } = require('../../src/hook-contract');
|
||||
const { Core } = require('@orbito/api-lib');
|
||||
const { PERMISSIONS, requirePermission } = require('../../src/register-permissions');
|
||||
|
||||
// Proxy do core/orders — statusy są współdzielone i zarządzane w core/orders.
|
||||
module.exports = async function(params, ctx) {
|
||||
requirePermission(PERMISSIONS.ORDERS_VIEW, ctx);
|
||||
return Core.callModule('core/orders', 'status.get_with_counts', params || {});
|
||||
return requestHook(Core, 'orders.status.get_with_counts', params || {});
|
||||
};
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
const { Core } = require('@orbito/api-lib');
|
||||
const { requestHook } = require('../../src/hook-contract');
|
||||
const { PERMISSIONS, requirePermission } = require('../../src/register-permissions');
|
||||
module.exports = { params: {}, async handler(params, ctx) {
|
||||
requirePermission(PERMISSIONS.ORDERS_VIEW, ctx);
|
||||
return requestHook(Core, 'orders.status.search', params || {});
|
||||
} };
|
||||
+2
-1
@@ -1,3 +1,4 @@
|
||||
const { requestHook } = require('../src/hook-contract');
|
||||
const { Core } = require('@orbito/api-lib');
|
||||
const PrestashopApi = require('../src/PrestaApi');
|
||||
const { importFromPSOrder } = require('../src/OrderImporter');
|
||||
@@ -29,7 +30,7 @@ module.exports = async function(params, ctx) {
|
||||
const errors = [];
|
||||
for (const order of orders) {
|
||||
const uniqueId = order.reference + ':' + order.id;
|
||||
const searchResult = await Core.callModule( 'core/orders', 'search', {
|
||||
const searchResult = await requestHook(Core, 'orders.search', {
|
||||
// własny kod modułu bierzemy z core (po rejestracji), nie z hardcode'u
|
||||
source: { moduleCode: Core.getModuleInfo().code, uniqueId }
|
||||
});
|
||||
|
||||
+11
-7
@@ -1,9 +1,13 @@
|
||||
{
|
||||
"name": "core/prestashop",
|
||||
"version": "1.1.4",
|
||||
"singleton": false,
|
||||
"dependsOn": [
|
||||
"core/orders",
|
||||
"core/products"
|
||||
]
|
||||
"name": "core/prestashop",
|
||||
"version": "1.3.2",
|
||||
"singleton": false,
|
||||
"files": [
|
||||
"index.js",
|
||||
"package.json",
|
||||
"package-lock.json",
|
||||
"src/",
|
||||
"methods/",
|
||||
"README.md"
|
||||
]
|
||||
}
|
||||
|
||||
Generated
+7
-6
@@ -1,18 +1,19 @@
|
||||
{
|
||||
"name": "core.prestashop",
|
||||
"version": "1.1.4",
|
||||
"version": "1.3.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "core.prestashop",
|
||||
"version": "1.1.4",
|
||||
"version": "1.3.2",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@orbito/api-lib": "^2.2.1",
|
||||
"@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",
|
||||
@@ -20,9 +21,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@orbito/api-lib": {
|
||||
"version": "2.2.1",
|
||||
"resolved": "https://git.kozminski.net.pl/api/packages/orbito/npm/%40orbito%2Fapi-lib/-/2.2.1/api-lib-2.2.1.tgz",
|
||||
"integrity": "sha512-y0xFkU8IIObdniRiuEX9t4+gOxdwA3t6+a7xkJVvAogB4+4r+7Vlo9VNW9w6GABXX5xTrSIsPRkx/I1lnVdsVQ==",
|
||||
"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",
|
||||
|
||||
+4
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "core.prestashop",
|
||||
"version": "1.1.4",
|
||||
"version": "1.3.2",
|
||||
"description": "Integracja zamówień i płatności PrestaShop",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
@@ -10,13 +10,14 @@
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@orbito/api-lib": "^2.2.1",
|
||||
"@orbito/api-lib": "^4.4.3",
|
||||
"cron": "^4.4.0",
|
||||
"dotenv": "^17.2.3",
|
||||
"ejs": "^4.0.1",
|
||||
"js2xmlparser": "^5.0.0",
|
||||
"nanoid": "^5.1.6",
|
||||
"node-cache": "^5.1.2",
|
||||
"uuid": "^11.1.0"
|
||||
"uuid": "^11.1.0",
|
||||
"fastest-validator": "^1.19.1"
|
||||
}
|
||||
}
|
||||
|
||||
+150
-64
@@ -1,7 +1,15 @@
|
||||
const { requestHook } = require('./hook-contract');
|
||||
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 { mapOrderDiscounts } = require('./order-discounts');
|
||||
const {
|
||||
buildProductSourceId,
|
||||
resolveProductMetadata,
|
||||
} = require('./product-metadata');
|
||||
|
||||
const DEFAULT_PACK_ITEM_TAX = 0.23;
|
||||
|
||||
function getPSMultiLangField(param, langId) {
|
||||
if (Array.isArray(param)) {
|
||||
@@ -18,8 +26,52 @@ function getPSMultiLangField(param, langId) {
|
||||
return param;
|
||||
}
|
||||
|
||||
function normalizeCombinationId(value) {
|
||||
const id = String(value ?? '').trim();
|
||||
return /^\d+$/.test(id) && id !== '0' ? id : '0';
|
||||
}
|
||||
|
||||
function isCombinationForProduct(combination, productId) {
|
||||
return combination
|
||||
&& String(combination.id_product ?? '').trim() === String(productId ?? '').trim();
|
||||
}
|
||||
|
||||
function resolveProductWeight(product, combination = null) {
|
||||
const baseWeight = Number.parseFloat(product?.weight);
|
||||
if (!combination) return Number.isFinite(baseWeight) ? baseWeight : undefined;
|
||||
|
||||
// In PrestaShop a combination's weight is an impact added to the base
|
||||
// product weight, not the final weight of the variant.
|
||||
const weightImpact = Number.parseFloat(combination.weight);
|
||||
if (Number.isFinite(baseWeight) && Number.isFinite(weightImpact)) return baseWeight + weightImpact;
|
||||
if (Number.isFinite(baseWeight)) return baseWeight;
|
||||
return Number.isFinite(weightImpact) ? weightImpact : undefined;
|
||||
}
|
||||
|
||||
function applyCombinationFields(target, combination) {
|
||||
if (!combination) return;
|
||||
if (String(combination.reference || '').trim()) target.sku = combination.reference;
|
||||
if (Object.hasOwn(combination, 'ean13')) target.ean = combination.ean13 || '';
|
||||
}
|
||||
|
||||
async function resolvePackItemTax(api, productId, combinationId, context) {
|
||||
try {
|
||||
if (typeof api.getProductTaxRate === 'function') {
|
||||
const tax = await api.getProductTaxRate(productId, combinationId, context);
|
||||
if (Number.isFinite(tax) && tax >= 0 && tax <= 1) return tax;
|
||||
}
|
||||
} catch (error) {
|
||||
Log.warn('Could not resolve PrestaShop pack item VAT; using the default rate', {
|
||||
productId,
|
||||
combinationId,
|
||||
error: error?.message,
|
||||
});
|
||||
}
|
||||
return DEFAULT_PACK_ITEM_TAX;
|
||||
}
|
||||
|
||||
async function resolveImportStatusId(config) {
|
||||
const statusResult = await Core.callModule( 'core/orders', 'status.search', {});
|
||||
const statusResult = await requestHook(Core, 'orders.status.search', {});
|
||||
const statuses = statusResult?.results ?? [];
|
||||
const byId = new Map();
|
||||
|
||||
@@ -50,65 +102,124 @@ async function importFromPSOrder(orderId, api, config) {
|
||||
throw new Error(`PrestaShop order ${orderId} not found`);
|
||||
}
|
||||
|
||||
const addressResponse = await api.makeRequest(
|
||||
'addresses/' + order.id_address_delivery,
|
||||
'GET',
|
||||
{ output_format: "JSON" }
|
||||
);
|
||||
const address = addressResponse.address;
|
||||
if (!address) throw new Error(`Delivery address ${order.id_address_delivery} not found`);
|
||||
const productTaxContext = {
|
||||
countryId: address.id_country,
|
||||
stateId: address.id_state,
|
||||
postcode: address.postcode,
|
||||
currencyId: order.id_currency,
|
||||
};
|
||||
|
||||
Log.info( "Importing order: " + order.reference);
|
||||
|
||||
let products = [];
|
||||
for (let product of order.associations.order_rows) {
|
||||
const productId = String(product.product_id);
|
||||
const combinationId = normalizeCombinationId(product.product_attribute_id);
|
||||
let unitPriceNet = parseFloat(product.unit_price_tax_excl); // jednak cen nie możemy zaokrąglać, bo presta pracuje w cenach brutto
|
||||
let unitPriceGross = parseFloat(product.unit_price_tax_incl);
|
||||
let taxRate = unitPriceNet ? (unitPriceGross - unitPriceNet) / unitPriceNet : 0;
|
||||
const p = {
|
||||
name: product.product_name,
|
||||
sourceId: product.product_id,
|
||||
sourceId: buildProductSourceId(productId, combinationId),
|
||||
sku: product.product_reference,
|
||||
ean: product.product_ean13,
|
||||
unitPrice: unitPriceNet,
|
||||
tax: taxRate ? Math.round(taxRate * 100) / 100 : 0,
|
||||
qty: parseFloat(product.product_quantity)
|
||||
};
|
||||
// Jednorazowa migracja starej tożsamości produktu odbywa się już po
|
||||
// stronie katalogu produktów przez synchroniczny kontrakt zamówieniach.
|
||||
p.previousSourceId = productId;
|
||||
|
||||
const psProduct = await api.getProduct(product.product_id);
|
||||
const psProduct = await api.getProduct(productId);
|
||||
Log.debug( "Fetched product details: " + getPSMultiLangField(psProduct.name));
|
||||
p.weight = parseFloat(psProduct.weight);
|
||||
|
||||
let productCombination = null;
|
||||
if (combinationId !== '0') {
|
||||
const combination = await api.getProductCombination(combinationId);
|
||||
if (isCombinationForProduct(combination, productId)) {
|
||||
productCombination = combination;
|
||||
applyCombinationFields(p, combination);
|
||||
}
|
||||
}
|
||||
const productWeight = resolveProductWeight(psProduct, productCombination);
|
||||
if (productWeight !== undefined) p.weight = productWeight;
|
||||
|
||||
try {
|
||||
const imgUrl = await api.getProductCoverImageUrl(product.product_id);
|
||||
const imgUrl = await api.getProductCoverImageUrl(productId, productCombination);
|
||||
if (imgUrl) p.coverImageUrl = imgUrl;
|
||||
} catch (_) { /* no image available */ }
|
||||
|
||||
if (parseInt(product.product_attribute_id) > 0) {
|
||||
const combination = await api.getProductCombination(product.product_attribute_id);
|
||||
if (combination) {
|
||||
const w = parseFloat(combination.weight);
|
||||
if (!isNaN(w)) p.weight = w;
|
||||
try {
|
||||
const metadata = await resolveProductMetadata(api, psProduct, {
|
||||
sourceId: productId,
|
||||
sku: p.sku,
|
||||
combination: productCombination,
|
||||
requiresCombination: combinationId !== '0',
|
||||
});
|
||||
if (Object.hasOwn(metadata, 'unitPrice')) {
|
||||
p.baseUnitPrice = metadata.unitPrice;
|
||||
delete metadata.unitPrice;
|
||||
}
|
||||
}
|
||||
Object.assign(p, metadata);
|
||||
} catch (_) { /* optional product metadata must not block order import */ }
|
||||
|
||||
if (psProduct.type == "pack" && psProduct.associations.product_bundle) {
|
||||
p.isPack = true;
|
||||
p.pack = [];
|
||||
for (const packItem of psProduct.associations.product_bundle) {
|
||||
const psItem = await api.getProduct(packItem.id);
|
||||
const packProductId = String(packItem.id);
|
||||
const packCombinationId = normalizeCombinationId(packItem.id_product_attribute);
|
||||
const psItem = await api.getProduct(packProductId);
|
||||
const pData = {
|
||||
name: getPSMultiLangField(psItem.name),
|
||||
sourceId: psItem.id,
|
||||
sourceId: buildProductSourceId(packProductId, packCombinationId),
|
||||
sku: psItem.reference,
|
||||
ean: psItem.ean13,
|
||||
weight: parseFloat(psItem.weight),
|
||||
qty: parseFloat(packItem.quantity)
|
||||
};
|
||||
pData.previousSourceId = packProductId;
|
||||
|
||||
if (parseInt(packItem.id_product_attribute) > 0) {
|
||||
const combination = await api.getProductCombination(packItem.id_product_attribute);
|
||||
if (combination) {
|
||||
const w = parseFloat(combination.weight);
|
||||
if (!isNaN(w)) pData.weight = w;
|
||||
pData.sku = combination.reference || pData.sku;
|
||||
let packCombination = null;
|
||||
if (packCombinationId !== '0') {
|
||||
const combination = await api.getProductCombination(packCombinationId);
|
||||
if (isCombinationForProduct(combination, packProductId)) {
|
||||
packCombination = combination;
|
||||
applyCombinationFields(pData, combination);
|
||||
}
|
||||
}
|
||||
const packWeight = resolveProductWeight(psItem, packCombination);
|
||||
if (packWeight !== undefined) pData.weight = packWeight;
|
||||
pData.tax = await resolvePackItemTax(
|
||||
api,
|
||||
packProductId,
|
||||
packCombinationId,
|
||||
productTaxContext
|
||||
);
|
||||
|
||||
try {
|
||||
const imgUrl = await api.getProductCoverImageUrl(packItem.id);
|
||||
const metadata = await resolveProductMetadata(api, psItem, {
|
||||
sourceId: packProductId,
|
||||
sku: pData.sku,
|
||||
combination: packCombination,
|
||||
requiresCombination: packCombinationId !== '0',
|
||||
});
|
||||
if (Object.hasOwn(metadata, 'unitPrice')) {
|
||||
pData.baseUnitPrice = metadata.unitPrice;
|
||||
delete metadata.unitPrice;
|
||||
}
|
||||
Object.assign(pData, metadata);
|
||||
} catch (_) { /* optional product metadata must not block order import */ }
|
||||
|
||||
try {
|
||||
const imgUrl = await api.getProductCoverImageUrl(packProductId, packCombination);
|
||||
if (imgUrl) pData.coverImageUrl = imgUrl;
|
||||
} catch (_) { /* no image */ }
|
||||
|
||||
@@ -119,35 +230,18 @@ async function importFromPSOrder(orderId, api, config) {
|
||||
products.push(p);
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
products
|
||||
.filter(p => p.sourceId && p.name)
|
||||
.map(p => Core.callModule( 'core/products', 'upsert', {
|
||||
// własny kod modułu bierzemy z core (po rejestracji), nie z hardcode'u
|
||||
sourceModule: Core.getModuleInfo().code,
|
||||
sourceId: String(p.sourceId),
|
||||
sku: p.sku || '',
|
||||
name: p.name,
|
||||
unitPrice: p.unitPrice,
|
||||
ean: p.ean,
|
||||
coverImageUrl: p.coverImageUrl || undefined,
|
||||
}).catch(() => {}))
|
||||
);
|
||||
|
||||
const fallbackStatusId = await resolveImportStatusId(config);
|
||||
if (!fallbackStatusId) {
|
||||
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
|
||||
});
|
||||
|
||||
@@ -155,9 +249,6 @@ async function importFromPSOrder(orderId, api, config) {
|
||||
const customer = res.customer;
|
||||
Log.debug( "Fetched customer details", { email: customer.email, name: customer.firstname + " " + customer.lastname });
|
||||
|
||||
res = await api.makeRequest('addresses/' + order.id_address_delivery, 'GET', { output_format: "JSON" });
|
||||
const address = res.address;
|
||||
|
||||
let carrierName = "Brak wybranej dostawy";
|
||||
if (order.id_carrier) {
|
||||
try {
|
||||
@@ -222,31 +313,24 @@ 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);
|
||||
const payments = [];
|
||||
if (totalPaidReal > 0) {
|
||||
payments.push({
|
||||
amount: Math.round(totalPaidReal * 100) / 100,
|
||||
method: order.payment || 'PrestaShop',
|
||||
date: new Date(order.date_add),
|
||||
date: createdAt,
|
||||
transactionId: paymentTransactionId(config, order.id, totalPaidReal),
|
||||
});
|
||||
}
|
||||
|
||||
const coreOrder = await Core.callModule( 'core/orders', 'create', {
|
||||
const customerNotes = await api.getCustomerNotes(order.id, order.id_cart, order.gift_message);
|
||||
|
||||
const coreOrder = await requestHook(Core, 'orders.create', {
|
||||
statusId: statusId,
|
||||
customer: {
|
||||
name: customer.firstname + " " + customer.lastname,
|
||||
@@ -285,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")
|
||||
@@ -294,11 +379,12 @@ async function importFromPSOrder(orderId, api, config) {
|
||||
payments,
|
||||
discounts,
|
||||
invoice: invoiceDataForOrder,
|
||||
createdAt: new Date(order.date_add),
|
||||
notes: customerNotes.map(text => ({ text, type: 'customer_message' })),
|
||||
createdAt,
|
||||
});
|
||||
|
||||
if (!coreOrder?._id) {
|
||||
throw new Error(`core/orders create did not return an id for PrestaShop order ${order.id}`);
|
||||
throw new Error(`Order creation did not return an id for PrestaShop order ${order.id}`);
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
@@ -307,7 +393,7 @@ async function importFromPSOrder(orderId, api, config) {
|
||||
psOrderId: parseInt(order.id),
|
||||
orbitoOrderId: coreOrder._id,
|
||||
reference: order.reference || '',
|
||||
syncedAt: parsePrestashopDate(order.date_add, now),
|
||||
syncedAt: createdAt,
|
||||
paymentTotalSynced: totalPaidReal,
|
||||
paymentSyncedAt: totalPaidReal > 0 ? now : undefined,
|
||||
paymentCheckedAt: now,
|
||||
|
||||
+261
-8
@@ -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);
|
||||
@@ -199,6 +203,103 @@ module.exports = class PrestashopApi {
|
||||
return combination;
|
||||
}
|
||||
|
||||
async getProductTaxRate(productId, combinationId = 0, context = {}) {
|
||||
const id = String(productId ?? '').trim();
|
||||
const attributeId = String(combinationId ?? '0').trim() || '0';
|
||||
if (!/^\d+$/.test(id) || id === '0' || !/^\d+$/.test(attributeId)) return null;
|
||||
|
||||
const countryId = String(context.countryId ?? '').trim();
|
||||
const stateId = String(context.stateId ?? '').trim();
|
||||
const currencyId = String(context.currencyId ?? '').trim();
|
||||
const postcode = String(context.postcode ?? '').trim().slice(0, 32);
|
||||
const cacheKey = [
|
||||
'product_tax_rate', id, attributeId, countryId, stateId, postcode, currencyId,
|
||||
].join('_');
|
||||
const cached = this.cache.get(cacheKey);
|
||||
if (cached !== undefined) return cached;
|
||||
|
||||
const params = { output_format: 'JSON' };
|
||||
const addPriceParams = (alias, useTax) => {
|
||||
params[`price[${alias}][use_tax]`] = useTax ? 1 : 0;
|
||||
params[`price[${alias}][use_reduction]`] = 0;
|
||||
params[`price[${alias}][use_ecotax]`] = 0;
|
||||
params[`price[${alias}][quantity]`] = 1;
|
||||
if (attributeId !== '0') params[`price[${alias}][product_attribute]`] = attributeId;
|
||||
if (/^\d+$/.test(countryId) && countryId !== '0') params[`price[${alias}][country]`] = countryId;
|
||||
if (/^\d+$/.test(stateId) && stateId !== '0') params[`price[${alias}][state]`] = stateId;
|
||||
if (postcode) params[`price[${alias}][postcode]`] = postcode;
|
||||
if (/^\d+$/.test(currencyId) && currencyId !== '0') params[`price[${alias}][currency]`] = currencyId;
|
||||
};
|
||||
addPriceParams('orbito_price_net', false);
|
||||
addPriceParams('orbito_price_gross', true);
|
||||
|
||||
const response = await this.makeRequest(`products/${id}`, 'GET', params, true);
|
||||
const product = response?.product;
|
||||
const net = Number.parseFloat(String(product?.orbito_price_net ?? '').replace(',', '.'));
|
||||
const gross = Number.parseFloat(String(product?.orbito_price_gross ?? '').replace(',', '.'));
|
||||
if (!Number.isFinite(net) || net <= 0 || !Number.isFinite(gross) || gross < net) return null;
|
||||
|
||||
const taxRate = Math.round(((gross - net) / net) * 100000000) / 100000000;
|
||||
if (!Number.isFinite(taxRate) || taxRate < 0 || taxRate > 1) return null;
|
||||
this.cache.set(cacheKey, taxRate);
|
||||
return taxRate;
|
||||
}
|
||||
|
||||
async getManufacturer(manufacturerId) {
|
||||
const id = String(manufacturerId || '').trim();
|
||||
if (!id) return null;
|
||||
|
||||
const cacheKey = "manufacturer_" + id;
|
||||
let manufacturer = this.cache.get(cacheKey);
|
||||
if (!manufacturer) {
|
||||
const res = await this.makeRequest('manufacturers/' + id, 'GET', { output_format: "JSON" });
|
||||
manufacturer = res.manufacturer || null;
|
||||
if (manufacturer) this.cache.set(cacheKey, manufacturer);
|
||||
}
|
||||
|
||||
return manufacturer;
|
||||
}
|
||||
|
||||
async findProductCombinationsByReference(productId, reference) {
|
||||
const id = String(productId || '').trim();
|
||||
const sku = String(reference || '').trim();
|
||||
if (!/^\d+$/.test(id) || !sku || /[\[\],|%]/.test(sku)) return null;
|
||||
|
||||
const cacheKey = `product_combinations_${id}_${sku}`;
|
||||
const cached = this.cache.get(cacheKey);
|
||||
if (cached) return cached;
|
||||
|
||||
const res = await this.makeRequest('combinations', 'GET', {
|
||||
output_format: "JSON",
|
||||
display: 'full',
|
||||
'filter[id_product]': `[${id}]`,
|
||||
'filter[reference]': `[${sku}]`,
|
||||
});
|
||||
const combinations = Array.isArray(res.combinations) ? res.combinations : [];
|
||||
this.cache.set(cacheKey, combinations);
|
||||
return combinations;
|
||||
}
|
||||
|
||||
async getStockAvailabilities(productId, productAttributeId = 0) {
|
||||
const id = String(productId || '').trim();
|
||||
const attributeId = String(productAttributeId || '0').trim();
|
||||
if (!/^\d+$/.test(id) || !/^\d+$/.test(attributeId)) return [];
|
||||
|
||||
const cacheKey = `stock_availabilities_${id}_${attributeId}`;
|
||||
const cached = this.cache.get(cacheKey);
|
||||
if (cached) return cached;
|
||||
|
||||
const res = await this.makeRequest('stock_availables', 'GET', {
|
||||
output_format: "JSON",
|
||||
display: 'full',
|
||||
'filter[id_product]': `[${id}]`,
|
||||
'filter[id_product_attribute]': `[${attributeId}]`,
|
||||
});
|
||||
const stockAvailabilities = Array.isArray(res.stock_availables) ? res.stock_availables : [];
|
||||
this.cache.set(cacheKey, stockAvailabilities);
|
||||
return stockAvailabilities;
|
||||
}
|
||||
|
||||
async getStatuses() {
|
||||
let cacheKey = "statuses";
|
||||
let statuses = this.cache.get(cacheKey);
|
||||
@@ -227,16 +328,159 @@ module.exports = class PrestashopApi {
|
||||
return res?.order_payments || [];
|
||||
}
|
||||
|
||||
async setOrderState(orderId, stateId) {
|
||||
if (this.legacy) {
|
||||
return await this.updateOrderLegacy(orderId, {
|
||||
current_state: stateId
|
||||
});
|
||||
async getCustomerNotes(orderId, cartId, giftMessage) {
|
||||
const sources = [];
|
||||
const safeOrderId = this._resourceId(orderId);
|
||||
const safeCartId = this._resourceId(cartId);
|
||||
|
||||
if (safeOrderId) {
|
||||
sources.push(this._getPublicMessages('id_order', safeOrderId, safeOrderId));
|
||||
sources.push(this._getPublicCustomerThreadMessages(safeOrderId));
|
||||
}
|
||||
if (safeCartId) sources.push(this._getPublicMessages('id_cart', safeCartId, safeOrderId));
|
||||
|
||||
const result = [];
|
||||
const seen = new Set();
|
||||
this._addCustomerNote(result, seen, giftMessage, { gift: true });
|
||||
|
||||
const settled = await Promise.allSettled(sources);
|
||||
for (const source of settled) {
|
||||
if (source.status === 'rejected') {
|
||||
Log.warn('PrestaShop customer-note source could not be read', { error: source.reason?.message });
|
||||
continue;
|
||||
}
|
||||
for (const message of source.value) this._addCustomerNote(result, seen, message);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
_resourceId(value) {
|
||||
const id = String(value ?? '').trim();
|
||||
return /^\d+$/.test(id) && id !== '0' ? id : null;
|
||||
}
|
||||
|
||||
_isPublicCustomerMessage(message) {
|
||||
if (!message || typeof message !== 'object') return false;
|
||||
const privateValue = String(message?.private ?? '').trim().toLowerCase();
|
||||
const employeeId = String(message?.id_employee ?? '').trim();
|
||||
return ['', '0', 'false'].includes(privateValue) && (!employeeId || employeeId === '0');
|
||||
}
|
||||
|
||||
_messageText(value) {
|
||||
return typeof value === 'string' ? value.trim() : '';
|
||||
}
|
||||
|
||||
_addCustomerNote(notes, seen, value, { gift = false } = {}) {
|
||||
const text = this._messageText(value);
|
||||
const key = text.replace(/\r\n/g, '\n');
|
||||
if (!text || seen.has(key)) return;
|
||||
seen.add(key);
|
||||
notes.push(gift ? `Wiadomość dołączona do prezentu: ${text}` : text);
|
||||
}
|
||||
|
||||
_matchesResourceId(value, expectedId) {
|
||||
return String(value ?? '').trim() === expectedId;
|
||||
}
|
||||
|
||||
async _getPublicMessages(field, id, orderId) {
|
||||
const res = await this.makeRequest('messages', 'GET', {
|
||||
output_format: 'JSON',
|
||||
display: 'full',
|
||||
sort: 'id_ASC',
|
||||
[`filter[${field}]`]: `[${id}]`,
|
||||
});
|
||||
const messages = Array.isArray(res?.messages) ? res.messages : [];
|
||||
return messages
|
||||
.filter(message => this._isPublicCustomerMessage(message))
|
||||
.filter(message => this._matchesResourceId(message?.[field], id))
|
||||
.filter(message => field !== 'id_cart'
|
||||
|| !this._resourceId(message?.id_order)
|
||||
|| this._matchesResourceId(message.id_order, orderId))
|
||||
.map(message => message.message);
|
||||
}
|
||||
|
||||
async _getPublicCustomerThreadMessages(orderId) {
|
||||
const res = await this.makeRequest('customer_threads', 'GET', {
|
||||
output_format: 'JSON',
|
||||
display: 'full',
|
||||
'filter[id_order]': `[${orderId}]`,
|
||||
});
|
||||
const threads = (Array.isArray(res?.customer_threads) ? res.customer_threads : [])
|
||||
.filter(thread => this._matchesResourceId(thread?.id_order, orderId));
|
||||
const threadIds = threads
|
||||
.map(thread => this._resourceId(thread?.id))
|
||||
.filter(Boolean);
|
||||
const settled = await Promise.allSettled(threadIds
|
||||
.map(threadId => this.makeRequest('customer_messages', 'GET', {
|
||||
output_format: 'JSON',
|
||||
display: 'full',
|
||||
sort: 'id_ASC',
|
||||
'filter[id_customer_thread]': `[${threadId}]`,
|
||||
})));
|
||||
|
||||
const messages = [];
|
||||
for (const [index, response] of settled.entries()) {
|
||||
if (response.status === 'rejected') {
|
||||
Log.warn('PrestaShop customer-thread messages could not be read', { error: response.reason?.message });
|
||||
continue;
|
||||
}
|
||||
const threadId = threadIds[index];
|
||||
for (const message of Array.isArray(response.value?.customer_messages) ? response.value.customer_messages : []) {
|
||||
if (this._isPublicCustomerMessage(message)
|
||||
&& this._matchesResourceId(message?.id_customer_thread, threadId)) {
|
||||
messages.push(message.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
return messages;
|
||||
}
|
||||
|
||||
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');
|
||||
}
|
||||
|
||||
return await this.updateOrder(orderId, {
|
||||
current_state: stateId
|
||||
// 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 (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
|
||||
|| 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 };
|
||||
}
|
||||
|
||||
async updateOrder(orderId, data) {
|
||||
@@ -291,7 +535,16 @@ module.exports = class PrestashopApi {
|
||||
return url + sep + 'ws_key=' + encodeURIComponent(this.apiKey);
|
||||
}
|
||||
|
||||
async getProductCoverImageUrl(productId) {
|
||||
async getProductCoverImageUrl(productId, combination = null) {
|
||||
const combinationImages = combination?.associations?.images;
|
||||
const combinationImage = Array.isArray(combinationImages)
|
||||
? combinationImages[0]
|
||||
: combinationImages;
|
||||
const combinationImageId = combinationImage?.id;
|
||||
if (combinationImageId && combinationImageId !== '0') {
|
||||
return this.getProductImageUrl(productId, combinationImageId);
|
||||
}
|
||||
|
||||
const product = await this.getProduct(productId);
|
||||
const defaultImageId = product.id_default_image;
|
||||
if (defaultImageId && defaultImageId !== '0' && defaultImageId !== '') {
|
||||
|
||||
+15
-25
@@ -1,5 +1,7 @@
|
||||
const { requestHook } = require('./hook-contract');
|
||||
const DEFAULT_PAGE_SIZE = 50;
|
||||
const DEFAULT_MAX_PAGES = 10;
|
||||
const { parsePrestashopDate } = require('./prestashop-date');
|
||||
|
||||
function money(value) {
|
||||
const number = Number(value);
|
||||
@@ -22,12 +24,6 @@ function orderUniqueId(order) {
|
||||
return `${order.reference}:${order.id}`;
|
||||
}
|
||||
|
||||
function parsePrestashopDate(value, fallback = new Date()) {
|
||||
if (!value) return fallback;
|
||||
const parsed = new Date(String(value).replace(' ', 'T'));
|
||||
return Number.isNaN(parsed.getTime()) ? fallback : parsed;
|
||||
}
|
||||
|
||||
async function upsertMapping(PsOrder, data) {
|
||||
const key = {
|
||||
shopConfigId: String(data.shopConfigId),
|
||||
@@ -64,26 +60,20 @@ async function ensureExistingOrderMapping({ config, api, psOrderSummary, orbitoO
|
||||
...key,
|
||||
orbitoOrderId: orbitoOrder._id,
|
||||
reference: psOrderSummary.reference || psOrder.reference || '',
|
||||
syncedAt: parsePrestashopDate(psOrder.date_add),
|
||||
syncedAt: parsePrestashopDate(psOrder.date_add, new Date(), config.timeZone),
|
||||
paymentTotalSynced: Math.min(psPaid, orbitoPaid),
|
||||
paymentCheckedAt: new Date(),
|
||||
nextPaymentCheckAt: new Date(),
|
||||
});
|
||||
}
|
||||
|
||||
function stableOrders(orders, nowMs = Date.now()) {
|
||||
function stableOrders(orders, nowMs = Date.now(), timeZone) {
|
||||
const cutoff = nowMs - 30 * 1000;
|
||||
const newestDate = orders[orders.length - 1]?.date_add;
|
||||
let offsetMs = 0;
|
||||
if (newestDate) {
|
||||
const drift = parsePrestashopDate(newestDate).getTime() - nowMs;
|
||||
if (drift > 60000) offsetMs = Math.round(drift / 3600000) * 3600000;
|
||||
}
|
||||
const stable = [];
|
||||
for (const order of orders) {
|
||||
// Only return a contiguous prefix. Skipping a still-changing order and
|
||||
// advancing to a later id would make that skipped id unreachable by the cursor.
|
||||
if (parsePrestashopDate(order.date_add).getTime() - offsetMs >= cutoff) break;
|
||||
if (parsePrestashopDate(order.date_add, new Date(nowMs), timeZone).getTime() >= cutoff) break;
|
||||
stable.push(order);
|
||||
}
|
||||
return stable;
|
||||
@@ -123,14 +113,15 @@ async function importOrdersForShop(config, api, dependencies = {}) {
|
||||
output_format: 'JSON',
|
||||
'filter[id]': `[${startingCursor + 1},999999999]`,
|
||||
});
|
||||
const orders = stableOrders(Array.isArray(response?.orders) ? response.orders : [], now());
|
||||
const orders = stableOrders(Array.isArray(response?.orders) ? response.orders : [], now(), config.timeZone);
|
||||
let cursor = startingCursor;
|
||||
let processed = 0;
|
||||
let hasGap = false;
|
||||
|
||||
for (const order of orders) {
|
||||
if (!isLockValid()) throw new Error('PrestaShop orders lock was lost');
|
||||
try {
|
||||
const result = await Core.callModule('core/orders', 'search', {
|
||||
const result = await requestHook(Core, 'orders.search', {
|
||||
source: { moduleCode: 'core/prestashop', uniqueId: orderUniqueId(order) },
|
||||
});
|
||||
const existingOrder = asOrders(result)[0];
|
||||
@@ -142,14 +133,13 @@ async function importOrdersForShop(config, api, dependencies = {}) {
|
||||
throw new Error(`Importer returned an invalid result for order ${order.id}`);
|
||||
}
|
||||
}
|
||||
cursor = Number(order.id);
|
||||
if (!hasGap) cursor = Number(order.id);
|
||||
processed += 1;
|
||||
} catch (error) {
|
||||
const previousCursor = cursor;
|
||||
cursor = Number(order.id);
|
||||
Log.error('Failed to import PS order; skipping order and continuing', {
|
||||
hasGap = true;
|
||||
Log.error('Failed to import PS order; keeping cursor before the gap and continuing', {
|
||||
orderId: order.id,
|
||||
previousCursor,
|
||||
previousCursor: cursor,
|
||||
cursor,
|
||||
error: error.message,
|
||||
});
|
||||
@@ -182,7 +172,7 @@ function duePaymentsQuery(config, since, until, nowDate) {
|
||||
async function processPaymentMapping(mapping, config, api, dependencies) {
|
||||
const { Core, PsOrder, nowDate, nextCheckMs, retryCheckMs, Log = console } = dependencies;
|
||||
try {
|
||||
const orderResult = await Core.callModule('core/orders', 'search', { _id: mapping.orbitoOrderId });
|
||||
const orderResult = await requestHook(Core, 'orders.search', { _id: mapping.orbitoOrderId });
|
||||
const order = asOrders(orderResult)[0];
|
||||
if (!order) throw new Error(`Orbito order ${mapping.orbitoOrderId} not found`);
|
||||
|
||||
@@ -206,12 +196,12 @@ async function processPaymentMapping(mapping, config, api, dependencies) {
|
||||
|
||||
if (amount > 0) {
|
||||
const transactionId = paymentTransactionId(config, mapping.psOrderId, psPaid);
|
||||
await Core.callModule('core/orders', 'payments.upsert', {
|
||||
await requestHook(Core, 'orders.payments.upsert', {
|
||||
orderId: String(mapping.orbitoOrderId),
|
||||
payment: {
|
||||
amount,
|
||||
method: psOrder.payment || 'PrestaShop',
|
||||
date: parsePrestashopDate(psOrder.date_upd || psOrder.date_add, nowDate),
|
||||
date: parsePrestashopDate(psOrder.date_upd || psOrder.date_add, nowDate, config.timeZone),
|
||||
transactionId,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
'use strict';
|
||||
|
||||
// Distributed with each module: no runtime dependency on another package.
|
||||
const PROTOCOL = 'orbito.contract/1';
|
||||
const INSTANCE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
||||
|
||||
function failure(code, message, details = {}) {
|
||||
return Object.assign(new Error(message || code), { code, ...details });
|
||||
}
|
||||
|
||||
function envelopes(value) {
|
||||
return (Array.isArray(value) ? value.flat(Infinity) : [value])
|
||||
.filter(item => item && item.protocol === PROTOCOL);
|
||||
}
|
||||
|
||||
async function resolveProvider(Core, contract, target = {}) {
|
||||
const discovered = envelopes(await Core.execHook(`${contract}.providers`, {
|
||||
targetInstanceId: target.instanceId, targetModuleCode: target.moduleCode,
|
||||
}));
|
||||
const candidates = discovered.filter(provider =>
|
||||
INSTANCE_ID.test(provider.instanceId || '')
|
||||
&& (!target.instanceId || provider.instanceId === target.instanceId)
|
||||
&& (!target.moduleCode || provider.moduleCode === target.moduleCode));
|
||||
// Never choose an arbitrary installation, even when both have the same code.
|
||||
if (candidates.length !== 1) {
|
||||
const code = candidates.length ? 'HOOK_PROVIDER_AMBIGUOUS' : 'HOOK_PROVIDER_UNAVAILABLE';
|
||||
throw failure(code, `${code}: ${contract}`, { outcomeUncertain: false, retryable: true });
|
||||
}
|
||||
return candidates[0];
|
||||
}
|
||||
|
||||
async function requestHook(Core, contract, params = {}, target = {}) {
|
||||
const provider = await resolveProvider(Core, contract, target);
|
||||
let results;
|
||||
try {
|
||||
results = envelopes(await Core.execHook(contract, {
|
||||
protocol: PROTOCOL, targetInstanceId: provider.instanceId, params,
|
||||
})).filter(result => result.instanceId === provider.instanceId);
|
||||
} catch (error) {
|
||||
throw failure('HOOK_RESULT_UNCERTAIN', error?.message, { outcomeUncertain: true, retryable: false });
|
||||
}
|
||||
if (results.length !== 1 || typeof results[0].ok !== 'boolean') {
|
||||
throw failure('HOOK_RESULT_UNCERTAIN', `Brak jednoznacznego wyniku: ${contract}`, {
|
||||
outcomeUncertain: true, retryable: false,
|
||||
});
|
||||
}
|
||||
const result = results[0];
|
||||
if (!result.ok) {
|
||||
const { message, ...details } = result.error || {};
|
||||
throw failure(details.code || 'HOOK_OPERATION_FAILED', message, details);
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
|
||||
function serializeError(error) {
|
||||
const result = { code: String(error?.code || 'HOOK_OPERATION_FAILED'), message: String(error?.message || error) };
|
||||
for (const key of ['outcomeUncertain', 'retryable', 'partialSuccess', 'externalId', 'status']) {
|
||||
if (error?.[key] !== undefined) result[key] = error[key];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function requestProvider(Core, domain, provider, operation, params = {}) {
|
||||
if (!/^[A-Za-z][A-Za-z0-9_.]*$/.test(operation || '')) {
|
||||
return Promise.reject(failure('INVALID_PROVIDER_OPERATION'));
|
||||
}
|
||||
return requestHook(Core, `${domain}.${operation}`, params, {
|
||||
instanceId: provider?.instanceId,
|
||||
// Historical records may only have a module code. Discovery still
|
||||
// requires exactly one installation before executing their operation.
|
||||
moduleCode: provider?.moduleCode,
|
||||
});
|
||||
}
|
||||
|
||||
function internalContext(context) {
|
||||
// Hooks document caller provenance, not the RPC-only system flag. The
|
||||
// platform authenticates this identity from the module connection. Map
|
||||
// that internal transport to the existing RPC context, preserving any
|
||||
// explicit permission restriction supplied by the platform. Public UI
|
||||
// entry points still check their user's permissions before emitting a hook.
|
||||
if (context?.system === false || !INSTANCE_ID.test(context?.caller?.instanceId || '')
|
||||
|| typeof context?.caller?.moduleCode !== 'string' || !context.caller.moduleCode.trim()) {
|
||||
throw failure('INTERNAL_CALL_REQUIRED', 'INTERNAL_CALL_REQUIRED', { outcomeUncertain: false });
|
||||
}
|
||||
return { ...context, system: true, permissions: Array.isArray(context.permissions) ? context.permissions : ['*'] };
|
||||
}
|
||||
|
||||
function registerContract(Core, contract, definition) {
|
||||
const handler = typeof definition === 'function' ? definition : definition.handler;
|
||||
if (typeof handler !== 'function') throw new TypeError(`Invalid contract handler: ${contract}`);
|
||||
const validate = definition.params
|
||||
? new (require('fastest-validator'))({ useNewCustomCheckerFunction: true }).compile(definition.params)
|
||||
: () => true;
|
||||
Core.registerHook(`${contract}.providers`, function() {
|
||||
return { protocol: PROTOCOL, instanceId: Core.getInstanceId(), moduleCode: Core.getModuleInfo().code };
|
||||
});
|
||||
Core.registerHook(contract, async function(request) {
|
||||
const instanceId = Core.getInstanceId();
|
||||
// Ignore another installation's command before validation or side effects.
|
||||
if (request?.protocol !== PROTOCOL || request.targetInstanceId !== instanceId) return null;
|
||||
try {
|
||||
const ctx = internalContext(this);
|
||||
const params = request.params;
|
||||
if (!params || typeof params !== 'object' || Array.isArray(params)) {
|
||||
throw failure('INVALID_CONTRACT_PARAMS');
|
||||
}
|
||||
for (const key of ['caller', 'permissions', 'userId', 'system']) {
|
||||
if (Object.prototype.hasOwnProperty.call(params, key)) throw failure('CONTRACT_CONTEXT_OVERRIDE_FORBIDDEN');
|
||||
}
|
||||
const valid = await validate(params);
|
||||
if (valid !== true) throw failure('INVALID_CONTRACT_PARAMS', JSON.stringify(valid), { outcomeUncertain: false });
|
||||
return { protocol: PROTOCOL, instanceId, ok: true, data: await handler.call(ctx, params, ctx) };
|
||||
} catch (error) {
|
||||
// SDK swallows thrown hook errors. Return them as protocol data.
|
||||
return { protocol: PROTOCOL, instanceId, ok: false, error: serializeError(error) };
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { PROTOCOL, requestHook, requestProvider, resolveProvider, registerContract, internalContext };
|
||||
+13
-4
@@ -13,21 +13,30 @@ function createJobRuntime(Core, Log = console) {
|
||||
return promise;
|
||||
}
|
||||
|
||||
async function withRenewedLock(lockName, ttlMs, operation) {
|
||||
const lockId = await Core.getLock(lockName, ttlMs);
|
||||
/**
|
||||
* Uruchamia operację pod rozproszonym lockiem, odnawiając go w tle.
|
||||
*
|
||||
* @param {string} lockName - Nazwa locka
|
||||
* @param {number} ttlSeconds - TTL locka w SEKUNDACH (jednostka wymagana przez Core.getLock/Core.extendLockTime)
|
||||
* @param {(isLockValid: () => boolean) => Promise<*>} operation - Operacja do wykonania pod lockiem
|
||||
*/
|
||||
async function withRenewedLock(lockName, ttlSeconds, operation) {
|
||||
const lockId = await Core.getLock(lockName, ttlSeconds);
|
||||
if (!lockId) return null;
|
||||
|
||||
let lockValid = true;
|
||||
let renewal = null;
|
||||
// Odnawiamy trzy razy częściej niż wynosi TTL; setInterval oczekuje milisekund.
|
||||
const renewIntervalMs = Math.max(1000, Math.floor(ttlSeconds * 1000 / 3));
|
||||
const timer = setInterval(() => {
|
||||
if (renewal || !lockValid) return;
|
||||
renewal = Core.extendLockTime(lockId, ttlMs)
|
||||
renewal = Core.extendLockTime(lockId, ttlSeconds)
|
||||
.catch(error => {
|
||||
lockValid = false;
|
||||
Log.error('PrestaShop cron lock renewal failed', { lockName, error: error.message });
|
||||
})
|
||||
.finally(() => { renewal = null; });
|
||||
}, Math.max(1000, Math.floor(ttlMs / 3)));
|
||||
}, renewIntervalMs);
|
||||
timer.unref?.();
|
||||
|
||||
try {
|
||||
|
||||
@@ -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;
|
||||
|
||||
+35
-15
@@ -1,4 +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';
|
||||
@@ -12,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;
|
||||
}
|
||||
}
|
||||
|
||||
// Shape kompatybilny z dotychczasowym użyciem (OrderImporter, CRON, PrestaApi).
|
||||
@@ -36,6 +50,7 @@ async function loadConfig() {
|
||||
shopName,
|
||||
shopPrefix,
|
||||
versionCode,
|
||||
timeZone,
|
||||
orderStatus,
|
||||
lastOrderId,
|
||||
psStates
|
||||
@@ -45,12 +60,13 @@ async function loadConfig() {
|
||||
Config.get('connection.shopName', ''),
|
||||
Config.get('connection.shopPrefix', ''),
|
||||
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,
|
||||
@@ -59,8 +75,9 @@ async function loadConfig() {
|
||||
shopName: shopName || '',
|
||||
shopPrefix: shopPrefix || '',
|
||||
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
|
||||
};
|
||||
@@ -84,7 +101,10 @@ module.exports = {
|
||||
isConfigured,
|
||||
loadConfig,
|
||||
loadEnabledConfigs,
|
||||
loadLastOrderId,
|
||||
loadPsStates,
|
||||
loadStatusMapping,
|
||||
initializeOutboundMapping,
|
||||
setLastOrderId,
|
||||
setPsStates
|
||||
};
|
||||
|
||||
@@ -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 };
|
||||
+3
-3
@@ -1,9 +1,10 @@
|
||||
const { requestHook } = require('./hook-contract');
|
||||
const { Core } = require('@orbito/api-lib');
|
||||
|
||||
// Helper proxy do modułu zamówień. Widoki PrestaShop (orders.search,
|
||||
// status.get_with_counts) nie trzymają własnych zamówień — odpytują core/orders.
|
||||
|
||||
const ORDERS_MODULE_ID = 'core/orders';
|
||||
|
||||
|
||||
// Własny kod modułu znamy dopiero po rejestracji w core, więc czytamy go leniwie
|
||||
// (moduł jest ładowany zanim połączenie zostanie nawiązane).
|
||||
@@ -20,7 +21,7 @@ function getModuleCodes() {
|
||||
}
|
||||
|
||||
async function callOrdersModule(method, params) {
|
||||
return Core.callModule(ORDERS_MODULE_ID, method, params);
|
||||
return requestHook(Core, `orders.${method}`, params);
|
||||
}
|
||||
|
||||
function normalizeSearchResult(raw) {
|
||||
@@ -157,7 +158,6 @@ async function getOrderStatuses() {
|
||||
module.exports = {
|
||||
getModuleCode,
|
||||
getModuleCodes,
|
||||
ORDERS_MODULE_ID,
|
||||
callOrdersModule,
|
||||
normalizeSearchResult,
|
||||
buildSearchParams,
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
const DEFAULT_SHOP_TIME_ZONE = 'Europe/Warsaw';
|
||||
const formatters = new Map();
|
||||
|
||||
function getFormatter(timeZone = DEFAULT_SHOP_TIME_ZONE) {
|
||||
const zone = String(timeZone || DEFAULT_SHOP_TIME_ZONE).trim() || DEFAULT_SHOP_TIME_ZONE;
|
||||
if (!formatters.has(zone)) {
|
||||
formatters.set(zone, new Intl.DateTimeFormat('en-GB-u-ca-iso8601-nu-latn', {
|
||||
timeZone: zone, year: 'numeric', month: '2-digit', day: '2-digit',
|
||||
hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23',
|
||||
}));
|
||||
}
|
||||
return formatters.get(zone);
|
||||
}
|
||||
|
||||
function validateTimeZone(timeZone) {
|
||||
getFormatter(timeZone);
|
||||
}
|
||||
|
||||
// PrestaShop's date_add/date_upd contain shop-local wall time without an offset.
|
||||
// Never let the module container's TZ decide which instant that string means.
|
||||
function parsePrestashopDate(value, fallback = new Date(), timeZone = DEFAULT_SHOP_TIME_ZONE) {
|
||||
if (value instanceof Date) return Number.isNaN(value.getTime()) ? fallback : new Date(value);
|
||||
const text = String(value || '').trim();
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?)?(Z|[+-]\d{2}:?\d{2})?$/.exec(text);
|
||||
if (!match) return fallback;
|
||||
const [, year, month, day, hour = '0', minute = '0', second = '0', fraction = '', offset] = match;
|
||||
const wallMs = Date.UTC(+year, +month - 1, +day, +hour, +minute, +second, +(fraction.padEnd(3, '0')));
|
||||
const wall = new Date(wallMs);
|
||||
if (+year < 1000 || wall.getUTCFullYear() !== +year || wall.getUTCMonth() !== +month - 1
|
||||
|| wall.getUTCDate() !== +day || wall.getUTCHours() !== +hour
|
||||
|| wall.getUTCMinutes() !== +minute || wall.getUTCSeconds() !== +second) return fallback;
|
||||
|
||||
if (offset) {
|
||||
const parsed = new Date(text.replace(' ', 'T'));
|
||||
return Number.isNaN(parsed.getTime()) ? fallback : parsed;
|
||||
}
|
||||
|
||||
const formatter = getFormatter(timeZone);
|
||||
const wallTimeAt = instant => {
|
||||
const parts = Object.fromEntries(formatter.formatToParts(instant).map(part => [part.type, part.value]));
|
||||
return Date.UTC(+parts.year, +parts.month - 1, +parts.day, +parts.hour, +parts.minute, +parts.second)
|
||||
+ new Date(instant).getUTCMilliseconds();
|
||||
};
|
||||
// Consider offsets on both sides of a DST transition. A repeated local time
|
||||
// resolves to its first occurrence; a nonexistent time uses the fallback.
|
||||
const offsets = new Set([-86400000, 0, 86400000].map(delta => {
|
||||
const instant = wallMs + delta;
|
||||
return wallTimeAt(instant) - instant;
|
||||
}));
|
||||
const candidates = [...offsets].map(offsetMs => wallMs - offsetMs)
|
||||
.filter(instant => wallTimeAt(instant) === wallMs);
|
||||
return candidates.length ? new Date(Math.min(...candidates)) : fallback;
|
||||
}
|
||||
|
||||
module.exports = { DEFAULT_SHOP_TIME_ZONE, parsePrestashopDate, validateTimeZone };
|
||||
@@ -0,0 +1,235 @@
|
||||
const MAX_METADATA_LENGTH = 200;
|
||||
const PRODUCT_SOURCE_ID_PATTERN = /^product:(\d+):combination:(\d+)$/;
|
||||
|
||||
function normalizePrestashopId(value) {
|
||||
const id = String(value ?? '').trim();
|
||||
return /^\d+$/.test(id) ? id : '';
|
||||
}
|
||||
|
||||
function buildProductSourceId(productId, combinationId = 0) {
|
||||
const normalizedProductId = normalizePrestashopId(productId);
|
||||
const normalizedCombinationId = normalizePrestashopId(combinationId);
|
||||
if (!normalizedProductId || !normalizedCombinationId) {
|
||||
throw new Error('Invalid PrestaShop product identity');
|
||||
}
|
||||
return `product:${normalizedProductId}:combination:${normalizedCombinationId}`;
|
||||
}
|
||||
|
||||
function parseProductSourceId(value) {
|
||||
const sourceId = String(value ?? '').trim();
|
||||
const match = sourceId.match(PRODUCT_SOURCE_ID_PATTERN);
|
||||
if (match) {
|
||||
return {
|
||||
sourceId,
|
||||
productId: match[1],
|
||||
combinationId: match[2],
|
||||
legacy: false,
|
||||
};
|
||||
}
|
||||
|
||||
// Records imported before variant identities were introduced stored only
|
||||
// the base PrestaShop product ID. Keep them refreshable during migration.
|
||||
const productId = normalizePrestashopId(sourceId);
|
||||
return productId
|
||||
? { sourceId, productId, combinationId: null, legacy: true }
|
||||
: null;
|
||||
}
|
||||
|
||||
function normalizeSku(value) {
|
||||
const sku = String(value ?? '').trim();
|
||||
if (!sku || sku.startsWith('~:')) return '';
|
||||
return sku.toUpperCase();
|
||||
}
|
||||
|
||||
function sameId(left, right) {
|
||||
return String(left ?? '').trim() === String(right ?? '').trim();
|
||||
}
|
||||
|
||||
function metadataText(value) {
|
||||
if (typeof value !== 'string' || value.length > MAX_METADATA_LENGTH) return undefined;
|
||||
return value;
|
||||
}
|
||||
|
||||
function ownMetadataField(record, field) {
|
||||
if (!record || !Object.hasOwn(record, field)) return undefined;
|
||||
return metadataText(record[field]);
|
||||
}
|
||||
|
||||
function resolveBaseUnitPrice(product, combination) {
|
||||
if (!product || !Object.hasOwn(product, 'price')) return undefined;
|
||||
const basePrice = Number.parseFloat(String(product.price).replace(',', '.'));
|
||||
if (!Number.isFinite(basePrice) || basePrice < 0) return undefined;
|
||||
|
||||
let impact = 0;
|
||||
if (combination && Object.hasOwn(combination, 'price')) {
|
||||
impact = Number.parseFloat(String(combination.price).replace(',', '.'));
|
||||
if (!Number.isFinite(impact)) return undefined;
|
||||
}
|
||||
const unitPrice = basePrice + impact;
|
||||
return Number.isFinite(unitPrice) && unitPrice >= 0 ? unitPrice : undefined;
|
||||
}
|
||||
|
||||
async function resolveBrand(api, product) {
|
||||
const inlineName = ownMetadataField(product, 'manufacturer_name');
|
||||
if (inlineName !== undefined) return inlineName;
|
||||
|
||||
const manufacturerId = String(product?.id_manufacturer ?? '').trim();
|
||||
if (!manufacturerId) return undefined;
|
||||
if (!/^\d+$/.test(manufacturerId)) return undefined;
|
||||
if (manufacturerId === '0') return '';
|
||||
|
||||
const manufacturer = await api.getManufacturer(manufacturerId);
|
||||
return ownMetadataField(manufacturer, 'name');
|
||||
}
|
||||
|
||||
function chooseStockLocation(stockAvailabilities, product, productAttributeId) {
|
||||
const expectedProductId = String(product?.id ?? '').trim();
|
||||
const expectedAttributeId = String(productAttributeId ?? '0').trim();
|
||||
const candidates = (Array.isArray(stockAvailabilities) ? stockAvailabilities : [])
|
||||
.filter(stock => sameId(stock.id_product, expectedProductId)
|
||||
&& sameId(stock.id_product_attribute, expectedAttributeId))
|
||||
.map(stock => ({ stock, location: ownMetadataField(stock, 'location') }))
|
||||
.filter(candidate => candidate.location !== undefined);
|
||||
|
||||
if (candidates.length === 0) return { status: 'missing' };
|
||||
|
||||
const defaultShopId = String(product?.id_shop_default ?? '').trim();
|
||||
if (defaultShopId) {
|
||||
const forDefaultShop = candidates.filter(({ stock }) => sameId(stock.id_shop, defaultShopId));
|
||||
if (forDefaultShop.length === 1) return { status: 'found', location: forDefaultShop[0].location };
|
||||
if (forDefaultShop.length > 1) return { status: 'ambiguous' };
|
||||
}
|
||||
|
||||
return candidates.length === 1
|
||||
? { status: 'found', location: candidates[0].location }
|
||||
: { status: 'ambiguous' };
|
||||
}
|
||||
|
||||
async function resolveStockLocation(api, product, productAttributeId) {
|
||||
try {
|
||||
const stocks = await api.getStockAvailabilities(product.id, productAttributeId);
|
||||
return chooseStockLocation(stocks, product, productAttributeId);
|
||||
} catch (_) {
|
||||
return { status: 'unavailable' };
|
||||
}
|
||||
}
|
||||
|
||||
function legacyLocationFallback(record, stockResult) {
|
||||
const location = ownMetadataField(record, 'location');
|
||||
if (location !== '') return location;
|
||||
return ['unavailable', 'ambiguous'].includes(stockResult.status) ? undefined : location;
|
||||
}
|
||||
|
||||
async function resolveWarehouseLocation(api, product, combination) {
|
||||
if (combination) {
|
||||
const combinationStockLocation = await resolveStockLocation(api, product, combination.id);
|
||||
if (combinationStockLocation.status === 'found') return combinationStockLocation.location;
|
||||
|
||||
const combinationLocation = legacyLocationFallback(combination, combinationStockLocation);
|
||||
if (combinationLocation !== undefined) return combinationLocation;
|
||||
|
||||
if (['unavailable', 'ambiguous'].includes(combinationStockLocation.status)) return undefined;
|
||||
}
|
||||
|
||||
const productStockLocation = await resolveStockLocation(api, product, 0);
|
||||
if (productStockLocation.status === 'found') return productStockLocation.location;
|
||||
|
||||
return legacyLocationFallback(product, productStockLocation);
|
||||
}
|
||||
|
||||
function isMatchingCombination(product, combination, normalizedSku) {
|
||||
return !!combination
|
||||
&& sameId(combination.id_product, product?.id)
|
||||
&& normalizeSku(combination.reference) === normalizedSku;
|
||||
}
|
||||
|
||||
async function resolveProductMetadata(api, product, {
|
||||
sourceId = null, sku, combination = null, requiresCombination = false,
|
||||
} = {}) {
|
||||
const normalizedSku = normalizeSku(sku);
|
||||
if (!product || !normalizedSku) return {};
|
||||
if (sourceId != null && !sameId(product.id, sourceId)) return {};
|
||||
|
||||
if (combination) {
|
||||
if (!isMatchingCombination(product, combination, normalizedSku)) return {};
|
||||
} else if (requiresCombination) {
|
||||
return {};
|
||||
} else if (normalizeSku(product.reference) !== normalizedSku) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const metadata = {};
|
||||
const unitPrice = resolveBaseUnitPrice(product, combination);
|
||||
if (unitPrice !== undefined) metadata.unitPrice = unitPrice;
|
||||
try {
|
||||
const brand = await resolveBrand(api, product);
|
||||
if (brand !== undefined) metadata.brand = brand;
|
||||
} catch (_) { /* optional manufacturer data must not block metadata sync */ }
|
||||
|
||||
const warehouseLocation = await resolveWarehouseLocation(api, product, combination);
|
||||
if (warehouseLocation !== undefined) metadata.warehouseLocation = warehouseLocation;
|
||||
return metadata;
|
||||
}
|
||||
|
||||
async function findMetadataBySourceAndSku(api, { sourceId, sku } = {}) {
|
||||
const identity = parseProductSourceId(sourceId);
|
||||
const normalizedSku = normalizeSku(sku);
|
||||
if (!identity || !normalizedSku) return null;
|
||||
|
||||
const product = await api.getProduct(identity.productId);
|
||||
if (!product || !sameId(product.id, identity.productId)) return null;
|
||||
|
||||
if (!identity.legacy) {
|
||||
if (identity.combinationId === '0') {
|
||||
if (normalizeSku(product.reference) !== normalizedSku) return null;
|
||||
const metadata = await resolveProductMetadata(api, product, {
|
||||
sourceId: identity.productId,
|
||||
sku,
|
||||
});
|
||||
return Object.keys(metadata).length > 0 ? metadata : null;
|
||||
}
|
||||
|
||||
const combination = await api.getProductCombination(identity.combinationId);
|
||||
if (!isMatchingCombination(product, combination, normalizedSku)) return null;
|
||||
const metadata = await resolveProductMetadata(api, product, {
|
||||
sourceId: identity.productId,
|
||||
sku,
|
||||
combination,
|
||||
requiresCombination: true,
|
||||
});
|
||||
return Object.keys(metadata).length > 0 ? metadata : null;
|
||||
}
|
||||
|
||||
const candidates = [];
|
||||
if (normalizeSku(product.reference) === normalizedSku) {
|
||||
candidates.push(null);
|
||||
}
|
||||
|
||||
const knownCombinations = product.associations?.combinations;
|
||||
const combinations = Array.isArray(knownCombinations) && knownCombinations.length === 0
|
||||
? []
|
||||
: await api.findProductCombinationsByReference(identity.productId, sku);
|
||||
if (combinations === null) return null;
|
||||
for (const combination of combinations) {
|
||||
if (isMatchingCombination(product, combination, normalizedSku)) candidates.push(combination);
|
||||
}
|
||||
|
||||
if (candidates.length !== 1) return null;
|
||||
const metadata = await resolveProductMetadata(api, product, {
|
||||
sourceId: identity.productId,
|
||||
sku,
|
||||
combination: candidates[0],
|
||||
});
|
||||
return Object.keys(metadata).length > 0 ? metadata : null;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
MAX_METADATA_LENGTH,
|
||||
buildProductSourceId,
|
||||
parseProductSourceId,
|
||||
normalizeSku,
|
||||
resolveBaseUnitPrice,
|
||||
chooseStockLocation,
|
||||
resolveProductMetadata,
|
||||
findMetadataBySourceAndSku,
|
||||
};
|
||||
+62
-65
@@ -3,22 +3,15 @@ const { PropertyType, DisplayFormat } = Config;
|
||||
const PrestashopApi = require('./PrestaApi');
|
||||
const { isLegacyApi } = require('./utils');
|
||||
const { extractPsStateName } = require('./status-mapper');
|
||||
const { setPsStates, loadPsStates } = require('./module-config');
|
||||
const { importStatusSchema, validateImportBlock, outboundMappingSchema, validateOutboundMapping } = require('./status-config');
|
||||
const { setPsStates, loadPsStates, initializeOutboundMapping } = require('./module-config');
|
||||
const { ensureShopIcon } = require('./shop-icon');
|
||||
|
||||
const ORBITO_STATUS_OPTIONS = {
|
||||
module: 'core/orders',
|
||||
method: 'status.search',
|
||||
params: {},
|
||||
responsePath: 'results',
|
||||
idKey: '_id',
|
||||
labelKey: 'name'
|
||||
};
|
||||
const { DEFAULT_SHOP_TIME_ZONE, validateTimeZone } = require('./prestashop-date');
|
||||
|
||||
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,9 +19,41 @@ 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.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function registerPrestashopConfigBlocks() {
|
||||
await initializeOutboundMapping();
|
||||
await Config.registerConfigBlocks({
|
||||
connection: {
|
||||
title: { pl: 'Połączenie ze sklepem', en: 'Shop connection' },
|
||||
@@ -66,6 +91,15 @@ async function registerPrestashopConfigBlocks() {
|
||||
]
|
||||
}
|
||||
},
|
||||
timeZone: {
|
||||
type: PropertyType.STRING,
|
||||
name: { pl: 'Strefa czasowa sklepu', en: 'Shop time zone' },
|
||||
default: DEFAULT_SHOP_TIME_ZONE,
|
||||
description: {
|
||||
pl: 'Strefa ustawiona w PrestaShop, np. Europe/Warsaw. Puste pole oznacza Europe/Warsaw. Dotyczy dat nowo importowanych zamówień i płatności.',
|
||||
en: 'Time zone configured in PrestaShop, e.g. Europe/Warsaw. An empty value means Europe/Warsaw. Applies to newly imported order and payment dates.'
|
||||
}
|
||||
},
|
||||
shopName: {
|
||||
type: PropertyType.STRING,
|
||||
name: { pl: 'Nazwa sklepu', en: 'Shop name' },
|
||||
@@ -93,6 +127,13 @@ async function registerPrestashopConfigBlocks() {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
validateTimeZone(params.timeZone);
|
||||
} catch {
|
||||
raport.addError('timeZone', 'Podaj prawidłową strefę czasową, np. Europe/Warsaw.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const psStates = await fetchPsStates(apiUrl, apiKey, params.versionCode);
|
||||
await setPsStates(psStates);
|
||||
@@ -112,68 +153,24 @@ async function registerPrestashopConfigBlocks() {
|
||||
import: {
|
||||
title: { pl: 'Import zamówień', en: 'Order import' },
|
||||
scope: 'global',
|
||||
schema: {
|
||||
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.'
|
||||
}
|
||||
},
|
||||
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 psStates = await loadPsStates();
|
||||
|
||||
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.'
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const schema = {
|
||||
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.'
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
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,
|
||||
}
|
||||
});
|
||||
|
||||
Log.info('PrestaShop: zarejestrowano bloki konfiguracji Config');
|
||||
}
|
||||
|
||||
module.exports = { registerPrestashopConfigBlocks };
|
||||
module.exports = {
|
||||
fetchPsStates,
|
||||
refreshPsStatesForMapping,
|
||||
registerPrestashopConfigBlocks,
|
||||
validateOutboundMapping,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
const { Core } = require('@orbito/api-lib');
|
||||
const { registerContract } = require('./hook-contract');
|
||||
|
||||
function registerContracts() {
|
||||
registerContract(Core, 'sources.product.get_metadata', require('../methods/product/get_metadata'));
|
||||
}
|
||||
|
||||
module.exports = { registerContracts };
|
||||
+2
-1
@@ -1,3 +1,4 @@
|
||||
const { requestHook } = require('./hook-contract');
|
||||
const { Config, Core, Log } = require('@orbito/api-lib');
|
||||
|
||||
const CACHE_KEY = 'runtime.shopIcon';
|
||||
@@ -176,7 +177,7 @@ async function downloadShopIcon(shopPageUrl) {
|
||||
|
||||
async function registerSourceProfile(cache, shopName) {
|
||||
try {
|
||||
await Core.callModule('core/orders', 'source.register', {
|
||||
await requestHook(Core, 'orders.source.register', {
|
||||
name: String(shopName || '').trim() || new URL(cache.shopUrl).hostname,
|
||||
iconDataUrl: cache.dataUrl || '',
|
||||
iconSourceUrl: cache.sourceUrl || '',
|
||||
|
||||
@@ -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 };
|
||||
@@ -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,6 +36,52 @@ function resolveStatusId(psStateId, statusMapping, fallbackStatusId) {
|
||||
return normalizeStatusId(match?.orbitoStatusId) ?? normalizeStatusId(fallbackStatusId);
|
||||
}
|
||||
|
||||
// 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) {
|
||||
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;
|
||||
}
|
||||
|
||||
// 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.';
|
||||
@@ -56,9 +104,13 @@ function extractPsStateName(name) {
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
LEGACY_CONFLICT,
|
||||
readStatusMapping,
|
||||
isPsStateId,
|
||||
normalizeStatusId,
|
||||
parseStatusMapping,
|
||||
resolveStatusId,
|
||||
resolvePsStateId,
|
||||
formatPsStatesPreview,
|
||||
extractPsStateName
|
||||
};
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
const { requestHook } = require('./hook-contract');
|
||||
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 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';
|
||||
|
||||
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 = 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) {
|
||||
// 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 }),
|
||||
loadConfig(),
|
||||
]);
|
||||
const order = asOrders(orderResult)[0];
|
||||
if (!order) return { skipped: true, reason: 'order_not_found' };
|
||||
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.
|
||||
const orbitoStatusId = text(order.statusId);
|
||||
const psStateId = resolvePsStateId(orbitoStatusId, config.statusMapping);
|
||||
if (psStateId == null) {
|
||||
return { skipped: true, reason: 'status_not_mapped' };
|
||||
}
|
||||
|
||||
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}`);
|
||||
}
|
||||
|
||||
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,
|
||||
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 {
|
||||
api?.close?.();
|
||||
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', 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,
|
||||
};
|
||||
@@ -1,3 +1,4 @@
|
||||
const { withHookFixtures } = require('./helpers/hook-fixtures');
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
@@ -29,14 +30,14 @@ test('first run safely starts at the newest order without backfilling history',
|
||||
assert.deepEqual(result, { status: 'initialized', cursor: 812, processed: 0 });
|
||||
});
|
||||
|
||||
test('a failed order is skipped so later orders can still be imported', async () => {
|
||||
test('a failed order leaves a retryable cursor gap while later orders are still inspected', async () => {
|
||||
const writes = [];
|
||||
const imported = [];
|
||||
const errors = [];
|
||||
const config = { _id: 'default', lastOrderId: 10 };
|
||||
const api = { makeRequest: async () => ({ orders: [oldOrder(11), oldOrder(12), oldOrder(13)] }) };
|
||||
const result = await importOrdersForShop(config, api, {
|
||||
Core: { callModule: async () => ({ data: [] }) },
|
||||
Core: withHookFixtures({ callModule: async () => ({ data: [] }) }),
|
||||
PsOrder: {},
|
||||
importFromPSOrder: async id => {
|
||||
imported.push(id);
|
||||
@@ -49,15 +50,15 @@ test('a failed order is skipped so later orders can still be imported', async ()
|
||||
});
|
||||
|
||||
assert.deepEqual(imported, [11, 12, 13]);
|
||||
assert.deepEqual(writes, [13]);
|
||||
assert.equal(config.lastOrderId, 13);
|
||||
assert.deepEqual(result, { status: 'processed', cursor: 13, processed: 2 });
|
||||
assert.deepEqual(writes, [11]);
|
||||
assert.equal(config.lastOrderId, 11);
|
||||
assert.deepEqual(result, { status: 'processed', cursor: 11, processed: 2 });
|
||||
assert.deepEqual(errors, [{
|
||||
message: 'Failed to import PS order; skipping order and continuing',
|
||||
message: 'Failed to import PS order; keeping cursor before the gap and continuing',
|
||||
details: {
|
||||
orderId: 12,
|
||||
previousCursor: 11,
|
||||
cursor: 12,
|
||||
cursor: 11,
|
||||
error: 'invalid order',
|
||||
},
|
||||
}]);
|
||||
@@ -77,7 +78,7 @@ test('existing Orbito order repairs a missing mapping before advancing the curso
|
||||
};
|
||||
|
||||
await importOrdersForShop(config, api, {
|
||||
Core: { callModule: async () => ({ data: [{ _id: 'orbito-21', summary: { paid: 25 } }] }) },
|
||||
Core: withHookFixtures({ callModule: async () => ({ data: [{ _id: 'orbito-21', summary: { paid: 25 } }] }) }),
|
||||
PsOrder,
|
||||
importFromPSOrder: async () => assert.fail('must not import an existing order'),
|
||||
setLastOrderId: async id => writes.push(id),
|
||||
@@ -100,11 +101,11 @@ test('payment sync appends only the cumulative delta with a deterministic transa
|
||||
const result = await processPaymentMapping(mapping, config, {
|
||||
getOrder: async () => ({ total_paid_real: '55.00', payment: 'Card', date_upd: '2026-01-02 12:00:00' }),
|
||||
}, {
|
||||
Core: { callModule: async (module, method, params) => {
|
||||
Core: withHookFixtures({ callModule: async (module, method, params) => {
|
||||
calls.push({ module, method, params });
|
||||
if (method === 'search') return { data: [{ summary: { paid: 20, gross: 100 } }] };
|
||||
return { success: true };
|
||||
} },
|
||||
} }),
|
||||
PsOrder: { update: async (...args) => updates.push(args) },
|
||||
nowDate: new Date('2026-01-02T12:01:00Z'),
|
||||
nextCheckMs: 1000,
|
||||
@@ -115,20 +116,43 @@ test('payment sync appends only the cumulative delta with a deterministic transa
|
||||
assert.equal(result.amount, 35);
|
||||
assert.equal(calls[1].method, 'payments.upsert');
|
||||
assert.equal(calls[1].params.payment.amount, 35);
|
||||
assert.equal(calls[1].params.payment.date.toISOString(), '2026-01-02T11:00:00.000Z');
|
||||
assert.equal(calls[1].params.payment.transactionId, 'prestashop:shop-a:44:paid:5500');
|
||||
assert.equal(updates[0][1].$set.paymentTotalSynced, 55);
|
||||
});
|
||||
|
||||
test('import waits for the 30-second stability window using shop time without guessing an offset', async () => {
|
||||
for (const [timeZone, localHour] of [['Europe/Warsaw', '11'], ['UTC', '09']]) {
|
||||
const imported = [], cursors = [];
|
||||
const result = await importOrdersForShop({ _id: 'default', lastOrderId: 10, timeZone }, {
|
||||
makeRequest: async () => ({ orders: [
|
||||
{ id: 11, reference: 'R11', date_add: `2026-09-25 ${localHour}:00:29` },
|
||||
{ id: 12, reference: 'R12', date_add: `2026-09-25 ${localHour}:00:45` },
|
||||
{ id: 13, reference: 'R13', date_add: '2026-09-25 15:00:00' },
|
||||
] }),
|
||||
}, {
|
||||
Core: withHookFixtures({ callModule: async () => ({ data: [] }) }),
|
||||
importFromPSOrder: async id => { imported.push(id); return { status: 'imported' }; },
|
||||
setLastOrderId: async id => cursors.push(id),
|
||||
now: () => Date.parse('2026-09-25T09:01:00Z'),
|
||||
Log: silentLog,
|
||||
});
|
||||
assert.deepEqual(imported, [11]);
|
||||
assert.deepEqual(cursors, [11]);
|
||||
assert.equal(result.cursor, 11);
|
||||
}
|
||||
});
|
||||
|
||||
test('legacy mapping establishes a conservative baseline instead of duplicating a payment', async () => {
|
||||
const methods = [];
|
||||
const updates = [];
|
||||
await processPaymentMapping({ _id: 'map-2', psOrderId: 45, orbitoOrderId: 'order-2' }, { _id: 'default' }, {
|
||||
getOrder: async () => ({ total_paid_real: '50.00' }),
|
||||
}, {
|
||||
Core: { callModule: async (_module, method) => {
|
||||
Core: withHookFixtures({ callModule: async (_module, method) => {
|
||||
methods.push(method);
|
||||
return { data: [{ summary: { paid: 50, gross: 100 } }] };
|
||||
} },
|
||||
} }),
|
||||
PsOrder: { update: async (...args) => updates.push(args) },
|
||||
nowDate: new Date(), nextCheckMs: 1000, retryCheckMs: 1000, Log: silentLog,
|
||||
});
|
||||
@@ -142,11 +166,11 @@ test('a mapping write failure retries the same payment transaction id safely', a
|
||||
let failMappingWrite = true;
|
||||
const mapping = { _id: 'map-3', psOrderId: 46, orbitoOrderId: 'order-3', paymentTotalSynced: 10 };
|
||||
const dependencies = {
|
||||
Core: { callModule: async (_module, method, params) => {
|
||||
Core: withHookFixtures({ callModule: async (_module, method, params) => {
|
||||
if (method === 'search') return { data: [{ summary: { paid: 10, gross: 100 } }] };
|
||||
transactionIds.push(params.payment.transactionId);
|
||||
return { success: true };
|
||||
} },
|
||||
} }),
|
||||
PsOrder: { update: async (_query, update) => {
|
||||
if (update.$set.paymentTotalSynced !== undefined && failMappingWrite) {
|
||||
failMappingWrite = false;
|
||||
@@ -181,9 +205,9 @@ test('payment scheduler drains multiple pages and includes orders older than fiv
|
||||
},
|
||||
update: async () => {},
|
||||
};
|
||||
const Core = { callModule: async (_module, method) => method === 'search'
|
||||
const Core = withHookFixtures({ callModule: async (_module, method) => method === 'search'
|
||||
? { data: [{ summary: { paid: 0, gross: 10 } }] }
|
||||
: { success: true } };
|
||||
: { success: true } });
|
||||
|
||||
const result = await syncPaymentsForShop(
|
||||
{ _id: 'default' },
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
'use strict';
|
||||
|
||||
// Test-only bus: keep existing business fixtures while exercising the real
|
||||
// request envelope, discovery and error propagation in src/hook-contract.
|
||||
// Transport behavior and actual provider registration are tested separately.
|
||||
function withHookFixtures(Core) {
|
||||
if (Core.__hookFixtures) return Core;
|
||||
Object.defineProperty(Core, '__hookFixtures', { value: true });
|
||||
const previousHook = Core.execHook?.bind(Core);
|
||||
const identities = new Map();
|
||||
Core.getInstanceId ||= () => 'fixture-instance';
|
||||
Core.getModuleInfo ||= () => ({ code: 'test/module' });
|
||||
Core.execHook = async function(name, request) {
|
||||
const contract = name.replace(/\.providers$/, '');
|
||||
const match = /^(orders|products|shipping|invoicing|printing|sources)\.(.+)$/.exec(contract);
|
||||
if (!match) return previousHook ? previousHook(name, request) : [];
|
||||
if (name.endsWith('.providers')) {
|
||||
const moduleCode = request?.targetModuleCode || `core/${match[1]}`;
|
||||
const instanceId = request?.targetInstanceId || `fixture:${moduleCode.replace('/', ':')}`;
|
||||
identities.set(`${contract}:${instanceId}`, moduleCode);
|
||||
return [{ protocol: 'orbito.contract/1', moduleCode, instanceId }];
|
||||
}
|
||||
if (request?.protocol !== 'orbito.contract/1') return previousHook ? previousHook(name, request) : [];
|
||||
const instanceId = request.targetInstanceId;
|
||||
const moduleCode = identities.get(`${contract}:${instanceId}`);
|
||||
try {
|
||||
let data;
|
||||
if (contract === 'orders.references') {
|
||||
const page = `details/${request.params.orderId}`;
|
||||
data = {
|
||||
link: { module: 'core/orders', instanceId, path: page },
|
||||
relation: { module: 'core/orders', object: 'order', id: request.params.orderId },
|
||||
navigation: { action: 'navigate', module: 'core/orders', instanceId, page },
|
||||
approveFinancialData: { action: 'callMethod', module: 'core/orders', instanceId, method: 'import.approveFinancialData', params: { orderId: request.params.orderId, confirmed: true } },
|
||||
};
|
||||
} else if (/^(shipping\.carrier|printing\.provider)\./.test(contract)) {
|
||||
data = await Core.callInstanceMethod(instanceId, match[2].replace(/^(carrier|provider)\./, ''), request.params);
|
||||
} else {
|
||||
data = await Core.callModule(moduleCode, match[2].replace(/^issuer\./, ''), request.params);
|
||||
}
|
||||
return [{ protocol: 'orbito.contract/1', instanceId, ok: true, data }];
|
||||
} catch (error) {
|
||||
return [{ protocol: 'orbito.contract/1', instanceId, ok: false,
|
||||
error: { message: error.message, code: error.code, outcomeUncertain: error.outcomeUncertain, retryable: error.retryable } }];
|
||||
}
|
||||
};
|
||||
return Core;
|
||||
}
|
||||
|
||||
module.exports = { withHookFixtures };
|
||||
@@ -1,18 +1,19 @@
|
||||
const { withHookFixtures } = require('./helpers/hook-fixtures');
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { createJobRuntime } = require('../src/job-runtime');
|
||||
|
||||
test('lock is released after success and after failure', async () => {
|
||||
const released = [];
|
||||
const Core = {
|
||||
const Core = withHookFixtures({
|
||||
getLock: async name => name,
|
||||
extendLockTime: async () => true,
|
||||
releaseLock: async id => released.push(id),
|
||||
};
|
||||
});
|
||||
const runtime = createJobRuntime(Core, { error() {}, warn() {} });
|
||||
|
||||
assert.equal(await runtime.withRenewedLock('ok', 5000, async valid => valid() && 7), 7);
|
||||
await assert.rejects(() => runtime.withRenewedLock('fail', 5000, async () => { throw new Error('boom'); }), /boom/);
|
||||
assert.equal(await runtime.withRenewedLock('ok', 5, async valid => valid() && 7), 7);
|
||||
await assert.rejects(() => runtime.withRenewedLock('fail', 5, async () => { throw new Error('boom'); }), /boom/);
|
||||
assert.deepEqual(released, ['ok', 'fail']);
|
||||
});
|
||||
|
||||
@@ -29,3 +30,26 @@ test('stop waits for tracked work and blocks subsequent runs until start', async
|
||||
runtime.start();
|
||||
assert.equal(await runtime.track(async () => 'running'), 'running');
|
||||
});
|
||||
|
||||
test('lock TTL is forwarded to Core in seconds, without conversion', async t => {
|
||||
t.mock.timers.enable({ apis: ['setInterval'] });
|
||||
const getLockCalls = [];
|
||||
const extendCalls = [];
|
||||
const Core = withHookFixtures({
|
||||
getLock: async (name, ttl) => { getLockCalls.push([name, ttl]); return 'lock-1'; },
|
||||
extendLockTime: async (id, ttl) => { extendCalls.push([id, ttl]); return true; },
|
||||
releaseLock: async () => true,
|
||||
});
|
||||
const runtime = createJobRuntime(Core, { error() {}, warn() {} });
|
||||
|
||||
let finish;
|
||||
const run = runtime.withRenewedLock('ttl', 5, () => new Promise(resolve => { finish = resolve; }));
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
// Interwał odnowienia to ttlSeconds * 1000 / 3 = ~1666 ms, więc jeden tick wystarczy.
|
||||
t.mock.timers.tick(1700);
|
||||
finish('done');
|
||||
assert.equal(await run, 'done');
|
||||
|
||||
assert.deepEqual(getLockCalls, [['ttl', 5]]);
|
||||
assert.deepEqual(extendCalls, [['lock-1', 5]]);
|
||||
});
|
||||
|
||||
@@ -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)$/);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
const { withHookFixtures } = require('./helpers/hook-fixtures');
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const Module = require('node:module');
|
||||
const path = require('node:path');
|
||||
|
||||
function loadImporter(Core, PsOrder) {
|
||||
const importerPath = path.resolve(__dirname, '../src/OrderImporter.js');
|
||||
const originalLoad = Module._load;
|
||||
Module._load = function(request, parent, isMain) {
|
||||
if (request === '@orbito/api-lib') return { Core, Log: { debug() {}, info() {}, warn() {}, error() {} } };
|
||||
if (request === './models/PsOrder') return PsOrder;
|
||||
return originalLoad.call(this, request, parent, isMain);
|
||||
};
|
||||
delete require.cache[importerPath];
|
||||
try {
|
||||
return require(importerPath);
|
||||
} finally {
|
||||
Module._load = originalLoad;
|
||||
}
|
||||
}
|
||||
|
||||
test('imports only public PrestaShop customer messages as customer_message notes', async () => {
|
||||
let createPayload;
|
||||
const Core = withHookFixtures({
|
||||
getModuleInfo: () => ({ code: 'core/prestashop' }),
|
||||
callModule: async (module, method, params) => {
|
||||
if (module === 'core/orders' && method === 'status.search') {
|
||||
return { results: [{ _id: '000000000000000000000001', positionInGroup: 1 }] };
|
||||
}
|
||||
if (module === 'core/products' && method === 'upsert') return {};
|
||||
if (module === 'core/orders' && method === 'create') {
|
||||
createPayload = params;
|
||||
return { _id: 'order-1' };
|
||||
}
|
||||
throw new Error(`Unexpected core call: ${module}.${method}`);
|
||||
},
|
||||
});
|
||||
const { importFromPSOrder } = loadImporter(Core, { findOne: async () => null, update: async () => {} });
|
||||
const order = {
|
||||
id: '1', id_cart: '15', reference: 'PS-1', current_state: '1', id_customer: '5', id_address_delivery: '6',
|
||||
id_currency: '1', id_carrier: '0', payment: 'Card', date_add: '2026-01-01 10:00:00',
|
||||
total_discounts: '0', total_paid_real: '0', total_shipping_tax_excl: '0', associations: {
|
||||
order_rows: [{ product_id: '10', product_attribute_id: '0', product_name: 'Product', product_reference: 'SKU', product_ean13: '', unit_price_tax_excl: '10', unit_price_tax_incl: '12.3', product_quantity: '1' }],
|
||||
},
|
||||
};
|
||||
const api = {
|
||||
isBLSupported: async () => false,
|
||||
makeRequest: async endpoint => {
|
||||
if (endpoint === 'orders/1') return { order };
|
||||
if (endpoint === 'customers/5') return { customer: { firstname: 'Ada', lastname: 'Lovelace', email: 'ada@test' } };
|
||||
if (endpoint === 'addresses/6') return { address: { firstname: 'Ada', lastname: 'Lovelace', address1: 'Street 1', city: 'Warsaw', postcode: '00-001', id_country: '1' } };
|
||||
throw new Error(`Unexpected API request: ${endpoint}`);
|
||||
},
|
||||
getProduct: async () => ({ name: 'Product', weight: '1', type: 'standard', associations: {} }),
|
||||
getProductCoverImageUrl: async () => null,
|
||||
getCurrency: async () => ({ iso_code: 'PLN' }),
|
||||
getCountry: async () => ({ iso_code: 'PL' }),
|
||||
getCustomerNotes: async (orderId, cartId, giftMessage) => {
|
||||
assert.equal(orderId, '1');
|
||||
assert.equal(cartId, '15');
|
||||
assert.equal(giftMessage, undefined);
|
||||
return ['Proszę zadzwonić przed dostawą', 'Tekst z checkoutu'];
|
||||
},
|
||||
getStockAvailabilities: async () => [],
|
||||
getManufacturer: async () => null,
|
||||
};
|
||||
|
||||
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' },
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
const { withHookFixtures } = require('./helpers/hook-fixtures');
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const Module = require('node:module');
|
||||
|
||||
test('order import sends the same corrected date to orders, initial payments and the mapping', async () => {
|
||||
const created = [], mappings = [];
|
||||
const originalLoad = Module._load;
|
||||
Module._load = function(request, parent, isMain) {
|
||||
if (request === '@orbito/api-lib') return {
|
||||
Log: { debug() {}, info() {}, warn() {} },
|
||||
Core: withHookFixtures({
|
||||
getModuleInfo: () => ({ code: 'core/prestashop' }),
|
||||
callModule: async (module, method, params) => {
|
||||
assert.equal(module, 'core/orders');
|
||||
if (method === 'status.search') return { results: [{ _id: '507f191e810c19729de860ea' }] };
|
||||
assert.equal(method, 'create');
|
||||
created.push(params);
|
||||
return { _id: 'new-order' };
|
||||
},
|
||||
}),
|
||||
};
|
||||
if (request === './models/PsOrder') return {
|
||||
findOne: async () => null,
|
||||
update: async (_query, update) => mappings.push(update.$set),
|
||||
};
|
||||
return originalLoad.call(this, request, parent, isMain);
|
||||
};
|
||||
let importFromPSOrder;
|
||||
try {
|
||||
delete require.cache[require.resolve('../src/OrderImporter')];
|
||||
({ importFromPSOrder } = require('../src/OrderImporter'));
|
||||
} finally { Module._load = originalLoad; }
|
||||
|
||||
for (const [date, timeZone, expected] of [
|
||||
['2026-09-25 10:53:43', undefined, '2026-09-25T08:53:43.000Z'],
|
||||
['2026-01-25 10:53:43', undefined, '2026-01-25T09:53:43.000Z'],
|
||||
['2026-09-25 10:53:43', 'UTC', '2026-09-25T10:53:43.000Z'],
|
||||
]) {
|
||||
const api = {
|
||||
isBLSupported: async () => false,
|
||||
makeRequest: async endpoint => {
|
||||
if (endpoint === 'orders/1') return { order: {
|
||||
id: '1', reference: 'PS-1', id_address_delivery: '2', id_customer: '3',
|
||||
id_currency: '1', id_carrier: '0', payment: 'Card', date_add: date,
|
||||
total_discounts: '0', total_paid_real: '20', total_shipping_tax_excl: '0',
|
||||
associations: { order_rows: [] },
|
||||
} };
|
||||
if (endpoint === 'addresses/2') return { address: { firstname: 'Jan', lastname: 'Test', id_country: '1' } };
|
||||
if (endpoint === 'customers/3') return { customer: { firstname: 'Jan', lastname: 'Test' } };
|
||||
throw new Error(`Unexpected endpoint: ${endpoint}`);
|
||||
},
|
||||
getCurrency: async () => ({ iso_code: 'PLN' }),
|
||||
getCountry: async () => ({ iso_code: 'PL' }),
|
||||
getCustomerNotes: async () => [],
|
||||
};
|
||||
await importFromPSOrder('1', api, { _id: 'default', timeZone });
|
||||
assert.equal(created.at(-1).createdAt.toISOString(), expected);
|
||||
assert.equal(created.at(-1).payments[0].date.toISOString(), expected);
|
||||
assert.equal(mappings.at(-1).syncedAt.toISOString(), expected);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
const { withHookFixtures } = require('./helpers/hook-fixtures');
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const Module = require('node:module');
|
||||
const path = require('node:path');
|
||||
|
||||
function loadImporter(Core, PsOrder) {
|
||||
const importerPath = path.resolve(__dirname, '../src/OrderImporter.js');
|
||||
const originalLoad = Module._load;
|
||||
Module._load = function(request, parent, isMain) {
|
||||
if (request === '@orbito/api-lib') return { Core, Log: { debug() {}, info() {}, warn() {}, error() {} } };
|
||||
if (request === './models/PsOrder') return PsOrder;
|
||||
return originalLoad.call(this, request, parent, isMain);
|
||||
};
|
||||
delete require.cache[importerPath];
|
||||
try {
|
||||
return require(importerPath);
|
||||
} finally {
|
||||
Module._load = originalLoad;
|
||||
}
|
||||
}
|
||||
|
||||
test('order import passes verified metadata and pack facts only through core/orders', async () => {
|
||||
const upserts = [];
|
||||
let createdOrder = null;
|
||||
const Core = withHookFixtures({
|
||||
getModuleInfo: () => ({ code: 'core/prestashop' }),
|
||||
callModule: async (module, method, params) => {
|
||||
if (module === 'core/orders' && method === 'status.search') return { results: [{ _id: '000000000000000000000001', positionInGroup: 1 }] };
|
||||
if (module === 'core/products' && method === 'upsert') {
|
||||
upserts.push(params);
|
||||
return {};
|
||||
}
|
||||
if (module === 'core/orders' && method === 'create') {
|
||||
createdOrder = params;
|
||||
return { _id: 'order-1' };
|
||||
}
|
||||
throw new Error(`Unexpected core call: ${module}.${method}`);
|
||||
},
|
||||
});
|
||||
const PsOrder = { findOne: async () => null, update: async () => {} };
|
||||
const { importFromPSOrder } = loadImporter(Core, PsOrder);
|
||||
const order = {
|
||||
id: '1', reference: 'PS-1', current_state: '1', id_customer: '5', id_address_delivery: '6',
|
||||
id_currency: '1', id_carrier: '0', payment: 'Card', date_add: '2026-01-01 10:00:00',
|
||||
total_discounts: '0', total_paid_real: '0', total_shipping_tax_excl: '0',
|
||||
associations: {
|
||||
order_rows: [{
|
||||
product_id: '10', product_attribute_id: '100', product_name: 'Pack', product_reference: 'PACK-V',
|
||||
product_ean13: '', unit_price_tax_excl: '10', unit_price_tax_incl: '12.3', product_quantity: '1',
|
||||
}, {
|
||||
product_id: '30', product_attribute_id: '300', product_name: 'Variant Blue', product_reference: 'OLD-BLUE',
|
||||
product_ean13: '', unit_price_tax_excl: '20', unit_price_tax_incl: '24.6', product_quantity: '1',
|
||||
}, {
|
||||
product_id: '30', product_attribute_id: '301', product_name: 'Variant Red', product_reference: 'OLD-RED',
|
||||
product_ean13: '', unit_price_tax_excl: '21', unit_price_tax_incl: '25.83', product_quantity: '1',
|
||||
}],
|
||||
},
|
||||
};
|
||||
const products = {
|
||||
'10': {
|
||||
id: '10', name: 'Pack', reference: 'PACK-BASE', manufacturer_name: 'Pack Brand', location: 'BASE-BIN',
|
||||
price: '8', weight: '1', type: 'pack', associations: { product_bundle: [
|
||||
{ id: '20', id_product_attribute: '200', quantity: '2' },
|
||||
{ id: '21', id_product_attribute: '0', quantity: '1' },
|
||||
] },
|
||||
},
|
||||
'20': {
|
||||
id: '20', name: 'Item', reference: 'ITEM-BASE', manufacturer_name: 'Item Brand', location: 'ITEM-BASE-BIN',
|
||||
price: '3', weight: '2', type: 'standard', associations: {},
|
||||
},
|
||||
'21': {
|
||||
id: '21', name: 'Regular item', reference: 'REGULAR-ITEM', manufacturer_name: 'Regular Brand',
|
||||
location: 'REGULAR-BIN', price: '4.5', weight: '0.5', type: 'standard', associations: {},
|
||||
},
|
||||
'30': {
|
||||
id: '30', name: 'Variant product', reference: 'VARIANT-BASE', manufacturer_name: 'Variant Brand',
|
||||
location: 'VARIANT-BASE-BIN', price: '15', weight: '1', type: 'standard', associations: {},
|
||||
},
|
||||
};
|
||||
const combinations = {
|
||||
'100': { id: '100', id_product: '10', reference: 'PACK-V', price: '1.5', weight: '1.5', location: 'PACK-V-BIN' },
|
||||
'200': { id: '200', id_product: '20', reference: 'ITEM-V', price: '0.25', weight: '2.5', location: 'ITEM-V-BIN' },
|
||||
'300': { id: '300', id_product: '30', reference: 'VARIANT-BLUE', price: '2', ean13: '5901234123457', weight: '0.1', location: 'BLUE-BIN' },
|
||||
'301': { id: '301', id_product: '30', reference: 'VARIANT-RED', price: '3', ean13: '5901234123464', weight: '0.2', location: 'RED-BIN' },
|
||||
};
|
||||
const taxLookups = [];
|
||||
const api = {
|
||||
isBLSupported: async () => false,
|
||||
makeRequest: async endpoint => {
|
||||
if (endpoint === 'orders/1') return { order };
|
||||
if (endpoint === 'customers/5') return { customer: { firstname: 'Ada', lastname: 'Lovelace', email: 'ada@test' } };
|
||||
if (endpoint === 'addresses/6') return { address: { firstname: 'Ada', lastname: 'Lovelace', address1: 'Street 1', city: 'Warsaw', postcode: '00-001', id_country: '1' } };
|
||||
throw new Error(`Unexpected API request: ${endpoint}`);
|
||||
},
|
||||
getProduct: async id => products[id],
|
||||
getProductCombination: async id => combinations[id],
|
||||
getProductTaxRate: async (productId, combinationId, context) => {
|
||||
taxLookups.push({ productId, combinationId, context });
|
||||
return productId === '20' ? 0.08 : null;
|
||||
},
|
||||
getProductCoverImageUrl: async () => null,
|
||||
getCurrency: async () => ({ iso_code: 'PLN' }),
|
||||
getCountry: async () => ({ iso_code: 'PL' }),
|
||||
getCustomerNotes: async () => [],
|
||||
getStockAvailabilities: async () => [],
|
||||
getManufacturer: async () => null,
|
||||
};
|
||||
await importFromPSOrder('1', api, { _id: 'default', orderStatus: '000000000000000000000001', statusMapping: [] });
|
||||
|
||||
assert.equal(upserts.length, 0, 'PrestaShop must not write the catalog beside core/orders');
|
||||
assert.equal(createdOrder.products[0].sourceId, 'product:10:combination:100');
|
||||
assert.equal(createdOrder.products[0].previousSourceId, '10');
|
||||
assert.equal(createdOrder.products[0].sku, 'PACK-V');
|
||||
assert.equal(createdOrder.products[0].brand, 'Pack Brand');
|
||||
assert.equal(createdOrder.products[0].warehouseLocation, 'PACK-V-BIN');
|
||||
assert.equal(createdOrder.products[0].pack[0].sourceId, 'product:20:combination:200');
|
||||
assert.equal(createdOrder.products[0].pack[0].previousSourceId, '20');
|
||||
assert.equal(createdOrder.products[0].pack[0].baseUnitPrice, 3.25);
|
||||
assert.equal(createdOrder.products[0].pack[0].tax, 0.08);
|
||||
assert.equal(createdOrder.products[0].pack[1].sourceId, 'product:21:combination:0');
|
||||
assert.equal(createdOrder.products[0].pack[1].sku, 'REGULAR-ITEM');
|
||||
assert.equal(createdOrder.products[0].pack[1].baseUnitPrice, 4.5);
|
||||
assert.equal(createdOrder.products[0].pack[1].tax, 0.23, 'missing tax data uses the configured fallback');
|
||||
assert.deepEqual(taxLookups, [{
|
||||
productId: '20', combinationId: '200',
|
||||
context: { countryId: '1', stateId: undefined, postcode: '00-001', currencyId: '1' },
|
||||
}, {
|
||||
productId: '21', combinationId: '0',
|
||||
context: { countryId: '1', stateId: undefined, postcode: '00-001', currencyId: '1' },
|
||||
}]);
|
||||
assert.deepEqual(createdOrder.products.slice(1).map(product => product.sku), [
|
||||
'VARIANT-BLUE', 'VARIANT-RED',
|
||||
]);
|
||||
assert.equal(createdOrder.products[0].unitPrice, 10, 'order keeps its transactional net price');
|
||||
assert.equal(createdOrder.products[0].baseUnitPrice, 9.5, 'order also carries the catalog base price');
|
||||
});
|
||||
+247
-2
@@ -1,7 +1,8 @@
|
||||
const { withHookFixtures } = require('./helpers/hook-fixtures');
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const Module = require('node:module');
|
||||
const Core = { fetch: null };
|
||||
const Core = withHookFixtures({ fetch: null });
|
||||
const originalLoad = Module._load;
|
||||
Module._load = function(request, parent, isMain) {
|
||||
if (request === '@orbito/api-lib') return { Core, Log: { warn() {} } };
|
||||
@@ -41,6 +42,79 @@ 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('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; });
|
||||
@@ -56,12 +130,20 @@ test('rejects non-retryable 4xx and invalid JSON', async t => {
|
||||
test('times out stalled requests', async t => {
|
||||
const originalFetch = Core.fetch;
|
||||
t.after(() => { Core.fetch = originalFetch; });
|
||||
// Timer timeoutu w fetchWithTimeout jest `unref`-owany, a Core.fetch nigdy się tu nie rozwiązuje,
|
||||
// więc na prawdziwych timerach pętla zdarzeń pustoszeje i node:test anuluje ten test.
|
||||
// Mockowany setTimeout pozwala wysterować timeout ręcznie przez tick().
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
Core.fetch = async () => new Promise(() => {});
|
||||
const api = new PrestashopApi('https://shop.example', 'secret', true, {
|
||||
timeoutMs: 5, maxGetAttempts: 1,
|
||||
});
|
||||
|
||||
await assert.rejects(() => api.makeRequest('orders', 'GET'), /timed out/);
|
||||
const pending = api.makeRequest('orders', 'GET');
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
t.mock.timers.tick(10);
|
||||
|
||||
await assert.rejects(() => pending, /timed out/);
|
||||
});
|
||||
|
||||
test('preserves the explicitly allowed product partial-success compatibility path', async t => {
|
||||
@@ -72,3 +154,166 @@ test('preserves the explicitly allowed product partial-success compatibility pat
|
||||
|
||||
assert.deepEqual(await api.makeRequest('products/1', 'GET', null, true), { product: { id: 1 } });
|
||||
});
|
||||
|
||||
test('looks up combinations and stock locations with exact product filters', async t => {
|
||||
const originalFetch = Core.fetch;
|
||||
t.after(() => { Core.fetch = originalFetch; });
|
||||
const urls = [];
|
||||
Core.fetch = async url => {
|
||||
urls.push(url);
|
||||
if (url.includes('combinations')) return response(200, { combinations: [{ id: '10' }] });
|
||||
return response(200, { stock_availables: [{ id: '20' }] });
|
||||
};
|
||||
const api = new PrestashopApi('https://shop.example', 'secret', true, { maxGetAttempts: 1 });
|
||||
|
||||
assert.deepEqual(await api.findProductCombinationsByReference('1', 'SKU-1'), [{ id: '10' }]);
|
||||
assert.deepEqual(await api.getStockAvailabilities('1', '10'), [{ id: '20' }]);
|
||||
assert.match(urls[0], /filter%5Bid_product%5D=%5B1%5D/);
|
||||
assert.match(urls[0], /filter%5Breference%5D=%5BSKU-1%5D/);
|
||||
assert.match(urls[1], /filter%5Bid_product_attribute%5D=%5B10%5D/);
|
||||
});
|
||||
|
||||
test('does not turn an unsafe reference filter into an empty combination match', async t => {
|
||||
const originalFetch = Core.fetch;
|
||||
t.after(() => { Core.fetch = originalFetch; });
|
||||
Core.fetch = async () => assert.fail('must not issue a broadened combination lookup');
|
||||
const api = new PrestashopApi('https://shop.example', 'secret', true, { maxGetAttempts: 1 });
|
||||
|
||||
assert.equal(await api.findProductCombinationsByReference('1', 'SKU[1]'), null);
|
||||
});
|
||||
|
||||
test('uses a combination image before the base product cover', async () => {
|
||||
const api = new PrestashopApi('https://shop.example', 'secret', true, { maxGetAttempts: 1 });
|
||||
api.getProduct = async () => assert.fail('base product must not be fetched when variant has an image');
|
||||
|
||||
const url = await api.getProductCoverImageUrl('1', {
|
||||
associations: { images: [{ id: '55' }] },
|
||||
});
|
||||
|
||||
assert.match(url, /images\/products\/1\/55\/home_default/);
|
||||
assert.match(url, /ws_key=secret/);
|
||||
});
|
||||
|
||||
test('derives a combination VAT rate from the base product tax calculation and caches it', async t => {
|
||||
const originalFetch = Core.fetch;
|
||||
t.after(() => { Core.fetch = originalFetch; });
|
||||
const urls = [];
|
||||
Core.fetch = async url => {
|
||||
urls.push(url);
|
||||
return response(200, { product: { orbito_price_net: '100.00', orbito_price_gross: '123.00' } });
|
||||
};
|
||||
const api = new PrestashopApi('https://shop.example', 'secret', true, { maxGetAttempts: 1 });
|
||||
const context = { countryId: '1', stateId: '0', postcode: '00-001', currencyId: '2' };
|
||||
|
||||
assert.equal(await api.getProductTaxRate('20', '200', context), 0.23);
|
||||
assert.equal(await api.getProductTaxRate('20', '200', context), 0.23);
|
||||
assert.equal(urls.length, 1);
|
||||
assert.match(urls[0], /products\/20\?/);
|
||||
assert.match(urls[0], /price%5Borbito_price_net%5D%5Buse_tax%5D=0/);
|
||||
assert.match(urls[0], /price%5Borbito_price_gross%5D%5Buse_tax%5D=1/);
|
||||
assert.match(urls[0], /price%5Borbito_price_gross%5D%5Bproduct_attribute%5D=200/);
|
||||
assert.match(urls[0], /price%5Borbito_price_gross%5D%5Bcountry%5D=1/);
|
||||
assert.match(urls[0], /price%5Borbito_price_gross%5D%5Bpostcode%5D=00-001/);
|
||||
});
|
||||
|
||||
test('returns no VAT rate when PrestaShop cannot provide comparable net and gross prices', async t => {
|
||||
const originalFetch = Core.fetch;
|
||||
t.after(() => { Core.fetch = originalFetch; });
|
||||
Core.fetch = async () => response(200, {
|
||||
product: { orbito_price_net: 'invalid', orbito_price_gross: '123.00' },
|
||||
});
|
||||
const api = new PrestashopApi('https://shop.example', 'secret', true, { maxGetAttempts: 1 });
|
||||
|
||||
assert.equal(await api.getProductTaxRate('20', '0', { countryId: '1' }), null);
|
||||
});
|
||||
|
||||
test('collects public customer notes from order, cart and customer thread without cross-order leakage', async t => {
|
||||
const originalFetch = Core.fetch;
|
||||
t.after(() => { Core.fetch = originalFetch; });
|
||||
const calls = [];
|
||||
Core.fetch = async url => {
|
||||
const parsed = new URL(url);
|
||||
calls.push(parsed);
|
||||
const orderId = parsed.searchParams.get('filter[id_order]');
|
||||
const cartId = parsed.searchParams.get('filter[id_cart]');
|
||||
const threadId = parsed.searchParams.get('filter[id_customer_thread]');
|
||||
if (parsed.pathname.endsWith('/messages') && orderId === '[7]') return response(200, {
|
||||
messages: [
|
||||
{ id: '1', id_order: '7', id_cart: '11', private: '0', id_employee: '0', message: 'Dostawa rano' },
|
||||
{ id: '2', id_order: '7', id_cart: '11', private: '1', id_employee: '0', message: 'Prywatna' },
|
||||
{ id: '3', id_order: '7', id_cart: '11', private: '0', id_employee: '5', message: 'Pracownik' },
|
||||
{ id: '4', id_order: '8', id_cart: '11', private: '0', id_employee: '0', message: 'Obce zamówienie' },
|
||||
{ id: '7', id_order: '7', id_cart: '11', private: '0', id_employee: '0', message: 42 },
|
||||
{ id: '8', id_order: '7', id_cart: '11', private: '0', id_employee: '0', message: {} },
|
||||
{ id: '9', id_order: '7', id_cart: '11', private: '0', id_employee: '0', message: ' ' },
|
||||
{ id: '10', id_order: '7', id_cart: '11', private: '0', id_employee: '0', message: 'Proszę o kontakt\r\npo 17:00' },
|
||||
],
|
||||
});
|
||||
if (parsed.pathname.endsWith('/messages') && cartId === '[11]') return response(200, {
|
||||
messages: [
|
||||
{ id: '1', id_order: '7', id_cart: '11', private: '0', id_employee: '0', message: 'Dostawa rano' },
|
||||
{ id: '5', id_order: '0', id_cart: '11', private: 'false', id_employee: '', message: 'Kod bramy: 1234' },
|
||||
{ id: '6', id_order: '8', id_cart: '11', private: '0', id_employee: '0', message: 'Drugi order z koszyka' },
|
||||
],
|
||||
});
|
||||
if (parsed.pathname.endsWith('/customer_threads')) return response(200, {
|
||||
customer_threads: [{ id: '30', id_order: '7' }, { id: '31', id_order: '8' }],
|
||||
});
|
||||
if (parsed.pathname.endsWith('/customer_messages') && threadId === '[30]') return response(200, {
|
||||
customer_messages: [
|
||||
{ id: '40', id_customer_thread: '30', id_employee: '0', message: 'Dostawa rano' },
|
||||
{ id: '41', id_customer_thread: '30', id_employee: '2', message: 'Odpowiedź pracownika' },
|
||||
{ id: '42', id_customer_thread: '31', id_employee: '0', message: 'Obcy wątek' },
|
||||
{ id: '43', id_customer_thread: '30', id_employee: '0', private: '2', message: 'Prywatny niestandardowy' },
|
||||
{ id: '44', id_customer_thread: '30', id_employee: '0', message: 'Proszę o kontakt\npo 17:00' },
|
||||
{ id: '45', id_customer_thread: '30', id_employee: '0', message: 'Dzwonek nie działa' },
|
||||
],
|
||||
});
|
||||
assert.fail(`Unexpected endpoint: ${url}`);
|
||||
};
|
||||
const api = new PrestashopApi('https://shop.example', 'secret', true, { maxGetAttempts: 1 });
|
||||
|
||||
assert.deepEqual(await api.getCustomerNotes('7', '11', 'Dla Ani'), [
|
||||
'Wiadomość dołączona do prezentu: Dla Ani',
|
||||
'Dostawa rano',
|
||||
'Proszę o kontakt\r\npo 17:00',
|
||||
'Dzwonek nie działa',
|
||||
'Kod bramy: 1234',
|
||||
]);
|
||||
assert.equal(calls.filter(call => call.pathname.endsWith('/customer_messages')).length, 1);
|
||||
assert.equal(calls.filter(call => call.pathname.endsWith('/messages')).length, 2);
|
||||
for (const call of calls.filter(call => call.pathname.endsWith('/messages')
|
||||
|| call.pathname.endsWith('/customer_messages'))) {
|
||||
assert.equal(call.searchParams.get('sort'), 'id_ASC');
|
||||
}
|
||||
});
|
||||
|
||||
test('keeps notes from available sources when one customer-note endpoint is forbidden', async t => {
|
||||
const originalFetch = Core.fetch;
|
||||
t.after(() => { Core.fetch = originalFetch; });
|
||||
Core.fetch = async url => {
|
||||
const parsed = new URL(url);
|
||||
if (parsed.pathname.endsWith('/messages') && parsed.searchParams.get('filter[id_order]') === '[7]') {
|
||||
return response(403, { errors: [] });
|
||||
}
|
||||
if (parsed.pathname.endsWith('/messages') && parsed.searchParams.get('filter[id_cart]') === '[11]') {
|
||||
return response(200, { messages: [{ id_cart: '11', id_order: '0', private: '0', id_employee: '0', message: 'Checkout działa' }] });
|
||||
}
|
||||
if (parsed.pathname.endsWith('/customer_threads')) return response(200, { customer_threads: [] });
|
||||
assert.fail(`Unexpected endpoint: ${url}`);
|
||||
};
|
||||
const api = new PrestashopApi('https://shop.example', 'secret', true, { maxGetAttempts: 1 });
|
||||
|
||||
assert.deepEqual(await api.getCustomerNotes('7', '11'), ['Checkout działa']);
|
||||
});
|
||||
|
||||
test('retains gift_message when every customer-note endpoint is unavailable', async t => {
|
||||
const originalFetch = Core.fetch;
|
||||
t.after(() => { Core.fetch = originalFetch; });
|
||||
Core.fetch = async () => response(403, { errors: [] });
|
||||
const api = new PrestashopApi('https://shop.example', 'secret', true, { maxGetAttempts: 1 });
|
||||
|
||||
assert.deepEqual(await api.getCustomerNotes('7', '11', 'Dla Ani'), [
|
||||
'Wiadomość dołączona do prezentu: Dla Ani',
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { execFileSync } = require('node:child_process');
|
||||
const { parsePrestashopDate } = require('../src/prestashop-date');
|
||||
|
||||
test('shop-local dates use the date-specific offset, including DST transitions and other shop zones', () => {
|
||||
const cases = [
|
||||
['2026-09-25 10:53:43', undefined, '2026-09-25T08:53:43.000Z'],
|
||||
['2026-01-25 10:53:43', undefined, '2026-01-25T09:53:43.000Z'],
|
||||
['2026-03-29 01:59:59', undefined, '2026-03-29T00:59:59.000Z'],
|
||||
['2026-03-29 03:00:00', undefined, '2026-03-29T01:00:00.000Z'],
|
||||
['2026-10-25 02:30:00', undefined, '2026-10-25T00:30:00.000Z'],
|
||||
['2026-10-25 03:00:00', undefined, '2026-10-25T02:00:00.000Z'],
|
||||
['2026-09-25 00:00:00.123', undefined, '2026-09-24T22:00:00.123Z'],
|
||||
['2026-09-25 10:53:43', 'UTC', '2026-09-25T10:53:43.000Z'],
|
||||
['2026-09-25 10:53:43', 'Europe/London', '2026-09-25T09:53:43.000Z'],
|
||||
['2026-09-25 10:53:43', 'Asia/Kolkata', '2026-09-25T05:23:43.000Z'],
|
||||
['2026-09-25T10:53:43+02:00', 'Europe/London', '2026-09-25T08:53:43.000Z'],
|
||||
['2026-09-25T08:53:43Z', undefined, '2026-09-25T08:53:43.000Z'],
|
||||
];
|
||||
for (const [input, zone, expected] of cases) {
|
||||
assert.equal(parsePrestashopDate(input, null, zone).toISOString(), expected, `${input} (${zone})`);
|
||||
}
|
||||
});
|
||||
|
||||
test('invalid calendar dates and nonexistent local times use the supplied fallback', () => {
|
||||
const fallback = new Date('2026-09-25T09:00:00Z');
|
||||
for (const value of [null, '', 'invalid', '0000-00-00 00:00:00', '2026-02-30 10:00:00',
|
||||
'2026-09-25 24:00:00', '2026-03-29 02:30:00', new Date(NaN)]) {
|
||||
assert.equal(parsePrestashopDate(value, fallback), fallback, String(value));
|
||||
}
|
||||
assert.equal(parsePrestashopDate(fallback).getTime(), fallback.getTime());
|
||||
assert.throws(() => parsePrestashopDate('2026-09-25 10:00:00', null, 'Not/AZone'), RangeError);
|
||||
});
|
||||
|
||||
test('the same PrestaShop date produces the same instant in UTC, Warsaw and US containers', () => {
|
||||
const script = `const { parsePrestashopDate } = require(${JSON.stringify(require.resolve('../src/prestashop-date'))});
|
||||
process.stdout.write(parsePrestashopDate('2026-09-25 10:53:43').toISOString());`;
|
||||
for (const TZ of ['UTC', 'Europe/Warsaw', 'America/New_York']) {
|
||||
assert.equal(execFileSync(process.execPath, ['-e', script], {
|
||||
env: { ...process.env, TZ }, encoding: 'utf8',
|
||||
}), '2026-09-25T08:53:43.000Z');
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,278 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const Module = require('node:module');
|
||||
const path = require('node:path');
|
||||
|
||||
function loadMethod({ onGetProduct, onGetCombination, onFindCombinations, onManufacturer, onStocks }) {
|
||||
const methodPath = path.resolve(__dirname, '../methods/product/get_metadata.js');
|
||||
const originalLoad = Module._load;
|
||||
Module._load = function(request, parent, isMain) {
|
||||
if (request === '../../src/PrestaApi') {
|
||||
return class PrestashopApi {
|
||||
async getProduct(id) { return onGetProduct(id); }
|
||||
async getProductCombination(id) { return onGetCombination ? onGetCombination(id) : null; }
|
||||
async findProductCombinationsByReference(id, sku) { return onFindCombinations(id, sku); }
|
||||
async getManufacturer(id) { return onManufacturer(id); }
|
||||
async getStockAvailabilities(id, attributeId) { return onStocks(id, attributeId); }
|
||||
};
|
||||
}
|
||||
if (request === '../../src/utils') return { isLegacyApi: () => false };
|
||||
if (request === '../../src/module-config') {
|
||||
return { loadConfig: async () => ({ apiUrl: 'https://shop.test', apiKey: 'key' }), isConfigured: () => true };
|
||||
}
|
||||
if (request === '../../src/register-permissions') {
|
||||
return { PERMISSIONS: { ORDERS_VIEW: 'orders.view' }, requirePermission() {} };
|
||||
}
|
||||
return originalLoad.call(this, request, parent, isMain);
|
||||
};
|
||||
delete require.cache[methodPath];
|
||||
delete require.cache[path.resolve(__dirname, '../src/product-metadata.js')];
|
||||
try {
|
||||
return require(methodPath);
|
||||
} finally {
|
||||
Module._load = originalLoad;
|
||||
}
|
||||
}
|
||||
|
||||
test('metadata lookup deduplicates source/SKU pairs and preserves confirmed empty values', async () => {
|
||||
const calls = [];
|
||||
const method = loadMethod({
|
||||
onGetProduct: async id => ({
|
||||
id,
|
||||
reference: id === '1' ? 'base-1' : 'base-2',
|
||||
id_manufacturer: id === '1' ? '8' : '0',
|
||||
location: id === '1' ? 'A-01' : '',
|
||||
}),
|
||||
onFindCombinations: async () => [],
|
||||
onManufacturer: async id => ({ id, name: 'Acme' }),
|
||||
onStocks: async () => [],
|
||||
});
|
||||
|
||||
const result = await method({ products: [
|
||||
{ sourceId: '1', sku: 'base-1' },
|
||||
{ sourceId: '1', sku: 'base-1' },
|
||||
{ sourceId: '1', sku: 'BASE-1' },
|
||||
{ sourceId: '2', sku: 'base-2' },
|
||||
] }, {});
|
||||
|
||||
assert.equal(result.results.length, 2);
|
||||
assert.deepEqual(result.results.find(item => item.sourceId === '1'), {
|
||||
sourceId: '1', sku: 'base-1', brand: 'Acme', warehouseLocation: 'A-01',
|
||||
});
|
||||
assert.deepEqual(result.results.find(item => item.sourceId === '2'), {
|
||||
sourceId: '2', sku: 'base-2', brand: '', warehouseLocation: '',
|
||||
});
|
||||
assert.equal(calls.length, 0);
|
||||
});
|
||||
|
||||
test('metadata lookup returns a variant only for exactly one verified reference match', async () => {
|
||||
const method = loadMethod({
|
||||
onGetProduct: async id => ({ id, reference: 'base', manufacturer_name: 'Brand', location: 'BASE' }),
|
||||
onFindCombinations: async () => [
|
||||
{ id: '10', id_product: '1', reference: 'variant', location: 'BIN-1' },
|
||||
],
|
||||
onManufacturer: async () => null,
|
||||
onStocks: async () => [],
|
||||
});
|
||||
|
||||
const result = await method({ products: [{ sourceId: '1', sku: ' VaRiAnT ' }] }, {});
|
||||
assert.deepEqual(result, {
|
||||
results: [{ sourceId: '1', sku: 'VaRiAnT', brand: 'Brand', warehouseLocation: 'BIN-1' }],
|
||||
});
|
||||
});
|
||||
|
||||
test('metadata lookup resolves a composite variant identity by exact combination ID', async () => {
|
||||
const combinationCalls = [];
|
||||
const method = loadMethod({
|
||||
onGetProduct: async id => ({ id, reference: 'base', manufacturer_name: 'Brand', location: 'BASE' }),
|
||||
onGetCombination: async id => {
|
||||
combinationCalls.push(id);
|
||||
return { id, id_product: '1', reference: 'variant', location: 'BIN-1' };
|
||||
},
|
||||
onFindCombinations: async () => assert.fail('composite identity must not search by reference'),
|
||||
onManufacturer: async () => null,
|
||||
onStocks: async () => [],
|
||||
});
|
||||
|
||||
const result = await method({
|
||||
products: [{ sourceId: 'product:1:combination:10', sku: ' VaRiAnT ' }],
|
||||
}, {});
|
||||
|
||||
assert.deepEqual(combinationCalls, ['10']);
|
||||
assert.deepEqual(result, {
|
||||
results: [{
|
||||
sourceId: 'product:1:combination:10',
|
||||
sku: 'VaRiAnT',
|
||||
brand: 'Brand',
|
||||
warehouseLocation: 'BIN-1',
|
||||
}],
|
||||
});
|
||||
});
|
||||
|
||||
test('product source identities distinguish base products and combinations', () => {
|
||||
const { buildProductSourceId, parseProductSourceId } = require('../src/product-metadata');
|
||||
|
||||
assert.equal(buildProductSourceId('10', 0), 'product:10:combination:0');
|
||||
assert.equal(buildProductSourceId('10', '101'), 'product:10:combination:101');
|
||||
assert.deepEqual(parseProductSourceId('product:10:combination:101'), {
|
||||
sourceId: 'product:10:combination:101',
|
||||
productId: '10',
|
||||
combinationId: '101',
|
||||
legacy: false,
|
||||
});
|
||||
assert.deepEqual(parseProductSourceId('10'), {
|
||||
sourceId: '10', productId: '10', combinationId: null, legacy: true,
|
||||
});
|
||||
});
|
||||
|
||||
test('metadata resolves the net base price including a combination price impact', async () => {
|
||||
const { resolveProductMetadata, resolveBaseUnitPrice } = require('../src/product-metadata');
|
||||
const api = {
|
||||
getManufacturer: async () => null,
|
||||
getStockAvailabilities: async () => [],
|
||||
};
|
||||
const product = {
|
||||
id: '1', reference: 'BASE', price: '19.90', manufacturer_name: '', location: '',
|
||||
};
|
||||
const combination = {
|
||||
id: '10', id_product: '1', reference: 'VARIANT', price: '2.60', location: '',
|
||||
};
|
||||
|
||||
assert.equal(resolveBaseUnitPrice(product), 19.9);
|
||||
assert.equal(resolveBaseUnitPrice(product, combination), 22.5);
|
||||
assert.deepEqual(await resolveProductMetadata(api, product, {
|
||||
sku: 'VARIANT', combination,
|
||||
}), {
|
||||
unitPrice: 22.5,
|
||||
brand: '',
|
||||
warehouseLocation: '',
|
||||
});
|
||||
});
|
||||
|
||||
test('metadata lookup omits synthetic SKUs and ambiguous variant matches', async () => {
|
||||
let requestedCombinations = 0;
|
||||
const method = loadMethod({
|
||||
onGetProduct: async id => ({ id, reference: 'base', manufacturer_name: 'Brand', location: 'BASE' }),
|
||||
onFindCombinations: async () => {
|
||||
requestedCombinations += 1;
|
||||
return [
|
||||
{ id: '10', id_product: '1', reference: 'variant', location: 'BIN-1' },
|
||||
{ id: '11', id_product: '1', reference: 'VARIANT', location: 'BIN-2' },
|
||||
];
|
||||
},
|
||||
onManufacturer: async () => null,
|
||||
onStocks: async () => [],
|
||||
});
|
||||
|
||||
const result = await method({ products: [
|
||||
{ sourceId: '1', sku: '~:core/prestashop:1' },
|
||||
{ sourceId: '1', sku: 'variant' },
|
||||
] }, {});
|
||||
|
||||
assert.deepEqual(result, { results: [] });
|
||||
assert.equal(requestedCombinations, 1);
|
||||
});
|
||||
|
||||
test('stock fallback only accepts a unique or default-shop record', async () => {
|
||||
const { chooseStockLocation } = require('../src/product-metadata');
|
||||
const product = { id: '1', id_shop_default: '2' };
|
||||
|
||||
assert.equal(chooseStockLocation([
|
||||
{ id_product: '1', id_product_attribute: '0', id_shop: '1', location: 'OTHER' },
|
||||
{ id_product: '1', id_product_attribute: '0', id_shop: '2', location: 'DEFAULT' },
|
||||
], product, 0).location, 'DEFAULT');
|
||||
assert.equal(chooseStockLocation([
|
||||
{ id_product: '1', id_product_attribute: '0', id_shop: '1', location: 'A' },
|
||||
{ id_product: '1', id_product_attribute: '0', id_shop: '3', location: 'B' },
|
||||
], product, 0).status, 'ambiguous');
|
||||
});
|
||||
|
||||
test('stock availability is authoritative over stale legacy product location, including a confirmed empty value', async () => {
|
||||
const { resolveProductMetadata } = require('../src/product-metadata');
|
||||
const api = {
|
||||
getManufacturer: async () => null,
|
||||
getStockAvailabilities: async () => [{
|
||||
id_product: '1', id_product_attribute: '0', id_shop: '1', location: 'A2',
|
||||
}],
|
||||
};
|
||||
const product = { id: '1', id_shop_default: '1', reference: 'sku', manufacturer_name: 'Brand', location: 'STALE' };
|
||||
|
||||
assert.deepEqual(await resolveProductMetadata(api, product, { sku: 'SKU' }), {
|
||||
brand: 'Brand', warehouseLocation: 'A2',
|
||||
});
|
||||
|
||||
api.getStockAvailabilities = async () => [{
|
||||
id_product: '1', id_product_attribute: '0', id_shop: '1', location: '',
|
||||
}];
|
||||
assert.deepEqual(await resolveProductMetadata(api, product, { sku: 'SKU' }), {
|
||||
brand: 'Brand', warehouseLocation: '',
|
||||
});
|
||||
});
|
||||
|
||||
test('a missing ordered combination never falls back to the base product metadata', async () => {
|
||||
const { resolveProductMetadata } = require('../src/product-metadata');
|
||||
const api = {
|
||||
getManufacturer: async () => null,
|
||||
getStockAvailabilities: async () => [{ id_product: '1', id_product_attribute: '0', location: 'BASE' }],
|
||||
};
|
||||
const product = { id: '1', reference: 'SKU', manufacturer_name: 'Brand', location: 'LEGACY' };
|
||||
|
||||
assert.deepEqual(await resolveProductMetadata(api, product, {
|
||||
sku: 'SKU', requiresCombination: true,
|
||||
}), {});
|
||||
});
|
||||
|
||||
test('failed or ambiguous stock lookups do not clear metadata through an empty legacy location', async () => {
|
||||
const { resolveProductMetadata } = require('../src/product-metadata');
|
||||
const product = { id: '1', reference: 'SKU', manufacturer_name: 'Brand', location: '' };
|
||||
const failedStockApi = {
|
||||
getManufacturer: async () => null,
|
||||
getStockAvailabilities: async () => { throw new Error('forbidden'); },
|
||||
};
|
||||
|
||||
const baseResult = await resolveProductMetadata(failedStockApi, product, { sku: 'SKU' });
|
||||
assert.deepEqual(baseResult, { brand: 'Brand' });
|
||||
assert.equal(Object.hasOwn(baseResult, 'warehouseLocation'), false);
|
||||
|
||||
const variantResult = await resolveProductMetadata(failedStockApi, product, {
|
||||
sku: 'VARIANT',
|
||||
combination: { id: '10', id_product: '1', reference: 'VARIANT', location: '' },
|
||||
});
|
||||
assert.deepEqual(variantResult, { brand: 'Brand' });
|
||||
assert.equal(Object.hasOwn(variantResult, 'warehouseLocation'), false);
|
||||
|
||||
const ambiguousStockApi = {
|
||||
getManufacturer: async () => null,
|
||||
getStockAvailabilities: async () => [
|
||||
{ id_product: '1', id_product_attribute: '0', id_shop: '2', location: 'A' },
|
||||
{ id_product: '1', id_product_attribute: '0', id_shop: '3', location: 'B' },
|
||||
],
|
||||
};
|
||||
const ambiguousResult = await resolveProductMetadata(ambiguousStockApi, product, { sku: 'SKU' });
|
||||
assert.equal(Object.hasOwn(ambiguousResult, 'warehouseLocation'), false);
|
||||
});
|
||||
|
||||
test('metadata lookup skips a base match when the variation reference cannot be filtered safely', async () => {
|
||||
const { findMetadataBySourceAndSku } = require('../src/product-metadata');
|
||||
const api = {
|
||||
getProduct: async id => ({ id, reference: 'SKU[1]', manufacturer_name: 'Brand' }),
|
||||
findProductCombinationsByReference: async () => null,
|
||||
};
|
||||
|
||||
assert.equal(await findMetadataBySourceAndSku(api, { sourceId: '1', sku: 'SKU[1]' }), null);
|
||||
});
|
||||
|
||||
test('metadata lookup skips combination API when product declares no combinations', async () => {
|
||||
const method = loadMethod({
|
||||
onGetProduct: async id => ({
|
||||
id, reference: 'base', manufacturer_name: 'Brand', location: 'LEGACY', associations: { combinations: [] },
|
||||
}),
|
||||
onFindCombinations: async () => assert.fail('must not request combinations for a known empty association'),
|
||||
onManufacturer: async () => null,
|
||||
onStocks: async () => [],
|
||||
});
|
||||
|
||||
assert.deepEqual(await method({ products: [{ sourceId: '1', sku: 'base' }] }, {}), {
|
||||
results: [{ sourceId: '1', sku: 'base', brand: 'Brand', warehouseLocation: 'LEGACY' }],
|
||||
});
|
||||
});
|
||||
@@ -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 () => [],
|
||||
};
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
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');
|
||||
|
||||
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;
|
||||
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,
|
||||
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 === './shop-icon') return { ensureShopIcon: async () => {} };
|
||||
return originalLoad.call(this, request, parent, isMain);
|
||||
};
|
||||
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);
|
||||
({ loadConfig, initializeOutboundMapping } = require('../src/module-config'));
|
||||
} finally { Module._load = originalLoad; }
|
||||
return {
|
||||
...loaded, store, requests, loadConfig, initializeOutboundMapping, Config,
|
||||
register: async () => {
|
||||
await loaded.registerPrestashopConfigBlocks();
|
||||
return blocks;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
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[`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('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);
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
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 () => {
|
||||
const module = loadConfigModule({ states: [{ id: '2', name: 'New' }] });
|
||||
const blocks = await module.register();
|
||||
assert.equal(blocks.connection.schema.timeZone.default, 'Europe/Warsaw');
|
||||
const errors = [];
|
||||
const report = { addError: (field, message) => errors.push({ field, message }) };
|
||||
const connection = { apiUrl: 'https://shop.test', apiKey: 'secret' };
|
||||
await blocks.connection.validate({ ...connection, timeZone: 'Not/AZone' }, report);
|
||||
assert.deepEqual(errors.map(error => error.field), ['timeZone']);
|
||||
errors.length = 0;
|
||||
for (const timeZone of ['', 'Europe/Warsaw', 'UTC', 'Europe/London']) {
|
||||
await blocks.connection.validate({ ...connection, timeZone }, report);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('config loading applies Warsaw to existing installations and passes a saved shop zone to jobs', async () => {
|
||||
let savedTimeZone;
|
||||
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);
|
||||
};
|
||||
let loadConfig;
|
||||
try {
|
||||
delete require.cache[require.resolve('../src/module-config')];
|
||||
({ loadConfig } = require('../src/module-config'));
|
||||
} finally { Module._load = originalLoad; }
|
||||
assert.equal((await loadConfig()).timeZone, 'Europe/Warsaw');
|
||||
savedTimeZone = ' ';
|
||||
assert.equal((await loadConfig()).timeZone, 'Europe/Warsaw');
|
||||
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);
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
const { withHookFixtures } = require('./helpers/hook-fixtures');
|
||||
const assert = require('node:assert/strict');
|
||||
const Module = require('node:module');
|
||||
const path = require('node:path');
|
||||
@@ -33,7 +34,7 @@ test('discovers, downloads and persists a favicon once before registering the so
|
||||
get: async (key, fallback) => config.has(key) ? config.get(key) : fallback,
|
||||
set: async (key, value) => config.set(key, value),
|
||||
},
|
||||
Core: {
|
||||
Core: withHookFixtures({
|
||||
fetch: async url => {
|
||||
calls.push(url);
|
||||
if (url === 'https://shop.test/b2b/') {
|
||||
@@ -45,7 +46,7 @@ test('discovers, downloads and persists a favicon once before registering the so
|
||||
throw new Error(`Unexpected URL: ${url}`);
|
||||
},
|
||||
callModule: async (...args) => registered.push(args),
|
||||
},
|
||||
}),
|
||||
Log: { warn() {} },
|
||||
});
|
||||
|
||||
@@ -89,10 +90,10 @@ test('a failed refresh retains the last icon for the same shop', async () => {
|
||||
get: async () => stored,
|
||||
set: async (key, value) => { stored = value; },
|
||||
},
|
||||
Core: {
|
||||
Core: withHookFixtures({
|
||||
fetch: async () => ({ status: 503, data: Buffer.alloc(0), headers: {} }),
|
||||
callModule: async () => ({}),
|
||||
},
|
||||
}),
|
||||
Log: { warn() {} },
|
||||
});
|
||||
|
||||
@@ -108,7 +109,7 @@ test('a failed refresh retains the last icon for the same shop', async () => {
|
||||
});
|
||||
|
||||
test('favicon discovery rejects cross-host candidates and recognizes common binary formats', () => {
|
||||
const shopIcon = loadShopIcon({ Config: {}, Core: {}, Log: { warn() {} } });
|
||||
const shopIcon = loadShopIcon({ Config: {}, Core: withHookFixtures({}), Log: { warn() {} } });
|
||||
const candidates = shopIcon.faviconCandidates(
|
||||
'<link rel="icon" href="https://cdn.test/icon.png"><link rel="apple-touch-icon" href="/touch.png">',
|
||||
'https://shop.test/catalog/'
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
const { resolvePsStateId, readStatusMapping } = 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/);
|
||||
});
|
||||
|
||||
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/);
|
||||
}
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -0,0 +1,159 @@
|
||||
const { withHookFixtures } = require('./helpers/hook-fixtures');
|
||||
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 = withHookFixtures({
|
||||
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 }),
|
||||
update: async () => ({ matchedCount: 1 }),
|
||||
},
|
||||
loadConfig: async () => ({
|
||||
apiUrl: 'https://shop.test',
|
||||
apiKey: 'secret',
|
||||
statusMapping: [{ psStateId: 7, orbitoStatusId: CURRENT_STATUS }],
|
||||
}),
|
||||
apiFor: () => ({
|
||||
setOrderState: async (...args) => {
|
||||
calls.setOrderState.push(args.slice(0, 2));
|
||||
await args[2]?.beforeWrite();
|
||||
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('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: [{
|
||||
_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