--explain analyze
with 
component as (
select siv.__id as siv_uid, siv.discount, siv.cnt as quantity, siv.type as pricing_model_id 
,siv.hash as line_key, siv.user_description, siv.is_actual as siv_is_actual
,siv.version, GREATEST(siv.date_nop,d."_plannedDueDate") as dt_from, siv.date_end as dt_to, siv.is_easy as is_simple, siv.cnt as quantity
, a.__id as agreement_uid, a.contract_uid, a.is_actual as agreement_is_actual, a.deal_uid
,d."_plannedDueDate", d.__name as deal
,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
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)
),


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

select * from 
dayscale
LEFT OUTER JOIN 
(
SELECT t.*,
coalesce((LEAD(t.dt_from) OVER (PARTITION BY t.line_key ORDER BY t.dt_from, t.agreement_version,t.line_version)), (select max(dt) from elma.mv_dt)) dt_next,
b.probability_pc, b.discount

FROM


(
  SELECT *,
    MIN(dt_from) OVER (PARTITION BY line_key ORDER BY agreement_version desc,line_version desc) running_min_dt	
  FROM elma.mv_line where siv_is_actual AND probability_pc > 0
) t 

LEFT OUTER JOIN 

(	select * from -- базовая лесенка
	(
	  SELECT *,
		MIN(dt_from) OVER (PARTITION BY line_key ORDER BY agreement_version desc,line_version desc) running_min_dt	
	  FROM elma.mv_line where siv_is_actual AND probability_pc=100 AND agreement_is_actual
	) i where i.dt_from=i.running_min_dt
) b on (b.siv_uid=(select siv_uid from
	( -- базовая лесенка
	  SELECT siv_uid, dt_from, agreement_version, line_version,
	    MIN(dt_from) OVER (PARTITION BY line_key ORDER BY agreement_version desc, line_version desc) running_min_dt	
	  FROM elma.mv_line where siv_is_actual AND probability_pc=100 AND agreement_is_actual
	) i where i.dt_from=i.running_min_dt
		AND i.dt_from < t.dt_from
	ORDER BY /*dt_from desc,*/ agreement_version desc, line_version desc
	LIMIT 1
)) 
where t.dt_from=t.running_min_dt -- это условие формирования лесенки, далко оторвано от ее селекта
AND t.line_pricing_model_id in (2,3)

--AND t.line_key in ('0a61f9e4-520b-4f0a-aac0-c1d42c037e1b','0bde160d-52d0-4d55-b4e0-05f45cfd739e','08485a0c-a913-4332-bb36-e40dec27d12e','1809bb31-4d37-424b-ba2b-26b9a873af7f')
) o 
on (dayscale.dt between o.dt_from AND o.dt_next)