diff --git a/README.md b/README.md index e7e6138..c4c866b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,18 @@ # Moduł do integracji Prestashop Moduł podłącza się do sklepu podanego w konfiguracji i dodaje zamówienia za pomocą -modułu `core/orders` \ No newline at end of file +modułu `core/orders` + +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ń. diff --git a/module.json b/module.json index 37df32f..8640e1a 100644 --- a/module.json +++ b/module.json @@ -1,6 +1,6 @@ { "name": "core/prestashop", - "version": "1.1.7", + "version": "1.1.8", "singleton": false, "dependsOn": [ "core/orders", diff --git a/package-lock.json b/package-lock.json index b892c1a..7e2b190 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "core.prestashop", - "version": "1.1.7", + "version": "1.1.8", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "core.prestashop", - "version": "1.1.7", + "version": "1.1.8", "license": "ISC", "dependencies": { "@orbito/api-lib": "^3.3.3", diff --git a/package.json b/package.json index 99df7ee..ac56aca 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "core.prestashop", - "version": "1.1.7", + "version": "1.1.8", "description": "Integracja zamówień i płatności PrestaShop", "main": "index.js", "scripts": { diff --git a/src/OrderImporter.js b/src/OrderImporter.js index 4352257..d686691 100644 --- a/src/OrderImporter.js +++ b/src/OrderImporter.js @@ -272,6 +272,8 @@ async function importFromPSOrder(orderId, api, config) { }); } + const customerNotes = await api.getCustomerNotes(order.id, order.id_cart, order.gift_message); + const coreOrder = await Core.callModule( 'core/orders', 'create', { statusId: statusId, customer: { @@ -320,6 +322,7 @@ async function importFromPSOrder(orderId, api, config) { payments, discounts, invoice: invoiceDataForOrder, + notes: customerNotes.map(text => ({ text, type: 'customer_message' })), createdAt: new Date(order.date_add), }); diff --git a/src/PrestaApi.js b/src/PrestaApi.js index a9cd0af..313c963 100644 --- a/src/PrestaApi.js +++ b/src/PrestaApi.js @@ -282,6 +282,113 @@ module.exports = class PrestashopApi { return res?.order_payments || []; } + 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: 'date_add_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: 'date_add_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 setOrderState(orderId, stateId) { if (this.legacy) { return await this.updateOrderLegacy(orderId, { diff --git a/test/order-importer-customer-message.test.js b/test/order-importer-customer-message.test.js new file mode 100644 index 0000000..892c305 --- /dev/null +++ b/test/order-importer-customer-message.test.js @@ -0,0 +1,74 @@ +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 = { + 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', statusMapping: [] }); + + assert.deepEqual(createPayload.notes, [ + { text: 'Proszę zadzwonić przed dostawą', type: 'customer_message' }, + { text: 'Tekst z checkoutu', type: 'customer_message' }, + ]); +}); diff --git a/test/order-importer-metadata.test.js b/test/order-importer-metadata.test.js index cd3bb1f..cd3c7c0 100644 --- a/test/order-importer-metadata.test.js +++ b/test/order-importer-metadata.test.js @@ -73,6 +73,7 @@ test('order import upserts verified metadata for the ordered product and pack it getProductCoverImageUrl: async () => null, getCurrency: async () => ({ iso_code: 'PLN' }), getCountry: async () => ({ iso_code: 'PL' }), + getCustomerNotes: async () => [], getStockAvailabilities: async () => [], getManufacturer: async () => null, }; diff --git a/test/presta-api.test.js b/test/presta-api.test.js index a260bdf..991dfe9 100644 --- a/test/presta-api.test.js +++ b/test/presta-api.test.js @@ -107,3 +107,89 @@ test('does not turn an unsafe reference filter into an empty combination match', assert.equal(await api.findProductCombinationsByReference('1', 'SKU[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); +}); + +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', + ]); +});