-- 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
	
