-- schema version 39 to 40

PRAGMA writable_schema = ON;

ALTER TABLE member RENAME COLUMN business_shares TO shares;
ALTER TABLE member ADD COLUMN shares_red       INTEGER NOT NULL DEFAULT 0;
ALTER TABLE member ADD COLUMN shares_white     INTEGER NOT NULL DEFAULT 0;
ALTER TABLE member ADD COLUMN shares_dormant   INTEGER NOT NULL DEFAULT 0;

UPDATE client_parameter SET value = '0' WHERE param = 'ENABLE_TIME_TRIGGERS';
UPDATE member
SET shares_dormant = shares + shares_red + shares_white,
    shares = 0, shares_red = 0, shares_white = 0
WHERE NOT active;
UPDATE client_parameter SET value = '1' WHERE param = 'ENABLE_TIME_TRIGGERS';

CREATE TABLE member_history_new (
    histnr          INTEGER NOT NULL,
    from_mgnr       INTEGER,
    from_type       INTEGER,
    to_mgnr         INTEGER,
    to_type         INTEGER,
    date            TEXT    NOT NULL CHECK (date REGEXP '^[1-9][0-9]{3}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$') DEFAULT CURRENT_DATE,
    reason          TEXT    NOT NULL CHECK (reason REGEXP '^[a-z_]+$'),
    source          TEXT    NOT NULL CHECK (source REGEXP '^[a-z_]+$'),

    shares          INTEGER NOT NULL,
    value_per_share INTEGER DEFAULT NULL,
    currency        TEXT    DEFAULT NULL,
    deduct_year     INTEGER DEFAULT NULL,
    comment         TEXT    DEFAULT NULL,

    CONSTRAINT pk_member_history PRIMARY KEY (histnr),
    CONSTRAINT fk_member_history_member_from FOREIGN KEY (from_mgnr) REFERENCES member (mgnr)
        ON UPDATE CASCADE
        ON DELETE RESTRICT,
    CONSTRAINT fk_member_history_member_to FOREIGN KEY (to_mgnr) REFERENCES member (mgnr)
        ON UPDATE CASCADE
        ON DELETE RESTRICT,
    CONSTRAINT fk_member_history_currency FOREIGN KEY (currency) REFERENCES currency (code)
        ON UPDATE CASCADE
        ON DELETE RESTRICT,
    CONSTRAINT c_member_history CHECK ((from_mgnr IS NOT NULL OR to_mgnr IS NOT NULL) AND
                                       ((from_mgnr IS NULL AND from_type IS NULL) OR (from_mgnr IS NOT NULL AND from_type IS NOT NULL)) AND
                                       ((to_mgnr IS NULL AND to_type IS NULL) OR (to_mgnr IS NOT NULL AND to_type IS NOT NULL)))
) STRICT;

INSERT INTO member_history_new (histnr, from_mgnr, from_type, to_mgnr, to_type, date, reason, source, shares, value_per_share, currency, deduct_year, comment)
SELECT ROW_NUMBER() OVER(ORDER BY h.date, h.mgnr), NULL, NULL, h.mgnr, 1, h.date, h.type, 'elwig', h.business_shares, s.bs_value / POW(10, s.precision - 2), s.currency, IIF(h.type = 'auto', s.year, NULL), comment
FROM member_history h
JOIN season s ON s.year = SUBSTR(h.date, 1, 4);

PRAGMA foreign_keys = OFF;
DROP TABLE member_history;
ALTER TABLE member_history_new RENAME TO member_history;
PRAGMA foreign_keys = ON;

CREATE TRIGGER t_member_history_i_member
    AFTER INSERT ON member_history FOR EACH ROW
    WHEN (SELECT value FROM client_parameter WHERE param = 'ENABLE_MEMBER_HISTORY_TRIGGERS') = 1
BEGIN
    UPDATE member SET shares         = shares         - NEW.shares WHERE mgnr = NEW.from_mgnr AND NEW.from_type = 1;
    UPDATE member SET shares_red     = shares_red     - NEW.shares WHERE mgnr = NEW.from_mgnr AND NEW.from_type = 2;
    UPDATE member SET shares_white   = shares_white   - NEW.shares WHERE mgnr = NEW.from_mgnr AND NEW.from_type = 3;
    UPDATE member SET shares_dormant = shares_dormant - NEW.shares WHERE mgnr = NEW.from_mgnr AND NEW.from_type = 9;
    UPDATE member SET shares         = shares         + NEW.shares WHERE mgnr = NEW.to_mgnr   AND NEW.to_type   = 1;
    UPDATE member SET shares_red     = shares_red     + NEW.shares WHERE mgnr = NEW.to_mgnr   AND NEW.to_type   = 2;
    UPDATE member SET shares_white   = shares_white   + NEW.shares WHERE mgnr = NEW.to_mgnr   AND NEW.to_type   = 3;
    UPDATE member SET shares_dormant = shares_dormant + NEW.shares WHERE mgnr = NEW.to_mgnr   AND NEW.to_type   = 9;
END;

CREATE TRIGGER t_member_history_u_member
    AFTER UPDATE ON member_history FOR EACH ROW
    WHEN (SELECT value FROM client_parameter WHERE param = 'ENABLE_MEMBER_HISTORY_TRIGGERS') = 1
BEGIN
    UPDATE member SET shares         = shares         + OLD.shares WHERE mgnr = OLD.from_mgnr AND OLD.from_type = 1;
    UPDATE member SET shares_red     = shares_red     + OLD.shares WHERE mgnr = OLD.from_mgnr AND OLD.from_type = 2;
    UPDATE member SET shares_white   = shares_white   + OLD.shares WHERE mgnr = OLD.from_mgnr AND OLD.from_type = 3;
    UPDATE member SET shares_dormant = shares_dormant + OLD.shares WHERE mgnr = OLD.from_mgnr AND OLD.from_type = 9;
    UPDATE member SET shares         = shares         - OLD.shares WHERE mgnr = OLD.to_mgnr   AND OLD.to_type   = 1;
    UPDATE member SET shares_red     = shares_red     - OLD.shares WHERE mgnr = OLD.to_mgnr   AND OLD.to_type   = 2;
    UPDATE member SET shares_white   = shares_white   - OLD.shares WHERE mgnr = OLD.to_mgnr   AND OLD.to_type   = 3;
    UPDATE member SET shares_dormant = shares_dormant - OLD.shares WHERE mgnr = OLD.to_mgnr   AND OLD.to_type   = 9;
    UPDATE member SET shares         = shares         - NEW.shares WHERE mgnr = NEW.from_mgnr AND NEW.from_type = 1;
    UPDATE member SET shares_red     = shares_red     - NEW.shares WHERE mgnr = NEW.from_mgnr AND NEW.from_type = 2;
    UPDATE member SET shares_white   = shares_white   - NEW.shares WHERE mgnr = NEW.from_mgnr AND NEW.from_type = 3;
    UPDATE member SET shares_dormant = shares_dormant - NEW.shares WHERE mgnr = NEW.from_mgnr AND NEW.from_type = 9;
    UPDATE member SET shares         = shares         + NEW.shares WHERE mgnr = NEW.to_mgnr   AND NEW.to_type   = 1;
    UPDATE member SET shares_red     = shares_red     + NEW.shares WHERE mgnr = NEW.to_mgnr   AND NEW.to_type   = 2;
    UPDATE member SET shares_white   = shares_white   + NEW.shares WHERE mgnr = NEW.to_mgnr   AND NEW.to_type   = 3;
    UPDATE member SET shares_dormant = shares_dormant + NEW.shares WHERE mgnr = NEW.to_mgnr   AND NEW.to_type   = 9;
END;

CREATE TRIGGER t_member_history_d_member
    AFTER DELETE ON member_history FOR EACH ROW
    WHEN (SELECT value FROM client_parameter WHERE param = 'ENABLE_MEMBER_HISTORY_TRIGGERS') = 1
BEGIN
    UPDATE member SET shares         = shares         + OLD.shares WHERE mgnr = OLD.from_mgnr AND OLD.from_type = 1;
    UPDATE member SET shares_red     = shares_red     + OLD.shares WHERE mgnr = OLD.from_mgnr AND OLD.from_type = 2;
    UPDATE member SET shares_white   = shares_white   + OLD.shares WHERE mgnr = OLD.from_mgnr AND OLD.from_type = 3;
    UPDATE member SET shares_dormant = shares_dormant + OLD.shares WHERE mgnr = OLD.from_mgnr AND OLD.from_type = 9;
    UPDATE member SET shares         = shares         - OLD.shares WHERE mgnr = OLD.to_mgnr   AND OLD.to_type   = 1;
    UPDATE member SET shares_red     = shares_red     - OLD.shares WHERE mgnr = OLD.to_mgnr   AND OLD.to_type   = 2;
    UPDATE member SET shares_white   = shares_white   - OLD.shares WHERE mgnr = OLD.to_mgnr   AND OLD.to_type   = 3;
    UPDATE member SET shares_dormant = shares_dormant - OLD.shares WHERE mgnr = OLD.to_mgnr   AND OLD.to_type   = 9;
END;

INSERT INTO client_parameter (param, value) VALUES ('ENABLE_MEMBER_HISTORY_TRIGGERS', '1');

CREATE TABLE season_new (
    year           INTEGER NOT NULL CHECK (year >= 1000 AND year <= 9999),
    currency       TEXT    NOT NULL,
    precision      INTEGER NOT NULL DEFAULT 4,

    max_kg_per_ha  INTEGER NOT NULL DEFAULT 10000,
    vat_normal     REAL    NOT NULL DEFAULT 0.10,
    vat_flatrate   REAL    NOT NULL DEFAULT 0.13,

    min_kg_per_share          INTEGER  DEFAULT NULL,
    max_kg_per_share          INTEGER  DEFAULT NULL,
    min_kg_per_share_red      INTEGER  DEFAULT NULL,
    max_kg_per_share_red      INTEGER  DEFAULT NULL,
    min_kg_per_share_white    INTEGER  DEFAULT NULL,
    max_kg_per_share_white    INTEGER  DEFAULT NULL,
    penalty_per_kg            INTEGER  DEFAULT NULL,
    penalty_amount            INTEGER  DEFAULT NULL,
    penalty_none              INTEGER  DEFAULT NULL,
    penalty_per_share_amount  INTEGER  DEFAULT NULL,
    penalty_per_share_none    INTEGER  DEFAULT NULL,
    share_value               INTEGER,

    start_date     TEXT CHECK (start_date REGEXP '^[1-9][0-9]{3}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$'),
    end_date       TEXT CHECK (end_date   REGEXP '^[1-9][0-9]{3}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$'),
    calc_mode      INTEGER NOT NULL DEFAULT 0,

    CONSTRAINT pk_season PRIMARY KEY (year),
    CONSTRAINT fk_season_currency FOREIGN KEY (currency) REFERENCES currency (code)
        ON UPDATE CASCADE
        ON DELETE RESTRICT
) STRICT;

INSERT INTO season_new (year, currency, precision, max_kg_per_ha, vat_normal, vat_flatrate, min_kg_per_share, max_kg_per_share, penalty_per_kg, penalty_amount, penalty_none, penalty_per_share_amount, penalty_per_share_none, share_value, start_date, end_date, calc_mode)
SELECT year, currency, precision, max_kg_per_ha, vat_normal, vat_flatrate, min_kg_per_bs, max_kg_per_bs, penalty_per_kg, penalty_amount, penalty_none, penalty_per_bs_amount, penalty_per_bs_none, bs_value, start_date, end_date, calc_mode
FROM season;

PRAGMA foreign_keys = OFF;
DROP TABLE season;
ALTER TABLE season_new RENAME TO season;
PRAGMA foreign_keys = ON;

DROP VIEW v_delivery;
CREATE VIEW v_delivery AS
SELECT p.year, p.did, p.dpnr,
       d.date, d.time, d.zwstid, d.lnr, d.lsnr,
       m.mgnr, m.name, m.given_name,
       v.sortid, v.type, a.attrid, p.cultid,
       p.weight, p.kmw, ROUND(p.kmw * (4.54 + 0.022 * p.kmw), 0) AS oe, p.qualid,
       p.hkid, p.kgnr, p.rdnr,
       p.net_weight, p.gebunden,
       p.qualid IN (SELECT l.qualid FROM wine_quality_level l WHERE NOT l.predicate AND (p.kmw >= l.min_kmw OR l.min_kmw IS NULL) ORDER BY l.min_kmw DESC LIMIT 1,100) AS abgewertet,
       p.qualid NOT IN ('WEI', 'RSW', 'LDW') AS min_quw,
       IIF(a.strict, COALESCE(a.fill_lower, 0), 0) AS attribute_prio,
       GROUP_CONCAT(o.modid) AS modifiers,
       d.comment, p.comment AS part_comment
FROM delivery_part p
    JOIN delivery d ON (d.year, d.did) = (p.year, p.did)
    JOIN member m ON m.mgnr = d.mgnr
    LEFT JOIN wine_variety v ON v.sortid = p.sortid
    LEFT JOIN wine_attribute a ON a.attrid = p.attrid
    LEFT JOIN delivery_part_modifier o ON (o.year, o.did, o.dpnr) = (p.year, p.did, p.dpnr)
GROUP BY p.year, p.did, p.dpnr
ORDER BY p.year, p.did, p.dpnr, o.modid;

DROP VIEW v_stat_season;
CREATE VIEW v_stat_season AS
SELECT year,
       SUM(weight) AS weight_total,
       SUM(IIF(type = 'R', weight, 0)) AS weight_red,
       SUM(IIF(type = 'W', weight, 0)) AS weight_white,
       ROUND(SUM(kmw * weight) / SUM(weight), 2) AS kmw,
       ROUND(SUM(oe * weight) / SUM(weight), 1) AS oe,
       COUNT(DISTINCT did) AS lieferungen,
       COUNT(DISTINCT mgnr) AS mitglieder
FROM v_delivery
GROUP BY year
ORDER BY year;

DROP VIEW v_stat_sort;
CREATE VIEW v_stat_variety AS
SELECT year, sortid,
       SUM(weight) AS weight_total,
       SUM(IIF(type = 'R', weight, 0)) AS weight_red,
       SUM(IIF(type = 'W', weight, 0)) AS weight_white,
       ROUND(SUM(kmw * weight) / SUM(weight), 2) AS kmw,
       ROUND(SUM(oe * weight) / SUM(weight), 1) AS oe,
       COUNT(DISTINCT did) AS lieferungen,
       COUNT(DISTINCT mgnr) AS mitglieder
FROM v_delivery
GROUP BY year, sortid
ORDER BY year, sortid;

DROP VIEW v_stat_attr;
CREATE VIEW v_stat_attr AS
SELECT year, attrid,
       SUM(weight) AS weight_total,
       SUM(IIF(type = 'R', weight, 0)) AS weight_red,
       SUM(IIF(type = 'W', weight, 0)) AS weight_white,
       ROUND(SUM(kmw * weight) / SUM(weight), 2) AS kmw,
       ROUND(SUM(oe * weight) / SUM(weight), 1) AS oe,
       COUNT(DISTINCT did) AS lieferungen,
       COUNT(DISTINCT mgnr) AS mitglieder
FROM v_delivery
GROUP BY year, attrid
ORDER BY year, attrid;

DROP VIEW v_stat_sort_attr;
CREATE VIEW v_stat_variety_attr AS
SELECT year, sortid, attrid,
       SUM(weight) AS weight_total,
       SUM(IIF(type = 'R', weight, 0)) AS weight_red,
       SUM(IIF(type = 'W', weight, 0)) AS weight_white,
       ROUND(SUM(kmw * weight) / SUM(weight), 2) AS kmw,
       ROUND(SUM(oe * weight) / SUM(weight), 1) AS oe,
       COUNT(DISTINCT did) AS lieferungen,
       COUNT(DISTINCT mgnr) AS mitglieder
FROM v_delivery
GROUP BY year, sortid, attrid
ORDER BY year, sortid, attrid;

DROP VIEW v_stat_member;
CREATE VIEW v_stat_member AS
SELECT year, mgnr,
       SUM(weight) AS weight_total,
       SUM(IIF(type = 'R', weight, 0)) AS weight_red,
       SUM(IIF(type = 'W', weight, 0)) AS weight_white,
       ROUND(SUM(kmw * weight) / SUM(weight), 2) AS kmw,
       ROUND(SUM(oe * weight) / SUM(weight), 1) AS oe,
       COUNT(DISTINCT did) AS lieferungen
FROM v_delivery
GROUP BY year, mgnr
ORDER BY year, mgnr;

CREATE VIEW v_member_history AS
SELECT m.mgnr, s.year,
       m.shares + SUM(IIF(h1.from_type = 1, h1.shares, 0)) - SUM(IIF(h2.to_type = 1, h2.shares, 0)) AS shares,
       m.shares_red + SUM(IIF(h1.from_type = 2, h1.shares, 0)) - SUM(IIF(h2.to_type = 2, h2.shares, 0)) AS shares_red,
       m.shares_white + SUM(IIF(h1.from_type = 3, h1.shares, 0)) - SUM(IIF(h2.to_type = 3, h2.shares, 0)) AS shares_white,
       m.shares_dormant + SUM(IIF(h1.from_type = 9, h1.shares, 0)) - SUM(IIF(h2.to_type = 9, h2.shares, 0)) AS shares_dormant
FROM member m, v_virtual_season s
    LEFT JOIN member_history h1 ON (SUBSTR(h1.date, 1, 4) + 0) > s.year AND h1.from_mgnr = m.mgnr
    LEFT JOIN member_history h2 ON (SUBSTR(h2.date, 1, 4) + 0) > s.year AND h2.to_mgnr = m.mgnr
GROUP BY m.mgnr, s.year
ORDER BY m.mgnr, s.year;

DROP VIEW v_total_under_delivery;
CREATE VIEW v_total_under_delivery AS
SELECT s.year, m.mgnr,
       h.shares,
       h.shares * COALESCE(s.min_kg_per_share, 0) AS min_kg,
       h.shares * COALESCE(s.max_kg_per_share, 0) AS max_kg,
       COALESCE(d.weight_total, 0) AS weight_total,
       IIF(COALESCE(d.weight_total, 0) < h.shares * COALESCE(s.min_kg_per_share, 0),
           COALESCE(d.weight_total, 0) - h.shares * COALESCE(s.min_kg_per_share, 0),
           IIF(COALESCE(d.weight_total, 0) > h.shares * COALESCE(s.max_kg_per_share, 0),
               COALESCE(d.weight_total, 0) - h.shares * COALESCE(s.max_kg_per_share, 0),
               0)) AS diff,
       h.shares_red,
       h.shares_red * COALESCE(s.min_kg_per_share_red, s.min_kg_per_share, 0) AS min_kg_red,
       h.shares_red * COALESCE(s.max_kg_per_share_red, s.max_kg_per_share, 0) AS max_kg_red,
       COALESCE(d.weight_red, 0) AS weight_red,
       IIF(COALESCE(d.weight_red, 0) < h.shares_red * COALESCE(s.min_kg_per_share_red, s.min_kg_per_share, 0),
           COALESCE(d.weight_red, 0) - h.shares_red * COALESCE(s.min_kg_per_share_red, s.min_kg_per_share, 0),
           IIF(COALESCE(d.weight_red, 0) > h.shares_red * COALESCE(s.max_kg_per_share_red, s.max_kg_per_share, 0),
               COALESCE(d.weight_red, 0) - h.shares_red * COALESCE(s.max_kg_per_share_red, s.max_kg_per_share, 0),
               0)) AS diff_red,
       h.shares_white,
       h.shares_white * COALESCE(s.min_kg_per_share_white, s.min_kg_per_share, 0) AS min_kg_white,
       h.shares_white * COALESCE(s.max_kg_per_share_white, s.max_kg_per_share, 0) AS max_kg_white,
       COALESCE(d.weight_white, 0) AS weight_white,
       IIF(COALESCE(d.weight_white, 0) < h.shares_white * COALESCE(s.min_kg_per_share_white, s.min_kg_per_share, 0),
           COALESCE(d.weight_white, 0) - h.shares_white * COALESCE(s.min_kg_per_share_white, s.min_kg_per_share, 0),
           IIF(COALESCE(d.weight_white, 0) > h.shares_white * COALESCE(s.max_kg_per_share_white, s.max_kg_per_share, 0),
               COALESCE(d.weight_white, 0) - h.shares_white * COALESCE(s.max_kg_per_share_white, s.max_kg_per_share, 0),
               0)) AS diff_white
FROM member m, season s
    LEFT JOIN v_member_history h ON (h.year, h.mgnr) = (s.year, m.mgnr)
    LEFT JOIN v_stat_member d ON (d.year, d.mgnr) = (s.year, m.mgnr)
ORDER BY s.year, m.mgnr;

DROP VIEW v_penalty_business_shares;
CREATE VIEW v_penalty_business_shares AS
SELECT u.year, u.mgnr,
       SUM(IIF(u.weight_total = 0, COALESCE(-s.penalty_none, 0) + COALESCE(-(u.shares + u.shares_red + u.shares_white) * s.penalty_per_share_none, 0), 0) +
           IIF(u.diff < 0 OR u.diff_red < 0 OR u.diff_white < 0, COALESCE(-s.penalty_amount, 0), 0) +
           COALESCE((u.diff + u.diff_red + u.diff_white) * s.penalty_per_kg, 0) +
           COALESCE(CEIL(CAST(u.diff AS REAL) / s.min_kg_per_share) * s.penalty_per_share_amount, 0) +
           COALESCE(CEIL(CAST(u.diff_red AS REAL) / s.min_kg_per_share_red) * s.penalty_per_share_amount, 0) +
           COALESCE(CEIL(CAST(u.diff_white AS REAL) / s.min_kg_per_share_white) * s.penalty_per_share_amount, 0)
       ) AS total_penalty
FROM v_total_under_delivery u
    JOIN season s ON u.year = s.year
    JOIN member m ON m.mgnr = u.mgnr
WHERE m.active
GROUP BY u.year, u.mgnr
HAVING total_penalty < 0
ORDER BY u.year, u.mgnr;

DROP VIEW v_auto_business_shares;
CREATE VIEW v_auto_business_shares AS
SELECT (SUBSTR(h.date, 1, 4) + 0) AS year,
       h.to_mgnr AS mgnr,
       SUM(h.shares) AS shares,
       SUM(h.shares * COALESCE(h.value_per_share, 0)) AS total_amount
FROM member_history h
WHERE h.reason = 'auto' AND h.source = 'elwig'
GROUP BY year, h.to_mgnr
ORDER BY year, h.to_mgnr;

PRAGMA writable_schema = OFF;
