{{ config( materialized='table', database=target.database, schema='transform', tags=['semantic_layer', 'chatbot'] ) }} with source_quotes as ( select quote_id, line_item, customer_id, material_id, quantity, net_value, quote_date, sales_person_id, source_timestamp from source_quotes where quote_date >= dateadd(day, -1, current_date()) ), enrich_product_portfolio as ( select sq.quote_id, sq.line_item, sq.customer_id, sq.material_id, sq.quantity, sq.net_value, sq.quote_date, sq.sales_person_id, /* Product portfolio classification */ case when sq.material_id like 'DI-%' then 'data-integration' when sq.material_id like 'AU-%' then 'automation' when sq.material_id like 'CO-%' then 'connectivity' else 'other' end as portfolio_code, pm.portfolio_name, pm.portfolio_category, pm.material_description from source_quotes sq left join {{ ref('dim_product_master') }} pm on sq.material_id = pm.material_id ), calculate_discounts as ( select epf.*, /* Discount hierarchy: customer segment -> discount tier */ coalesce(cd.discount_tier_pct, 0) as discount_hierarchy_pct, /* Customer-specific negotiated discount */ coalesce(cd.customer_discount_pct, 0) as discount_customer_pct, /* Agreement-based discounts (volume, multi-year, etc.) */ coalesce(ca.agreement_discount_pct, 0) as discount_agreement_pct, /* Maximum allowed discount (governance constraint) */ cd.discount_ceiling_pct, /* Total discount calculation */ coalesce(cd.discount_tier_pct, 0) + coalesce(cd.customer_discount_pct, 0) + coalesce(ca.agreement_discount_pct, 0) as discount_total_pct from enrich_product_portfolio epf left join {{ ref('dim_customer_discount_policy') }} cd on epf.customer_id = cd.customer_id and epf.portfolio_code = cd.portfolio_code left join {{ ref('fct_agreement_discounts') }} ca on epf.customer_id = ca.customer_id and epf.material_id = ca.material_id ), governance_flags as ( select cd.*, /* Flag: discount exceeds policy maximum */ case when cd.discount_total_pct > cd.discount_ceiling_pct then cd.discount_total_pct - cd.discount_ceiling_pct else 0 end as discount_above_ceiling, /* Governance indicator: quote ready for human review */ case when cd.discount_total_pct > cd.discount_ceiling_pct then 1 else 0 end as requires_exception_approval from calculate_discounts cd ) select quote_id, line_item, customer_id, material_id, portfolio_code, portfolio_name, material_description, quantity, net_value, discount_hierarchy_pct, discount_customer_pct, discount_agreement_pct, discount_total_pct, discount_ceiling_pct, discount_above_ceiling, requires_exception_approval, quote_date, sales_person_id, current_timestamp() as dbt_loaded_at from governance_flags