-- =============================================================================
-- Пересчёт roic_norm по методике (возврат денег по ходу продаж)
-- Таблицы: manufacturers, manufacturer_payment_stage
-- Алгоритм: avgReturnDay = logistics_days + days_of_sales/2
--           frozenDays = avgReturnDay - effectiveDeferralDays
--           roic_norm = 12 / (frozenDays/30) * 100
-- =============================================================================

USE [mag_pbi]
GO

;WITH stage_agg AS (
    SELECT
        manufacturer_id,
        SUM([percent] / 100.0 * [days]) AS effective_deferral_days,
        SUM([percent] / 100.0) AS total_percent
    FROM [analytics].[manufacturer_payment_stage]
    GROUP BY manufacturer_id
),
calc AS (
    SELECT
        man.id,
        man.days_of_sales,
        man.logistics_days,
        COALESCE(s.effective_deferral_days, 0) AS effective_deferral_days,
        COALESCE(s.total_percent, 0) AS total_percent,
        (man.logistics_days + man.days_of_sales / 2.0) AS avg_return_day
    FROM [analytics].[manufacturers] man
    LEFT JOIN stage_agg s ON s.manufacturer_id = man.id
),
roic_calc AS (
    SELECT
        id,
        CASE
            WHEN total_percent <= 0 THEN NULL
            WHEN (avg_return_day - effective_deferral_days) <= 0 THEN NULL
            ELSE ROUND(12.0 / ((avg_return_day - effective_deferral_days) / 30.0) * 100.0, 2)
        END AS new_roic
    FROM calc
)
UPDATE man
SET man.roic_norm = r.new_roic
FROM [analytics].[manufacturers] man
JOIN roic_calc r ON r.id = man.id;

SELECT
    COUNT(*) AS total,
    COUNT(roic_norm) AS with_roic,
    COUNT(*) - COUNT(roic_norm) AS without_roic
FROM [analytics].[manufacturers];
