From f1e9058d4ceacec04b6ae29989d48bc0d7da4f62 Mon Sep 17 00:00:00 2001 From: Fredrik Ringqvist <35255659+fredrikphotowall@users.noreply.github.com> Date: Mon, 31 Jan 2022 09:18:55 +0100 Subject: [PATCH] fix commissions (#249) --- migrations/000.355.sql | 47 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 migrations/000.355.sql diff --git a/migrations/000.355.sql b/migrations/000.355.sql new file mode 100644 index 0000000..5086a09 --- /dev/null +++ b/migrations/000.355.sql @@ -0,0 +1,47 @@ +-- Fix incorrect order_rows.commission_amount +-- We can calculate correct value using data->>'discountValue' which is the discount sum incl vat for the row +-- The first select identifies the rows to udpate. +-- The second select extracts only the two fields of interest. +-- The third select cleans up the values slightly +with to_update as ( +select + -- order_rows.inserted, + order_rows.id rowid, + type, + -- sub_type, + orders.delivery_vat, + orders.order_sum, + order_id, + price, + -- designer_id, + data->>'commission' as commission, + -- data->>'commission_resale'as commission_resale, + data->>'discountType' discount_type, + round(price * orders.delivery_vat, 2) as price_incl_vat, + round((data->>'discountValue')::numeric, 2) as discount_value, + round(price * orders.delivery_vat, 2) - round((data->>'discountValue')::numeric, 2) as commissionable_w_vat, + (round(price * orders.delivery_vat, 2) - round((data->>'discountValue')::numeric, 2)) / delivery_vat as commissionable_amount_ex_vat, + ((round(price * orders.delivery_vat, 2) - round((data->>'discountValue')::numeric, 2)) / delivery_vat) * (( data->>'commission')::numeric / 100) as new_commission_amount, + commission_amount +from + order_rows + left join orders on order_id = orders.id +where + order_rows.id >= 2500000 + and data->>'discountType' != '%' + and ( (data->>'commission' is not null) and ((data->>'commission')::numeric > 0)) +), id_and_amount as (select rowid, new_commission_amount from to_update), +nicer_zeroes as ( + select rowid, + case new_commission_amount + -- 0.0000000000000000000000000000000000000000 to 0 + when 0.0000 then 0 + -- 0.0826446280991735537190000000000000000000 to 10 decimals + else round(new_commission_amount, 10) + end as new_value + from to_update) +update order_rows +set commission_amount = new_value +from nicer_zeroes +where order_rows.id = rowid +