const { Core } = require('@orbito/api-lib'); const ShopConfig = require('../src/models/ShopConfig'); const PrestashopApi = require('../src/PrestaApi'); const { importFromPSOrder } = require('../src/OrderImporter'); const { isLegacyApi } = require('../src/utils'); module.exports = async function(params, ctx) { const configs = await ShopConfig.find({ isRemoved: { $ne: true } }); const active = configs.filter(c => c.apiUrl && c.apiKey); if (active.length === 0) return { error: 'No active shop configs found' }; const config = params.configId ? active.find(c => String(c._id) === String(params.configId)) : active[0]; if (!config) return { error: 'Config not found' }; const api = new PrestashopApi(config.apiUrl, config.apiKey, isLegacyApi(config.versionCode)); const queryParams = { display: '[id, reference, date_add]', sort: 'id_ASC', limit: 50, output_format: 'JSON', 'filter[id]': `[${(config.lastOrderId || 0) + 1},999999999]`, }; const raw = await api.makeRequest('orders', 'GET', queryParams); const orders = raw?.orders || []; if (params.import && orders.length > 0) { const imported = []; const errors = []; for (const order of orders) { const uniqueId = order.reference + ':' + order.id; const searchResult = await Core.callModule( 'core/orders', 'search', { source: { moduleCode: 'core/prestashop', uniqueId } }); if (searchResult?.data?.length > 0) { imported.push({ id: order.id, status: 'already_exists' }); continue; } try { await importFromPSOrder(order.id, api, config); imported.push({ id: order.id, status: 'imported' }); } catch (e) { errors.push({ id: order.id, error: e.message }); } } const maxId = Math.max(...orders.map(o => parseInt(o.id))); await ShopConfig.update({ _id: config._id }, { lastOrderId: maxId }); return { shopName: config.shopName, imported, errors, newLastOrderId: maxId }; } return { shopName: config.shopName, lastOrderId: config.lastOrderId, filterFrom: (config.lastOrderId || 0) + 1, apiResponse: raw, ordersCount: orders.length, hint: 'Add "import": true to params to import these orders', }; };