
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;

CREATE VIEW v_penalty_area_commitments AS
SELECT u.year, u.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_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;
