feat: sync shop icons and continue imports in v1.1.4

This commit is contained in:
fatequod
2026-09-10 11:40:15 +02:00
parent b232d3f18f
commit e5b2a90fc3
10 changed files with 490 additions and 14 deletions
+16 -6
View File
@@ -29,9 +29,10 @@ test('first run safely starts at the newest order without backfilling history',
assert.deepEqual(result, { status: 'initialized', cursor: 812, processed: 0 });
});
test('cursor advances only through confirmed successes and stops before failed order', async () => {
test('a failed order is skipped so later orders can still be imported', 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, {
@@ -43,14 +44,23 @@ test('cursor advances only through confirmed successes and stops before failed o
return { status: 'imported', psOrderId: id, orbitoOrderId: `orbito-${id}` };
},
setLastOrderId: async id => writes.push(id),
Log: silentLog,
Log: { ...silentLog, error: (message, details) => errors.push({ message, details }) },
now: () => new Date('2026-01-02T00:00:00Z').getTime(),
});
assert.deepEqual(imported, [11, 12]);
assert.deepEqual(writes, [11]);
assert.equal(config.lastOrderId, 11);
assert.deepEqual(result, { status: 'processed', cursor: 11, processed: 1 });
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(errors, [{
message: 'Failed to import PS order; skipping order and continuing',
details: {
orderId: 12,
previousCursor: 11,
cursor: 12,
error: 'invalid order',
},
}]);
});
test('existing Orbito order repairs a missing mapping before advancing the cursor', async () => {
+70
View File
@@ -0,0 +1,70 @@
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');
test('saving a valid shop connection refreshes the persisted source icon', async () => {
let blocks;
let iconOptions;
let savedStates;
const originalLoad = Module._load;
Module._load = function(request, parent, isMain) {
if (request === '@orbito/api-lib') {
return {
Config: {
PropertyType: { INFO: 'info', STRING: 'string' },
DisplayFormat: { URL: 'url', SECRET: 'secret' },
registerConfigBlocks: async value => { blocks = value; },
},
Log: { info() {}, warn() {} },
};
}
if (request === './PrestaApi') {
return class PrestashopApi {
async getStatuses() {
return [{ id: '2', name: 'Payment accepted', color: '#00ff00' }];
}
};
}
if (request === './utils') return { isLegacyApi: () => false };
if (request === './status-mapper') return { extractPsStateName: value => value };
if (request === './module-config') {
return {
setPsStates: async value => { savedStates = value; },
loadPsStates: async () => [],
};
}
if (request === './shop-icon') {
return { ensureShopIcon: async options => { iconOptions = options; } };
}
return originalLoad.call(this, request, parent, isMain);
};
delete require.cache[registerConfigPath];
try {
const { registerPrestashopConfigBlocks } = require(registerConfigPath);
await registerPrestashopConfigBlocks();
} finally {
Module._load = originalLoad;
}
const errors = [];
await blocks.connection.validate({
apiUrl: 'https://shop.test',
apiKey: 'secret',
versionCode: '8',
shopName: 'Sklep główny',
}, {
addError: (field, message) => errors.push({ field, message }),
});
assert.deepEqual(errors, []);
assert.deepEqual(savedStates, [{ id: 2, name: 'Payment accepted', color: '#00ff00' }]);
assert.deepEqual(iconOptions, {
apiUrl: 'https://shop.test',
shopName: 'Sklep główny',
force: true,
});
});
+125
View File
@@ -0,0 +1,125 @@
const assert = require('node:assert/strict');
const Module = require('node:module');
const path = require('node:path');
const test = require('node:test');
const shopIconPath = path.resolve(__dirname, '../src/shop-icon.js');
function pngBuffer() {
return Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 0]);
}
function loadShopIcon(api) {
const originalLoad = Module._load;
Module._load = function(request, parent, isMain) {
if (request === '@orbito/api-lib') return api;
return originalLoad.call(this, request, parent, isMain);
};
delete require.cache[shopIconPath];
try {
return require(shopIconPath);
} finally {
Module._load = originalLoad;
}
}
test('discovers, downloads and persists a favicon once before registering the source', async () => {
const calls = [];
const config = new Map();
const registered = [];
const page = Buffer.from('<html><head><link rel="shortcut icon" href="img/store-icon.png"></head></html>');
const shopIcon = loadShopIcon({
Config: {
get: async (key, fallback) => config.has(key) ? config.get(key) : fallback,
set: async (key, value) => config.set(key, value),
},
Core: {
fetch: async url => {
calls.push(url);
if (url === 'https://shop.test/b2b/') {
return { status: 200, data: page, headers: { 'content-type': 'text/html' } };
}
if (url === 'https://shop.test/b2b/img/store-icon.png') {
return { status: 200, data: pngBuffer(), headers: { 'content-type': 'image/png' } };
}
throw new Error(`Unexpected URL: ${url}`);
},
callModule: async (...args) => registered.push(args),
},
Log: { warn() {} },
});
const first = await shopIcon.ensureShopIcon({
apiUrl: 'https://shop.test/b2b/api/',
shopName: 'Sklep B2B',
force: true,
});
const second = await shopIcon.ensureShopIcon({
apiUrl: 'https://shop.test/b2b/api/',
shopName: 'Sklep B2B',
force: false,
});
assert.deepEqual(calls, [
'https://shop.test/b2b/',
'https://shop.test/b2b/img/store-icon.png',
]);
assert.equal(first.cacheHit, false);
assert.equal(second.cacheHit, true);
assert.equal(first.mime, 'image/png');
assert.match(first.dataUrl, /^data:image\/png;base64,/);
assert.equal(config.get('runtime.shopIcon').sourceUrl, 'https://shop.test/b2b/img/store-icon.png');
assert.deepEqual(registered[0].slice(0, 2), ['core/orders', 'source.register']);
assert.equal(registered[0][2].name, 'Sklep B2B');
assert.equal(registered[0][2].iconDataUrl, first.dataUrl);
assert.equal(registered.length, 2, 'cache hits still re-register metadata after a module restart');
});
test('a failed refresh retains the last icon for the same shop', async () => {
const oldIcon = `data:image/png;base64,${pngBuffer().toString('base64')}`;
let stored = {
shopUrl: 'https://shop.test/',
dataUrl: oldIcon,
mime: 'image/png',
sourceUrl: 'https://shop.test/old.png',
fetchedAt: '2026-01-01T00:00:00.000Z',
};
const shopIcon = loadShopIcon({
Config: {
get: async () => stored,
set: async (key, value) => { stored = value; },
},
Core: {
fetch: async () => ({ status: 503, data: Buffer.alloc(0), headers: {} }),
callModule: async () => ({}),
},
Log: { warn() {} },
});
const result = await shopIcon.ensureShopIcon({
apiUrl: 'https://shop.test/api',
shopName: 'Sklep',
force: true,
});
assert.equal(result.dataUrl, oldIcon);
assert.equal(result.sourceUrl, 'https://shop.test/old.png');
assert.equal(stored.dataUrl, oldIcon);
});
test('favicon discovery rejects cross-host candidates and recognizes common binary formats', () => {
const shopIcon = loadShopIcon({ Config: {}, Core: {}, 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/'
);
assert.deepEqual(candidates, [
'https://cdn.test/icon.png',
'https://shop.test/touch.png',
'https://shop.test/catalog/favicon.ico',
]);
assert.equal(shopIcon.detectIconMime(pngBuffer()), 'image/png');
assert.equal(shopIcon.detectIconMime(Buffer.from([0, 0, 1, 0])), 'image/vnd.microsoft.icon');
assert.equal(shopIcon.storefrontUrl('https://shop.test/catalog/api?key=secret'), 'https://shop.test/catalog/');
});