~savoy/ade

ref: 90e5cadb9eafac71b1fe05077f790922dd067fd6 ade/ade/lib/remote.py -rw-r--r-- 118.8 KiB
90e5cadbsavoy bug: prior to Compile pivoting, NA cols are cleaned 2 months ago
                                                                                
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
# Main functions for pulling and modifying ade database information
# Copyright (C) 2018-2022 savoy

# This file is part of ade.
#
# ade is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ade is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ade. If not, see <http://www.gnu.org/licenses/>.

from __future__ import annotations
import builtins
from collections import defaultdict
import copy
import datetime as dt
import inspect
import logging
import os
from pathlib import Path
import platform
import re
import shutil
from typing import Any, Optional, Union

import numpy as np
import pandas as pd

from lib import (
    admin,
    connections,
    dates,
    formatting,
    local,
    mail,
    reports as rep,
    natural_keys as nk,
)
from lib.util import cleanup, data as util_data, sql

if platform.system() in ["Windows"]:
    import xlwings as xw


class _Parameters:
    """Subclass for Construct parameters, verifies the string pattern.

    Attributes
    ----------
    operators : str
        Pattern for allowed operators that map to their SQL equivalents.
    date_pt : re.Pattern
        Allowed date format (YYYY-MM) as ade works by close date.
    str_pt : re.Pattern
        General string pattern for "names" as <region> and <area>.
    int_pt : re.Pattern
        Integers are passed through initially as strings, this verifies they are
        actual ints.
    code_pt : re.Pattern
        General purpose pattern that includes any word character.
    cost_center_pt : re.Pattern
        BCs have a specific pattern that this verifies for.
    dept_pt : re.Pattern
        Departments have a specific pattern that this verifies for.
    division_pt : re.Pattern
        Divisions have a specific pattern that this verifies for.
    client_pt : re.Pattern
        Not currently used as the client pattern of US00001234 is not followed well
        with non-NAM clients.
    agreement_pt : re.Pattern
        Agreements have a specific pattern that this verifies for.
    acc_category_desc_pt : re.Pattern
        Accounting category descriptions have a specific pattern that this verifies for.
    account_pt : re.Pattern
        Accounting codes have a specific pattern that this verifies for.
    account_group_pt : re.Pattern
        Accounting groups have a specific pattern that this verifies for.
    account_category_pt : re.Pattern
        Accounting categories have a specific pattern that this verifies for.
    types : dict[str, re.Pattern]
        Collection of parameters that _Parameters checks for along with its
        required pattern.

    """

    # list of all pattern matches used for verifying user-input in _verify()
    operators = r"(<|>|<=|>=|!=|<>|)"
    date_pt = re.compile(r"^[0-9]{4}-[0-9]{2}$")
    str_pt = re.compile(r"^[A-Za-z. ]+$")
    int_pt = re.compile(r"^[0-9]+$")
    code_pt = re.compile(r"^[\w\W]+$")
    cost_center_pt = re.compile(r"^[A-Z]{2}[0-9]{3}$")
    dept_pt = re.compile(r"^[0-9]{3}$")
    division_pt = re.compile(r"^[A-Z]{3}[0-9]{3}$")
    client_pt = re.compile(r"^[A-Z]{2,4}[0-9]{6,8}$")
    agreement_pt = re.compile("^" + operators + r"[A-Z]{1}[0-9]{6}$")
    acc_category_desc_pt = re.compile(r"^[A-Z]{2,}$")
    account_pt = re.compile(r"^[0-9]{5}$")
    account_group_pt = re.compile(r"^[0-9]{4}$")
    account_category_pt = re.compile(r"^[0-9]{2}$")

    # Collection of all valid arguments and their valid string pattern for
    # verification.
    types = {
        "table": code_pt,
        "columns": code_pt,
        "date": date_pt,
        "joins": code_pt,
        "sql": code_pt,
        "clients": code_pt,
        "agreements": agreement_pt,
        "invoices": code_pt,
        "pos": int_pt,
        "departments": dept_pt,
        "region": str_pt,
        "area": str_pt,
        "businessUnit": str_pt,
        "costCenterCode": cost_center_pt,
        "location": str_pt,
        "category": account_category_pt,
        "categoryDesc": acc_category_desc_pt,
        "accountGroup": account_group_pt,
        "accountGroupDesc": str_pt,
        "account": account_pt,
        "accountIdDesc": str_pt,
        "productFamily": str_pt,
        "productLine": str_pt,
        "productCategory": code_pt,
        "productGroup": code_pt,
        "productCode": code_pt,
        "itemCode": code_pt,
        "individualItemNumber": code_pt,
        "purchaseOrderNbr": int_pt,
        "customerOrderNo": int_pt,
        "industryGrouping": code_pt,
        "industryDesc": code_pt,
        "industry": code_pt,
    }

    def to_dict(self) -> dict:
        """Converts all of the attributes into a key: value dictionary.

        Returns
        -------
        dict
            Parameters values.

        """
        params = {key: value for key, value in vars(self).items()}
        return params

    def to_list(self) -> list:
        """Converts all of the attributes into a (key, value) nested list.

        Returns
        -------
        list
            Parameters values.

        """
        params = [(key, value) for key, value in vars(self).items()]
        return params

    def _verify(self, arguments: dict) -> None:
        """Verifies each parameter value against its pattern and sets the attribute.

        Parameters
        ----------
        arguments : dict
            The parameters to verify.


        Attributes
        ----------
        *attributes : Any
            Set dynamically with `setattr`, an attribute for each parameter initialized.


        Raises
        ------
        AssertionError
            The specified column/value is not a valid entry.

        """
        for key, value in arguments.items():
            # To match the values together in one loop, converts any
            # non-dicts to dicts with the key as the parameter name.
            if type(value) != dict:
                # Sets string/int values as tuples of len to allow iteration
                if type(value) not in [list, tuple]:
                    value = (value,)
                iterator = {key: value}
            else:
                iterator = value

            for k, val in iterator.items():
                # Didn't want to do it, but have to have a special condition
                # where joins aren't checked against parameters as they're
                # technically not parameters to be used as no value is
                # defined. The join check happens in Query. Also does not
                # check against the currently unused 'sql' and the 'other'
                # parameters (as the latter can be used for any column).
                if key not in ["joins", "sql", "ors", "other"]:
                    assert k in self.types.keys(), (
                        f'"{k}" is not a valid SQL column to use as a ' "parameter."
                    )
                    for v in val:
                        assert re.match(self.types[k], v), (
                            f'"{v}" does not match its associated pattern'
                            " and therefore is not considered a valid "
                            f"value for {k}"
                        )

            setattr(self, key, value)


class _Query:
    """Subclass for Construct query, prepares the SQL statement.

    Attributes
    ----------
    matches : dict[str, Union[str, list[tuple[Union[str, re.Pattern]]]]]
        Parameters whose names do not match the SQL column; the value is the match.
    not_where : list[str]
        The parameters that are not to be constructed into WHERE statements.

    """

    # Matching column name choices for each of the non-dict parameters. Any
    # pairing which contains more than one value (i.e. more than one column
    # the key could be attributed with) MUST have the value be a list of
    # tuples of len 1. A tuple of len 2 are for cases (i.e. date) where the
    # values to be between are two different columns (e.g. validFromDate
    # and validToDate). The second tuple will consist of the the words to
    # substitute for the regex group. The different columns are taken into
    # account under _verify_where() as the only case this belongs to are for
    # date parameters.
    matches = {
        "date": [
            (re.compile(r"effective(\w{2,4})Date"), ("To", "From")),
            (r"accDateId",),
            (r"timeId",),
            (r"statisticsDateId",),
            (r"invoiceAccountingDateId",),
            (r"invoiceDateId",),
            (r"entryDateId",),
            (re.compile(r"valid(\w{2,4})DateId"), ("To", "From")),
            (r"creationDateId",),
            (r"createDateId",),
            (r"dateId",),
        ],
        "clients": "customerNumber",
        "agreements": "agreementNumber",
        "invoices": "invoiceNumber",
        "departments": "department",
        "divisions": "division",
    }

    # Parameters to not construct into the query WHERE statement
    not_where = ["table", "columns", "joins", "sql", "ors"]

    def _verify_join(self, arg_joins: dict[str, list[tuple[str, str]]]) -> None:
        """Creates the SQL join statements based off of _Parameters.joins.

        Parameters
        ----------
        arg_joins : dict[str, tuple[str, str]]
            The collection of JOINs to be used in the SQL query. Brought together
            through the Parameters class, consisting of the table to join (key)
            and the join values (tuple).


        Raises
        ------
        AssertionError
            The JOIN statement is not valid.

        """
        # Once passed verification, will now pull the full name of
        # the scope_table from the schema, as well as iterating
        # through the full list of tables (as the JOIN will not always
        # be on a column from the base table) to find the first table
        # where the column is in. This means that args.joins IS AN
        # ORDERED DICTIONARY and the joins must be in order as it
        # would be in a standard SQL query i.e. if you're joining
        # 2 columns into the base and the second one is dependent on
        # the first, they must be written in that order.
        for key, value in arg_joins.items():
            # Gets the full name of the table being joined (same process
            # as getting <self.table>) and its prefix.
            join_prefix: str = "".join(re.findall(r"([A-Z]\w{2})", key)).lower()
            join_table: str = (
                self.schema.loc[
                    self.schema.tableName == key, ["catalog", "modifier", "tableName"]
                ]
                .drop_duplicates()
                .agg(".".join, axis=1)
                .item()
            )

            # Calculates the prefix for the left-joined table, looking
            # for the table from the full list of <self.tables> (if it's
            # not equal to the <scope_table> of this loop i.e. if its
            # checking for costCenterCode, it won't do any good to join
            # the table its in with itself.
            first_table_list: list = [
                x
                for x in [y for y in self.tables if y != key]
                if x
                in self.schema.loc[
                    (self.schema.columnCamel == value[0][0])
                    & (self.schema.tableName == x),
                    "tableName",
                ].to_list()
            ]
            try:
                first_table: str = first_table_list[0]
            except IndexError:
                raise AssertionError(
                    f"The JOIN for table {key} is malformed; there is no "
                    f'column "{value[0]}" in any table outside of the base.'
                )

            first_prefix: str = "".join(
                re.findall(r"([A-Z]\w{2})", first_table)
            ).lower()

            # Pulls the actual name (not camel case) of the columns based
            # on <args.joins>.
            join_query = f" LEFT OUTER JOIN {join_table} {join_prefix} "
            for idx, v in enumerate(value):
                try:
                    first_name: str = self.schema.loc[
                        (self.schema.tableName == first_table)
                        & (self.schema.columnCamel == v[0]),
                        "columnName",
                    ].item()
                    second_name: str = self.schema.loc[
                        (self.schema.tableName == key)
                        & (self.schema.columnCamel == v[1]),
                        "columnName",
                    ].item()
                except ValueError:
                    raise AssertionError(
                        f"There is a problem joining {first_table} and {key} "
                        f"on the columns {v[0]} and {v[1]}."
                    )

                if idx == 0:
                    concatenator = "ON "
                else:
                    concatenator = "AND "

                join_query += f"{concatenator} {first_prefix}.{first_name} = {join_prefix}.{second_name} "

            # Appends the formulated JOIN string to the list of joins.
            self.joins[key] = join_query

    def _verify_column(
        self,
        arg_table: str,
        arg_cols: Union[list, dict],
        arg_where: bool = False,
        arg_joins: dict = None,
    ) -> None:
        """Creates the SQL select statements based off _Parameters.columns.

        Also verifies if columns being selected through a JOIN are valid, as
        well as the columns being used in the WHERE statement.

        Parameters
        ----------
        arg_table : str
            The base table used in the SQL query. From _Parameters.table.

        arg_cols : Union[list, dict]
            Can either be the list of SELECT columns from _Parameters.columns or the
            dictionary of WHERE columns from the full list of Parameters.to_dict()
            (excluding the keys of 'table', 'columns', and 'joins').

        arg_where : bool
            The needed flag to allow for arg_cols to be parsed as the parameters for
            the WHERE statement instead of as SELECT columns.

        arg_joins : dict
            The dictionary of JOINs from _Parameters.joins. Required for the
            preliminary checking of JOINs for columns in the SELECT statement that are
            brought in through that join. Not needed if running the verification for
            WHERE.


        Raises
        ------
        AssertionError
            The column is not valid.

        """
        # Splits up the column lists for those that are part of the base table
        # <local> and those that will be pulled from a JOIN <joins>.
        cols: list = self.schema.columnCamel.to_list()

        # Verifies if args.columns are all valid columns given the table,
        # combining them with self.prefix and self.table. Adds each column
        # individually in case of stupid fucking cases like "agreementnumber"
        # in the Revenue table instead of "agreementNumber", as it must use
        # the modified .lower() version.
        if type(arg_cols) != dict:
            iterator = {key: None for key in arg_cols}
        else:
            iterator = arg_cols

        for key, value in iterator.items():  # type: ignore - iterator is guaranteed dict above
            if key not in cols or key == "date":
                # If the check is of the argument parameters, part of the
                # WHERE statement.
                if type(value) in [list, tuple]:
                    try:
                        # As of now, only required for the date parameter as
                        # there are multiple "date" fields to choose from.
                        if type(self.matches[key]) == list:
                            for tup in self.matches[key]:
                                col_list: list = [
                                    y
                                    for y in cols
                                    if re.search(tup[0], y)
                                    and y
                                    in self.schema.loc[
                                        self.schema.tableName == self.tables[0],
                                        "columnCamel",
                                    ].to_list()
                                ]
                                if col_list:
                                    # Gets the matching column if the item
                                    # is in the base table.
                                    col: str = col_list[0]
                                    # Gets the second date tuple (see # for
                                    # <matches>) if needed.
                                    if key == "date":
                                        if len(tup) == 2:
                                            second_date: Optional[tuple] = tup[1]
                                        else:
                                            second_date = None
                                    break
                        else:
                            col: str = self.matches[key]

                        # Now that it's gotten the correct column name, checks
                        # if the column actually exists
                        assert col, f'"{key}" is missing a JOIN to be a valid ' "column"  # type: ignore - col not possibly unbound given above if/else
                        assert col in cols, f'"{col}" is not a valid SQL column'
                    except (IndexError, KeyError):
                        raise AssertionError(f'"{key}" is not a valid SQL column')
                    except UnboundLocalError as e:
                        print(
                            "Does this table have a correct and documented date field?"
                        )
                        raise e

                # If the column check is one for the SELECT statement
                else:
                    assert key.lower() in cols, f'"{key}" is not a valid SQL column'
                    col: str = key.lower()
            else:
                col: str = key

            # Up to this point, the column has been verified as corect. Now
            # its time to use the column name <key> as the AS nickname in SQL,
            # while self.schema will be used to lookup up the actual column
            # and table name (to get the prefix even if it's a join) and add
            # them to the query string. It prepares the data necessary to make
            # this happen, while the appending of the SQL column statement
            # will happen below, after it checks if its a join.
            col: str = f"^{col}$" if type(col) == str else col
            scope: pd.DataFrame = self.schema.loc[
                self.schema.columnCamel.str.contains(col)
            ].iloc[0]
            actual_name: str = scope.columnName
            scope_table: str = scope.tableName
            scope_prefix: str = "".join(
                re.findall(r"([A-Z]\w{2})", scope_table)
            ).lower()
            full_name: str = f"{scope_prefix}.{actual_name}"

            # One more check to see if this column is part of a join. The
            # column must be defined in args.joins, otherwise it raises an
            # exception. Then it will check if the items you're joining on
            # are valid items available in the tables being pulled as the base
            # or in the JOIN. Remember, the verification will check if a JOIN
            # is possible, NOT that it will give you the right data or that
            # the JOIN is the correct form. Further JOIN verification will
            # occur after the column checks.
            if scope_table != arg_table and arg_joins:
                assert (
                    scope_table in arg_joins.keys()
                ), f"{scope_table} has not been defined as a JOIN."
                for x in [item for t in arg_joins[scope_table] for item in t]:
                    assert x in cols, (
                        f'The JOIN for "{col}" is malformed; "{x}" is '
                        f"not a valid JOIN key for {scope_table}"
                    )

            # Adds the verified column to the collection for joining.
            if arg_where:
                self._verify_where(key, full_name, value, second_date)  # type: ignore - second_date not possibly unbound as it not existing is impossible due to exception raises
            else:
                self.columns[key] = f"{full_name} AS {key}"

    def _verify_where(
        self,
        key: str,
        column: str,
        value: Union[list, tuple],
        secondary: Union[None, tuple[str, str]],
    ) -> None:
        """Creates the SQL where statements based off of _Parameters.

        Run while still in the column loop of _verify_column, therefore each
        argument is a single value.

        Parameters
        ----------
        key : str
            The parameter name of the dictionary for the given WHERE statement
            e.g. the <dates> argument from Construct is the key for the date parameter.
        column : str
            The actual column name for the given parameter e.g. depending on the table,
            the <dates> argument's column could be re.accDateId i.e. the actual column
            in the ABI DB schema.
        value : Union[tuple, list]
            The actual parameter values to search for with the WHERE statement
            e.g. <dates> value would be ('1917-02', '1917-10').
        secondary : tuple[str, str]
            The second value fom self.matches for the corresponding date column,
            consisting of the strings to sub to create the second column.

        """
        # Checks for a value to be filtered against
        assert value, (
            f"The WHERE statement against column {column} does not "
            "have a value to set to. Check your Construct and try again"
        )

        # Initial list creation of the cleaned up and parsed WHERE parameters
        combo = []

        # Date is a special case scenario which adds the operators necessary
        # for the statement as it will always be >= and <= for a standard
        # date and >= and < for "range" dates (pulling any value with the
        # two date range between the parameter dates ie AgreementLines).
        if key == "date":
            if secondary:
                value = [">=" + x if n == 0 else "<" + x for n, x in enumerate(value)]
            else:
                value = [">=" + x if n == 0 else "<=" + x for n, x in enumerate(value)]

        multiple = True if len(value) > 1 else False
        where_concat = []
        param_concat = []
        for v in value:
            where, param = sql.operator(column, v, multiple=multiple)
            param_concat.append(param)
            where_concat.append(where)

        param_concat = tuple(param_concat)
        # Another Date special-case where it converts the original string
        # values to their ordinal dates necessary for proper filtering against
        # the date ID columns. This is also where (see # for class variable
        # <matches>) more special-case scenarios for date are taken into
        # account (i.e. if the date value must be in between 2 different
        # columns like validFromDate and validToDate).
        if key == "date":
            param_concat = dates.to_date_id(param_concat)
            if secondary:
                where_concat = [
                    x.replace(secondary[1], y) for x, y in zip(where_concat, secondary)
                ]
        combo.append(param_concat)

        if multiple:
            temp: str = "(" + "".join(where_concat)[:-4] + ") AND "
            combo.append(temp)
        else:
            combo.append(where_concat[0])

        self.where[column] = combo

    def _create(self, args: _Parameters) -> None:
        """The main work in _Query. Calls the other helper functions and creates the SQL.

        Parameters
        ----------
        args : _Parameters
            The cleaned parameters.


        Attributes
        ----------
        tables : tuple[str]
            All of the SQL tables to be accessed in order to construct the query.
        string : str
            The SQL query string itself to be built off of.
        columns : dict[str, str]
            The ade column name and its SELECT statement equivalent
        joins : dict[str, str]
            The table name and its JOIN statement equivalent
        where : dict[str, list[Union[tuple[int, int], tuple[str, ...]]]]
            The SQL column name along with both the parameter values to be injected and
            its corresponding WHERE statement.
        params : list[Union[int, str]]
            The full list of parameters to be injected into the SQL statement, in the correct
            order to match the WHERE statement.
        schema : pd.DataFrame
            The SQL schema of each table being accessed.
        table : str
            The full SQL name of the main table being accessed (which includes
            its catalog and its modifier).
        prefix : str
            The alias of <table> to be used in the SQL statement. Taken from the
            first 3 letters of each word as split by PascalCase (alias pascas).


        Raises
        ------
        AssertionError
            Whenever an error comes up in validating the SQL statement as correct.
            Validations are handled locally vs relying on the SQL server in order to
            minimize calls.

        """
        # Creates a total list of columns if joins have been defined as well
        # as the other instance variables: the query string to be appended and
        # the collections detailing the columns and joins.
        self.tables: tuple = args.table + tuple(args.joins.keys())  # type: ignore - can acccess .joins, it's just init'ed through loop
        self.string = "SELECT "
        self.columns = {}
        self.joins = {}
        self.where = {}
        self.params = []

        # Pulls in the schema for the given table, along with the necessary
        # columns needed to create the query correctly. Creates self.table
        # from the concatenation of the <catalog> and <modifier> columns, and
        # checks if the passed table exists if the schema is not empty.
        self.schema: pd.DataFrame = local.schema(  # type: ignore - pull=True, always a DF
            columns=[
                "catalog",
                "modifier",
                "tableName",
                "columnName",
                "columnCamel",
                "dataType",
            ],
            slicers={"tableName": self.tables},
        )
        # Before continuing, the schema table will be ordered with the base table first
        # followed by the joins ordered as they are in reports.yaml
        self.schema["tableName_cat"] = pd.Categorical(self.schema["tableName"], categories=self.tables, ordered=True)  # type: ignore - pull=True, always a DF
        self.schema.sort_values("tableName_cat", inplace=True)  # type: ignore - pull=True, always a DF

        tbls: list = self.schema.tableName.drop_duplicates().to_list()
        for t in self.tables:
            assert t in tbls, f'"{t}" is not a valid SQL table.'

        # Gets the catalog.modifier for the tables to be pulled. Includes
        # joins prior to their verification as they get verified during
        # column creation.
        self.table: str = (
            self.schema.loc[
                self.schema.tableName == args.table[0],  # type: ignore - can acccess .joins, it's just init'ed through loop
                ["catalog", "modifier", "tableName"],
            ]
            .drop_duplicates()
            .agg(".".join, axis=1)
            .item()
        )

        # Sets the table prefix created from args.table to prepare for it to
        # be added to the query string.
        self.prefix: str = "".join(re.findall(r"([A-Z]\w{2})", args.table[0])).lower()  # type: ignore - can acccess .joins, it's just init'ed through loop

        # Column verification and additions to the query string
        self._verify_column(args.table[0], args.columns, arg_joins=args.joins)  # type: ignore - can acccess .joins, it's just init'ed through loop
        self.string += ", ".join(self.columns.values())
        self.string += f" FROM {self.table} {self.prefix}"

        # Join verification and addition to the query string
        self._verify_join(args.joins)  # type: ignore - can acccess .joins, it's just init'ed through loop
        self.string += " ".join(self.joins.values())

        # Parsing of the WHERE parameters from the full list of arguments
        wheres = {}
        for key, value in args.to_dict().items():
            if key not in self.not_where:
                if type(value) == dict:
                    for k, v in value.items():
                        wheres[k] = v
                else:
                    wheres[key] = value

        # Where verification and addition to the query string
        self._verify_column(args.table[0], wheres, arg_where=True)  # type: ignore - can acccess .joins, it's just init'ed through loop
        self.string += " WHERE "
        for key, value in self.where.items():
            # Adds the tupled paramter to the parameter list
            self.params.extend(value[0])
            # Adds the string query statement
            self.string += value[1]

        # Final special case. Any column listed in `ors` from Construct
        # will be combined with an OR instead of an AND. The only case
        # this comes up in is when pulling for national accounts, as you
        # need to get the lines where the customer number is X or (meaning
        # as well as) when the agreement number is Y, not a combination
        # drill down of them both. IT RELIES ON ORDER so the two WHERE
        # filters (e.g. clients and agreements) must be next to each other in
        # the parameter listing.
        try:
            if args.ors:  # type: ignore - can acccess .joins, it's just init'ed through loop
                actual_cols = []
                for x in args.ors:  # type: ignore - can acccess .joins, it's just init'ed through loop
                    for y in x:
                        z = re.findall(f"([A-Za-z._0-9]+) AS {y}", self.string)[0]
                        actual_cols.append(z)

                # Sets the `ors` connection as OR instead of AND
                self.string = self.string.replace(
                    f"{actual_cols[0]}=?) AND ({actual_cols[1]}",
                    f"{actual_cols[0]}=?) OR ({actual_cols[1]}",
                )

                # Encloses the OR items within parenthesis so they can be
                # viewed as one (e.g. both will be affected by the TIME
                # statement instead of just the first; noticed in the national
                # account report.
                self.string = self.string.replace(
                    f"({actual_cols[0]}=?", f"(({actual_cols[0]}=?"
                )
                self.string = self.string.replace(
                    f"{actual_cols[1]}=?)", f"{actual_cols[1]}=?))"
                )
        except AttributeError:
            pass

        self.string = self.string[:-5]


class Construct:
    """Parses, validates, and constructs the passed SQL parameters and columns."""

    def __init__(
        self,
        table: str,
        columns: list[str],
        date: tuple[str, str],
        joins: dict[str, list[tuple[str, str]]] = {},
        clients: list[str] = None,
        agreements: list[str] = None,
        invoices: list[str] = None,
        departments: list[str] = None,
        pos: dict[str, list[str]] = None,
        regions: dict[str, list[str]] = None,
        accounts: dict[str, list[str]] = None,
        products: dict[str, list[str]] = None,
        sectors: dict[str, list[str]] = None,
        other: dict[str, list[Union[str, int]]] = None,
        ors: list[tuple[str, str]] = None,
        sql: dict[str, list[str]] = None,
    ):
        """Sets up the argument validation based on given criteria, further
        setting up the SQL query to run.

        Parameters
        ----------
        table : str
            The name of the table to pull from the CorporateODS SQL server
        columns : list[str]
            Collection of table columns to be pulled (includes columns obtained
            through JOINs).
        date : tuple[str, str]
            The date range for the SQL pull. Must be in YYYY-MM format, and will be
            further converted to create the params.ordate attribute.
        joins : dict[str, tuple[str, str]], optional
            Collection of the column to join and a tuple of the two columns to be
            joined on.
        clients : list[str], optional
            Collection of customerNumber to be parameterized.
        agreements : list[str], optional
            Collection of agreementNumber to be parameterized.
        invoices : list[str], optional
            Collection of invoiceNumber to be parameterized.
        departments : list[str], optional
            Collection of department to be parameterized.
        divisions : list[str], optional
            Collection of division to be parameterized.
        pos : dict[str, list[str]], optional
            Collection of customerOrderNo OR purchaseOrderNo to be parameterized.
        regions : dict[str, list[str]], optional
            Collection of the specific region column and a list of its values to be
            parameterized. The keys can be any of the following: region, area,
            businessUnit, or costCenterCode.
        accounts : dict[str, list[str]], optional
            Collection of the specific accounting code column and a list of its values
            to be parameterized. The keys can be any of the following: category,
            categoryDesc, accountGroup, accountGroupDesc, account, or accountIdDesc.
        products : dict[str, list[str]], optional
            Collection of the specific product column and a list of its values to be
            parameterized. The keys can be any of the following: productFamily, productLine,
            productCategory, productGroup, productCode, itemCode, or individualItemNumber.
        sectors : dict[str, list[str]], optional
            Collection of the specific sector column and a list of its values to be
            parameterized. The keys can be any of the following: industryGroup, industry,
            or aicCode.
        other : dict[str, list[Union[str, int]]], optional
            Collection of any other column and the values to be parameterized.
        ors : list[tuple[str, str]], optional
            Special case parameter. WHERE statements for a column are joined with OR,
            while those columns WHEREs are combined with an AND to other WHEREs. This overrides
            it so that the listed columns in the tuple are combined with an OR instead.
            Required for certain SQL queries (e.g. national hierarchy).
        sql : dict[str, list[str]], optional
            Specific modifiers to be used in the SQL query.
            e.g. SELECT : [DISTINCT] or GROUP BY: [<columns>...]


        Attributes
        ----------
        params : _Parameters
            The cleaned parameters of _Parameters.
        query : _Query
            The verified parameters of _Query.

        """
        # Initialization of the sub-classes where all of the SQL argument
        # attributes and query information will be stored.
        self.params = _Parameters()
        self.query = _Query()

        # Creates the parameter attributes through the Parameters subclass,
        # verifying and parsing through the user-input.
        args = {
            key: value
            for key, value in locals().items()
            if key not in ("self") and value
        }

        # Bug fix with new dataclass additions in reports, at this point joins can still be None and therefore not exist as a param despite it should
        if "joins" not in args:
            args["joins"] = {}

        self.params._verify(args)
        self.query._create(self.params)

    def __repr__(self) -> str:
        return (
            f"{self.query.table}(Columns: {len(self.query.columns)}, "
            f"Joins: {len(self.query.joins)}, "
            f"Parameters: {len(self.query.params) - 2}, "
            f"Date: {self.params.date})"  # type: ignore - can acccess .date, it's just init'ed through loop
        )

    def _metadata(
        self,
    ) -> dict[str, Union[str, list[str]]]:
        """Prepares the metadata of the class to easily insert into the spreadsheet output."""
        metadata = {
            "class": "Construct",
            "query": self.query.string,
            "params": self.query.params,
        }

        return metadata

    def pull(
        self, pull_methods: list[str] = None, post_methods: list[str] = None
    ) -> Output:
        """Calls Output and pulls the SQL data given the Construct.

        Parameters
        ----------
        pull_methods : list[str], optional
            Additional pull methods to run with Output. Overrides Report if initialized
            with Super.
        post_methods : list[str], optional
            Additional post methods to run with Output. Overrides Report if initialized
            with Super.

        """
        try:
            self.report  # type: ignore - self.report only exists if Construct initialized as Super
        except AttributeError:
            pass
        else:
            if not pull_methods:
                pull_methods = self.report.function.pull  # type: ignore - therefore if Super and no methods override, uses Report methods
            if not post_methods:
                post_methods = self.report.function.post  # type: ignore - therefore if Super and no methods override, uses Report methods

        return Output(self, pull_methods=pull_methods, post_methods=post_methods)


class Super(Construct):
    """Overrider for Construct to make an easy way to Construct off a given Report config."""

    def __init__(self, report: rep.Report):
        """Initializes Construct with the prepared arguments of a Report.

        Parameters
        ----------
        report : rep.Report
            A Report configuration.


        Attributes
        ----------
        report : rep.Report
            A Report configuration.

        """
        self.report = report
        super().__init__(
            **self.report.required.__dict__, **self.report.optional.__dict__
        )


class Output:
    """Runs the SQL query and any additional functions to complement the data."""

    def __init__(
        self,
        construct: Union[Construct, Super],
        pull_methods: list[str] = None,
        post_methods: list[str] = None,
    ):
        """Manages the initial SQL query pull and queues the pull/post methods to run.

        Parameters
        ----------
        construct : Union[Construct, Super]
            The Construct object.
        pull_methods : list[str], optional
            Additional pull methods to run.
        post_methods : list[str], optional
            Additional post methods to run.


        Attributes
        ----------
        construct : Union[Construct, Super]
            The Construct object.
        pull_methods : list[str], optional
            Additional pull methods to run.
        post_methods : list[str], optional
            Additional post methods to run.
        df : pd.DataFrame
            The data of the main Construct query pull.
        report : rep.Report
            The Report if initialized with Super. Otherwise a generic adhoc Report
            is generated with the Construct parameters specified.

        """
        self.construct = construct
        self.pull_methods = pull_methods
        self.post_methods = post_methods
        self.df: pd.DataFrame = self.get()

        # No construct.report means it's a Super, blank adhoc report to be created
        try:
            self.report = self.construct.report  # type: ignore - report attribute may not exist, try/except catches
        except AttributeError:
            params = self.construct.params.to_dict()
            self.report = rep.Report(
                parent=rep.Parent(
                    "adhoc",
                    "__adhoc__",
                    ".xlsx",
                    "Data pull or un-templated adhoc report",
                    None,
                ),
                name="adhoc",
                key="adhoc",
                filename=f'{dt.datetime.today().strftime("%Y-%m-%dT%H%M%S")}_adhoc',
                structure=None,
                email=None,
                required=rep.RequiredArgs(
                    params["table"], params["columns"], params["date"]
                ),
                optional=rep.OptionalArgs(
                    **rep.fill_unused_optional_args(
                        {
                            key: value
                            for key, value in params.items()
                            if key not in ("table", "columns", "date")
                        }
                    )
                ),
                function=rep.FunctionArgs([], []),
                pivot=[],
                compilate=rep.CompilateArgs({}),
            )

        self._change_data_types()
        queue = self._process_methods()

        if queue:
            self._join_methods(queue)

        # shitty hack to take FunctionArgs.post into account
        if self.post_methods:
            for meth in self.post_methods:
                self.df = globals()[meth](self.df)

    def __repr__(self) -> str:
        table_shortname = re.findall(
            r"(?:\.)([A-Za-z0-9]+)$", self.construct.query.table
        )[0]

        types = defaultdict(int)
        for col in self.df.columns:
            types[self.df[col].dtype.name] += 1
        type_descriptions = ", ".join(
            [f"{key}({value})" for key, value in types.items()]
        )

        size = self.df.memory_usage().sum()  # type: ignore - .sum() is known, pandas has no type hinting
        power = 2 ** 10
        n = 0
        power_labels = {0: "", 1: "K", 2: "M", 3: "G", 4: "T", 5: "P"}
        while size > power:
            size /= power
            n += 1
        size_label = power_labels[n] + "B"

        return (
            f"{table_shortname}("
            f"Indices: {len(self.df.index)} "
            f"[dtype: {self.df.index.dtype.name}], "
            f"Columns: {len(self.df.columns)} "
            f"[dtypes: {type_descriptions}], "
            f"Memory usage: {int(size)}+ {size_label})"
        )

    def _metadata(
        self,
    ) -> dict[
        str,
        Union[
            str,
            list[str],
            tuple[str, str],
            dict[str, Union[list[Union[int, str]], tuple[str, str]]],
        ],
    ]:
        """Prepares the metadata of the class to easily insert into the spreadsheet output."""
        metadata = {
            "class": "Output",
            "parent": self.report.parent.key,
            "report": self.report.key,
            **self.report.required.__dict__,
            **self.report.optional.__dict__,
            **self.report.function.__dict__,
        }

        return metadata

    def _change_data_types(self):
        """Changes the data types to their correct versions as per the schema.

        This functionality isn't part of pd.read_sql in a way that's comparable to
        pd.read_csv so it must be done after the fact.

        """
        # Changes the data types to their correct versions as that
        # functionality isn't implemented in read_sql (compare to
        # read_csv where you can convert to dtypes).
        types = (
            self.construct.query.schema.loc[
                self.construct.query.schema.columnCamel.isin(self.df.columns),
                ["columnCamel", "dataType"],
            ]
            .drop_duplicates(["columnCamel"])
            .to_dict(orient="list")
        )
        types = dict(zip(types["columnCamel"], types["dataType"]))

        # Does the special-case Decimal convert for money values, also filling
        # NaN values with 0 before doing so
        decimals = {k: v for k, v in types.items() if v == "Decimal"}
        dtypes = {k: v for k, v in types.items() if v != "Decimal"}
        self.df = util_data.convert_decimal(self.df, cols=list(decimals.keys()))
        self.df = self.df.astype(dtype=dtypes)

        # If a dateId column is present, convert it to datetime from the number
        # so that it takes the difference between SQL and Excel
        for col in self.df.columns:
            if "DateId" in col or "dateId" in col:
                self.df[col] = self.df[col].map(lambda x: dates.from_excel(x, sql=True))

    def _process_methods(
        self,
    ) -> Optional[list[tuple[pd.DataFrame, Union[tuple[str, str], str], str]]]:
        """Loads the queue with the output of any pull methods to be run.

        The queue is run in the order the methods are specified. Returns None if
        no pull methods were given.

        Returns
        -------
        Optional[list[tuple[pd.DataFrame, Union[tuple[str, str], str], str]]]
            Includes the data output as well as the columns to merge onto Output.df
            and additional cleanup functions.

        """
        if not self.pull_methods:
            return None

        queue = []
        for method in self.pull_methods:
            queue.append(getattr(self, method)(init=True))

        return queue

    def _join_methods(
        self, queue: list[tuple[pd.DataFrame, Union[tuple[str, str], str], str]]
    ):
        """Takes the finalized queue to merge onto Output.df and cleanup.

        Parameters
        ----------
        queue : list[tuple[pd.DataFrame, Union[tuple[str, str], str], str]]
            Includes the data output as well as the columns to merge onto Output.df
            and additional cleanup functions.

        """
        post_init_queue = []

        for proc in queue:
            try:
                temp = proc[0]
            except TypeError:
                continue

            merger = proc[1]
            cleaning_method = proc[2]

            try:
                self.df = self.df.merge(temp, how="left", on=merger, validate="m:1")
            except (TypeError, KeyError):
                if type(temp) == str:
                    post_init_queue.append(proc)
            finally:
                try:
                    self.df = getattr(cleanup, cleaning_method)(self.df)
                except AttributeError:
                    pass

        for proc in post_init_queue:
            getattr(self, proc)(init=False)

    def _assert_column_existence(self, cols: tuple, built: str, method: str) -> bool:
        """Verifies if the needed columns are present in Output.df for the pull method.

        Parameters
        ----------
        cols : tuple
            The columns required for the pull method.
        build : str
            The builtin to verify the columns vs Output.df.columns (any, all).
        method : str
            The method this function was called from. Needed for the logger warning.


        Returns
        -------
        bool
            True if the columns exist in Output.df, False if not.


        Raises
        ------
        AttributeError
            The builtin function does not exist. Needs to be `any` or `all`.

        """
        if not getattr(builtins, built)([x for x in cols if x in self.df.columns]):
            logging.warning(
                f'The column(s) ({" ,".join(cols)}) area not present in the '
                f"DataFrame. {method} cannot be compiled."
            )
            return False
        else:
            return True

    def get(self) -> pd.DataFrame:
        """Pulls the SQL query from the given Construct.

        Returns
        -------
        pd.DataFrame

        """
        with connections.Sql("new") as conn:
            df = pd.read_sql(
                self.construct.query.string, conn, params=self.construct.query.params
            )

        return df

    def compile(
        self,
        compilate_args: rep.CompilateArgs = None,
        pivot_args: list[rep.PivotArgs] = None,
        include_data: bool = False,
    ) -> Compile:
        """Calls Compile to modify the data given its Report specification.

        Parameters
        ----------
        compilate_args : rep.CompilateArgs, optional
            The args required for Compile. If None, uses the specified
            Construct.report.CompilateArgs.

        pivot_args : list[rep.PivotArgs], optional
            The arguments to pass in order to create a PivotTable.

        include_data : bool
            Saves the original dataframe in the compiled output.


        Returns
        -------
        Compile

        """
        if compilate_args:
            self.report.compilate = compilate_args
        if pivot_args:
            self.report.pivot = pivot_args

        return Compile(self, include_data=include_data)

    def file(self, open_file: bool = False, filename: str = "") -> File:
        """Calls File to finalize the report into a spreadsheet and save the file.

        In reality a helper to quicky get to File as this method still calls compile().

        Parameters
        ----------
        open_file : bool
            To specify if the report should be created and saved in the background or
            opened up for the user to modify.

        filename : str, optional
            The override for the report filename. If "", will default.


        Returns
        -------
        File

        """
        return self.compile().file(open_file, filename)

    def get_usage(self, index: list) -> Optional[pd.DataFrame]:
        """Calculates a usage dataframe.

        Will only run if Construct.query.table == FleetUtilisation as that data is
        required in order to calculate usage.

        Parameters
        ----------
        index : list
            The columns to be used as the index in the outputted PivotTable.


        Returns
        -------
        pd.DataFrame, optional
            The calculated usage dataframe. Will return None if unable to calculate.

        """
        # The necessary columns to run for the query and/or check against
        if not self.construct.query.table == "CorporateODS.fle.FleetUtilisation":
            print("Usage must be calculated on the FleetUtilisation table")
            return None
        else:
            # Make sure needed joins and cols are included
            assert all(
                map(
                    lambda v: v in self.construct.query.joins.keys(),
                    ["ProductHierarchy", "Time"],
                )
            ), "ProductHierarchy and Time are required joins"

        if not self._assert_column_existence(
            ("daysOnhire", "usRating", "financialYear", "financialPeriod"),
            "all",
            "usage",
        ):
            return None

        usage = self.df.pivot_table(
            index=index + ["financialYear", "financialPeriod"],
            values=["daysOnhire"],
            aggfunc="sum",
        ).reset_index()
        usage = dates.days_in_month(usage, "financialYear", "financialPeriod")
        usage["usage"] = usage["usRating"] * (
            usage["daysOnhire"] / usage["daysInMonth"]
        )

        usage = usage.pivot_table(
            index=index,
            values=["usage"],
            columns=["financialYear", "financialPeriod"],
            aggfunc="mean",
        )

        return usage

    def get_rate(self, output: Output) -> Optional[pd.DataFrame]:
        """Calculates a rate dataframe IN PROGRESS.

        Parameters
        ----------
        output : Output


        Returns
        -------
        pd.DataFrame, optional

        """
        # TODO
        if not self._assert_column_existence(
            ("usdRevenue", "earnedRevenueUsd", "account"), "any", "rate"
        ):
            return None

        if not self.is_usage:
            print("Usage is required. Calculating...")
            self.usage()

        revenue = (
            "usdRevenue" if "usdRevenue" in self.df.columns else "earnedRevenueUsd"
        )

        rate = self.df.copy()
        rate["rate"] = rate[revenue] / rate["usage"] / rate["weeksInMonth"]

        rate = util_data.remove_column_duplicates(rate)
        rate.drop(
            index=rate.loc[
                (rate["rate"].isin([pd.NA, np.NaN, np.inf, -np.inf]))
                | (rate[revenue] <= 0)
                | ((rate["account"] < "50000") | (rate["account"] > "50400"))
            ].index,
            inplace=True,
        )

        return rate

    def parent(self, init: bool = False) -> Optional[tuple[pd.DataFrame, str, str]]:
        """Pulls the national account hierarchy into Output.df.

        The customerNumber column must be present in the dataframe in order to pull.

        Parameters
        ----------
        init : bool, default=False
            If True, the data and its instruction set are queued by __init__ to be processed.
            False will join the output immediately with the dataframe.


        Returns
        -------
        Optional[tuple[pd.DataFrame, str, str]]

        """
        if not self._assert_column_existence(("customerNumber",), "all", "parent"):
            return None

        temp: pd.DataFrame = local.get(
            "national",
            "Hierarchy",
            slicers={
                "customerNumber": (self.df.customerNumber.drop_duplicates().to_list())
            },
        ).reset_index()  # type: ignore - output is always DF; list only occurs if cols=True is passed

        queue = (temp, "customerNumber", "parent")
        if init:
            return queue
        else:
            self._join_methods([queue])

    def site(
        self, init: bool = False
    ) -> Optional[tuple[pd.DataFrame, tuple[str, str], str]]:
        """Pulls the agreement site into Output.df.

        The customerNumber and agreementNumber columns must be present in the dataframe
        in order to pull.

        Parameters
        ----------
        init : bool, default=False
            If True, the data and its instruction set are queued by __init__ to be processed.
            False will join the output immediately with the dataframe.


        Returns
        -------
        Optional[tuple[pd.DataFrame, tuple[str, str], str]]

        """
        if not self._assert_column_existence(
            ("agreementNumber", "customerOrderNo"), "all", "site"
        ):
            return None

        temp: pd.DataFrame = local.sites()  # type: ignore - pull=True, always a DF

        queue = (temp, ("agreementNumber", "customerOrderNo"), "site")
        if init:
            return queue
        else:
            self._join_methods([queue])  # type: ignore - doing that Literal[str] thing

    def product(self, init: bool = False) -> Optional[tuple[pd.DataFrame, str, str]]:
        """Pulls the product information into Output.df.

        Either the productCode, itemCode, or individualItemNumber columns must be present
        in the dataframe in order to pull.

        Parameters
        ----------
        init : bool, default=False
            If True, the data and its instruction set are queued by __init__ to be processed.
            False will join the output immediately with the dataframe.


        Returns
        -------
        Optional[tuple[pd.DataFrame, str, str]]

        """
        codes = [
            ("productCode", "product"),
            ("itemCode", "item"),
            ("individualItemNumber", "individual"),
        ]
        for idx, col in enumerate(codes):
            if col[0] in self.df.columns:
                if not self._assert_column_existence((col[0],), "all", "product"):
                    return None

                self.product_codes = codes[: idx + 1]
                pr = local.products(key=col[1]).reset_index()  # type: ignore - pull=True, always a DF
                queue = (pr, col[0], "product")
                break

        try:
            queue  # type: ignore - unbound duh-doy that's why there's a try/except
        except UnboundLocalError:
            logging.warning("Product or item code required.")
            return None

        if init:
            return queue  # type: ignore - unbound will properly die
        else:
            self._join_methods([queue])  # type: ignore - unbound will properly die

    def location(
        self, init: bool = False
    ) -> Optional[tuple[Optional[pd.DataFrame], Optional[str], str]]:
        """Pulls the agreement location/address information into Output.df.

        The agreementNumber and customerNumber columns must be present in the dataframe
        in order to pull.

        Parameters
        ----------
        init : bool, default=False
            If True, the data and its instruction set are queued by __init__ to be processed.
            False will join the output immediately with the dataframe.


        Returns
        -------
        Optional[tuple[pd.DataFrame, Optional[str], str]]

        """
        # The necessary columns to run for the query and/or check against
        need = [
            "agreementNumber",
            "customerNumber",
            "siteAddress1",
            "siteAddress3",
            "siteAddress4",
        ]

        if not self._assert_column_existence(
            ("agreementNumber", "customerNumber"), "all", "location"
        ):
            return None

        # Checks if there are columns that are required for location that are
        # missing. If they are, the full location needs to be pulled. Creates
        # a Construct object which will be pulled further down.
        if not all(col in self.df.columns for col in need):
            joins = {
                "Customer": [("customerId", "customerId")],
                "AgreementLines": [("agreementHeaderId", "agreementHeaderId")],
            }
            if len(values := self.df.customerNumber.drop_duplicates().to_list()) > 2100:
                params = {"regions": {"region": ["North America"]}}
                joins["BusinessHierarchy"] = (
                    "businessHierarchyId",
                    "businessHierarchyId",
                )
            else:
                params = {"clients": values}
            queue = (
                Construct(
                    "AgreementHeader",
                    need,
                    ("2000-01", self.construct.params.date[1]),  # type: ignore - params made implicitly through loop
                    joins=joins,
                    **params,
                )
                .pull(pull_methods=("location",))
                .df,
                "agreementNumber",
                "location",
            )

        # Checks if the only columns present in the DataFrame are those
        # required for location, meaning it's either a one-off pull for
        # location data or this is recurisve and part of the merge process
        # spawned from the first if statement above. If so, it prepares the
        # DataFrame by dropping duplicates so that the merge will work.
        elif set(self.df.columns.to_list()) == set(need):
            self.df.drop_duplicates(subset="agreementNumber", inplace=True)  # type: ignore - Literal trash, will always be DF
            queue = (None, None, "location")

        # Will hold True if the columns in need already exist in the
        # DataFrame (like if pulling AgreementLines with the right columns).
        # Will pass the necessary data into the constructors list so that
        # the location cleanup will still happen.
        else:
            queue = (pd.DataFrame(), "agreementNumber", "location")

        if init:
            return queue  # type: ignore - more Literal trash
        else:
            self._join_methods([queue])  # type: ignore - more Literal trash

    def opptype(
        self, init: bool = False
    ) -> Optional[tuple[Optional[pd.DataFrame], Optional[str], str]]:
        """Pulls the Salesforce opportunity type into Output.df.

        The agreementNumber column must be present in the dataframe in order to pull.

        Parameters
        ----------
        init : bool, default=False
            If True, the data and its instruction set are queued by __init__ to be processed.
            False will join the output immediately with the dataframe.


        Returns
        -------
        Optional[tuple[pd.DataFrame, Optional[str], str]]

        """
        # The necessary columns to run for the query and/or check against
        need = ["agreementNumber", "opportunityType", "opportunityTypeDesc"]

        if not self._assert_column_existence(("agreementNumber",), "all", "opptype"):
            return None

        # Checks if there are columns that are required for location that are
        # missing. If they are, the full location needs to be pulled. Creates
        # a Construct object which will be pulled further down.
        if not all(col in self.df.columns for col in need):
            param = self.df.agreementNumber.drop_duplicates().to_list()
            queue = (
                Construct(
                    "CRM_Opportunity",
                    need,
                    ("2000-01", self.construct.params.date[1]),  # type: ignore - params made implicitly through loop
                    agreements=param,
                    joins={
                        "CRM_OpportunityType": [
                            (
                                "crmOpportunityTypeId",
                                "crmOpportunityTypeId",
                            )
                        ]
                    },
                )
                .pull(pull_methods=("opptype",))
                .df,
                "agreementNumber",
                "opportunity",
            )

        # Checks if the only columns present in the DataFrame are those
        # required for location, meaning it's either a one-off pull for
        # location data or this is recurisve and part of the merge process
        # spawned from the first if statement above. If so, it prepares the
        # DataFrame by dropping duplicates so that the merge will work.
        elif set(self.df.columns.to_list()) == set(need):
            self.df.drop_duplicates(subset="agreementNumber", inplace=True)  # type: ignore - Literal trash, will always be DF
            queue = (None, None, "opportunity")

        # Will hold True if the columns in need already exist in the
        # DataFrame (like if pulling AgreementLines with the right columns).
        # Will pass the necessary data into the constructors list so that
        # the location cleanup will still happen.
        else:
            queue = (pd.DataFrame(), "agreementNumber", "opportunity")

        if init:
            return queue  # type: ignore - more Literal trash
        else:
            self._join_methods([queue])  # type: ignore - more Literal trash

    def po_expiry(self, init: bool = False) -> Optional[tuple[pd.DataFrame, str, str]]:
        """Pulls the PO Expiry information into Output.df.

        The agreementNumber column must be present in the dataframe in order to pull.
        This is the only method in ade which calls the old ABIODSQuery.adenet.biz
        SQL database instead of the new CorporateODS database. This old DB is less
        reliable and prone to timeouts.

        Parameters
        ----------
        init : bool, default=False
            If True, the data and its instruction set are queued by __init__ to be processed.
            False will join the output immediately with the dataframe.


        Returns
        -------
        Optional[tuple[pd.DataFrame, str, str]]

        """
        if not self._assert_column_existence(("agreementNumber",), "all", "po_expiry"):
            return None

        param = self.df.agreementNumber.drop_duplicates().to_list()

        where = "BHAGCN = ? OR "

        # Sets up WHERE expression for insertion into SQL query
        where = (len(param) * where)[:-4]

        # Query for client revenue
        string = f"""
                SELECT DISTINCT
                BHAGNB as agreementNumber, BHCFJ1 as poExpiryDate

                FROM ABIODS.dbo.STAGHE
                WHERE {where}
                """

        # Query pull
        with connections.Sql("old") as conn:
            temp = pd.read_sql(string, conn, params=param)

        queue = (temp, "agreementNumber", "po_expiry")
        if init:
            return queue
        else:
            self._join_methods([queue])

    def product_description(self, init: bool = False) -> Optional[str]:
        """Creates the productDescription column to merge into Output.df.

        The productGroup and productCategory columns must be present in the dataframe
        in order to create.

        Parameters
        ----------
        init : bool, default=False
            If True, None is outputted as it directly modifies Output.df and does not
            need to be processed as a pull_method. False will not return anything for
            the same reason.


        Returns
        -------
        Optional[str]

        """
        frame = inspect.currentframe()
        whoami = inspect.getframeinfo(frame).function

        if init:
            return whoami
        else:
            self.df["productDescription"] = (
                self.df.productGroup + " - " + self.df.productCategory
            )

    def triple_shift(self, init: bool = False) -> Optional[str]:
        """Adds columns checking if triple shift has been charged on agremeent
        line equipment.

        The rateTypeDescription, netRate, fullWeeks, noOfOnhireDays, lineAmount, and
        shifts columns must be present in the dataframe in order to create.

        Parameters
        ----------
        init : bool, default=False
            If True, None is outputted as it directly modifies Output.df and does not
            need to be processed as a pull_method. False will not return anything for
            the same reason.


        Returns
        -------
        Optional[str]

        """
        frame = inspect.currentframe()
        whoami = inspect.getframeinfo(frame).function

        if init:
            return whoami
        else:
            self.df["calculatedAmount"] = np.select(
                [
                    self.df.rateTypeDescription.isin(
                        ["Month", "Best Price", "Periodic"]
                    ),
                    self.df.rateTypeDescription == "Week",
                    self.df.rateTypeDescription == "Day",
                ],
                [
                    self.df.netRate * (self.df.fullWeeks / 4),
                    self.df.netRate * self.df.fullWeeks,
                    self.df.netRate * self.df.noOfOnhireDays,
                ],
                0,
            )

            self.df["checkTriple"] = np.select(
                [
                    (self.df.calculatedAmount < (self.df.lineAmount / 1.5))
                    & (self.df.calculatedAmount != 0),
                    self.df.calculatedAmount > (self.df.lineAmount * 1.5),
                ],
                ["Triple Shift Charged", "Triple Shift NOT Charged"],
                pd.NA,
            )

            self.df["ifTripleCharged"] = np.where(
                (self.df.shifts == 3) & (self.df.checkTriple != "Triple Shift Charged"),
                self.df.lineAmount * 2,
                self.df.lineAmount,
            )

    def fuel_tank(self, init: bool = False) -> Optional[str]:
        """Creates the fuelTank column to merge into Output.df.

        The itemDescription, agreementNumber, and individualItemNumber columns must be
        present in the dataframe in order to create.

        Parameters
        ----------
        init : bool, default=False
            If True, None is outputted as it directly modifies Output.df and does not
            need to be processed as a pull_method. False will not return anything for
            the same reason.


        Returns
        -------
        Optional[str]

        """

        frame = inspect.currentframe()
        whoami = inspect.getframeinfo(frame).function

        if init:
            return whoami
        else:
            ft = self.df.loc[
                self.df["itemDescription"].str.contains("Fuel Tank"),
                ["agreementNumber", "individualItemNumber"],
            ].copy()
            ft.rename(columns={"individualItemNumber": "fuelTank"}, inplace=True)
            ft.drop_duplicates(subset="agreementNumber", inplace=True)
            self.df = self.df.merge(ft, how="left", on="agreementNumber")

    def power_source(self, init: bool = False) -> Optional[str]:
        """Creates the powerSource column to merge into Output.df.

        The productLine and productGroup columns must be present in the dataframe
        in order to create.

        Parameters
        ----------
        init : bool, default=False
            If True, None is outputted as it directly modifies Output.df and does not
            need to be processed as a pull_method. False will not return anything for
            the same reason.


        Returns
        -------
        Optional[str]

        """
        frame = inspect.currentframe()
        whoami = inspect.getframeinfo(frame).function

        if init:
            return whoami
        else:
            self.df["powerSource"] = np.select(
                [
                    self.df["productLine"].astype("object") == "Generator",
                    self.df["productLine"].astype("object") == "Compressor",
                ],
                ["Diesel", self.df["productGroup"]],
                default=pd.NA,
            )

    def recurring_monthly(self, init: bool = False) -> Optional[str]:
        """Creates the recurringMonthly column to merge into Output.df.

        The lineStatusDesc, monthlyItemRate, and orderedQuantity columns must be present
        in the dataframe in order to create.

        Parameters
        ----------
        init : bool, default=False
            If True, None is outputted as it directly modifies Output.df and does not
            need to be processed as a pull_method. False will not return anything for
            the same reason.


        Returns
        -------
        Optional[str]

        """
        frame = inspect.currentframe()
        whoami = inspect.getframeinfo(frame).function

        if init:
            return whoami
        else:
            self.df["recurringMonthly"] = np.where(
                (self.df["lineStatusDesc"] == "Terminated")
                | (self.df["lineStatusDesc"] == "Invoiced"),
                0,
                self.df["monthlyItemRate"] * self.df["orderedQuantity"].astype("int64"),
            )

    def itemrate_split(self, init: bool = False) -> Optional[str]:
        """Creates the daily, weekly, and montly rate columns to merge into Output.df.

        The rateTypeDescription and netRate columns must be present in the dataframe in
        order to create.

        Parameters
        ----------
        init : bool, default=False
            If True, None is outputted as it directly modifies Output.df and does not
            need to be processed as a pull_method. False will not return anything for
            the same reason.


        Returns
        -------
        Optional[str]

        """
        frame = inspect.currentframe()
        whoami = inspect.getframeinfo(frame).function

        if init:
            return whoami
        else:
            self.df["dailyItemRate"] = np.select(
                [
                    self.df["rateTypeDescription"].astype("object") == "Week",
                    self.df["rateTypeDescription"].astype("object") == "Day",
                ],
                [self.df["netRate"] / 7, self.df["netRate"]],
                default=self.df["netRate"] / 28,
            )

            self.df["weeklyItemRate"] = self.df["dailyItemRate"] * 7
            self.df["monthlyItemRate"] = self.df["dailyItemRate"] * 28

            self.df = util_data.convert_decimal(
                self.df, cols=["dailyItemRate", "weeklyItemRate", "monthlyItemRate"]
            )

    def daily_agreement(self, init: bool = False) -> Optional[str]:
        """Creates the dailyAgreementRate column to merge into Output.df.

        The lineStatusDesc and dailyItemRate columns must be present in the dataframe in
        order to create.

        Parameters
        ----------
        init : bool, default=False
            If True, None is outputted as it directly modifies Output.df and does not
            need to be processed as a pull_method. False will not return anything for
            the same reason.


        Returns
        -------
        Optional[str]

        """
        frame = inspect.currentframe()
        whoami = inspect.getframeinfo(frame).function

        if init:
            return whoami
        else:
            self.df["dailyAgreementRate"] = np.where(
                self.df["lineStatusDesc"] == "Rented", self.df["dailyItemRate"], np.NaN
            )

    def rate_by_days(self, init: bool = False) -> Optional[str]:
        """Creates the rateByDays column to merge into Output.df.

        The noOfOnhireDays and dailyItemRate columns must be present in the dataframe in
        order to create.

        Parameters
        ----------
        init : bool, default=False
            If True, None is outputted as it directly modifies Output.df and does not
            need to be processed as a pull_method. False will not return anything for
            the same reason.


        Returns
        -------
        Optional[str]

        """
        frame = inspect.currentframe()
        whoami = inspect.getframeinfo(frame).function

        if init:
            return whoami
        else:
            self.df["rateByDays"] = self.df["noOfOnhireDays"] * self.df[
                "dailyItemRate"
            ].astype("int64")


class Compile:
    """Runs the main report functions that modify/aggreate/create Output to prep for File."""

    def __init__(
        self,
        output: Output,
        include_data: bool = False,
    ):
        """Manages the main report function and sets up the data along with its sheet struct.

        Parameters
        ----------
        output : Output
            The Output object.
        pivot_args : list[rep.PivotArgs], optional
            The arguments to pass in order to create a PivotTable.


        Attributes
        ----------
        output : Output
            The Output object.
        construct : Union[Construct, Super]
            The Construct object.
        report : rep.Report
            The Report specification.
        data : dict[str, rep.DataStructure]
            The amalgamation of the compiled report and its spreadsheet output location.

        """
        self.output: Output = output
        self.construct = self.output.construct
        self.report: rep.Report = self.output.report

        try:
            if self.report.parent.key == "data":
                self.data = getattr(self, self.report.key)(
                    **self.output.report.compilate.args
                )
            else:
                self.data = getattr(self, self.report.parent.key)(
                    **self.output.report.compilate.args
                )
            if include_data:
                self.data["df"] = rep.DataStructure(
                    rep.SheetStructure("df", "A1", True),
                    self.output.df,
                    None,
                )
        except AttributeError:
            if self.report.pivot:
                self.data = {}
                getattr(self, "adhoc_pivot")()

            if include_data or not self.report.pivot:
                if self.report.structure:
                    structure = rep.DataStructure(
                        self.report.structure,
                        self.output.df,
                        None,
                    )
                else:
                    structure = rep.DataStructure(
                        rep.SheetStructure("df", "A1", True),
                        self.output.df,
                        None,
                    )
                try:
                    self.data["df"] = structure
                except AttributeError:
                    self.data = {"df": structure}

    def _metadata(self) -> dict[str, Union[str, dict[str, Any]]]:
        """Prepares the metadata of the class to easily insert into the spreadsheet output."""
        metadata = {
            "class": "Compile",
            "type": self.report.parent.key,
            **self.report.compilate.args,
        }

        return metadata

    def file(self, open_file: bool = False, filename: str = "") -> File:
        """Calls File to finalize the report into a spreadsheet and save the file.

        Parameters
        ----------
        open_file : bool
            To specify if the report should be created and saved in the background or
            opened up for the user to modify.

        filename : str, optional
            The override for the report filename. If "", will default.


        Returns
        -------
        File

        """
        return File(self, open_file, filename)

    def adhoc_pivot(self) -> None:
        """Creates pivot tables based on the criteria given.

        Parameters
        ----------
        pivot_args : list[rep.PivotArgs]
            The arguments to pass in order to create a PivotTable.

        """
        for idx, collection in enumerate(self.report.pivot):
            try:
                if type(collection.aggfunc) == str:
                    self.report.pivot[idx].aggfunc = {
                        value: collection.aggfunc for value in collection.values
                    }
            except KeyError:
                pass

            if collection.query:
                slice_for_pivot = cleanup.na(self.output.df.query(collection.query))
            else:
                slice_for_pivot = cleanup.na(self.output.df)

            if collection.structure:
                structure = collection.structure
            else:
                structure = rep.SheetStructure(collection.name, "B4", True)

            if collection.subs:
                self.data[collection.name] = rep.DataStructure(
                    structure,
                    util_data.subtotal(
                        slice_for_pivot,
                        collection.subs,
                        index=collection.index,
                        columns=collection.columns,
                        values=collection.values,
                        aggfunc=collection.aggfunc,
                        margins=collection.margins,
                    ),
                    collection,
                )
            else:
                self.data[collection.name] = rep.DataStructure(
                    structure,
                    slice_for_pivot.pivot_table(
                        index=collection.index,
                        columns=collection.columns,
                        values=collection.values,
                        aggfunc=collection.aggfunc,
                        margins=collection.margins,
                    ),
                    collection,
                )

    def equipment_report(
        self, style: str = None, cols: list = None, agg: dict = None, sort: list = None
    ) -> dict[str, rep.DataStructure]:
        """Compiles an equipment report.

        Parameters
        ----------
        style : str, optional
            Specific report style. Changes how parts of the report are created; legacy
            from the old repo. The style options are axiall, teresa, exxon, serialized,
            standard, total, and nototal.
        cols : list, optional
            The columns to include in the final output. If None, all columns present in the
            initial data["df"].df are used in the final pivot table.
        agg : dict, optional
            The options used to pivot the data by (index and values).
        sort : list, optional
            Will sort the final output by the specified columns.


        Returns
        -------
        dict[str, rep.DataStructure]

        """
        # Sets the structure of where data gets pasted in the appropriate template
        data = {
            "df": rep.DataStructure(
                rep.SheetStructure("Summary", "A8", False),
                self.output.df.copy(),
                None,
            )
        }

        # Cleans up some columns, setting NAs to something else
        for x in [
            ("productLine", ("productLine", ["Not Applicable"]), pd.NA, "productLine"),
            (
                "usRatingDescription",
                ("usRatingDescription", ["Not Rated"]),
                pd.NA,
                "usRatingDescription",
            ),
            (
                "individualItemNumber",
                ("individualItemNumber", [" ", np.NaN, pd.NA, None]),
                "Accessories",
                "individualItemNumber",
            ),
        ]:
            try:
                data["df"].data[x[0]] = np.where(
                    data["df"].data[x[1][0]].isin(x[1][1]), x[2], data["df"].data[x[3]]
                )
            except KeyError:
                pass

        # Style specific changes
        if style == "axiall":
            # Drops uneeeded data
            data["df"].data.drop(
                data["df"]
                .data.loc[data["df"].data["contactName"] == "Justin Trahan"]
                .index,
                inplace=True,
            )
            data["df"].data.drop(
                data["df"]
                .data.loc[
                    ~data["df"].data["location"].str.contains("Lake Charles|Westlake")
                ]
                .index,
                inplace=True,
            )

            # Drops one-day rentals
            data["df"].data.drop(
                data["df"].data.loc[data["df"].data.noOfOnhireDays == 1].index,
                inplace=True,
            )

        elif style == "teresa":
            data["df"].data.drop(
                data["df"].data.loc[data["df"].data.location != "Ardmore"].index,
                inplace=True,
            )

        elif style == "exxon":
            data["df"].data.drop(
                data["df"].data.loc[data["df"].data["location"] != "Beaumont"].index,
                inplace=True,
            )

        elif style == "serialized":
            data["df"].data.drop(
                data["df"]
                .data.loc[data["df"].data["individualItemNumber"] == "Accessories"]
                .index,
                inplace=True,
            )

        # Column sort and slice
        if cols:
            data["df"].data = data["df"].data[cols]

        if agg:
            # Aggregation if needed
            # Checks if values are attributed to the style that must be aggregated
            if type(agg["values"]) == dict:
                values = list(agg["values"].keys())
                ind = agg["index"]
                loc = ind + values
            else:
                values = None
                ind = agg["index"]
                loc = ind

            # Data to be used to aggregate
            to_total = data["df"].data.loc[:, loc].copy()

            # Aggregates the values or simply prepares the total rows
            if values:
                to_total = pd.pivot_table(
                    data["df"].data, index=ind, values=values, aggfunc=agg["values"]
                ).reset_index()
            else:
                to_total = (
                    to_total.loc[:, ind]
                    .drop_duplicates(subset=ind)
                    .reset_index(drop=True)
                )

            # Post-compile modifications
            if style in ["axiall", "standard"]:
                if style == "axiall":
                    data["df"].data["outstanding"] = np.NaN
                    data["df"].data["dailyAgreementRate"] = np.NaN

                data["df"].data["lineAmount"] = np.NaN

            # Setting 'total' as only the total lines as the style dictates
            if style == "total":
                cols = [x for x in list(data["df"].data.columns) if x not in values]
                data["df"].data = to_total.merge(
                    data["df"]
                    .data.loc[:, cols]
                    .drop_duplicates(subset="customerOrderNo"),
                    how="left",
                    on="customerOrderNo",
                    validate="1:1",
                )

                # Re-index
                data["df"].data = data["df"].data[cols]

            # Does not append total lines or anything to the national style
            elif style == "nototal":
                pass

            else:
                try:
                    to_total[ind[1]] = to_total[ind[1]] + " Total"
                except IndexError:
                    to_total[ind[0]] = to_total[ind[0]] + " Total"
                data["df"].data = pd.concat(
                    [data["df"].data, to_total], ignore_index=True, sort=False
                )

            # Index sort
            if sort:
                data["df"].data = (
                    data["df"].data.sort_values(by=sort).reset_index(drop=True)
                )
            else:
                data["df"].data = (
                    data["df"]
                    .data.sort_values(by=["customerOrderNo", "agreementNumber"])
                    .reset_index(drop=True)
                )

        return data

    def national_account(
        self, is_recursion: bool = False, pull_previous: bool = False
    ) -> dict[str, rep.DataStructure]:
        """Compiles the national account report.

        Parameters
        ----------
        is_recursion : bool
            If True, the method is being run recursively in order to pull the previous
            year's revenue. Should not be set to True, it is done in the method itself.
        pull_previous : bool
            If True, forces the previous year revenue to be pulled regardless of the
            circumstances.


        Returns
        -------
        dict[str, rep.DataStructure]

        """
        close = dates.close()[2]
        if (
            close.month == 1 and is_recursion == False and pull_previous == True
        ) or pull_previous == True:
            previous_year = close.year - 1
            last_args = copy.copy(self.report)
            last_args.required.date = (
                f"{previous_year - 1}-01",
                f"{previous_year - 1}-12",
            )
            last_args.compilate.args = {"is_recursion": True}

            last = (
                Super(last_args)
                .pull(last_args.function.pull, last_args.function.post)
                .compile(last_args.compilate)
            )

        df = self.output.df.copy()
        df.manager.fillna("Other", inplace=True)
        df.fillna("", inplace=True)

        pivot = pd.pivot_table(
            df,
            index=[
                "businessUnit",
                "area",
                "salesperson",
                "manager",
                "parent",
                "customerName",
                "customerNumber",
                "location",
                "agreementNumber",
                "overallType",
                "opportunityType",
                "opportunityTypeDesc",
                "proposalNumber",
                "opportunityId",
                "accountName",
                "industryGrouping",
                "industry",
                "financialYear",
                "financialPeriod",
            ],
            values=["earnedRevenueUsd"],
            aggfunc="sum",
        )

        data = {
            "pivot": rep.DataStructure(
                rep.SheetStructure("ABI Data", "D1", False), pivot, None
            ),
        }

        if (
            close.month == 1 and is_recursion == False and pull_previous == True
        ) or pull_previous == True:
            data["last_pivot"] = last.data["pivot"]  # type: ignore - can't be unbound as same if criteria above guarantees existence

        return data

    def client_slides(self) -> dict[str, rep.DataStructure]:
        """Compiles a client_slides report.

        Returns
        -------
        dict[str, rep.DataStructure]

        """
        # Data pivots that sum up everything we need
        rev_lc = (
            pd.pivot_table(
                self.output.df,
                index=["location"],
                columns=["financialYear"],
                values=["earnedRevenueUsd"],
                aggfunc=np.sum,
                margins=True,
            )
            .round()
            .sort_values(by=("earnedRevenueUsd", "All"), ascending=False)
        )

        rev_pr = (
            pd.pivot_table(
                self.output.df,
                index=["productFamily"],
                columns=["financialYear"],
                values=["earnedRevenueUsd"],
                aggfunc=np.sum,
                margins=True,
            )
            .round()
            .sort_values(by=("earnedRevenueUsd", "All"), ascending=False)
        )

        dtp_lc = (
            pd.pivot_table(
                self.output.df,
                index=["location"],
                columns=["financialYear"],
                values=["daysToPay"],
                aggfunc=np.mean,
                margins=True,
            )
            .fillna(0)
            .round()
            .astype(int)
            .sort_values(by=("daysToPay", "All"), ascending=False)
        )

        rev_tp = pd.pivot_table(
            self.output.df,
            index=["overallType", "opportunityType", "opportunityTypeDesc"],
            columns=["financialYear"],
            values=["earnedRevenueUsd"],
            aggfunc=np.sum,
            margins=True,
        ).round()

        data = {
            "revenue_location": rep.DataStructure(
                rep.SheetStructure("RevenueByLocation", "A1", False),
                rev_lc,
                None,
            ),
            "revenue_product": rep.DataStructure(
                rep.SheetStructure("RevenueByProduct", "A1", False),
                rev_pr,
                None,
            ),
            "dtp_location": rep.DataStructure(
                rep.SheetStructure("DaysToPay", "A1", False), dtp_lc, None
            ),
            "revenue_type": rep.DataStructure(
                rep.SheetStructure("RevenueByType", "A1", False),
                rev_tp,
                None,
            ),
        }

        return data

    def rentals_rates(self) -> dict[str, rep.DataStructure]:
        """Compiles a rentals and rates report.

        Returns
        -------
        dict[str, rep.DataStructure]

        """
        df = self.output.df.copy()
        # Calculates YTD and monthly spend based on line amount
        year = str(dt.datetime.strptime(self.report.required.date[1], "%Y-%m").year)

        df["ytdTotalSpend"] = (
            df["lineAmount"].astype(int) / df["noOfOnhireDays"]
        ) * df[year]

        # Creates Tier Level column (1600 Electric = 4, others = 2)
        df["tierLevel"] = np.where(df["usRatingDescription"] == "1600 CFM", "4f", "2")

        # Splits ValidDateTo to Specified if in the future and Actual if in the past
        today = pd.Timestamp(dt.date.today())
        start = pd.Timestamp(dt.date(1900, 1, 1))
        df["specified"] = pd.to_datetime(
            np.select(
                (df["validToDate"] > today, df["validToDate"] <= start),
                (df["validToDate"], dates.calendar(int(year))[1]),
                pd.NaT,
            )
        )
        df["actual"] = pd.to_datetime(
            np.where(
                (df["validToDate"] <= today) & (df["validToDate"] > start),
                df["validToDate"],
                pd.NaT,
            )
        )

        # Finalizes output
        df = df[
            [
                "location",
                "manufacturerName",
                "fleetOrigin",
                "individualItemNumber",
                "validFromDate",
                "specified",
                "actual",
                "agreementNumber",
                "customerOrderNo",
                "ytdTotalSpend",
                "itemNumber",
                "usRatingDescription",
                "productGroup",
                "tierLevel",
            ]
        ]

        df.rename(
            columns={
                "location": "Refinery",
                "manufacturerName": "Compressor Manufacturer",
                "fleetOrigin": "Rental Company",
                "individualItemNumber": "Model Number",
                "validFromDate": "Date Rented",
                "specified": "Specified",
                "actual": "Actual",
                "agreementNumber": "Agreement Number",
                "customerOrderNo": "PO Number",
                "ytdTotalSpend": "YTD Total Spend",
                "itemNumber": "Compressor Description",
                "usRatingDescription": "Size",
                "productGroup": "Driver",
                "tierLevel": "Tier Level",
            },
            inplace=True,
        )

        df = df.sort_values(
            by=["YTD Total Spend", "Date Rented"], ascending=[False, True]
        ).reset_index(drop=True)
        df.index.name = "Item"

        data = {
            "df": rep.DataStructure(rep.SheetStructure("ade", "B3", False), df, None)
        }

        return data

    def product_revenue(self) -> dict[str, rep.DataStructure]:
        """Compiles a product revenue report.

        Returns
        -------
        dict[str, rep.DataStructure]

        """
        # Must create a separate listing DF as the template isn't a combined
        # pivot table. The listing will get pasted in the first 3 columns without
        # an index while the pivot table will get pasted with the index.
        listing = (
            self.output.df.loc[
                :, ["productLine", "usRatingDescription", "productDescription"]
            ]
            .drop_duplicates()
            .sort_values(
                by=["productLine", "usRatingDescription", "productDescription"]
            )
            .copy()
        )
        listing.set_index("productLine", inplace=True)

        # Creates main pivot table which mimics the listing order but with values
        values = self.output.df.pivot_table(
            index=["productLine", "usRatingDescription", "productDescription"],
            columns=["financialYear"],
            values=["usdRevenue"],
            aggfunc="sum",
            margins=True,
        )

        # Creates the sub-labor frame which gets append to the values pivot table
        labor = self.output.df.loc[
            self.output.df.accountGroupDesc == "Service Revenue"
        ].pivot_table(
            index=["accountGroupDesc"],
            columns=["financialYear"],
            values=["usdRevenue"],
            aggfunc="sum",
        )

        # Prepares the "index" of the pivot table to paste blanks except for the
        # total rows.
        values = pd.concat([values.reset_index(drop=True), labor]).reset_index()
        values.iloc[-2, 0] = "Product"
        values.iloc[-1, 0] = "Labor"
        values.rename(columns={"index": "Month"}, inplace=True)
        values.set_index("Month", inplace=True)
        values.index = np.where(
            values.index.isin(["Product", "Labor"]), values.index, ""
        )

        data = {
            "listing": rep.DataStructure(
                rep.SheetStructure("Summary", "A2", False), listing, None
            ),
            "values": rep.DataStructure(
                rep.SheetStructure("Summary", "I1", False), values, None
            ),
        }

        return data

    def rebate(self) -> dict[str, rep.DataStructure]:
        """Compiles a rebate report.

        Returns
        -------
        dict[str, rep.DataStructure]

        """
        df = self.output.df.merge(
            self.output.df.groupby(["invoiceNumber"])["netValue"]
            .sum()
            .reset_index()
            .rename(columns={"netValue": "outstanding"}),
            how="left",
            on="invoiceNumber",
        )
        data = {
            "rebate": rep.DataStructure(
                rep.SheetStructure("Sheet1", "A1", False), df, None
            ),
        }

        return data


@admin.initializor
class File:
    """Finalizes the report by setting its output file, pasting, and saving."""

    def __init__(self, compile: Compile, open_file: bool, filename: str = ""):
        """Manages setting of the template and saving the file.

        Parameters
        ----------
        compile : Compile
            The Compile object.
        open_file : bool
            To specify if the report should be created and saved in the background or
            opened up for the user to modify.
        filename : str
            Custom filename to replace the default.


        Attributes
        ----------
        open_file : bool
            To specify if the report should be created and saved in the background or
            opened up for the user to modify.
        compile : Compile
            The Compile object.
        data : dict[str, rep.DataStructure]
            The amalgamation of the compiled report and its spreadsheet output location
            from compile.data.
        output : Output
            The Output object.
        construct : Union[Construct, Super]
            The Construct object.
        report : rep.Report
            The Report specification.
        file : Path
            The filepath to where the report will be saved.
        is_template : bool
            If the report has a template file.

        """
        self.open_file: bool = open_file

        self.compile: Compile = compile
        self.data: dict[str, rep.DataStructure] = self.compile.data
        self.output: Output = self.compile.output

        self.construct = self.output.construct
        self.report: rep.Report = self.output.report
        if filename:
            self.report.filename = filename

        self.file, self.is_template = self._get_template()
        self._create_file()

    def __repr__(self) -> str:
        return f"{self.compile.output.report.parent.key} - {self.compile.output.report.key}"

    def _get_template(self) -> tuple[Path, bool]:
        """Gets the filepath of where the report will be saved.

        Returns
        -------
        tuple[Path, bool]
            The filepath and whether or not the report save is based off of a template.

        """
        if self.report.parent.key in ("data", "__adhoc__"):
            self.report_name = self.report.key
        else:
            self.report_name = self.report.parent.key

        report_dir = admin.instance.report_home / self.report_name
        template_dir = admin.instance.reference / "templates/"

        try:
            template_file = list(
                template_dir.glob(
                    f"{self.report_name}_template{self.report.parent.ext}"
                )
            )[0]
            save_file = report_dir / template_file.name
            is_template = True
        except IndexError:
            admin.instance.logger.info(
                f"{self.report_name} template not found. Proceeding with adhoc sheet..."
            )
            save_file = report_dir / f"{self.report_name}{self.report.parent.ext}"
            is_template = False

        if not report_dir.is_dir():
            report_dir.mkdir()

        if is_template == True:
            if not save_file.exists():
                shutil.copyfile(template_file, save_file)  # type: ignore - template_file will always exist with is_template

            if os.path.getmtime(save_file) < os.path.getmtime(template_file):  # type: ignore - impossible as is_template == True
                save_file.unlink()
                shutil.copyfile(template_file, save_file)  # type: ignore - unbound caught with NameError

        return save_file, is_template

    def _prepare_excel_metadata(self) -> dict:
        """Insert the report creation metadata into the spreadsheet.

        Returns
        -------
        dict

        """
        # TODO
        pass

    def _to_excel(self) -> None:
        """Saves the report as an Excel file following the rep.SheetStructure."""
        app = xw.App(visible=self.open_file, add_book=False)
        try:
            book = app.books.open(self.file)
        except FileNotFoundError:
            book = app.books.add()

        self._prepare_filename()

        for data_struct in self.data.values():
            # Excel is incompatible with pd.NAType and pd.NA, so fill all NA
            # values with ""
            data_struct.data = cleanup.na(data_struct.data)

            if not data_struct.data.index.name:
                data_struct.data.index.name = "index"

            sht_name = data_struct.structure.sheet
            if sht_name not in [i.name for i in book.sheets]:
                book.sheets.add(sht_name, after=book.sheets[-1])
            sht = book.sheets[sht_name]

            rng = sht.range(data_struct.structure.cell)
            # TODO: clear contents by manually getting range (# of rows/columns from DF.clear)
            # full.expand("table").clear_contents()
            rng.value = data_struct.data
            # full.api.AutoFilter(Field=1)

            if data_struct.structure.formatting:
                if data_struct.pivot:
                    formatting.adhoc_pivot(
                        app, book, sht, rng, data_struct.data, data_struct.pivot
                    )
                else:
                    formatting.adhoc_data(sht, rng, data_struct.data)

                if not self.is_template:
                    for sheet in book.sheets:
                        if sheet.name not in [
                            i.structure.sheet for i in self.data.values()
                        ]:
                            sheet.delete()

            book.save(self.file)

        # Closes out
        if not self.open_file:
            book.close()
            app.quit()

    def _to_csv(self) -> None:
        """Saves the report as a CSV dump, with each DataFrame its own CSV."""
        self._prepare_filename()

        for data_struct in self.data.values():
            data_struct.data.to_csv(self.file)

    def _prepare_filename(self) -> None:
        """Sets the final name the file will be saved as and whether it should be versioned.

        Attributes
        ----------
        version : str
            Defaults to the next-highest version number as vN.

        """
        if f"_{self.report_name}_template" in self.file.name:
            file_report_descriptor = (
                f"_{self.file.name.replace(f'_{self.report_name}_template', '')}"
            )
        else:
            file_report_descriptor = self.report.parent.ext

        base_file = self.file.parent / f"{self.report.filename}{file_report_descriptor}"

        if base_file.exists():
            versions = list(base_file.parent.glob(f"{base_file.stem}*"))
            try:
                highest_version = sorted(
                    [i.name for i in versions if re.findall(r"(_v[0-9]+)", i.name)],
                    key=nk.natural_keys,
                    reverse=True,
                )[0]
                next_version = (
                    f"{int(re.findall(r'_v([0-9]+)', highest_version)[0]) + 1}"
                )
            except IndexError:
                highest_version = base_file
                next_version = "1"
        else:
            highest_version = base_file
            next_version = ""

        if next_version:
            if int(next_version) > 1:
                to_save = highest_version.replace(
                    f"_v{int(next_version)-1}", f"_v{next_version}"
                )
            else:
                to_save = (
                    f"{self.report.filename}_v{next_version}{file_report_descriptor}"
                )
            self.file = self.file.parent / f"{to_save}"
        else:
            self.file = base_file

    def _create_file(self) -> None:
        """Manages whether the file-to-be is a CSV or Excel based off the Report suffix."""
        if self.file.suffix == ".csv":
            self._to_csv()
        else:
            self._to_excel()

    def mail(self, confirmation: Optional[bool] = None) -> bool:
        """Sends the report given the Report configuration. Will fail if not set.

        Parameters
        ----------
        confirmation : bool, optional
            If None, goes by the ade config. Will either require or not a confirmation
            prior to sending the email.

        """
        if not any(i for i in self.report.email.__dict__.values()):
            admin.instance.logger.warning(
                "Unable to send: no email recipients configured"
            )
            return False
        else:
            if confirmation is None:
                confirmation = admin.instance.conf["confirmation"]

            mail.email(
                **self.report.email.__dict__,
                path=self.file.as_posix(),
                signature=admin.instance.conf["signature"],
                confirmation=confirmation,
            )
            return True


class MetadataConverter(xw.conversion.Converter):
    """Custom xlwings converter for reading/writing either dictionaries with
    greater than single values (e.g. lists) or passing through standard
    DataFrames.

    """

    # base = xw.conversion.PandasDataFrameConverter
    # TODO: make sure works with pasting metadata

    @staticmethod
    def read_value(value, options):
        convert = {x[0]: x[1:] for x in value}
        return convert

    @staticmethod
    def write_value(value, options):
        if type(value) == dict:
            convert = pd.DataFrame(dict([(k, pd.Series(v)) for k, v in value.items()]))
        else:
            convert = value

        return convert


def pull(
    repkey: str,
    subkey: str,
    slicers: dict = {},
    comp: dict = {},
    pivots: Optional[list[rep.PivotArgs]] = None,
    include_data: bool = False,
) -> Compile:
    """Creates the query and pulls the data for the given report structure.

    Parameters
    ----------
    report : string
        The name of the report specification as set by config.yaml
    sub : string
        The name of the sub-report as set by config.yaml
    slicers : dict, optional
        The keyword arguments for the query. Allows you to overwrite report
        specifications before running the SQL query. Date is also an allowed
        field to replace.
    comp : dict, optional
        Additional values used for specific reports in this module. For
        instance, equipment_report has a value "style" which can be modified
        here.
    pivots : list[rep.PivotArgs], optional
        The arguments to pass in order to create a PivotTable.
    include_data : bool
        Saves the original dataframe in the compiled output.

    Returns
    -------
    Union[pd.DataFrame, Dict[str, pd.DataFrame]]
        If the report specification has an excel configuration or further
        modification to the data, it will output a dictionary with the data,
        excel config, and the original args. Otherwise, only the DataFrame will
        be returned.

    Raises
    ------
    AssertionError
        If there is no data present after the SQL query is run.

    """
    # Get report specifications
    report: rep.Report = rep.parse(repkey, subkey)

    # If any values in dict params, will overwrite the original report param specifications.
    for key, value in slicers.items():
        if key in report.required.__annotations__:
            setattr(report.required, key, value)
        elif key in report.optional.__annotations__:
            setattr(report.optional, key, value)

    for key, value in comp.items():
        if key in report.compilate.args:
            setattr(report, key, value)

    if pivots:
        report.pivot = pivots

    # Construct the query and pull the data.
    out = Super(report).pull()

    compilate = out.compile(include_data=include_data)

    return compilate


def run(
    repkey: str,
    subkey: str,
    slicers: dict = {},
    comp: dict = {},
    filename: str = "",
    open_file: bool = False,
) -> None:
    """Creates the query and pulls the data for the given report structure.

    Parameters
    ----------
    report : string
        The name of the report specification as set by config.yaml
    sub : string
        The name of the sub-report as set by config.yaml
    slicers : dict, optional
        The keyword arguments for the query. Allows you to overwrite report
        specifications before running the SQL query. Date is also an allowed
        field to replace.
    comp : dict, optional
        Additional values used for specific reports in this module. For
        instance, equipment_report has a value "style" which can be modified
        here.
    filename : str, optional
        The override for the report filename. If "", will default.


    Returns
    -------
    Union[pd.DataFrame, Dict[str, pd.DataFrame]]
        If the report specification has an excel configuration or further
        modification to the data, it will output a dictionary with the data,
        excel config, and the original args. Otherwise, only the DataFrame will
        be returned.


    Raises
    ------
    AssertionError
        If there is no data present after the SQL query is run.

    """
    compilate = pull(repkey, subkey, slicers, comp)

    compilate.file(open_file=open_file, filename=filename).mail()


@admin.initializor
def invoice_base(df: pd.DataFrame, cols: list) -> pd.DataFrame:
    """Preparation of the invoice query to further calculate DTP and Outstanding.

    Parameters
    ----------
    df : pandas.DataFrame
        Pre-existing data.
    cols : list
        Columns to pull.


    Returns
    -------
    pd.DataFrame
        Prepared invoice data.

    """
    # TODO: absolute mess of legacy code, basically hacked into kind of working with the rewrite
    # Pulls the agreement numbers to search for in SQL
    assert all([x for x in ("agreementNumber", "customerNumber") if x in df.columns]), (
        'The columns "agreementNumber" and "customerNumber" are '
        "not present in the initial query. Outstanding amount "
        "cannot be pulled."
    )

    construct = Construct(
        "Invoice",
        cols,
        ("1970-01", dt.date.today().strftime("%Y-%m")),
        clients=df.customerNumber.drop_duplicates().to_list(),
    )
    query = construct.pull().df

    # Convert invoice Value to Decimal type
    # query = data.convert_decimal(query, cols=['value'])

    # Matching agreements to invoices with ags of -1 or unknown (payments)
    agmts = query.loc[:, ["invoiceNumber", "agreementNumber"]].drop(
        index=query.loc[query["agreementHeaderId"] == -1].index
    )
    query = query.drop(columns=["agreementHeaderId", "agreementNumber"]).merge(  # type: ignore - query will always pull DF
        agmts, how="left", on="invoiceNumber", validate="m:1"
    )

    # Giving each invoice it's 50% 'paid-off' value in order to correctly
    # calculate DaysToPay.
    query["toPaid"] = np.where(query.isInvoice == 1, query.value * 0.5, np.NaN)

    # Drops payment lines to only include only invoice values. For both an
    # individual DF and for filtering out invoices that aren't just payments
    # from the others.
    main = query.drop(index=query.loc[query.isInvoice != 1].index).copy()  # type: ignore - query will always pull DF
    query = query.loc[query.invoiceNumber.isin(main.invoiceNumber.to_list())].copy()

    # Pivoted Invoice + Value in case there are multiple lines for one invoice
    # to act as a failsafe against additional credit lines etc. Otherwise
    # checks the net invoice value against the 50% ToPaid limit and if the net
    # is less than or equal to ToPaid, the invoice is considered paid.
    summ = query.pivot_table(
        index=["invoiceNumber"], values=["value", "toPaid"], aggfunc="sum"
    ).reset_index()
    summ["paid"] = np.where(summ.toPaid >= summ.value, 1, 0)
    query = query.merge(
        summ.loc[:, ["invoiceNumber", "toPaid", "paid"]], how="left", on="invoiceNumber"
    )
    query = util_data.remove_column_duplicates(query, reverse=True)

    return query


@admin.initializor
def outstanding(df: pd.DataFrame, inv: pd.DataFrame = None) -> pd.DataFrame:
    """Creation of the Outstanding series for the Equipment Report.

    Parameters
    ----------
    df : pd.DataFrame
        Equipment Report data.
    inv : pd.DataFrame, optional
        Invoice data created by invoice_base


    Returns
    -------
    pd.DataFrame
        Equipment Report data with the Outstanding series.

    """
    # TODO: absolute mess of legacy code, basically hacked into kind of working with the rewrite
    # Checks if an existing DF from invoice_base is passed. If not, runs
    # the method.
    if not inv:
        query = invoice_base(
            df,
            [
                "invoiceNumber",
                "agreementNumber",
                "agreementHeaderId",
                "value",
                "isInvoice",
                "daysToPay",
            ],
        )
    else:
        query = inv

    # Sets up query for outstanding invoices by dropping paid-off items
    out = query.loc[query.isInvoice == 1].copy()
    out.drop(out.loc[out.paid == 1].index, inplace=True)
    out.rename(columns={"value": "outstanding"}, inplace=True)
    query = query.merge(
        out.loc[:, ["invoiceNumber", "outstanding"]],
        how="left",
        on="invoiceNumber",
        validate="m:1",
    )

    query = query.pivot_table(
        index=["agreementNumber"], values=["outstanding"], aggfunc="sum"
    )

    df = df.merge(query, how="left", on="agreementNumber", validate="m:1")

    return df


def days_to_pay(df: pd.DataFrame, inv: pd.DataFrame = None) -> pd.DataFrame:
    """Creation of the Days To Pay series.

    Parameters
    ----------
    df : pd.DataFrame
        Equipment Report data.

    inv : pd.DataFrame, optional
        Invoice data from invoice_base


    Returns
    -------
    pd.DataFrame
        Equipment Report data with the Outstanding series.

    """
    # TODO: absolute mess of legacy code, basically hacked into kind of working with the rewrite
    # Checks if an existing DF from invoice_base is passed. If not, runs
    # the method.
    if not inv:
        query = invoice_base(
            df,
            [
                "invoiceNumber",
                "agreementNumber",
                "value",
                "isInvoice",
                "daysToPay",
                "paymentDate",
                "invoiceRaisedDate",
                "isPayment",
                "agreementHeaderId",
                "agreementNumber",
            ],
        )
    else:
        query = inv

    # Slice for payments to being process of calculating which specific payment
    # pushed the inovice into Paid territory.
    dtp = query.loc[
        query.isPayment == 1,
        [
            "invoiceNumber",
            "paymentDate",
            "invoiceRaisedDate",
            "isPayment",
            "value",
            "toPaid",
            "paid",
        ],
    ].copy()
    dtp.sort_values(by=["invoiceNumber", "paymentDate"], inplace=True, ascending=True)

    # Convert Value from Decimal to float in order to be properly summed
    # cummulatively to figure out which payment pushes the total past 50%.
    dtp.value = dtp.value.astype("float64")
    dtp = dtp.reset_index()
    cum = (
        dtp.groupby(["invoiceNumber", "index", "paid"])["value"]
        .sum()
        .groupby(level=[0])
        .cumsum()
        .reset_index()
    )
    cum = cum.merge(
        dtp.loc[:, ["invoiceNumber", "index", "toPaid"]],
        how="left",
        on=["index", "invoiceNumber"],
    )

    # Prepare data to do as done to 'summ' by converting back to Decimal and
    # comparing Value to ToPaid to calculate which payment is past the 50%
    # threshold.
    cum.value = cum.value * -1
    cum = util_data.convert_decimal(cum, cols=["value"])
    cum["paidPayment"] = np.where(cum.toPaid <= cum.value, 1, 0)
    cum = cum.loc[cum.paid == 1].drop_duplicates(subset=["invoiceNumber"])

    # Merging cumsum back into dtp with data on which payment is THE ONE
    # in order to calculate the correct DaysToPay
    for frame in [dtp, cum]:
        frame.index = frame["index"]
        frame.drop(columns=["index"], inplace=True)
    dtp = dtp.merge(cum.loc[:, ["paidPayment"]], how="left", on="index")
    dtp["daysToPay"] = dtp.paymentDate - dtp.invoiceRaisedDate
    dtp.daysToPay = dtp.daysToPay.dt.days
    dtp.daysToPay = np.where(
        dtp.paidPayment.isnull(), pd.Timedelta(days=0).days, dtp.daysToPay
    )

    # Final merge of dtp into query with data, first for which payments are
    # the 50% payment and second for DaysToPay for each invoice
    query.index.name = "index"
    query = query.merge(cum.loc[:, ["paidPayment"]], how="left", on="index")
    query = query.merge(
        dtp.loc[~dtp.daysToPay.isnull(), ["invoiceNumber", "daysToPay"]],
        how="left",
        on="invoiceNumber",
    )
    query = util_data.remove_column_duplicates(query, reverse=True)

    query = query.pivot_table(
        index=["agreementNumber"], values=["daysToPay"], aggfunc=np.mean
    ).reset_index()

    df = df.merge(query, how="left", on="agreementNumber", validate="m:1")

    return df


def customer_search(
    search: list[str], world: bool = False, glob: bool = False
) -> Optional[pd.DataFrame]:
    """Returns a table of ade customers abiding by the search parameter.

    Parameters
    ----------
    search : list[str]
        The list of SQL matches to search for.
    world : bool, default=False
        To expand the search outside of NAM.
    glob : bool, default=False
        To search wildcard SQL strings.


    Returns
    -------
    Optional[pd.DataFrame]
        Will return None if <search> is empty.

    """

    if not list:
        print("Non-empty list required")
        return None

    # Query setup
    if glob:
        operator = "LIKE"
    else:
        operator = "="

    where = f"cu.Name {operator} ? OR "

    if len(search) > 1:
        where += f"{where * (len(search) - 1)}"

    string = f"""
            SELECT cu.Number, cu.Name

            FROM CorporateODS.dim.Customer cu

            WHERE ({where[:-4]})
            """
    if not world:
        string += (
            f" AND (cu.Number {operator} 'US%' OR cu.Number {operator} 'CA%'"
            f"OR cu.Number {operator} 'PR%')"
        )

    # Query pull
    with connections.Sql("new") as conn:
        query = pd.read_sql(string, conn, params=search)

    return query


def location_search(
    search: list[str], world: bool = False, city: bool = False, glob: bool = False
) -> Optional[pd.DataFrame]:
    """Returns a table of ade customer locations abiding by the search parameter.

    Parameters
    ----------
    search : list[str]
        The list of SQL matches to search for.
    world : bool, default=False
        To expand the search outside of NAM.
    city : bool, default=False
        If searching by city instead of street address.
    glob : bool, default=False
        To search wildcard SQL strings.


    Returns
    -------
    Optional[pd.DataFrame]
        Will return None if <search> is empty.

    """

    if not list:
        print("Non-empty list required")
        return None

    # Query setup
    if glob:
        operator = "LIKE"
    else:
        operator = "="

    if city:
        address = "agl.SiteAddress3"
    else:
        address = "agl.SiteAddress1"

    where = f"{address} {operator} ? OR "

    if len(search) > 1:
        where += f"{where * (len(search) - 1)}"

    string = f"""
            SELECT cu.Number, cu.Name, agl.SiteAddress1, agl.SiteAddress3, agl.SiteAddress4

            FROM CorporateODS.nrc.AgreementLines agl
            LEFT OUTER JOIN CorporateODS.dim.Customer cu
            ON agl.CustomerID = cu.CustomerId

            WHERE ({where[:-4]})
            """
    if not world:
        string += (
            f" AND (cu.Number {operator} 'US%' OR cu.Number {operator} 'CA%'"
            f"OR cu.Number {operator} 'PR%')"
        )

    # Query pull
    with connections.Sql("new") as conn:
        query = pd.read_sql(string, conn, params=search)

    return query