-- schema version 10 to 11

-- Drop columns, if they exist...
ALTER TABLE payment_delivery_part DROP COLUMN price_1;
ALTER TABLE payment_delivery_part DROP COLUMN price_2;
ALTER TABLE payment_delivery_part DROP COLUMN price_3;
ALTER TABLE payment_delivery_part DROP COLUMN price_4;
ALTER TABLE payment_delivery_part DROP COLUMN price_5;
ALTER TABLE payment_delivery_part DROP COLUMN price_6;
ALTER TABLE payment_delivery_part DROP COLUMN price_7;
ALTER TABLE payment_delivery_part DROP COLUMN price_8;
ALTER TABLE payment_delivery_part DROP COLUMN price_9;

DROP TRIGGER t_payment_delivery_part_i;
CREATE TRIGGER t_payment_delivery_part_i
    AFTER INSERT ON payment_delivery_part FOR EACH ROW
BEGIN
    INSERT INTO payment_member (year, avnr, mgnr, net_amount)
    SELECT year, NEW.avnr, mgnr, NEW.amount FROM delivery WHERE (year, did) = (NEW.year, NEW.did)
    ON CONFLICT DO UPDATE SET net_amount = net_amount + excluded.net_amount;
END;

DROP TRIGGER t_payment_delivery_part_u;
CREATE TRIGGER t_payment_delivery_part_u
    AFTER UPDATE ON payment_delivery_part FOR EACH ROW
BEGIN
    UPDATE payment_member
    SET net_amount = net_amount - OLD.amount
    WHERE (year, avnr, mgnr) IN (SELECT year, OLD.avnr, mgnr FROM delivery WHERE (year, did) = (OLD.year, OLD.did));
    INSERT INTO payment_member (year, avnr, mgnr, net_amount)
    SELECT year, NEW.avnr, mgnr, NEW.amount FROM delivery WHERE (year, did) = (NEW.year, NEW.did)
    ON CONFLICT DO UPDATE SET net_amount = net_amount + excluded.net_amount;
END;

DROP TRIGGER t_payment_delivery_part_d;
CREATE TRIGGER t_payment_delivery_part_d
    AFTER DELETE ON payment_delivery_part FOR EACH ROW
BEGIN
    UPDATE payment_member
    SET net_amount = net_amount - OLD.amount
    WHERE (year, avnr, mgnr) IN (SELECT year, OLD.avnr, mgnr FROM delivery WHERE (year, did) = (OLD.year, OLD.did));
END;

DROP TRIGGER t_payment_delivery_part_bucket_u;
CREATE TRIGGER t_payment_delivery_part_bucket_u
    AFTER UPDATE ON payment_delivery_part_bucket FOR EACH ROW
BEGIN
    UPDATE payment_delivery_part
    SET net_amount = net_amount - OLD.amount
    WHERE (year, did, dpnr, avnr) = (OLD.year, OLD.did, OLD.dpnr, OLD.avnr);
    UPDATE payment_delivery_part
    SET net_amount = net_amount + NEW.amount
    WHERE (year, did, dpnr, avnr) = (NEW.year, NEW.did, NEW.dpnr, NEW.avnr);
END;

ALTER TABLE payment_member DROP COLUMN amount;
ALTER TABLE payment_member ADD COLUMN amount INTEGER NOT NULL GENERATED ALWAYS AS (ROUND(net_amount * (1 + mod_rel) + mod_abs)) VIRTUAL;
