-- schema version 14 to 15

ALTER TABLE season ADD COLUMN calc_mode INTEGER NOT NULL DEFAULT 0;

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 d.year, v.avnr, d.mgnr, NEW.amount
    FROM delivery d, payment_variant v
    WHERE (d.year, d.did) = (NEW.year, NEW.did) AND (v.year, v.avnr) = (NEW.year, NEW.avnr)
    ON CONFLICT DO UPDATE SET net_amount = net_amount + excluded.net_amount;
END;
