diff --git a/README.md b/README.md index 47143c4..868b92e 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,19 @@ Moduł podłącza się do sklepu podanego w konfiguracji i dodaje zamówienia za pomocą modułu `core/orders` +## VAT rabatów + +Importer zachowuje kwotę brutto rabatu ze sklepu. Przy jednej stawce VAT +produktów (również składowych zestawów) stosuje tę stawkę i wylicza netto +z brutto. Niespójne sumy netto/brutto ze źródła nie tworzą nowej stawki VAT. +Przykład: 75,35 zł brutto przy VAT 23% daje 61,26 zł netto, nawet gdy sklep +przekazał 63,51 zł netto. Pozycje bezpłatne nie wyznaczają VAT rabatu. + +Przy kilku stawkach VAT albo brakujących danych importer zgłasza +`DISCOUNT_TAX_AMBIGUOUS` przed utworzeniem zamówienia. W takim przypadku +potrzebne jest potwierdzone rozbicie rabatu według stawek; importer nie +wybiera pierwszej stawki ani stawki uśrednionej. + ## Daty zamówień i płatności Daty PrestaShop bez oznaczenia strefy (`date_add`, `date_upd`) są odczytywane diff --git a/module.json b/module.json index c125658..a2d8b9d 100644 --- a/module.json +++ b/module.json @@ -1,9 +1,5 @@ { - "name": "core/prestashop", - "version": "1.2.3", - "singleton": false, - "dependsOn": [ - "core/orders", - "core/products" - ] + "name": "core/prestashop", + "version": "1.2.4", + "singleton": false } diff --git a/package-lock.json b/package-lock.json index 9b77112..395da9b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "core.prestashop", - "version": "1.2.3", + "version": "1.2.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "core.prestashop", - "version": "1.2.3", + "version": "1.2.4", "license": "ISC", "dependencies": { "@orbito/api-lib": "^3.10.0", diff --git a/package.json b/package.json index 404ec41..e665af2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "core.prestashop", - "version": "1.2.3", + "version": "1.2.4", "description": "Integracja zamówień i płatności PrestaShop", "main": "index.js", "scripts": { diff --git a/src/OrderImporter.js b/src/OrderImporter.js index 55e6366..af5ceee 100644 --- a/src/OrderImporter.js +++ b/src/OrderImporter.js @@ -3,6 +3,7 @@ const { Log, Core } = require("@orbito/api-lib"); const PsOrder = require('./models/PsOrder'); const { normalizeStatusId } = require('./status-mapper'); const { paymentTransactionId, parsePrestashopDate, upsertMapping } = require('./automation-jobs'); +const { mapOrderDiscounts } = require('./order-discounts'); const { buildProductSourceId, resolveProductMetadata, @@ -312,18 +313,7 @@ async function importFromPSOrder(orderId, api, config) { pickupPoint.address = { street, zipCode, city }; } - const discounts = []; - if (parseFloat(order.total_discounts)) { - let net = parseFloat(order.total_discounts_tax_excl); - let gross = parseFloat(order.total_discounts_tax_incl); - let tax = net ? (gross - net) / net : 0; - discounts.push({ - name: "Rabat", - amount: Math.round(net * 100) / 100, - gross: Math.round(gross * 100) / 100, - tax: Math.round(tax * 100) / 100 - }); - } + const discounts = mapOrderDiscounts(order, products); const totalPaidReal = parseFloat(order.total_paid_real) || 0; const createdAt = parsePrestashopDate(order.date_add, new Date(), config.timeZone); diff --git a/src/order-discounts.js b/src/order-discounts.js new file mode 100644 index 0000000..f85260a --- /dev/null +++ b/src/order-discounts.js @@ -0,0 +1,36 @@ +function discountTaxError(message) { + const error = new Error(message); + error.code = 'DISCOUNT_TAX_AMBIGUOUS'; + return error; +} + +// A total discount's net/gross ratio is not a VAT rate. In particular, source +// totals can be inconsistent or combine several rates. Use the taxed goods. +function mapOrderDiscounts(order, products) { + if (!(Number.parseFloat(order.total_discounts) > 0)) return []; + const gross = Number.parseFloat(order.total_discounts_tax_incl); + if (!Number.isFinite(gross) || gross < 0) { + throw discountTaxError('Nieprawidłowa kwota brutto rabatu PrestaShop.'); + } + if (gross === 0) return []; + const taxes = new Set(); + for (const product of products) { + if (!(product.qty > 0 && product.unitPrice > 0)) continue; + const lines = product.isPack && product.pack?.length ? product.pack : [product]; + for (const line of lines) { + if (!(line.qty > 0)) continue; + if (!Number.isFinite(line.tax) || line.tax < 0 || line.tax > 1) { + throw discountTaxError('Brak jednoznacznej stawki VAT produktów objętych rabatem.'); + } + taxes.add(line.tax); + } + } + if (taxes.size !== 1) { + throw discountTaxError('Rabat wymaga rozbicia według stawek VAT produktów; nie można utworzyć stawki z sum netto i brutto.'); + } + const [tax] = taxes; + return [{ name: 'Rabat', type: 'product', gross: Math.round(gross * 100) / 100, + amount: Math.round(gross / (1 + tax) * 100) / 100, tax }]; +} + +module.exports = { mapOrderDiscounts }; diff --git a/test/order-discounts.test.js b/test/order-discounts.test.js new file mode 100644 index 0000000..d8b5fc8 --- /dev/null +++ b/test/order-discounts.test.js @@ -0,0 +1,94 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { mapOrderDiscounts } = require('../src/order-discounts'); +const Module = require('node:module'); +const path = require('node:path'); + +const source = { total_discounts: '75.35', total_discounts_tax_excl: '63.51', total_discounts_tax_incl: '75.35' }; +const product = { qty: 3, unitPrice: 62.03, tax: 0.23 }; + +test('6Q3-M9R: inconsistent source totals cannot manufacture 19% VAT', () => { + assert.deepEqual(mapOrderDiscounts(source, [product]), [ + { name: 'Rabat', type: 'product', amount: 61.26, gross: 75.35, tax: 0.23 }, + ]); +}); + +test('discounts follow actual VAT, including exempt and fractional rates', () => { + for (const tax of [0, 0.08, 0.19, 0.077]) { + const [discount] = mapOrderDiscounts(source, [{ ...product, tax }]); + assert.equal(discount.tax, tax); + assert.equal(discount.amount, Math.round(75.35 / (1 + tax) * 100) / 100); + assert.equal(discount.gross, 75.35); + } + assert.equal(mapOrderDiscounts(source, [product, { ...product, unitPrice: 0, tax: 0.08 }])[0].tax, 0.23); + assert.deepEqual(mapOrderDiscounts({ total_discounts: '0' }, []), []); +}); + +test('mixed or missing VAT requires a verified breakdown instead of a synthetic rate', () => { + for (const products of [[], [{ ...product, tax: undefined }], [product, { ...product, tax: 0.08 }], + [{ ...product, isPack: true, pack: [{ qty: 1, tax: 0.23 }, { qty: 1, tax: 0.08 }] }]]) { + assert.throws(() => mapOrderDiscounts(source, products), { code: 'DISCOUNT_TAX_AMBIGUOUS' }); + } + assert.throws(() => mapOrderDiscounts({ ...source, total_discounts_tax_incl: 'invalid' }, [product]), /brutto/); +}); + +async function importThroughHooks(providers) { + const created = []; + const original = Module._load; + const Core = { + getModuleInfo: () => ({ code: 'core/prestashop' }), + async execHook(name, envelope) { + if (name.endsWith('.providers')) return providers.map(instanceId => ({ protocol: 'orbito.contract/1', moduleCode: 'alternative/orders', instanceId })); + let data; + if (name === 'orders.status.search') data = { results: [{ _id: '000000000000000000000001' }] }; + else if (name === 'orders.create') { created.push(envelope.params); data = { _id: 'created-1' }; } + else throw new Error(name); + return [{ protocol: 'orbito.contract/1', instanceId: envelope.targetInstanceId, ok: true, data }]; + }, + }; + Module._load = function(request, ...args) { + if (request === '@orbito/api-lib') return { Core, Log: { debug() {}, info() {}, warn() {}, error() {} } }; + if (request === './models/PsOrder') return { update: async () => {}, findOne: async () => null }; + return original.call(this, request, ...args); + }; + const filename = path.resolve(__dirname, '../src/OrderImporter'); + delete require.cache[require.resolve(filename)]; + let importer; + try { importer = require(filename); } finally { Module._load = original; } + const order = { ...source, id: '4858', reference: 'MWSKTWLNP', id_address_delivery: '1', id_customer: '1', + id_currency: '1', total_shipping_tax_excl: '12', payment: 'B2B', date_add: '2026-10-08 11:40:00', + associations: { order_rows: [{ product_id: '1', product_name: 'PAVING', product_reference: 'NS.02.J', + product_attribute_id: '0', product_quantity: '3', unit_price_tax_excl: '62.03', unit_price_tax_incl: '76.30' }] }, + }; + const api = { isBLSupported: async () => false, + makeRequest: async endpoint => { + if (endpoint === 'orders/4858') return { order }; + if (endpoint === 'addresses/1') return { address: { id_country: '1', address1: 'Street', postcode: '00-001' } }; + if (endpoint === 'customers/1') return { customer: { firstname: 'Test', lastname: 'Test', email: 'test@example.com' } }; + throw new Error(endpoint); + }, + getProduct: async () => ({ name: 'PAVING', type: 'standard' }), + getProductCoverImageUrl: async () => null, + getCurrency: async () => ({ iso_code: 'PLN' }), getCountry: async () => ({ iso_code: 'PL' }), + getCustomerNotes: async () => [], + }; + try { + await importer.importFromPSOrder('4858', api, { _id: 'shop-1', orderStatus: '000000000000000000000001' }); + return { created }; + } catch (error) { return { created, error }; } +} + +test('real hook import delivers corrected discount to an alternative orders provider once', async () => { + const { created, error } = await importThroughHooks(['orders-account-1']); + assert.equal(error, undefined); + assert.equal(created.length, 1); + assert.deepEqual(created[0].discounts, [{ name: 'Rabat', type: 'product', amount: 61.26, gross: 75.35, tax: 0.23 }]); +}); + +test('absent or multiple orders accounts do not create an order', async () => { + for (const providers of [[], ['orders-account-1', 'orders-account-2']]) { + const result = await importThroughHooks(providers); + assert.equal(result.created.length, 0); + assert.match(result.error.code, /^HOOK_PROVIDER_(UNAVAILABLE|AMBIGUOUS)$/); + } +});