DROP VIEW IF EXISTS STOR.V_SI_MDLP_PAYMENT_TYPE;
CREATE VIEW STOR.V_SI_MDLP_PAYMENT_TYPE
AS
select 
	si.InvoiceID
,	case when si.PaymentType is not null 
		then pt.MarkType
		when tt.c > 1 
		then 5 
		else tt.MarkType 
	end as MdlpPaymentType
from STOR.T_STORAGE_INVOICE si
left join STOR.T_PAYMENT_TYPE pt on pt.Code = si.PaymentType
left join lateral
(
	select 
		max(ptIi.MarkType) as MarkType
	,	count(distinct ptIi.MarkType) as c
	from STOR.T_INVOICE_ITEM ii
	join STOR.T_SUPPLIER_CONTRACT_ABR abr 
		on abr.Abr = ii.SupplierContractAbr
	left join STOR.T_PAYMENT_TYPE ptIi on ptIi.Code = abr.PaymentType
	where ii.StorageInvoice = si.InvoiceID
	group by ii.StorageInvoice
) tt on true;