-- Reject History Summary
-- Template slots:
--   BASE_QUERY (base reject-history daily dataset SQL)
--   WHERE_CLAUSE (QueryBuilder-generated WHERE clause against alias b)

{{ BASE_WITH_CTE }}
SELECT
    NVL(SUM(b.MOVEIN_QTY), 0) AS MOVEIN_QTY,
    NVL(SUM(b.REJECT_TOTAL_QTY), 0) AS REJECT_TOTAL_QTY,
    NVL(SUM(b.DEFECT_QTY), 0) AS DEFECT_QTY,
    CASE
        WHEN NVL(SUM(b.MOVEIN_QTY), 0) = 0 THEN 0
        ELSE ROUND(NVL(SUM(b.REJECT_TOTAL_QTY), 0) * 100 / SUM(b.MOVEIN_QTY), 4)
    END AS REJECT_RATE_PCT,
    CASE
        WHEN NVL(SUM(b.MOVEIN_QTY), 0) = 0 THEN 0
        ELSE ROUND(NVL(SUM(b.DEFECT_QTY), 0) * 100 / SUM(b.MOVEIN_QTY), 4)
    END AS DEFECT_RATE_PCT,
    CASE
        WHEN NVL(SUM(b.REJECT_TOTAL_QTY), 0) + NVL(SUM(b.DEFECT_QTY), 0) = 0 THEN 0
        ELSE ROUND(
            NVL(SUM(b.REJECT_TOTAL_QTY), 0) * 100
            / (NVL(SUM(b.REJECT_TOTAL_QTY), 0) + NVL(SUM(b.DEFECT_QTY), 0)),
            4
        )
    END AS REJECT_SHARE_PCT,
    COUNT(DISTINCT b.WORKCENTER_GROUP || ':' || b.WORKCENTERNAME || ':' || b.SPECNAME || ':' || b.TXN_DAY) AS AFFECTED_EVENT_BUCKET_COUNT,
    NVL(SUM(b.AFFECTED_LOT_COUNT), 0) AS AFFECTED_LOT_COUNT,
    NVL(SUM(b.AFFECTED_WORKORDER_COUNT), 0) AS AFFECTED_WORKORDER_COUNT
FROM base b
{{ WHERE_CLAUSE }}
