/* Shows all invoices with outstanding balance based on closing date with an outstanding amount greater than InvValue */
DECLARE @ClosingDate AS VARCHAR(20)
DECLARE @InvValue FLOAT
SET @ClosingDate = '2024-2-1'
SET @InvValue = 1
SELECT B.booking_no AS [Code],
B.organizationv6 AS [Organisation],
B.contact_namev6 AS [Contact Name],
B.ddate AS [Warehouse Out Date],
I.invoice_cred_no AS [Invoice #],
I.invdate AS [Invoice Date],
CASE
WHEN I.inv_cred_note = 0 THEN Cast(( I.invoice_amount ) AS
DECIMAL(9, 2))
ELSE 0
END AS [Invoice Amount],
(SELECT TOP 1 P.datef
FROM tblpayment P
WHERE P.invoice_no = I.invoice_cred_no
ORDER BY datef DESC) AS [Payment Date],
CASE
WHEN I.inv_cred_note = 0 THEN Cast(Isnull((SELECT Sum(P.amount)
FROM tblpayment P
WHERE P.invoice_no =
I.invoice_cred_no), 0) AS
DECIMAL(9, 2))
ELSE 0
END AS [Payment Amount],
Cast(I.invoice_amount - Isnull((SELECT Sum(P.amount)
FROM tblpayment P
WHERE P.invoice_no = I.invoice_cred_no), 0) -
i.credit_amount - Isnull((SELECT Sum(credit_amount)
FROM tblinvhead
WHERE invoice_cred_no = I.invoice_cred_no
AND inv_cred_note = 1), 0) AS DECIMAL
(9, 2)) AS [Balance],
p.paytermname [Payment Terms],
B.last_operators AS [Booking Last Modified By],
Concat(O.firstname, ' ', O.lastname) AS [Original Operator],
B.condate AS [Confirm Date],
CASE
WHEN B.bookingprogressstatus = 0 THEN 'Quote'
WHEN B.bookingprogressstatus = 1 THEN 'Light Pencil'
WHEN B.bookingprogressstatus = 2 THEN 'Heavy Pencil'
WHEN B.bookingprogressstatus = 3 THEN 'Confirmed'
ELSE 'Cancelled'
END AS [Status],
C.address_l1v6 AS [Physical Address],
C.address_l2v6 AS [Physical Adress Cont.],
C.address_l3v6 [City],
C.streetstate AS [State],
C.post_code AS [Zip Code],
C.phone1countrycode,
C.phone1areacode,
C.phone1digits AS [Phone Number],
C.emailaddress AS [Email],
C.webaddress AS [Website]
FROM tblinvhead I
LEFT OUTER JOIN tblbookings B
ON I.invoice_cred_no = B.invoice_no
LEFT OUTER JOIN tblvenues V
ON V.id = B.venueid
LEFT OUTER JOIN tblpayterms T
ON B.booking_no = T.booking_no
LEFT OUTER JOIN tblcust C
ON C.id = B.custid
LEFT OUTER JOIN tbloperators O
ON O.id = B.operatorsid
LEFT OUTER JOIN tblpaytermnames P
ON P.termno = c.account_type
WHERE i.inv_cred_note = 0
AND I.invdate <= @ClosingDate
AND i.invoice_amount > @InvValue
AND ( Isnull(i.invoice_amount - i.credit_amount, 0) > @InvValue )
AND b.bookingprogressstatus = 3
AND ( i.invoice_amount - Isnull(i.credit_amount, 0) - Isnull(
(SELECT Sum(amount)
FROM tblpayment
WHERE
invoice_no = I.invoice_cred_no), 0) - Isnull(
(SELECT Sum(credit_amount)
FROM tblinvhead
WHERE invoice_cred_no =
I.invoice_cred_no
AND inv_cred_note = 1), 0) > @InvValue )
ORDER BY b.ddate