| 1 | CREATE OR REPLACE PROCEDURE proc_suspend_overdue_accounts()
|
|---|
| 2 | LANGUAGE plpgsql
|
|---|
| 3 | AS $$
|
|---|
| 4 | DECLARE
|
|---|
| 5 | v_accounts_suspended INT;
|
|---|
| 6 | v_subscriptions_suspended INT;
|
|---|
| 7 | BEGIN
|
|---|
| 8 | -- site invoices gi markirame so overdue
|
|---|
| 9 | UPDATE invoices i
|
|---|
| 10 | SET status = 'overdue'
|
|---|
| 11 | FROM accounts a
|
|---|
| 12 | LEFT JOIN billing_cycles bc
|
|---|
| 13 | ON bc.billing_cycle_id = a.billing_cycle_id
|
|---|
| 14 | WHERE i.account_id = a.account_id
|
|---|
| 15 | AND i.status = 'issued'
|
|---|
| 16 | AND i.due_date + bc.grace_days < CURRENT_DATE;
|
|---|
| 17 |
|
|---|
| 18 |
|
|---|
| 19 | -- suspendirame accounts
|
|---|
| 20 | UPDATE accounts a
|
|---|
| 21 | SET account_status = 'suspended',
|
|---|
| 22 | updated_at = CURRENT_TIMESTAMP
|
|---|
| 23 | WHERE a.account_status = 'active'
|
|---|
| 24 | AND EXISTS (
|
|---|
| 25 | SELECT 1
|
|---|
| 26 | FROM invoices i
|
|---|
| 27 | WHERE i.account_id = a.account_id
|
|---|
| 28 | AND i.status = 'overdue'
|
|---|
| 29 | );
|
|---|
| 30 |
|
|---|
| 31 | GET DIAGNOSTICS v_accounts_suspended = ROW_COUNT;
|
|---|
| 32 |
|
|---|
| 33 |
|
|---|
| 34 | -- suspendirame subscriptions
|
|---|
| 35 | UPDATE subscriptions s
|
|---|
| 36 | SET status = 'suspended'
|
|---|
| 37 | WHERE s.status = 'active'
|
|---|
| 38 | AND s.account_id IN (
|
|---|
| 39 | SELECT account_id
|
|---|
| 40 | FROM accounts
|
|---|
| 41 | WHERE account_status = 'suspended'
|
|---|
| 42 | );
|
|---|
| 43 |
|
|---|
| 44 | GET DIAGNOSTICS v_subscriptions_suspended = ROW_COUNT;
|
|---|
| 45 |
|
|---|
| 46 |
|
|---|
| 47 | RAISE NOTICE '% account(s) suspended.', v_accounts_suspended;
|
|---|
| 48 | RAISE NOTICE '% subscription(s) suspended.', v_subscriptions_suspended;
|
|---|
| 49 | END;
|
|---|
| 50 | $$;
|
|---|
| 51 |
|
|---|
| 52 | --korisnikot ne smee da gi pravi drugi raboti se dodeka ne se plati fakturata
|
|---|
| 53 |
|
|---|
| 54 | SELECT
|
|---|
| 55 | a.account_id,
|
|---|
| 56 | a.account_number,
|
|---|
| 57 | a.account_status,
|
|---|
| 58 | i.invoice_id,
|
|---|
| 59 | i.due_date,
|
|---|
| 60 | COALESCE(bc.grace_days, 0) AS grace_days,
|
|---|
| 61 | i.due_date + COALESCE(bc.grace_days, 0) AS suspend_after,
|
|---|
| 62 | i.status
|
|---|
| 63 | FROM accounts a
|
|---|
| 64 | JOIN invoices i
|
|---|
| 65 | ON i.account_id = a.account_id
|
|---|
| 66 | LEFT JOIN billing_cycles bc
|
|---|
| 67 | ON bc.billing_cycle_id = a.billing_cycle_id
|
|---|
| 68 | WHERE a.account_status = 'active'
|
|---|
| 69 | AND i.status = 'issued'
|
|---|
| 70 | AND i.due_date + COALESCE(bc.grace_days, 0) < CURRENT_DATE;
|
|---|
| 71 |
|
|---|
| 72 |
|
|---|
| 73 | BEGIN;
|
|---|
| 74 |
|
|---|
| 75 | CALL proc_suspend_overdue_accounts();
|
|---|
| 76 |
|
|---|
| 77 | ROLLBACK; |
|---|