From ff011e7e28a55ae58f318669b1d6610d748297ab Mon Sep 17 00:00:00 2001 From: fatequod Date: Tue, 20 Oct 2026 10:34:31 +0200 Subject: [PATCH] Fix free sample orders with delivery discounts --- README.md | 6 ++++ module.json | 12 ++++--- package-lock.json | 4 +-- package.json | 2 +- src/OrderImporter.js | 2 ++ src/order-discounts.js | 34 ++++++++++++++++++ test/order-discounts.test.js | 69 ++++++++++++++++++++++++++++++++---- 7 files changed, 116 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index fc58655..cd445a3 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,12 @@ 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. +Zamówienia z bezpłatnymi produktami i darmową dostawą są importowane z cenami +0 zł. Gdy zerowe sumy zamówienia i produktów oraz rabat netto/brutto równy +kosztowi dostawy potwierdzają ten przypadek, rabat ma typ `delivery` i VAT +z `carrier_tax_rate`. Koszt dostawy otrzymuje tę samą stawkę. Późniejsza +edycja ceny produktu, np. na 0,01 zł, nie jest pomniejszana rabatem dostawy. + 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 diff --git a/module.json b/module.json index b3fb685..7215aa0 100644 --- a/module.json +++ b/module.json @@ -1,9 +1,13 @@ { "name": "core/prestashop", - "version": "1.3.1", + "version": "1.3.2", "singleton": false, - "dependsOn": [ - "core/orders", - "core/products" + "files": [ + "index.js", + "package.json", + "package-lock.json", + "src/", + "methods/", + "README.md" ] } diff --git a/package-lock.json b/package-lock.json index 659d0be..1a2fda7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "core.prestashop", - "version": "1.3.1", + "version": "1.3.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "core.prestashop", - "version": "1.3.1", + "version": "1.3.2", "license": "ISC", "dependencies": { "@orbito/api-lib": "^4.4.3", diff --git a/package.json b/package.json index b78e8a2..8ca53d8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "core.prestashop", - "version": "1.3.1", + "version": "1.3.2", "description": "Integracja zamówień i płatności PrestaShop", "main": "index.js", "scripts": { diff --git a/src/OrderImporter.js b/src/OrderImporter.js index af5ceee..742c8a4 100644 --- a/src/OrderImporter.js +++ b/src/OrderImporter.js @@ -314,6 +314,7 @@ async function importFromPSOrder(orderId, api, config) { } const discounts = mapOrderDiscounts(order, products); + const deliveryDiscount = discounts.find(discount => discount.type === 'delivery'); const totalPaidReal = parseFloat(order.total_paid_real) || 0; const createdAt = parsePrestashopDate(order.date_add, new Date(), config.timeZone); @@ -368,6 +369,7 @@ async function importFromPSOrder(orderId, api, config) { cost: { amount: parseFloat(order.total_shipping_tax_excl), + ...(deliveryDiscount ? { tax: deliveryDiscount.tax } : {}), }, isCod: (order.payment + "").toLowerCase().includes("pobranie") diff --git a/src/order-discounts.js b/src/order-discounts.js index f85260a..a50a864 100644 --- a/src/order-discounts.js +++ b/src/order-discounts.js @@ -4,6 +4,38 @@ function discountTaxError(message) { return error; } +function sourceNumber(value) { + if (value === undefined || value === null || String(value).trim() === '') return NaN; + return Number(value); +} + +function cents(value) { + return Math.round(value * 100); +} + +function freeSampleDeliveryDiscount(order, products, gross) { + // With free goods and a zero order total, a discount equal to shipping + // cancels delivery only. Keep that benefit separate from editable goods. + if (!products.length || !products.every(product => + Number.isFinite(product.qty) && product.qty > 0 && product.unitPrice === 0)) return null; + if (!['total_products', 'total_products_wt', 'total_paid_tax_excl', 'total_paid_tax_incl'] + .every(field => sourceNumber(order[field]) === 0)) return null; + if (!['total_wrapping_tax_excl', 'total_wrapping_tax_incl'] + .every(field => order[field] === undefined || sourceNumber(order[field]) === 0)) return null; + + const amount = sourceNumber(order.total_shipping_tax_excl); + const shippingGross = sourceNumber(order.total_shipping_tax_incl); + const discountNet = sourceNumber(order.total_discounts_tax_excl); + const tax = sourceNumber(order.carrier_tax_rate) / 100; + if (!(Number.isFinite(amount) && amount > 0 && Number.isFinite(shippingGross) && shippingGross > 0 + && Number.isFinite(discountNet) && discountNet >= 0 + && Number.isFinite(tax) && tax >= 0 && tax <= 1)) return null; + if (cents(amount) !== cents(discountNet) || cents(shippingGross) !== cents(gross) + || cents(amount * (1 + tax)) !== cents(shippingGross)) return null; + + return { name: 'Darmowa dostawa', type: 'delivery', amount, gross: cents(gross) / 100, tax }; +} + // 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) { @@ -13,6 +45,8 @@ function mapOrderDiscounts(order, products) { throw discountTaxError('Nieprawidłowa kwota brutto rabatu PrestaShop.'); } if (gross === 0) return []; + const deliveryDiscount = freeSampleDeliveryDiscount(order, products, gross); + if (deliveryDiscount) return [deliveryDiscount]; const taxes = new Set(); for (const product of products) { if (!(product.qty > 0 && product.unitPrice > 0)) continue; diff --git a/test/order-discounts.test.js b/test/order-discounts.test.js index d8b5fc8..7d8ce73 100644 --- a/test/order-discounts.test.js +++ b/test/order-discounts.test.js @@ -6,6 +6,17 @@ 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 }; +const sampleOrder = { + id: '4888', reference: 'MCBPBQOGI', payment: 'Próbki', + total_products: '0.000000', total_products_wt: '0.000000', + total_paid_tax_excl: '0.000000', total_paid_tax_incl: '0.000000', total_paid_real: '0.000000', + total_wrapping_tax_excl: '0.000000', total_wrapping_tax_incl: '0.000000', + total_discounts: '14.760000', total_discounts_tax_excl: '12.000000', total_discounts_tax_incl: '14.760000', + total_shipping_tax_excl: '12.000000', total_shipping_tax_incl: '14.760000', carrier_tax_rate: '23.000', + associations: { order_rows: [{ product_id: '784', product_attribute_id: '0', + product_name: 'MULTICOLOR', product_reference: 'NS.40.H.7016', + product_quantity: '2', unit_price_tax_excl: '0.000000', unit_price_tax_incl: '0.000000' }] }, +}; test('6Q3-M9R: inconsistent source totals cannot manufacture 19% VAT', () => { assert.deepEqual(mapOrderDiscounts(source, [product]), [ @@ -32,7 +43,36 @@ test('mixed or missing VAT requires a verified breakdown instead of a synthetic assert.throws(() => mapOrderDiscounts({ ...source, total_discounts_tax_incl: 'invalid' }, [product]), /brutto/); }); -async function importThroughHooks(providers) { +test('4888: zero-price samples retain a delivery discount using the source carrier VAT', () => { + for (const tax of [0, 0.08, 0.23, 0.077]) { + const gross = Math.round(12 * (1 + tax) * 100) / 100; + const order = { ...sampleOrder, carrier_tax_rate: String(tax * 100), + total_shipping_tax_incl: String(gross), total_discounts_tax_incl: String(gross), total_discounts: String(gross) }; + assert.deepEqual(mapOrderDiscounts(order, [{ ...product, unitPrice: 0, qty: 2 }]), [ + { name: 'Darmowa dostawa', type: 'delivery', amount: 12, gross, tax }, + ]); + } +}); + +test('zero-price orders require matching source totals and an explicit delivery VAT', () => { + for (const overrides of [ + { total_products: '1' }, { total_products_wt: '1' }, + { total_paid_tax_excl: '1' }, { total_paid_tax_incl: '1' }, + { total_wrapping_tax_excl: '1' }, { total_wrapping_tax_incl: '1' }, + { total_products: undefined }, { total_paid_tax_incl: undefined }, + { total_discounts_tax_excl: '11' }, { total_shipping_tax_incl: '15' }, + { carrier_tax_rate: undefined }, { carrier_tax_rate: '' }, { carrier_tax_rate: '19' }, + { carrier_tax_rate: '-1' }, { carrier_tax_rate: 'invalid' }, { carrier_tax_rate: '101' }, + ]) { + assert.throws(() => mapOrderDiscounts({ ...sampleOrder, ...overrides }, [{ ...product, unitPrice: 0 }]), + { code: 'DISCOUNT_TAX_AMBIGUOUS' }, JSON.stringify(overrides)); + } + assert.throws(() => mapOrderDiscounts(sampleOrder, []), { code: 'DISCOUNT_TAX_AMBIGUOUS' }); + assert.throws(() => mapOrderDiscounts(sampleOrder, [{ ...product, unitPrice: 0, qty: NaN }]), + { code: 'DISCOUNT_TAX_AMBIGUOUS' }); +}); + +async function importThroughHooks(providers, overrides = {}) { const created = []; const original = Module._load; const Core = { @@ -59,10 +99,11 @@ async function importThroughHooks(providers) { 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' }] }, + ...overrides, }; const api = { isBLSupported: async () => false, makeRequest: async endpoint => { - if (endpoint === 'orders/4858') return { order }; + if (endpoint === `orders/${order.id}`) 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); @@ -73,7 +114,7 @@ async function importThroughHooks(providers) { getCustomerNotes: async () => [], }; try { - await importer.importFromPSOrder('4858', api, { _id: 'shop-1', orderStatus: '000000000000000000000001' }); + await importer.importFromPSOrder(order.id, api, { _id: 'shop-1', orderStatus: '000000000000000000000001' }); return { created }; } catch (error) { return { created, error }; } } @@ -85,10 +126,26 @@ test('real hook import delivers corrected discount to an alternative orders prov assert.deepEqual(created[0].discounts, [{ name: 'Rabat', type: 'product', amount: 61.26, gross: 75.35, tax: 0.23 }]); }); +test('4888 imports once through hooks with unchanged zero prices and matching delivery VAT', async () => { + const { created, error } = await importThroughHooks(['orders-account-1'], sampleOrder); + assert.equal(error, undefined); + assert.equal(created.length, 1); + assert.equal(created[0].source.uniqueId, 'MCBPBQOGI:4888'); + assert.equal(created[0].products[0].unitPrice, 0); + assert.equal(created[0].products[0].qty, 2); + assert.deepEqual(created[0].delivery.cost, { amount: 12, tax: 0.23 }); + assert.deepEqual(created[0].discounts, [ + { name: 'Darmowa dostawa', type: 'delivery', amount: 12, gross: 14.76, tax: 0.23 }, + ]); + assert.deepEqual(created[0].payments, []); +}); + 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)$/); + for (const order of [{}, sampleOrder]) { + const result = await importThroughHooks(providers, order); + assert.equal(result.created.length, 0); + assert.match(result.error.code, /^HOOK_PROVIDER_(UNAVAILABLE|AMBIGUOUS)$/); + } } });