-- schema version 26 to 27

PRAGMA writable_schema = ON;

ALTER TABLE member RENAME COLUMN family_name TO name;
ALTER TABLE member ADD COLUMN attn TEXT DEFAULT NULL;
ALTER TABLE member ADD COLUMN juridical_pers INTEGER NOT NULL CHECK (juridical_pers IN (TRUE, FALSE)) DEFAULT FALSE;

UPDATE sqlite_schema SET sql = REPLACE(sql, 'given_name       TEXT    NOT NULL', 'given_name       TEXT DEFAULT NULL')
WHERE type = 'table' AND name = 'member';

DROP VIEW v_bki_member;
CREATE VIEW v_bki_member AS
SELECT s.year, m.mgnr, m.lfbis_nr, m.name,
       (COALESCE(m.prefix || ' ', '') || m.given_name || COALESCE(' ' || m.middle_names, '') || COALESCE(' ' || m.suffix, '')) AS other_names,
       a.name AS billing_name, COALESCE(a.address, m.address) AS address,
       COALESCE(a.country, m.country) AS country, COALESCE(a.postal_dest, m.postal_dest) AS postal_dest,
       SUM(IIF(c.year_from <= s.year AND (c.year_to IS NULL OR c.year_to >= s.year), c.area, 0)) AS area
FROM season s, member m
    LEFT JOIN member_billing_address a ON a.mgnr = m.mgnr
    LEFT JOIN area_commitment c ON c.mgnr = m.mgnr
GROUP BY s.year, m.mgnr;

DROP VIEW v_bki_delivery;
CREATE VIEW v_bki_delivery AS
SELECT m.lfbis_nr, m.name, m.other_names, m.billing_name,
       m.address, plz.plz, IIF(INSTR(o.name, ',') = 0, o.name, SUBSTR(o.name, 1, INSTR(o.name, ',') - 1)) AS ort,
       d.date, d.weight, v.type, v.sortid, d.qualid, d.year, d.hkid, d.kmw, d.oe,
       m.area
FROM v_delivery d
    JOIN v_bki_member m ON (m.year, m.mgnr) = (d.year, d.mgnr)
    JOIN postal_dest pd ON (pd.country, pd.id) = (m.country, m.postal_dest)
    LEFT JOIN AT_plz_dest ap ON (ap.country, ap.id) = (pd.country, pd.id)
    LEFT JOIN AT_plz plz ON plz.plz = ap.plz
    LEFT JOIN AT_ort o ON o.okz = ap.okz
    JOIN wine_variety v ON v.sortid = d.sortid
ORDER BY d.date, d.time;

PRAGMA schema_version = 2601;
PRAGMA writable_schema = OFF;

UPDATE member
SET name = a.name, juridical_pers = TRUE
FROM member_billing_address a
WHERE a.mgnr = member.mgnr AND member.name = '';

DELETE FROM member_billing_address
WHERE mgnr IN (SELECT mgnr FROM member WHERE name = member_billing_address.name)
