Skip to content

Commit

Permalink
Use invoice_date of sent invoices for target month deduction
Browse files Browse the repository at this point in the history
  • Loading branch information
akheron committed Oct 3, 2024
1 parent 4c8e4d5 commit fc0cfed
Showing 1 changed file with 6 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,17 @@ WITH applied_corrections AS (
LEFT JOIN updated_invoice_rows ir ON ir.correction_id = ac.new_correction_id
WHERE ic.target_month IS NULL
GROUP BY ic.id
), first_uninvoiced_month AS (
-- Invoices of month N are sent in month N+1, so the invoice date of the last sent invoice is the first uninvoiced month.
SELECT date_trunc('month', MAX(invoice_date)) AS month
FROM invoice
WHERE status = 'SENT'
)
UPDATE invoice_correction ic
SET
amount = CASE WHEN rc.remaining_correction % ic.unit_price = 0 THEN rc.remaining_correction / ic.unit_price ELSE ic.amount END,
unit_price = CASE WHEN rc.remaining_correction % ic.unit_price = 0 THEN ic.unit_price ELSE rc.remaining_correction / ic.amount END,
target_month = date_trunc('month', now()) + interval '1 month',
target_month = (SELECT month FROM first_uninvoiced_month),
applied_completely = FALSE
FROM remaining_corrections rc
WHERE ic.id = rc.id AND rc.remaining_correction != 0;
Expand Down

0 comments on commit fc0cfed

Please sign in to comment.