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
+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');
});