-- =============================================================================
-- Добавить колонку roic_norm в contractor_producer_mapping
-- =============================================================================

USE [mag_pbi]
GO

IF NOT EXISTS (
    SELECT 1 FROM sys.columns 
    WHERE object_id = OBJECT_ID(N'[analytics].[contractor_producer_mapping]') 
    AND name = 'roic_norm'
)
BEGIN
    ALTER TABLE [analytics].[contractor_producer_mapping]
    ADD [roic_norm] DECIMAL(12,4) NULL;

    EXEC sys.sp_addextendedproperty
        @name = N'MS_Description',
        @value = N'Нормированный ROIC (при торговой надбавке 100%). Рассчитывается по этапам оплаты.',
        @level0type = N'SCHEMA', @level0name = N'analytics',
        @level1type = N'TABLE', @level1name = N'contractor_producer_mapping',
        @level2type = N'COLUMN', @level2name = N'roic_norm';
END
GO

-- Обновить представление v_contractor_producer_mapping
IF OBJECT_ID(N'[analytics].[v_contractor_producer_mapping]', N'V') IS NOT NULL
    DROP VIEW [analytics].[v_contractor_producer_mapping];
GO

CREATE VIEW [analytics].[v_contractor_producer_mapping] AS
SELECT
    m.id,
    m.contractor_1c_id,
    c.contractor_id,
    c.contractor_name,
    m.producer_1c_id,
    p.producer_id,
    p.producer_name,
    m.days_of_sales,
    m.logistics_days,
    m.roic_norm,
    m.created_at,
    m.updated_at
FROM [analytics].[contractor_producer_mapping] m
LEFT JOIN [analytics].[v_contractors] c ON c.contractor_1c_id = m.contractor_1c_id
LEFT JOIN [analytics].[v_producers]   p ON p.producer_1c_id = m.producer_1c_id;
GO
