fix(prestashop): import dates in the shop time zone (1.1.15)

This commit is contained in:
fatequod
2026-09-25 11:46:21 +02:00
parent 93ebfe728d
commit 6b5e03246e
13 changed files with 269 additions and 24 deletions
+14
View File
@@ -3,6 +3,20 @@
Moduł podłącza się do sklepu podanego w konfiguracji i dodaje zamówienia za pomocą
modułu `core/orders`
## 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ń.
## Statusy zamówień
Orbito jest źródłem prawdy dla statusów zamówień. Przy ładowaniu zakładki
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "core/prestashop",
"version": "1.1.14",
"version": "1.1.15",
"singleton": false,
"dependsOn": [
"core/orders",
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "core.prestashop",
"version": "1.1.14",
"version": "1.1.15",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "core.prestashop",
"version": "1.1.14",
"version": "1.1.15",
"license": "ISC",
"dependencies": {
"@orbito/api-lib": "^3.3.3",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "core.prestashop",
"version": "1.1.14",
"version": "1.1.15",
"description": "Integracja zamówień i płatności PrestaShop",
"main": "index.js",
"scripts": {
+4 -3
View File
@@ -325,12 +325,13 @@ async function importFromPSOrder(orderId, api, config) {
}
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),
});
}
@@ -386,7 +387,7 @@ async function importFromPSOrder(orderId, api, config) {
discounts,
invoice: invoiceDataForOrder,
notes: customerNotes.map(text => ({ text, type: 'customer_message' })),
createdAt: new Date(order.date_add),
createdAt,
});
if (!coreOrder?._id) {
@@ -399,7 +400,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,
+6 -17
View File
@@ -1,5 +1,6 @@
const DEFAULT_PAGE_SIZE = 50;
const DEFAULT_MAX_PAGES = 10;
const { parsePrestashopDate } = require('./prestashop-date');
function money(value) {
const number = Number(value);
@@ -22,12 +23,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 +59,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,7 +112,7 @@ 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;
@@ -211,7 +200,7 @@ async function processPaymentMapping(mapping, config, api, dependencies) {
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,
},
});
+4
View File
@@ -1,4 +1,5 @@
const { Config } = require('@orbito/api-lib');
const { DEFAULT_SHOP_TIME_ZONE } = require('./prestashop-date');
/** Stały identyfikator sklepu (jeden sklep na firmę) — używany w PsOrder.shopConfigId. */
const SHOP_ID = 'default';
@@ -36,6 +37,7 @@ async function loadConfig() {
shopName,
shopPrefix,
versionCode,
timeZone,
orderStatus,
lastOrderId,
psStates
@@ -45,6 +47,7 @@ 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),
loadPsStates()
@@ -59,6 +62,7 @@ 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),
psStates,
+55
View File
@@ -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 };
+17
View File
@@ -5,6 +5,7 @@ const { isLegacyApi } = require('./utils');
const { extractPsStateName, normalizeStatusId } = require('./status-mapper');
const { setPsStates, loadPsStates } = require('./module-config');
const { ensureShopIcon } = require('./shop-icon');
const { DEFAULT_SHOP_TIME_ZONE, validateTimeZone } = require('./prestashop-date');
const ORBITO_STATUS_OPTIONS = {
module: 'core/orders',
@@ -121,6 +122,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' },
@@ -148,6 +158,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);
+23
View File
@@ -115,10 +115,33 @@ 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: { 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 = [];
+61
View File
@@ -0,0 +1,61 @@
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: {
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);
}
});
+44
View File
@@ -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');
}
});
+37
View File
@@ -86,3 +86,40 @@ test('mapping validation prevents two PrestaShop states from sharing one Orbito
assert.deepEqual(errors.map(error => error.field), ['state_2', 'state_3']);
});
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: {
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');
});