-- schema version 13 to 14

CREATE VIEW v_penalty_area_commitments AS
SELECT year, mgnr,
      SUM(COALESCE(IIF(u.weight = 0, -t.penalty_none, 0), 0) +
          COALESCE(IIF(u.diff < 0, -t.penalty_amount, 0), 0) +
          COALESCE(u.diff * t.penalty_per_kg, 0)
      ) AS total_penalty
FROM v_under_delivery u
   JOIN area_commitment_type t ON t.vtrgid = u.bucket
GROUP BY year, mgnr
HAVING total_penalty < 0
ORDER BY year, mgnr;

CREATE VIEW v_penalty_business_shares AS
SELECT s.year, u.mgnr,
       (COALESCE(IIF(u.weight = 0, -s.penalty_none, 0), 0) +
        COALESCE(IIF(u.diff < 0, -s.penalty_amount, 0), 0) +
        COALESCE(u.diff * s.penalty_per_kg, 0)
       ) AS total_penalty
FROM v_total_under_delivery u
   JOIN season s ON s.year = u.year
WHERE u.diff < 0 AND total_penalty < 0
ORDER BY s.year, u.mgnr;

CREATE VIEW v_auto_business_shares AS
SELECT s.year, h.mgnr,
       SUM(h.business_shares) AS business_shares,
       SUM(h.business_shares) * s.bs_value AS total_amount
FROM member_history h, season s
WHERE h.type = 'auto' AND h.date >= s.year || '-01-01' AND h.date <= s.year || '-12-31'
GROUP BY s.year, h.mgnr
ORDER BY s.year, h.mgnr;
