-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfix-closed-applications.sql
More file actions
48 lines (44 loc) · 1.73 KB
/
fix-closed-applications.sql
File metadata and controls
48 lines (44 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
-- ================================================================
-- FIX: Auto-close applications that are fully funded
-- This script updates applications where total approved >= total requested
-- Run this in your PostgreSQL shell
-- ================================================================
-- Step 0: Add closed_at column if it doesn't exist
ALTER TABLE applications ADD COLUMN IF NOT EXISTS closed_at TIMESTAMPTZ;
-- Step 1: Show applications that should be closed but aren't
SELECT
a.id,
a.status as current_status,
a.total_amount_requested,
COALESCE(SUM(aa.approved_amount), 0) as total_approved,
a.total_amount_requested - COALESCE(SUM(aa.approved_amount), 0) as remaining
FROM applications a
LEFT JOIN application_approvals aa ON aa.application_id = a.id AND aa.status = 'approved'
GROUP BY a.id, a.status, a.total_amount_requested
HAVING COALESCE(SUM(aa.approved_amount), 0) >= a.total_amount_requested
AND a.status != 'closed';
-- Step 2: Update these applications to 'closed' status
UPDATE applications
SET
status = 'closed',
closed_at = NOW(),
updated_at = NOW()
WHERE id IN (
SELECT a.id
FROM applications a
LEFT JOIN application_approvals aa ON aa.application_id = a.id AND aa.status = 'approved'
GROUP BY a.id, a.total_amount_requested, a.status
HAVING COALESCE(SUM(aa.approved_amount), 0) >= a.total_amount_requested
AND a.status != 'closed'
);
-- Step 3: Verify the changes
SELECT
a.id,
a.status,
a.total_amount_requested,
COALESCE(SUM(aa.approved_amount), 0) as total_approved,
a.closed_at
FROM applications a
LEFT JOIN application_approvals aa ON aa.application_id = a.id AND aa.status = 'approved'
GROUP BY a.id, a.status, a.total_amount_requested, a.closed_at
ORDER BY a.created_at DESC;