with 

dayscale as (SELECT dd::date as dt
	, DATE_PART('days', DATE_TRUNC('month', dd) + '1 MONTH'::INTERVAL - '1 DAY'::INTERVAL) monthdays 
	FROM generate_series( 
	 '2023-01-01'::timestamp
	,'2026-01-01'::timestamp
	,'1 day'::interval) dd
),

status(status, status_id, probability_pc) as (VALUES
	('Закрыта неуспешно',7,0),('Закрыта успешно',6,100),('Договор подписан',5,100),('Договор на подписании',15,90),('Договор на согласовании',12,70),
	('Тестирование',8,50),('Отправлено ТКП',10,20),('Внутреннее согласование',37,10),('Проработка решения',4,10),('Сбор потребностей',1,0)
),

component as (
select siv.__id as siv_uid, siv.discount, siv.type as line_pricing_model_id 
,siv.hash as line_key, siv.user_description, siv.is_actual as siv_is_actual
,siv.version::numeric, GREATEST(siv.date_nop,d."_plannedDueDate")::date as dt_from, siv.date_end::date as dt_to
,siv.is_easy as is_simple, siv.cnt as quantity -- maybe should mutliply
, a.__id as agreement_uid, a.contract_uid, a.is_actual as agreement_is_actual, a.deal_uid
,d."_plannedDueDate", d.__name as deal, d.__status_status as deal_status_id
,p.code, p.price, p.cnt as param_quantity, p.discount as param_discount, p.name as sku
,p.price*p.cnt*(100-p.discount)/100 as cost
,c.__name as contract
,s.probability_pc
from elma.deals_services siv
join elma.additional_agreements a on (a.__id = ANY(siv.additional_agreement)) 
join elma.deals d on (d.__id = ANY(siv.deal)) 
join elma.service_parametrs p on (p.__id = ANY (siv.params))
join elma.aggrements c on (a.contract_uid = c.__id)
join status s on (d.__status_status=s.status_id)
),

maxver as (
	select max(version) as version, count(*) as cnt, dt_from, line_key, contract_uid, agreement_is_actual 
	from component 
	group by dt_from, line_key, contract_uid, agreement_is_actual
)

select 
 dayscale.dt, (c.dt_from) as dt_from, (c.dt_to) as dt_to
,(mv.version) as working_ver, (mb.version) as base_ver
,(mv.line_key) as line_key, (c.code) as code
,(mv.agreement_is_actual::int), (mb.agreement_is_actual::int)
,(
	COALESCE(case when (c.dt_to > dayscale.dt OR c.dt_to IS NULL) then 
	c.cost*(
	case when c.agreement_is_actual then 100 else c.probability_pc end
	)/100/dayscale.monthdays
	else 0 /*по окончании рабочей сделки она дает нулевой вклад*/
	end,0)	
	+
	COALESCE(case when (b.dt_to > dayscale.dt OR b.dt_to IS NULL) then 
	b.cost/dayscale.monthdays*(100- COALESCE(
	case when c.agreement_is_actual then 100 else c.probability_pc end
	,0))/100
	else 0 /*по окончании базовой сделки она дает нулевой вклад*/
	end,0)
) as income_recurring
,(
	case when (c.dt_to > dayscale.dt OR c.dt_to IS NULL) then 
	b.cost*COALESCE(
	case when c.agreement_is_actual then 100 else c.probability_pc end
	,0)/100/dayscale.monthdays
	else 0 
	end
) as rec1
,(
	case when (b.dt_to > dayscale.dt OR b.dt_to IS NULL) then 0 else
	b.cost*(100-COALESCE(
	case when c.agreement_is_actual then 100 else c.probability_pc end
	,0))/100/dayscale.monthdays 
	end
) as rec0
,round((c.cost/*/dayscale.monthdays*/)::numeric,2) as cost_month 
,(c.deal_status_id) as status_id, (c.contract) as contract

from 
-- свежая версия на каждую дату
dayscale  
join component c on (dayscale.dt = c.dt_from)
join maxver mv on (c.line_key = mv.line_key AND c.version=mv.version AND dayscale.dt = mv.dt_from)
-- базовая версия
left outer join maxver mb on (c.line_key = mb.line_key AND mv.version > mb.version AND dayscale.dt = mb.dt_from /*AND mb.agreement_is_actualcheck it*/)
left outer join component b on (c.line_key = b.line_key AND mb.version = b.version AND dayscale.dt = b.dt_from)
where --c.agreement_uid='0198183f-6dbc-73f7-914a-ce1347aea1a6'
--c.contract_uid='0194a838-0351-7fea-b722-4289dfb4f240'
c.contract='01914_1' AND c.deal_status_id IN ('5','6') /*нет уверенности, что наличие допсоглашения гарантирует валидность записи*/
--AND maxver.contract_uid='0194a838-0351-7fea-b722-4289dfb4f240'
AND c.line_pricing_model_id in (2,3) -- на уровне компонента
--group by dayscale.dt --, mv.version, mv.line_key
order by dayscale.dt