-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathnep_postgres_client.py
More file actions
executable file
·3394 lines (2951 loc) · 140 KB
/
nep_postgres_client.py
File metadata and controls
executable file
·3394 lines (2951 loc) · 140 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
PostgreSQL Client for NEP Analysis
Handles all NEP queries using PostgreSQL instead of ChromaDB
"""
import os
import asyncio
import asyncpg
from typing import List, Dict, Any, Optional
import json
import math
# Database connection settings from environment variables
import os
from dotenv import load_dotenv
load_dotenv()
DB_CONFIG = {
'host': os.getenv('POSTGRES_HOST', 'localhost'),
'port': int(os.getenv('POSTGRES_PORT', 5432)),
'database': os.getenv('POSTGRES_DB_NEP', 'nep'),
'user': os.getenv('POSTGRES_USER', 'budget_admin'),
'password': os.getenv('POSTGRES_PASSWORD', 'wuQ5gBYCKkZiOGb61chLcByMu')
}
async def get_db_connection():
"""Get PostgreSQL database connection"""
try:
conn = await asyncpg.connect(**DB_CONFIG)
return conn
except Exception as e:
print(f"💥 [PostgreSQL] Error connecting to database: {e}")
return None
def calculate_duplicate_score(matched_columns: int, total_columns: int, amount1: float, amount2: float, amount_weight: float = 20.0) -> float:
"""
Calculate duplicate score based on column matches and amount similarity.
Formula:
score = (X/N) * 100 + w * I(amount1 = amount2)
Where:
X = number of column matches
N = total columns compared
w = extra weight if amounts match
I() = indicator (1 if equal, else 0)
Amount similarity is also factored in:
amount_score = 1 - (|amount1 - amount2| / max(amount1, amount2))
"""
# Calculate base score from column matches
if total_columns == 0:
return 0.0
base_score = (matched_columns / total_columns) * 100
# Calculate amount similarity score
if amount1 == 0 and amount2 == 0:
amount_score = 1.0 # Both amounts are 0, perfect match
elif amount1 == 0 or amount2 == 0:
amount_score = 0.0 # One amount is 0, other is not, no similarity
else:
# amount_score = 1 - (|amount1 - amount2| / max(amount1, amount2))
max_amount = max(amount1, amount2)
amount_difference = abs(amount1 - amount2)
amount_score = 1 - (amount_difference / max_amount)
# Check if amounts are exactly equal (indicator function)
amounts_equal = 1 if amount1 == amount2 else 0
# Calculate final score
if amount_weight > 0:
score = base_score + (amount_weight * amounts_equal * amount_score)
else:
score = base_score # No amount weight contribution
# Cap at 100%
return round(min(100.0, score), 1)
async def get_budget_columns_comparison():
"""Get column comparison between 2024 and 2025 budget data"""
try:
print("🔍 [PostgreSQL] Getting budget columns comparison for 2024 vs 2025")
conn = await get_db_connection()
if not conn:
return {"success": False, "error": "Database connection failed"}
# Get columns for both years
columns_2024_query = """
SELECT column_name, data_type, is_nullable
FROM budget_2024_columns_metadata
ORDER BY ordinal_position
"""
columns_2025_query = """
SELECT column_name, data_type, is_nullable
FROM budget_2025_columns_metadata
ORDER BY ordinal_position
"""
rows_2024 = await conn.fetch(columns_2024_query)
rows_2025 = await conn.fetch(columns_2025_query)
# Convert to dictionaries for easier comparison
columns_2024 = {row['column_name']: {'data_type': row['data_type'], 'is_nullable': row['is_nullable']} for row in rows_2024}
columns_2025 = {row['column_name']: {'data_type': row['data_type'], 'is_nullable': row['is_nullable']} for row in rows_2025}
# Find common columns
common_columns = set(columns_2024.keys()) & set(columns_2025.keys())
# Find unique columns
unique_to_2024 = set(columns_2024.keys()) - set(columns_2025.keys())
unique_to_2025 = set(columns_2025.keys()) - set(columns_2024.keys())
# Column mapping for descriptions
column_descriptions = {
"sorder": "Sort Order - Sequential numbering of budget items",
"department": "Department Code - Government department identifier",
"uacs_dpt_dsc": "Department Description - Full name of the government department",
"agency": "Agency Code - Specific agency within the department",
"uacs_agy_dsc": "Agency Description - Full name of the government agency",
"uacs_func_dsc": "Function Description - Budget function classification",
"uacs_obj_dsc": "Object Description - Budget object classification",
"uacs_prog_dsc": "Program Description - Specific program name",
"uacs_proj_dsc": "Project Description - Specific project name",
"uacs_act_dsc": "Activity Description - Specific activity name",
"uacs_spec_dsc": "Special Purpose Description - Special purpose classification",
"uacs_loc_dsc": "Location Description - Geographic location",
"uacs_reg_dsc": "Region Description - Administrative region",
"uacs_prov_dsc": "Province Description - Province name",
"uacs_city_dsc": "City Description - City or municipality name",
"uacs_brgy_dsc": "Barangay Description - Barangay (village) name",
"uacs_reg_id": "Region ID - Philippine administrative region (1-15, self-explanatory, important for geolocation)",
"uacs_operdiv_id": "Division ID - Administrative division identifier (important for geolocation)",
"uacs_div_dsc": "Division Description - Administrative division name (maps to uacs_operdiv_id)",
"fundcd": "Fund Code - Budget fund classification code",
"operunit": "Operation Unit Code - Specific operation unit identifier (maps to uacs_oper_dsc)",
"uacs_oper_dsc": "Operation Unit Description - Specific operation unit name (maps to operunit)",
"uacs_exp_cd": "Expense Code - Budget expense classification code",
"uacs_exp_dsc": "Expense Description - Budget expense classification name",
"uacs_ppacd": "PPA Code - Programs, Projects and Activities code",
"uacs_ppa_dsc": "PPA Description - Programs, Projects and Activities name",
"uacs_ppacd2": "PPA Code 2 - Secondary PPA code",
"uacs_ppa_dsc2": "PPA Description 2 - Secondary PPA name",
"uacs_ppacd3": "PPA Code 3 - Tertiary PPA code",
"uacs_ppa_dsc3": "PPA Description 3 - Tertiary PPA name",
"uacs_ppacd4": "PPA Code 4 - Quaternary PPA code",
"uacs_ppa_dsc4": "PPA Description 4 - Quaternary PPA name",
"uacs_ppacd5": "PPA Code 5 - Quinary PPA code",
"uacs_ppa_dsc5": "PPA Description 5 - Quinary PPA name",
"uacs_ppacd6": "PPA Code 6 - Senary PPA code",
"uacs_ppa_dsc6": "PPA Description 6 - Senary PPA name",
"uacs_ppacd7": "PPA Code 7 - Septenary PPA code",
"uacs_ppa_dsc7": "PPA Description 7 - Septenary PPA name",
"uacs_ppacd8": "PPA Code 8 - Octonary PPA code",
"uacs_ppa_dsc8": "PPA Description 8 - Octonary PPA name",
"uacs_ppacd9": "PPA Code 9 - Nonary PPA code",
"uacs_ppa_dsc9": "PPA Description 9 - Nonary PPA name",
"uacs_ppacd10": "PPA Code 10 - Denary PPA code",
"uacs_ppa_dsc10": "PPA Description 10 - Denary PPA name",
"uacs_ppacd11": "PPA Code 11 - Undenary PPA code",
"uacs_ppa_dsc11": "PPA Description 11 - Undenary PPA name",
"uacs_ppacd12": "PPA Code 12 - Duodenary PPA code",
"uacs_ppa_dsc12": "PPA Description 12 - Duodenary PPA name",
"uacs_ppacd13": "PPA Code 13 - Tredenary PPA code",
"uacs_ppa_dsc13": "PPA Description 13 - Tredenary PPA name",
"uacs_ppacd14": "PPA Code 14 - Quattuordenary PPA code",
"uacs_ppa_dsc14": "PPA Description 14 - Quattuordenary PPA name",
"uacs_ppacd15": "PPA Code 15 - Quindenary PPA code",
"uacs_ppa_dsc15": "PPA Description 15 - Quindenary PPA name",
"uacs_ppacd16": "PPA Code 16 - Sexdenary PPA code",
"uacs_ppa_dsc16": "PPA Description 16 - Sexdenary PPA name",
"uacs_ppacd17": "PPA Code 17 - Septendenary PPA code",
"uacs_ppa_dsc17": "PPA Description 17 - Septendenary PPA name",
"uacs_ppacd18": "PPA Code 18 - Octodenary PPA code",
"uacs_ppa_dsc18": "PPA Description 18 - Octodenary PPA name",
"uacs_ppacd19": "PPA Code 19 - Novemdenary PPA code",
"uacs_ppa_dsc19": "PPA Description 19 - Novemdenary PPA name",
"uacs_ppacd20": "PPA Code 20 - Vigenary PPA code",
"uacs_ppa_dsc20": "PPA Description 20 - Vigenary PPA name",
"amount": "Amount - Budget allocation amount in Philippine Peso",
"year": "Year - Budget year (integer format)",
"migration_year": "Migration Year - Metadata field for data migration tracking"
}
# Prepare response data
result = {
"success": True,
"comparison": {
"2024": {
"columns": [{"name": col, "description": column_descriptions.get(col, "No description available"), "data_type": columns_2024[col]['data_type'], "is_nullable": columns_2024[col]['is_nullable']} for col in sorted(columns_2024.keys())],
"count": len(columns_2024)
},
"2025": {
"columns": [{"name": col, "description": column_descriptions.get(col, "No description available"), "data_type": columns_2025[col]['data_type'], "is_nullable": columns_2025[col]['is_nullable']} for col in sorted(columns_2025.keys())],
"count": len(columns_2025)
},
"common_columns": list(sorted(common_columns)),
"unique_to_2024": list(sorted(unique_to_2024)),
"unique_to_2025": list(sorted(unique_to_2025)),
"mappings": {
"uacs_oper_dsc_2024_to_uacs_div_dsc_2025": "Division descriptions (2024: uacs_oper_dsc → 2025: uacs_div_dsc)",
"operunit_2024_to_uacs_operdiv_id_2025": "Operation unit IDs (2024: operunit → 2025: uacs_operdiv_id)",
"year_text_2024_to_year_integer_2025": "Year field format change (2024: text → 2025: integer)"
}
}
}
print(f"🔍 [PostgreSQL] Columns comparison: 2024={len(columns_2024)}, 2025={len(columns_2025)}, common={len(common_columns)}")
return result
except Exception as e:
print(f"💥 [PostgreSQL] Error in get_budget_columns_comparison: {e}")
return {"success": False, "error": str(e)}
async def get_budget_columns(year: str = "2025"):
"""Get all available columns from budget data for a specific year"""
try:
# Validate year format
if not year.isdigit() or len(year) != 4:
return {"success": False, "error": "Invalid year format"}
# Try to load from JSON cache first
import json
from pathlib import Path
import os
# Get project root (where this file is located)
project_root = Path(__file__).parent
cache_file = project_root / "static" / "data" / "budget_columns_cache.json"
if cache_file.exists():
try:
with open(cache_file, 'r') as f:
cache_data = json.load(f)
if year in cache_data and cache_data[year].get("success"):
print(f"✅ [Cache] Loaded budget columns for {year} from cache")
return cache_data[year]
except Exception as e:
print(f"⚠️ [Cache] Error loading cache: {e}, falling back to database")
# Fallback to database
print(f"🔍 [PostgreSQL] Getting budget columns for {year} from database")
conn = await get_db_connection()
if not conn:
return {"success": False, "error": "Database connection failed"}
table_name = f"budget_{year}"
columns_view = f"{table_name}_columns_metadata"
# Check if metadata view exists, otherwise fallback to information_schema
view_exists = await conn.fetchval("""
SELECT EXISTS (
SELECT FROM information_schema.views
WHERE table_schema = 'public'
AND table_name = $1
)
""", columns_view)
if view_exists:
columns_query = f"""
SELECT column_name, data_type, is_nullable
FROM {columns_view}
ORDER BY ordinal_position
"""
rows = await conn.fetch(columns_query)
else:
# Fallback: query information_schema directly
print(f"⚠️ [PostgreSQL] View {columns_view} not found, using information_schema fallback")
columns_query = """
SELECT column_name, data_type, is_nullable, ordinal_position
FROM information_schema.columns
WHERE table_name = $1 AND table_schema = 'public'
AND column_name NOT IN ('id', 'source_file', 'created_at', 'updated_at')
ORDER BY ordinal_position
"""
rows = await conn.fetch(columns_query, table_name)
# Column mapping for descriptions
column_descriptions = {
"sorder": "Sort Order - Sequential numbering of budget items",
"department": "Department Code - Government department identifier",
"uacs_dpt_dsc": "Department Description - Full name of the government department",
"agency": "Agency Code - Specific agency within the department",
"uacs_agy_dsc": "Agency Description - Full name of the government agency",
"uacs_func_dsc": "Function Description - Budget function classification",
"uacs_obj_dsc": "Object Description - Budget object classification",
"uacs_prog_dsc": "Program Description - Specific program name",
"uacs_proj_dsc": "Project Description - Specific project name",
"uacs_act_dsc": "Activity Description - Specific activity name",
"uacs_spec_dsc": "Special Purpose Description - Special purpose classification",
"uacs_loc_dsc": "Location Description - Geographic location",
"uacs_reg_dsc": "Region Description - Administrative region",
"uacs_prov_dsc": "Province Description - Province name",
"uacs_city_dsc": "City Description - City or municipality name",
"uacs_brgy_dsc": "Barangay Description - Barangay (village) name",
"uacs_reg_id": "Region ID - Philippine administrative region (1-15, self-explanatory, important for geolocation)",
"uacs_operdiv_id": "Division ID - Administrative division identifier (important for geolocation)",
"uacs_div_dsc": "Division Description - Administrative division name (maps to uacs_operdiv_id)",
"fundcd": "Fund Code - Budget fund classification code",
"operunit": "Operation Unit Code - Specific operation unit identifier (maps to uacs_oper_dsc)",
"uacs_oper_dsc": "Operation Unit Description - Specific operation unit name (maps to operunit)",
"uacs_exp_cd": "Expense Code - Budget expense classification code",
"amt": "Amount - Budget allocation amount in Philippine Peso",
"year": "Fiscal Year - Budget year",
"type": "Budget Type - Type of budget allocation",
"status": "Status - Budget item status"
}
columns = []
for row in rows:
col_name = row['column_name']
col_type = row['data_type']
# Determine display type
display_type = "text"
if col_type in ['integer', 'bigint']:
display_type = "number"
elif col_type in ['numeric', 'decimal']:
display_type = "currency"
elif col_type in ['date', 'timestamp']:
display_type = "date"
elif 'code' in col_name.lower() or col_name.lower() in ['sorder', 'department', 'agency']:
display_type = "code"
columns.append({
"name": col_name,
"description": column_descriptions.get(col_name, f"Budget data field: {col_name}"),
"type": display_type,
"significance": f"Budget data field from {year} GAA documents"
})
await conn.close()
print(f"🔍 [PostgreSQL] Found {len(columns)} columns")
return {
"success": True,
"columns": columns,
"count": len(columns)
}
except Exception as e:
print(f"💥 [PostgreSQL] Error in get_budget_columns: {e}")
return {"success": False, "error": str(e)}
async def get_budget_statistics(year: str = "2025"):
"""Get comprehensive budget statistics from PostgreSQL"""
try:
print(f"🔍 [PostgreSQL] Getting budget statistics for {year}")
conn = await get_db_connection()
if not conn:
return {"success": False, "error": "Database connection failed"}
# Get statistics from the year-specific table (validate year to prevent injection)
if not year.isdigit() or len(year) != 4:
await conn.close()
return {"success": False, "error": "Invalid year format"}
table_name = f"budget_{year}"
# Check if table exists
table_exists_query = """
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = $1
)
"""
table_exists = await conn.fetchval(table_exists_query, table_name)
if not table_exists:
await conn.close()
return {"success": False, "error": f"Table {table_name} does not exist"}
# Check which columns exist
columns_query = """
SELECT column_name
FROM information_schema.columns
WHERE table_name = $1
AND table_schema = 'public'
"""
columns_result = await conn.fetch(columns_query, table_name)
available_columns = [row['column_name'] for row in columns_result]
# Build WHERE clause based on available columns (NEP schema)
where_conditions = [
"amount IS NOT NULL",
"amount > 0"
]
# NEP data may have negative amounts as valid data, so don't exclude -0.01
# NEP sort_order is often NULL, so don't filter on it
# org_uacs_code can be NULL in NEP data
where_clause = " AND ".join(where_conditions)
stats_query = f"""
SELECT
COUNT(*) as total_rows,
MAX(amount) as highest_amount,
AVG(amount) as average_amount,
SUM(amount) as total_amount
FROM {table_name}
WHERE {where_clause}
"""
stats = await conn.fetchrow(stats_query)
await conn.close()
statistics = {
"total_rows": stats['total_rows'],
"total_columns": 16, # NEP schema has 16 columns
"highest_amount": float(stats['highest_amount']) if stats['highest_amount'] else 0,
"average_amount": float(stats['average_amount']) if stats['average_amount'] else 0,
"total_amount": float(stats['total_amount']) if stats['total_amount'] else 0
}
print(f"🔍 [PostgreSQL] Generated statistics: {statistics}")
return {
"success": True,
"statistics": statistics,
"count": 1
}
except Exception as e:
print(f"💥 [PostgreSQL] Error in get_budget_statistics: {e}")
return {"success": False, "error": str(e)}
async def get_budget_data_browser(year: str = "2025", page: int = 1, limit: int = 50, sort_by: str = "amount", sort_order: str = "DESC", filters: dict = None):
"""Get paginated budget data with sorting and column filtering"""
try:
print(f"🔍 [PostgreSQL] Getting budget data browser for {year}, page {page}, limit {limit}, sort by {sort_by} {sort_order}")
conn = await get_db_connection()
if not conn:
return {"success": False, "error": "Database connection failed"}
# Validate year parameter
if not year.isdigit() or len(year) != 4:
await conn.close()
return {"success": False, "error": "Invalid year format"}
# Validate pagination parameters
if page < 1:
page = 1
if limit < 1 or limit > 1000:
limit = 50
# Validate sort parameters
allowed_sort_columns = ['department', 'uacs_dpt_dsc', 'agency', 'uacs_agy_dsc', 'dsc', 'uacs_fundsubcat_dsc', 'uacs_exp_dsc', 'uacs_sobj_dsc', 'uacs_operdiv_id', 'uacs_reg_id', 'amount', 'year']
if sort_by not in allowed_sort_columns:
sort_by = 'amount'
if sort_order.upper() not in ['ASC', 'DESC']:
sort_order = 'DESC'
table_name = f"budget_{year}"
offset = (page - 1) * limit
# Check if table exists
table_exists_query = """
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = $1
)
"""
table_exists = await conn.fetchval(table_exists_query, table_name)
if not table_exists:
await conn.close()
return {
"success": False,
"error": f"No data available for year {year}. Table {table_name} does not exist.",
"rows": [],
"pagination": {
"current_page": 1,
"total_pages": 0,
"total_count": 0,
"limit": limit,
"has_next": False,
"has_prev": False
}
}
# Get all columns from the table (excluding metadata columns)
all_columns_query = f"""
SELECT column_name
FROM information_schema.columns
WHERE table_name = $1
AND table_schema = 'public'
AND column_name NOT IN ('id', 'source_file', 'created_at')
ORDER BY column_name
"""
all_columns = await conn.fetch(all_columns_query, table_name)
selected_columns = [row['column_name'] for row in all_columns]
if not selected_columns:
await conn.close()
return {
"success": False,
"error": f"No columns found in table {table_name}",
"rows": [],
"pagination": {
"current_page": 1,
"total_pages": 0,
"total_count": 0,
"limit": limit,
"has_next": False,
"has_prev": False
}
}
# Build the query with all columns
columns_str = ', '.join([f'"{col}"' for col in selected_columns])
# Build WHERE clause with filters - only include columns that exist
where_conditions = [
"amount IS NOT NULL",
"amount > 0",
"amount != -0.01" # Exclude sentinel values
]
# Add sorder conditions only if column exists
if 'sorder' in selected_columns:
where_conditions.extend([
"sorder IS NOT NULL",
"sorder != -1" # Exclude sentinel values
])
# Add department/agency conditions only if columns exist
if 'department' in selected_columns:
where_conditions.extend([
"department IS NOT NULL",
"department != -1" # Exclude sentinel values (now numeric)
])
if 'agency' in selected_columns:
where_conditions.extend([
"agency IS NOT NULL",
"agency != -1" # Exclude sentinel values (now numeric)
])
# Add filter conditions
if filters:
for column, value in filters.items():
if value and str(value).strip(): # Only add non-empty filters
if column == 'amt_min':
where_conditions.append(f"amount >= {float(value)}")
elif column == 'amt_max':
where_conditions.append(f"amount <= {float(value)}")
elif column in ['department', 'agency']:
# Numeric filters for department and agency
try:
numeric_value = int(value)
where_conditions.append(f'"{column}" = {numeric_value}')
except (ValueError, TypeError):
# If not a valid number, skip this filter
print(f"⚠️ [PostgreSQL] Invalid numeric value for {column}: {value}")
elif column == 'uacs_reg_id':
# Numeric filter for region ID
try:
numeric_value = int(value)
where_conditions.append(f'"{column}" = {numeric_value}')
except (ValueError, TypeError):
# If not a valid number, skip this filter
print(f"⚠️ [PostgreSQL] Invalid numeric value for {column}: {value}")
elif column == 'uacs_div_dsc':
# Text filter for division description
where_conditions.append(f'"{column}" ILIKE \'%{str(value).strip()}%\'')
else:
# Text filters - use ILIKE for case-insensitive partial matching
where_conditions.append(f'"{column}" ILIKE \'%{str(value).strip()}%\'')
where_clause = " AND ".join(where_conditions)
query = f"""
SELECT {columns_str}
FROM {table_name}
WHERE {where_clause}
ORDER BY "{sort_by}" {sort_order}
LIMIT {limit} OFFSET {offset}
"""
# Get total count for pagination (same filters as main query)
count_query = f"""
SELECT COUNT(*) as total_count
FROM {table_name}
WHERE {where_clause}
"""
rows = await conn.fetch(query)
total_count = await conn.fetchval(count_query)
await conn.close()
if rows:
# Convert rows to dictionaries
rows_list = []
for row in rows:
row_dict = dict(row)
# Convert all Decimal values to float for JSON serialization
for key, value in row_dict.items():
if hasattr(value, '__class__') and 'Decimal' in str(type(value)):
row_dict[key] = float(value)
elif hasattr(value, '__class__') and 'datetime' in str(type(value)).lower():
row_dict[key] = value.isoformat()
rows_list.append(row_dict)
total_pages = (total_count + limit - 1) // limit # Ceiling division
print(f"🔍 [PostgreSQL] Found {len(rows_list)} rows (page {page}/{total_pages}), total: {total_count}")
return {
"success": True,
"rows": rows_list,
"pagination": {
"current_page": page,
"total_pages": total_pages,
"total_count": total_count,
"limit": limit,
"has_next": page < total_pages,
"has_prev": page > 1
},
"sorting": {
"sort_by": sort_by,
"sort_order": sort_order
}
}
else:
print(f"🔍 [PostgreSQL] No budget data found for {year}")
return {
"success": True,
"rows": [],
"pagination": {
"current_page": page,
"total_pages": 0,
"total_count": 0,
"limit": limit,
"has_next": False,
"has_prev": False
},
"sorting": {
"sort_by": sort_by,
"sort_order": sort_order
},
"message": f"No budget data found for {year}"
}
except Exception as e:
print(f"💥 [PostgreSQL] Error in get_budget_data_browser: {e}")
return {"success": False, "error": str(e)}
async def get_budget_top_duplicates(year: str = "2025"):
"""Get top duplicates by column count from PostgreSQL"""
try:
print(f"🔍 [PostgreSQL] Getting top duplicates for {year}")
conn = await get_db_connection()
if not conn:
return {"success": False, "error": "Database connection failed"}
# Find duplicates based on description and key columns (validate year to prevent injection)
if not year.isdigit() or len(year) != 4:
await conn.close()
return {"success": False, "error": "Invalid year format"}
table_name = f"budget_{year}"
duplicates_query = f"""
WITH duplicate_groups AS (
SELECT
uacs_prog_dsc,
uacs_proj_dsc,
uacs_act_dsc,
department,
agency,
COUNT(*) as duplicate_count,
MAX(amt) as max_amount,
SUM(amt) as total_amount
FROM {table_name}
WHERE uacs_prog_dsc IS NOT NULL
AND uacs_prog_dsc != ''
GROUP BY uacs_prog_dsc, uacs_proj_dsc, uacs_act_dsc, department, agency
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC, SUM(amt) DESC
LIMIT 5
)
SELECT
dg.*,
bi1.sorder as sorder1, bi1.uacs_dpt_dsc as dept_desc1, bi1.amt as amt1,
bi2.sorder as sorder2, bi2.uacs_dpt_dsc as dept_desc2, bi2.amt as amt2
FROM duplicate_groups dg
LEFT JOIN {table_name} bi1 ON (
bi1.uacs_prog_dsc = dg.uacs_prog_dsc AND
bi1.uacs_proj_dsc = dg.uacs_proj_dsc AND
bi1.uacs_act_dsc = dg.uacs_act_dsc AND
bi1.department = dg.department AND
bi1.agency = dg.agency
)
LEFT JOIN {table_name} bi2 ON (
bi2.uacs_prog_dsc = dg.uacs_prog_dsc AND
bi2.uacs_proj_dsc = dg.uacs_proj_dsc AND
bi2.uacs_act_dsc = dg.uacs_act_dsc AND
bi2.department = dg.department AND
bi2.agency = dg.agency AND
bi2.sorder != bi1.sorder
)
WHERE bi1.sorder IS NOT NULL AND bi2.sorder IS NOT NULL
LIMIT 5
"""
rows = await conn.fetch(duplicates_query)
await conn.close()
duplicates = []
for row in rows:
# Create comparison rows
row1 = {
"sorder": row['sorder1'],
"uacs_dpt_dsc": row['dept_desc1'],
"amt": float(row['amt1']) if row['amt1'] else 0
}
row2 = {
"sorder": row['sorder2'],
"uacs_dpt_dsc": row['dept_desc2'],
"amt": float(row['amt2']) if row['amt2'] else 0
}
duplicates.append({
"description": row['uacs_prog_dsc'],
"amount": float(row['max_amount']) if row['max_amount'] else 0,
"duplicate_count": row['duplicate_count'],
"matching_columns": 5, # We're matching on 5 columns
"suspicion_level": "high" if row['duplicate_count'] >= 3 else "medium",
"reason": f"Found {row['duplicate_count']} rows with matching program, project, activity, department, and agency",
"comparison_rows": [row1, row2],
"matching_values": [
f"uacs_prog_dsc:{row['uacs_prog_dsc']}",
f"uacs_proj_dsc:{row['uacs_proj_dsc']}",
f"uacs_act_dsc:{row['uacs_act_dsc']}",
f"department:{row['department']}",
f"agency:{row['agency']}"
]
})
print(f"🔍 [PostgreSQL] Found {len(duplicates)} duplicate groups")
return {
"success": True,
"duplicates": duplicates,
"count": len(duplicates)
}
except Exception as e:
print(f"💥 [PostgreSQL] Error in get_budget_top_duplicates: {e}")
return {"success": False, "error": str(e)}
async def get_budget_duplicates_with_scoring(year: str = "2025"):
"""Get budget duplicates using 7-column matching system with scoring - no authentication required"""
try:
print(f"🔍 [PostgreSQL] Getting budget duplicates with scoring for year {year}")
conn = await get_db_connection()
if not conn:
return {"success": False, "error": "Database connection failed"}
# Validate year parameter
if not year.isdigit() or len(year) != 4:
await conn.close()
return {"success": False, "error": "Invalid year format"}
table_name = f"budget_{year}"
# Use 7 specific columns for matching as requested
duplicates_query = f"""
WITH duplicate_groups AS (
SELECT
dsc,
uacs_agy_dsc,
uacs_dpt_dsc,
uacs_exp_dsc,
uacs_fundsubcat_dsc,
uacs_sobj_dsc,
amt,
COUNT(*) as duplicate_count,
MAX(amt) as max_amount,
SUM(amt) as total_amount
FROM {table_name}
WHERE dsc IS NOT NULL
AND dsc != 'INVALID'
AND amt IS NOT NULL
AND amt > 0
AND amt != -0.01
GROUP BY dsc, uacs_agy_dsc, uacs_dpt_dsc, uacs_exp_dsc, uacs_fundsubcat_dsc, uacs_sobj_dsc, amt
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC, SUM(amt) DESC
LIMIT 10
)
SELECT
dg.*,
bi1.sorder as sorder1, bi1.uacs_dpt_dsc as dept_desc1, bi1.amt as amt1,
bi2.sorder as sorder2, bi2.uacs_dpt_dsc as dept_desc2, bi2.amt as amt2
FROM duplicate_groups dg
LEFT JOIN {table_name} bi1 ON (
bi1.dsc = dg.dsc AND
bi1.uacs_agy_dsc = dg.uacs_agy_dsc AND
bi1.uacs_dpt_dsc = dg.uacs_dpt_dsc AND
bi1.uacs_exp_dsc = dg.uacs_exp_dsc AND
bi1.uacs_fundsubcat_dsc = dg.uacs_fundsubcat_dsc AND
bi1.uacs_sobj_dsc = dg.uacs_sobj_dsc AND
bi1.amt = dg.amt
)
LEFT JOIN {table_name} bi2 ON (
bi2.dsc = dg.dsc AND
bi2.uacs_agy_dsc = dg.uacs_agy_dsc AND
bi2.uacs_dpt_dsc = dg.uacs_dpt_dsc AND
bi2.uacs_exp_dsc = dg.uacs_exp_dsc AND
bi2.uacs_fundsubcat_dsc = dg.uacs_fundsubcat_dsc AND
bi2.uacs_sobj_dsc = dg.uacs_sobj_dsc AND
bi2.amt = dg.amt AND
bi2.sorder != bi1.sorder
)
WHERE bi1.sorder IS NOT NULL AND bi2.sorder IS NOT NULL
LIMIT 10
"""
rows = await conn.fetch(duplicates_query)
await conn.close()
duplicates = []
for row in rows:
# Create comparison rows
row1 = {
"sorder": row['sorder1'],
"uacs_dpt_dsc": row['dept_desc1'],
"amt": float(row['amt1']) if row['amt1'] else 0
}
row2 = {
"sorder": row['sorder2'],
"uacs_dpt_dsc": row['dept_desc2'],
"amt": float(row['amt2']) if row['amt2'] else 0
}
# Calculate score: matched columns / 7 * 100
score = (7 / 7) * 100 # All 7 columns matched
duplicates.append({
"description": row['dsc'],
"amount": float(row['max_amount']) if row['max_amount'] else 0,
"duplicate_count": row['duplicate_count'],
"matching_columns": 7, # We're matching on 7 columns
"score": score,
"severity": "high" if row['duplicate_count'] >= 3 else "medium",
"reason": f"Found {row['duplicate_count']} rows with matching description, agency, department, expense, fund category, object, and amount",
"comparison_rows": [row1, row2],
"matching_values": [
f"dsc:{row['dsc']}",
f"uacs_agy_dsc:{row['uacs_agy_dsc']}",
f"uacs_dpt_dsc:{row['uacs_dpt_dsc']}",
f"uacs_exp_dsc:{row['uacs_exp_dsc']}",
f"uacs_fundsubcat_dsc:{row['uacs_fundsubcat_dsc']}",
f"uacs_sobj_dsc:{row['uacs_sobj_dsc']}",
f"amt:{row['amt']}"
]
})
print(f"🔍 [PostgreSQL] Found {len(duplicates)} duplicate groups with 7-column matching")
return duplicates
except Exception as e:
print(f"💥 [PostgreSQL] Error in get_budget_duplicates_with_scoring: {e}")
return []
async def get_budget_scored_duplicates(year: str = "2025", limit: int = 10):
"""Get budget duplicates with progressive matching - start with 7 columns, work down to 2, stop at first match"""
try:
print(f"🔍 [PostgreSQL] Getting budget scored duplicates for year {year}, limit {limit}")
conn = await get_db_connection()
if not conn:
return {"success": False, "error": "Database connection failed"}
# Validate year parameter
if not year.isdigit() or len(year) != 4:
await conn.close()
return {"success": False, "error": "Invalid year format"}
table_name = f"budget_{year}"
all_duplicates = []
# Define column combinations from 9 down to 2
# Use correct column mappings: numeric codes for matching, text descriptions for display
column_combinations = [
# 9 columns - using correct mappings with all available columns
{
"match_columns": ["dsc", "amt", "agency", "department", "fundcd", "uacs_exp_cd", "operunit", "uacs_operdiv_id", "uacs_reg_id"],
"display_columns": ["dsc", "amt", "uacs_agy_dsc", "uacs_dpt_dsc", "uacs_fundsubcat_dsc", "uacs_exp_dsc", "uacs_oper_dsc", "uacs_div_dsc", "uacs_reg_id"],
"count": 9,
"description": "9 columns (dsc, amt, agency, department, fundcd, expense, operation unit, division, region)"
},
# 8 columns
{
"match_columns": ["dsc", "amt", "agency", "department", "fundcd", "uacs_exp_cd", "operunit", "uacs_operdiv_id"],
"display_columns": ["dsc", "amt", "uacs_agy_dsc", "uacs_dpt_dsc", "uacs_fundsubcat_dsc", "uacs_exp_dsc", "uacs_oper_dsc", "uacs_div_dsc"],
"count": 8,
"description": "8 columns (dsc, amt, agency, department, fundcd, expense, operation unit, division)"
},
{
"match_columns": ["dsc", "amt", "agency", "department", "fundcd", "uacs_exp_cd", "operunit", "uacs_reg_id"],
"display_columns": ["dsc", "amt", "uacs_agy_dsc", "uacs_dpt_dsc", "uacs_fundsubcat_dsc", "uacs_exp_dsc", "uacs_oper_dsc", "uacs_reg_id"],
"count": 8,
"description": "8 columns (dsc, amt, agency, department, fundcd, expense, operation unit, region)"
},
# 7 columns - using correct mappings with all available columns
{
"match_columns": ["dsc", "amt", "agency", "department", "fundcd", "uacs_exp_cd", "operunit"],
"display_columns": ["dsc", "amt", "uacs_agy_dsc", "uacs_dpt_dsc", "uacs_fundsubcat_dsc", "uacs_exp_dsc", "uacs_oper_dsc"],
"count": 7,
"description": "7 columns (dsc, amt, agency, department, fundcd, expense, operation unit)"
},
# 6 columns
{
"match_columns": ["dsc", "amt", "agency", "department", "fundcd", "uacs_exp_cd"],
"display_columns": ["dsc", "amt", "uacs_agy_dsc", "uacs_dpt_dsc", "uacs_fundsubcat_dsc", "uacs_exp_dsc"],
"count": 6,
"description": "6 columns (dsc, amt, agency, department, fundcd, expense)"
},
{
"match_columns": ["dsc", "amt", "agency", "department", "fundcd", "operunit"],
"display_columns": ["dsc", "amt", "uacs_agy_dsc", "uacs_dpt_dsc", "uacs_fundsubcat_dsc", "uacs_oper_dsc"],
"count": 6,
"description": "6 columns (dsc, amt, agency, department, fundcd, operation unit)"
},
{
"match_columns": ["dsc", "amt", "agency", "department", "uacs_exp_cd", "operunit"],
"display_columns": ["dsc", "amt", "uacs_agy_dsc", "uacs_dpt_dsc", "uacs_exp_dsc", "uacs_oper_dsc"],
"count": 6,
"description": "6 columns (dsc, amt, agency, department, expense, operation unit)"
},
# 5 columns
{
"match_columns": ["dsc", "amt", "agency", "department", "fundcd"],
"display_columns": ["dsc", "amt", "uacs_agy_dsc", "uacs_dpt_dsc", "uacs_fundsubcat_dsc"],
"count": 5,
"description": "5 columns (dsc, amt, agency, department, fundcd)"
},
{
"match_columns": ["dsc", "amt", "agency", "department", "uacs_exp_cd"],
"display_columns": ["dsc", "amt", "uacs_agy_dsc", "uacs_dpt_dsc", "uacs_exp_dsc"],
"count": 5,
"description": "5 columns (dsc, amt, agency, department, expense)"
},
{
"match_columns": ["dsc", "amt", "agency", "department", "operunit"],
"display_columns": ["dsc", "amt", "uacs_agy_dsc", "uacs_dpt_dsc", "uacs_oper_dsc"],
"count": 5,
"description": "5 columns (dsc, amt, agency, department, operation unit)"
},
# 4 columns
{
"match_columns": ["dsc", "amt", "agency", "department"],
"display_columns": ["dsc", "amt", "uacs_agy_dsc", "uacs_dpt_dsc"],
"count": 4,
"description": "4 columns (dsc, amt, agency, department)"
},
{
"match_columns": ["dsc", "amt", "agency", "fundcd"],
"display_columns": ["dsc", "amt", "uacs_agy_dsc", "uacs_fundsubcat_dsc"],
"count": 4,
"description": "4 columns (dsc, amt, agency, fundcd)"
},
{
"match_columns": ["dsc", "amt", "department", "fundcd"],
"display_columns": ["dsc", "amt", "uacs_dpt_dsc", "uacs_fundsubcat_dsc"],
"count": 4,
"description": "4 columns (dsc, amt, department, fundcd)"
},
# 3 columns
{
"match_columns": ["dsc", "amt", "agency"],
"display_columns": ["dsc", "amt", "uacs_agy_dsc"],
"count": 3,
"description": "3 columns (dsc, amt, agency)"
},
{
"match_columns": ["dsc", "amt", "department"],