-- Lista dokumentów sprzedażowych
SELECT top 2000
x.invoiceID,
x.invoiceID remoteid,
x.invoiceFullNR + ' ' +
case when cp.remoteid is not null then 'H'
else ''
end invoiceFullNR
,x.invoiceIssueDate
,x.saleDate
,x.financialSystemExport
,x.grossValue /*- ISNULL(corrected_IV.grossValue,0)*/ grossValue
,x.netValue /*- ISNULL(corrected_IV.netValue,0)*/ netValue
,x.accDate
,x.accUsername
,x.warehouseID warehouseidPoz
--,x.payerID
,dt.componentName
,x.status
,isModified --znacznik czy byla reczna modyfikacja pozycji
,x.addDate
,1 'mode'
,@datefrom datefrom
,@dateto dateto
,@warehouseid warehouseid
FROM document.invoice x
left join document.invoice cor_inv on x.correctInvoiceID = cor_inv.invoiceID
--inner join [document].invoiceline il on x.invoiceID=il.invoiceID
left JOIN document.documentType dt ON dt.documentType=x.invoiceCategory
left join document.invoice corrected_IV on corrected_IV.invoiceID = x.prevCorrectionID
left join (
select distinct invoiceid,1 ismodified from document.invoiceLine il inner join accounting.customeAccounting ca
on il.invoiceLineID = ca.remoteID) modified on modified.invoiceid= x.invoiceid
left join (select distinct remoteid from common.paymentschedule where status >-1) cp on x.invoiceid= cp.remoteid
left join document.documentRelation br2 on br2.invoiceID = x.invoiceID and br2.documentRelationType = 5--aby odfiltrować paragony mające faktury
where x.status>=0
and (x.invoiceFullNR like '%' + @documentnr +'%' or @documentnr is null)
and (x.invoiceIssueDate>= isnull(@datefrom,getdate()-1000) and x.invoiceIssueDate <= isnull(@dateto,getdate()+1000) )
and dt.componentName in ('saleInvoice')
and (@warehouseid is null or x.warehouseID = @warehouseid)
and dt.isProforma = 0
and br2.documentRelationID is null
and case when x.invoiceFullNR like 'k%' and cor_inv.invoiceFullNR not like 'k%' and cor_inv.sysGrossValue=0 then 1
when x.invoiceFullNR like 'k%' and x.sysGrossValue=0 then 0 else 1 end =1
order by x.invoiceIssueDate , x.invoiceFullNR