Skip to content

Commit 802d95c

Browse files
committed
Use invoice_date of sent invoices for target month deduction
Also, don't delete any rows to catch possible errors instead of just deleting data.
1 parent 4c8e4d5 commit 802d95c

File tree

1 file changed

+6
-3
lines changed

1 file changed

+6
-3
lines changed

service/src/main/resources/db/migration/V444__invoice_correction_target.sql

+6-3
Original file line numberDiff line numberDiff line change
@@ -22,18 +22,21 @@ WITH applied_corrections AS (
2222
LEFT JOIN updated_invoice_rows ir ON ir.correction_id = ac.new_correction_id
2323
WHERE ic.target_month IS NULL
2424
GROUP BY ic.id
25+
), first_uninvoiced_month AS (
26+
-- Invoices of month N are sent in month N+1, so the invoice date of the last sent invoice is the first uninvoiced month.
27+
SELECT date_trunc('month', MAX(invoice_date)) AS month
28+
FROM invoice
29+
WHERE status = 'SENT'
2530
)
2631
UPDATE invoice_correction ic
2732
SET
2833
amount = CASE WHEN rc.remaining_correction % ic.unit_price = 0 THEN rc.remaining_correction / ic.unit_price ELSE ic.amount END,
2934
unit_price = CASE WHEN rc.remaining_correction % ic.unit_price = 0 THEN ic.unit_price ELSE rc.remaining_correction / ic.amount END,
30-
target_month = date_trunc('month', now()) + interval '1 month',
35+
target_month = (SELECT month FROM first_uninvoiced_month),
3136
applied_completely = FALSE
3237
FROM remaining_corrections rc
3338
WHERE ic.id = rc.id AND rc.remaining_correction != 0;
3439

35-
DELETE FROM invoice_correction WHERE target_month IS NULL;
36-
3740
ALTER TABLE invoice_correction
3841
DROP COLUMN applied_completely,
3942
ALTER COLUMN target_month SET NOT NULL,

0 commit comments

Comments
 (0)