create or alter function HM.hm_ContractorSettlements
(
	@ContractorId int, 
	@typKh int 
)
returns table
as
return
select    
	CAST(IsNull(-SUM(case when typ & 0x2 = 0 and wyplata = 0 THEN (kwota - kwotarozl) * kurs ELSE 0 END), 0) as decimal(10,2)) Receivables, -- Należności
	CAST(IsNull(SUM(case when typ & 0x2 = 0 and wyplata = 1 THEN (kwota - kwotarozl) * kurs ELSE 0 END), 0) as decimal(10,2)) Liabilities,  -- Zobowiązania
	CAST(IsNull(SUM(case when typ & 0x2 = 2 and wyplata = 0 THEN ROUND((kwota - kwotarozl) * kurs, 2) ELSE 0 END), 0) as decimal) Payments,		-- Wpłaty
	CAST(IsNull(-SUM(case when typ & 0x2 = 2 and wyplata = 1 THEN ROUND((kwota - kwotarozl) * kurs, 2) ELSE 0 END), 0) as decimal) Withdrawals	-- Wypłaty
from PN
where typ <> 4 and ok = 0 and khid = @ContractorId and typkh = @typKh;