
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER VIEW [dbo].[FakturyWartoscWplaty] AS
SELECT 
F.id_faktury AS IdFaktury, 
FD.S_VAT AS ProcentVat, 
Netto = 
CASE 
  WHEN K.Netto IS NULL THEN ROUND(SUM(FD.NETTO), 2)
  ELSE K.Netto
END,
Vat = 
CASE
  WHEN K.Netto IS NULL THEN ROUND(SUM(FD.VAT), 2)
  ELSE K.Vat
END, 
Brutto = 
CASE
  WHEN K.Netto IS NULL THEN ROUND(SUM(FD.NETTO * (1 + FD.S_VAT)), 2)
  ELSE K.Brutto
END,
--F.waluta_brutto AS WalutaBrutto,
WalutaBrutto = 
CASE
  WHEN K.Netto IS NULL THEN F.waluta_brutto
  ELSE K.waluta_brutto
END,
WalutaMiano = 
CASE
  WHEN F.waluta_miano IS NULL OR F.waluta_miano='' THEN 'PLN'
  ELSE F.waluta_miano
END,
F.waluta_kurs AS KursWaluty,
W.brutto AS WplataBrutto,
W.waluta_brutto AS WplataWaluta,
Korekta = 
CASE 
	WHEN K.Netto IS NULL THEN 0
	ELSE 1
END,
FD.TYTUL AS IdTytulu
FROM FAKTURA_DETAILS FD
INNER JOIN FAKTURY F ON FD.ID_FAKTURY=F.ID_FAKTURY
INNER JOIN Wplaty W ON W.idFaktury=F.ID_FAKTURY
LEFT OUTER JOIN VIEW_KOREKTY AS K ON K.idFakturyKorekta = F.ID_FAKTURY 
GROUP BY 
F.id_faktury, F.waluta_brutto, F.waluta_miano, F.waluta_kurs,
FD.s_vat,
FD.TYTUL,
W.brutto,
W.waluta_brutto,
K.Netto, K.Brutto, K.Vat, K.waluta_brutto
GO

SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

