-- Persist PO header taxable amount and support GST-on-taxable calc
-- taxable_amount = sub_total + freight_charges + other_charges - discount_amount

ALTER TABLE purchase_orders
  ADD COLUMN IF NOT EXISTS taxable_amount NUMERIC(15, 4) NOT NULL DEFAULT 0;

UPDATE purchase_orders
SET taxable_amount = ROUND(
  COALESCE(sub_total, 0)
  + COALESCE(freight_charges, 0)
  + COALESCE(other_charges, 0)
  - COALESCE(discount_amount, 0),
  4
)
WHERE taxable_amount = 0
  AND (
    COALESCE(sub_total, 0) <> 0
    OR COALESCE(freight_charges, 0) <> 0
    OR COALESCE(other_charges, 0) <> 0
    OR COALESCE(discount_amount, 0) <> 0
  );
