Py.Cafe

tanguyboete/

Dashboard

Hello Panel Text Input Example

DocsPricing
  • CM-Transfer_Project-Overview_10-30-2024.xlsx
  • Clear-to-Build.ipynb
  • app.py
  • requirements.txt
Clear-to-Build.ipynb
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
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c2aeb8da-b2c6-4399-a832-c843c484e75f",
   "metadata": {},
   "source": [
    "<h2 style=\"text-align:left;\">Filtering & Formatting - WIP - Priority database, Summary, Snapshot, Backlog, TurnoverReport, Dashboard included </h2> "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "1e2da197-de01-467d-a24e-cc551a1c5155",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Inventory file Date: 10-30-2024\n",
      "Workbook state after save and close: ['Gantt']\n",
      "Initialisation of the Transfer Project Overview spreadsheet ... Processing ...\n",
      " |CM-Inventory| & |CM-BOM| saved to 'CM-Transfer_Project-Overview_10-31-2024.xlsx'.\n",
      "Processing |Clear-to-Build| ...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Tanguy.Boete\\AppData\\Local\\Temp\\ipykernel_27888\\3416105912.py:300: DeprecationWarning: DataFrameGroupBy.apply operated on the grouping columns. This behavior is deprecated, and in a future version of pandas the grouping columns will be excluded from the operation. Either pass `include_groups=False` to exclude the groupings or explicitly select the grouping columns after groupby to silence this warning.\n",
      "  df_CTB_updated = df_CTB_updated.groupby(['IDD Top Level', 'IDD Component'], as_index=False).apply(select_row_with_priority)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Number of rows in df_CTB_updated after keeping only unique 'IDD Component' per 'IDD Top Level': 12663\n",
      "Max Qty (GS) filled.\n",
      "Top Level sharing Components filled and saved to CM-Transfer_Project-Overview_10-31-2024.xlsx\n",
      "Cost cancelation impact filled.\n",
      "Number of missing components: 2676\n",
      "Number of rows in |Clear-to-Build| before including missing component: 12663\n",
      "Number of rows in |Clear-to-Build| after appending missing components - Including Make Part: 15339\n",
      "Missing components from |CM-BOM| have been included in |Clear-to-Build|.\n",
      "Max Qty (GS) updated.\n",
      "Max Qty (GS) updated with Floor stock Item and Make Part from CUU\n",
      "|Clear-to-Build| after updating Max Qty (GS) and handling Pur/Mfg == 'M' condition.\n",
      "Remaining critical quantity filled for inventory status 'Component not in Inventory'.\n",
      "Floor-stock CUU identified for relevant rows.\n",
      "Priority database added successfully as |CM-Priority| in CM-Transfer_Project-Overview_10-31-2024.xlsx\n",
      "Tabs in the workbook:\n",
      "['Gantt', 'Clear-to-Build', 'CM-Inventory', 'CM-BOM', 'CM-Priority']\n",
      "Processing |CM-Backlog| ...\n",
      "Backlog files loaded successfully.\n",
      "Backlog added successfully as |CM-Backlog| in CM-Transfer_Project-Overview_10-31-2024.xlsx\n",
      "Tabs in the workbook:\n",
      "['Gantt', 'Clear-to-Build', 'CM-Inventory', 'CM-BOM', 'CM-Priority', 'CM-Backlog']\n",
      "Processing |CM-TurnoverReport| ...\n",
      "TurnoverReport added successfully as |CM-TurnoverReport| in CM-Transfer_Project-Overview_10-31-2024.xlsx\n",
      "Tabs in the workbook:\n",
      "['Gantt', 'Clear-to-Build', 'CM-Inventory', 'CM-BOM', 'CM-Priority', 'CM-Backlog', 'CM-TurnoverReport']\n",
      "Processing |CM-WIP| ...\n",
      "WIP files loaded successfully.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Tanguy.Boete\\AppData\\Local\\Temp\\ipykernel_27888\\3416105912.py:2274: DeprecationWarning: DataFrameGroupBy.apply operated on the grouping columns. This behavior is deprecated, and in a future version of pandas the grouping columns will be excluded from the operation. Either pass `include_groups=False` to exclude the groupings or explicitly select the grouping columns after groupby to silence this warning.\n",
      "  df_WIP_Temp = df_WIP_Temp.groupby(['WO', 'Pty Indice'], group_keys=False).apply(select_closest_to_today).reset_index(drop=True)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WIP added successfully as |CM-WIP| in CM-Transfer_Project-Overview_10-31-2024.xlsx\n",
      "Tabs in the workbook:\n",
      "['Gantt', 'Clear-to-Build', 'CM-Inventory', 'CM-BOM', 'CM-Priority', 'CM-Backlog', 'CM-TurnoverReport', 'CM-WIP']\n",
      "Processing |PendingReport| ...\n",
      "Pending Report added successfully as |PendingReport| in CM-Transfer_Project-Overview_10-31-2024.xlsx\n",
      "Tabs in the workbook:\n",
      "['Gantt', 'Clear-to-Build', 'CM-Inventory', 'CM-BOM', 'CM-Priority', 'CM-Backlog', 'CM-TurnoverReport', 'CM-WIP', 'PendingReport']\n",
      "Processing |Historic| ...\n",
      "Historic added successfully as |CM-Historic| in CM-Transfer_Project-Overview_10-31-2024.xlsx\n",
      "Tabs in the workbook:\n",
      "['Gantt', 'Clear-to-Build', 'CM-Inventory', 'CM-BOM', 'CM-Priority', 'CM-Backlog', 'CM-TurnoverReport', 'CM-WIP', 'PendingReport', 'CM-Historic']\n",
      "Processing |CM-LaborReport| ...\n",
      "LaborReport added successfully as |CM-LaborReport| in CM-Transfer_Project-Overview_10-31-2024.xlsx\n",
      "Tabs in the workbook:\n",
      "['Gantt', 'Clear-to-Build', 'CM-Inventory', 'CM-BOM', 'CM-Priority', 'CM-Backlog', 'CM-TurnoverReport', 'CM-WIP', 'PendingReport', 'CM-Historic', 'CM-LaborReport']\n",
      "Processing |CM-MakeArchitecutre| ...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Tanguy.Boete\\AppData\\Local\\Temp\\ipykernel_27888\\3416105912.py:4004: DeprecationWarning: DataFrameGroupBy.apply operated on the grouping columns. This behavior is deprecated, and in a future version of pandas the grouping columns will be excluded from the operation. Either pass `include_groups=False` to exclude the groupings or explicitly select the grouping columns after groupby to silence this warning.\n",
      "  df_filtered = grouped.apply(process_group).reset_index(drop=True).copy()\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Make Architecture added successfully as |CM-MakeArchi| in CM-Transfer_Project-Overview_10-31-2024.xlsx\n",
      "Tabs in the workbook:\n",
      "['Gantt', 'Clear-to-Build', 'CM-Inventory', 'CM-BOM', 'CM-Priority', 'CM-Backlog', 'CM-TurnoverReport', 'CM-WIP', 'PendingReport', 'CM-Historic', 'CM-LaborReport', 'CM-MakeArchitecture']\n",
      "Processing |Summary| ...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Tanguy.Boete\\AppData\\Local\\Temp\\ipykernel_27888\\3416105912.py:4591: DeprecationWarning: DataFrameGroupBy.apply operated on the grouping columns. This behavior is deprecated, and in a future version of pandas the grouping columns will be excluded from the operation. Either pass `include_groups=False` to exclude the groupings or explicitly select the grouping columns after groupby to silence this warning.\n",
      "  .apply(lambda x: x.sort_values(by='Level').sort_values(by='Priority'))\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Summary added successfully as |Summary| in CM-Transfer_Project-Overview_10-31-2024.xlsx\n",
      "Tabs in the workbook:\n",
      "['Summary', 'Gantt', 'Clear-to-Build', 'CM-Inventory', 'CM-BOM', 'CM-Priority', 'CM-Backlog', 'CM-TurnoverReport', 'CM-WIP', 'PendingReport', 'CM-Historic', 'CM-LaborReport', 'CM-MakeArchitecture']\n",
      "Processing |Snapshot| ...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Tanguy.Boete\\AppData\\Local\\Temp\\ipykernel_27888\\3416105912.py:4684: DeprecationWarning: DataFrameGroupBy.apply operated on the grouping columns. This behavior is deprecated, and in a future version of pandas the grouping columns will be excluded from the operation. Either pass `include_groups=False` to exclude the groupings or explicitly select the grouping columns after groupby to silence this warning.\n",
      "  min_qty_rows = grouped.apply(lambda df: df.loc[df['Max Qty (GS)'].idxmin()]).reset_index(drop=True)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Pty Indice to update: ['COMAC-New1' 'EMBRAER-15' 'EMBRAER-17' 'EMBRAER-22' 'EMBRAER-29'\n",
      " 'EMBRAER-30' 'EMBRAER-New1' 'P10D' 'P14A' 'P14B' 'P19B' 'P2A' 'P2AA'\n",
      " 'P2AE' 'P2AF' 'P2B' 'P2C' 'P2D' 'P2E' 'P2F' 'P2G' 'P2H' 'P2I' 'P2J' 'P2K'\n",
      " 'P2Q' 'P2R' 'P2S' 'P2U' 'P2X' 'P2Y' 'P2Z' 'SIK-1' 'SIK-14' 'SIK-20']\n",
      "35 rows from df_snapshot updated with df_Historic\n",
      "34 rows updated with 'Completed - No Backlog'\n",
      "0 rows updated with 'Not completed - No Backlog'\n",
      "34 rows updated with production costs.\n",
      "Snapshot added successfully as |Snapshot| in CM-Transfer_Project-Overview_10-31-2024.xlsx\n",
      "Tabs in the workbook:\n",
      "['Snapshot', 'Summary', 'Gantt', 'Clear-to-Build', 'CM-Inventory', 'CM-BOM', 'CM-Priority', 'CM-Backlog', 'CM-TurnoverReport', 'CM-WIP', 'PendingReport', 'CM-Historic', 'CM-LaborReport', 'CM-MakeArchitecture']\n",
      "Processing |CM-ADCNReport| ...\n",
      "SEDA Shortages added successfully as|SEDA-Shortages| in CM-Transfer_Project-Overview_10-31-2024.xlsx\n",
      "Workbook saved successfully.\n",
      "Sheet names in CM-Transfer_Project-Overview_10-31-2024.xlsx: ['Snapshot', 'Summary', 'SEDA-Shortages', 'Gantt', 'Clear-to-Build', 'CM-Inventory', 'CM-BOM', 'CM-Priority', 'CM-Backlog', 'CM-TurnoverReport', 'CM-WIP', 'PendingReport', 'CM-Historic', 'CM-LaborReport', 'CM-MakeArchitecture', 'CM-ADCNReport']\n",
      "Transfer Project Overview spreadsheet generated sucessfully!\n",
      "File Inputs\\CM_Priority_Database_updated.xlsx created successfully.\n",
      "File Inputs\\CM_Priority_Database.xlsx updated successfully.\n"
     ]
    }
   ],
   "source": [
    "#Tagged Formatting\n",
    "import pandas as pd\n",
    "from IPython.display import display\n",
    "import tkinter as tk\n",
    "from tkinter import messagebox, simpledialog\n",
    "import openpyxl\n",
    "from openpyxl import Workbook \n",
    "from openpyxl import load_workbook\n",
    "from openpyxl.utils.dataframe import dataframe_to_rows\n",
    "from openpyxl.styles import PatternFill, Font, Alignment, Border, Side\n",
    "from datetime import datetime, date\n",
    "from openpyxl.utils.cell import get_column_letter\n",
    "import numpy as np\n",
    "from shutil import copyfile\n",
    "import os\n",
    "import re\n",
    "import shutil\n",
    "import warnings\n",
    "import xlsxwriter\n",
    "from openpyxl.chart import BarChart, PieChart, Reference\n",
    "from openpyxl.styles import NamedStyle\n",
    "from openpyxl.formatting.rule import CellIsRule\n",
    "\n",
    "#***************************************************************************************************************************\n",
    "#############################################################################################################################\n",
    "## ########  #########  ####    ##  ###########  ##########\n",
    "## ##        ###    ##  ##  ##  ##      ##           ##\n",
    "## ##  ####  #########  ##   ## ##      ##           ##\n",
    "## ##    ##  ##     ##  ##    ####      ##           ##\n",
    "## ########  ##     ##  ##      ##      ##           ## \n",
    "##############################################################################################################################\n",
    "#***************************************************************************************************************************\n",
    "# Starting the process with the chart as |Gantt| and create all other tabs based on the Gantt file \n",
    "#***************************************************************************************************************************\n",
    "def handle_error(error_message):\n",
    "    root = tk.Tk()\n",
    "    root.withdraw()\n",
    "    messagebox.showerror(\"Error\", error_message)\n",
    "    root.destroy()\n",
    "  \n",
    "Path = 'Inputs'  # Source folder where the file to copy resides\n",
    "PathTemp = '2_Temp-file' # Temporary folder for intermediate files\n",
    "\n",
    "try:\n",
    "    # Initialize Tkinter root\n",
    "    root = tk.Tk()\n",
    "    root.withdraw()\n",
    "\n",
    "    # Pre-fill today's date\n",
    "    default_date = datetime.now().strftime('%m-%d-%Y')\n",
    "    file_date_inventory = simpledialog.askstring(\"Inputs date\", \"Enter the date of your inputs (Inventory, Backlog, TurnoverReport) with format MM-DD-YYYY (Ex: 07-03-2024):\", parent=root, initialvalue=default_date)\n",
    "    \n",
    "    if not file_date_inventory:\n",
    "        raise ValueError(\"Date input is required.\")\n",
    "    \n",
    "    # Validate date format using regular expressions\n",
    "    if not re.match(r'\\d{2}-\\d{2}-\\d{4}', file_date_inventory):\n",
    "        raise ValueError(\"Invalid date format. Please enter the date in MM-DD-YYYY format (Ex: 07-03-2024).\")\n",
    "    \n",
    "    print(\"Inventory file Date:\", file_date_inventory)\n",
    "    \n",
    "    # Define paths and file names - New files created \n",
    "    source_file = 'CM_Gantt.xlsx'\n",
    "    original_input = f'CM-Transfer_Project-Overview_{file_date_inventory}.xlsx'\n",
    "    input_file_filtered_name = f'Clear-to-Build-{file_date_inventory}_Filtered.xlsx'\n",
    "    input_file_filtered = os.path.join(PathTemp, input_file_filtered_name)\n",
    "    \n",
    "    # Define the input file names - Existings files in 'Inputs'\n",
    "    input_file_name_CM_BOM = os.path.join(Path,'CM_BOM-QAD_Formatted.xlsx')  \n",
    "    input_file_name_Inventory = os.path.join(Path, f'CM_IDD_Inventory-{file_date_inventory}_Formatted.xlsx')\n",
    "    \n",
    "    #Check if the Inventory source file exists\n",
    "    if not os.path.isfile(input_file_name_Inventory):\n",
    "        messagebox.showwarning(\"File Not Found\", f\"Filtered file '{input_file_name_Inventory}' does not exist. Please check the entered date format.\")\n",
    "        raise ValueError(f\"Filtered file '{input_file_name_Inventory}' does not exist. Please check the entered date format.\")\n",
    "    \n",
    "    # Check if the source file exists\n",
    "    if not os.path.isfile(os.path.join(Path, source_file)):\n",
    "        raise FileNotFoundError(f\"Source file '{source_file}' not found in '{Path}'.\")\n",
    "\n",
    "    # Create the destination folder if it doesn't exist\n",
    "    os.makedirs(Path, exist_ok=True)\n",
    "    # Copy the file to the current working directory with the desired name\n",
    "    copied_file = os.path.join(os.getcwd(), original_input)\n",
    "    shutil.copy(os.path.join(Path, source_file), copied_file)\n",
    "\n",
    "    #print(f\"File '{source_file}' copied successfully as '{original_input}'.\")\n",
    "\n",
    "    # Load the copied workbook and remove external links\n",
    "    with warnings.catch_warnings():\n",
    "        warnings.simplefilter(\"ignore\")\n",
    "        wb = load_workbook(copied_file, keep_links=False)\n",
    "    \n",
    "    # Rename the first sheet to 'Gantt'\n",
    "    sheet = wb.worksheets[0]  # Assuming the first sheet needs to be renamed\n",
    "    sheet.title = 'Gantt'\n",
    "            \n",
    "    # Save the workbook\n",
    "    wb.save(copied_file)\n",
    "    wb.close()\n",
    "\n",
    "    # Verify the workbook state (optional, for debugging)\n",
    "    print(f\"Workbook state after save and close: {wb.sheetnames}\")\n",
    "    \n",
    "    print('Initialisation of the Transfer Project Overview spreadsheet ... Processing ...')\n",
    "    #print(f\"Sheet 1 renamed to 'Gantt' successfully in copied file.\")\n",
    "\n",
    "#********************************************************************************************************************************************\n",
    "#********************************************************************************************************************************************\n",
    "#############################################################################################################################\n",
    "## ##########        ##############    #########\n",
    "## ##                      ##          ##      ##\n",
    "## ##                      ##          #########\n",
    "## ##                      ##          ##      ##\n",
    "## ########## LEAR         ## O        ######### UILD\n",
    "##############################################################################################################################\n",
    "#********************************************************************************************************************************************\n",
    "#********************************************************************************************************************************************\n",
    "    # Load the Excel souce files into DataFrames\n",
    "    Inventory = pd.read_excel(input_file_name_Inventory, sheet_name=0)\n",
    "    CM_BOM = pd.read_excel(input_file_name_CM_BOM, sheet_name=0)\n",
    "\n",
    "    #Update 08/28 to make it case incensitive \n",
    "    # Filter and merge data\n",
    "    filtered_inventory = Inventory[Inventory['Site'] == 100]\n",
    "    # Make 'M/P/F' column case-insensitive\n",
    "    filtered_cm_bom = CM_BOM[\n",
    "        (CM_BOM['M/P/F'].str.upper() == 'P') | \n",
    "        (CM_BOM['M/P/F'].str.upper() == 'M')\n",
    "    ]\n",
    "    # Merge the filtered data\n",
    "    merged_data = pd.merge(filtered_inventory, filtered_cm_bom, how='inner', on=['IDD Component', 'IDD Top Level'])\n",
    "    \n",
    "    # Write data to 'Clear-to-Build' tabs in input_file_filtered\n",
    "    with pd.ExcelWriter(input_file_filtered, engine='openpyxl') as writer:\n",
    "        merged_data.to_excel(writer, sheet_name='Clear-to-Build', index=False)\n",
    "        Inventory.to_excel(writer, sheet_name='CM-Inventory', index=False)\n",
    "        CM_BOM.to_excel(writer, sheet_name='CM-BOM', index=False)\n",
    "\n",
    "    #print(f\"3 tabs added to {input_file_filtered}\")\n",
    "\n",
    "    # Load the workbook again for further manipulation\n",
    "    workbook = load_workbook(input_file_filtered)\n",
    "\n",
    "    # Drop specified columns in 'Clear-to-Build' tab in input_file_filtered\n",
    "    columns_to_drop = ['O', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA']  # drop + phantom\n",
    "    ws_clear_to_build = workbook['Clear-to-Build']\n",
    "\n",
    "    for col_letter in reversed(columns_to_drop):\n",
    "        col_index = openpyxl.utils.cell.column_index_from_string(col_letter)\n",
    "        ws_clear_to_build.delete_cols(col_index)\n",
    "\n",
    "    # Save the workbook with the modifications\n",
    "    workbook.save(input_file_filtered)\n",
    "    workbook.close()\n",
    "    #print(\"Columns dropped in |Clear-to-Build| tab.\")\n",
    "    \n",
    "    # Reorder and rename columns in 'Clear-to-Build' tab\n",
    "    ws_clear_to_build_df = pd.read_excel(input_file_filtered, sheet_name='Clear-to-Build')\n",
    "\n",
    "    # Define the new column order and names\n",
    "    columns_order = ['Priority_x', 'Pty Indice_x', 'Inventory Status', 'Site', 'Pur/Mfg', 'Description',\n",
    "                     'Qty On Hand', 'Unit cost', 'Cost Total', 'IDD Component', 'Level_x', 'BOM Qty_x',\n",
    "                     'IDD Top Level', 'SEDA Top Level_x', 'Critical Qty', 'Shipped', 'Remain. crit. Qty',\n",
    "                     'BOM Index', 'Last update']\n",
    "\n",
    "    # Reorder the columns in the DataFrame\n",
    "    ws_clear_to_build_df = ws_clear_to_build_df[columns_order]\n",
    "\n",
    "    # Rename the columns in the DataFrame\n",
    "    new_column_names = ['Priority', 'Pty Indice', 'Inventory Status', 'Site', 'Pur/Mfg', 'Description',\n",
    "                        'Qty On Hand', 'Unit cost', 'Cost Total', 'IDD Component', 'Level', 'BOM Qty',\n",
    "                        'IDD Top Level', 'SEDA Top Level', 'Critical Qty', 'Shipped', 'Remain. crit. Qty',\n",
    "                        'BOM Index', 'Last update']\n",
    "    ws_clear_to_build_df.columns = new_column_names\n",
    "\n",
    "    #display(ws_clear_to_build_df)\n",
    "    \n",
    "    # Write the modified DataFrame back to the Excel file\n",
    "    with pd.ExcelWriter(input_file_filtered, engine='openpyxl') as writer:\n",
    "        ws_clear_to_build_df.to_excel(writer, sheet_name='Clear-to-Build', index=False)\n",
    "\n",
    "    #print(\"Columns reordered and renamed in |Clear-to-Build| tab.\")\n",
    "\n",
    "    # Append modified 'Clear-to-Build' tab and 'CM-Inventory' and 'CM-BOM' tabs to original_input\n",
    "    with pd.ExcelWriter(original_input, engine='openpyxl', mode='a') as writer:\n",
    "        ws_clear_to_build_df.to_excel(writer, sheet_name='Clear-to-Build', index=False)\n",
    "        Inventory.to_excel(writer, sheet_name='CM-Inventory', index=False)\n",
    "        CM_BOM.to_excel(writer, sheet_name='CM-BOM', index=False)\n",
    "        \n",
    "    #print(f\"Modified |Clear-to-Build|, |CM-Inventory| and |CM-BOM| saved to '{original_input}'.\")\n",
    "    print(f\" |CM-Inventory| & |CM-BOM| saved to '{original_input}'.\")\n",
    "\n",
    "    #Close workbook\n",
    "    #workbook.close() # closing workbook related to input_file_filtered\n",
    "    \n",
    "    # Load the workbook to see the sheet names\n",
    "    #workbook = load_workbook(original_input)\n",
    "    # Print the sheet names\n",
    "    #print(\"Sheet names in the workbook:\")\n",
    "    #print(workbook.sheetnames)\n",
    "    print(\"Processing |Clear-to-Build| ...\")\n",
    "\n",
    "except FileNotFoundError as e:\n",
    "    print(f\"File not found: {e}\")\n",
    "\n",
    "except ValueError as e:\n",
    "    print(f\"Value error: {e}\")\n",
    "\n",
    "except Exception as e:\n",
    "    print(f\"An unexpected error occurred: {e}\")\n",
    "    \n",
    "#********************************************************************************************************************************************\n",
    "#********************************************************************************************************************************************\n",
    "## ------------------------------>>>> CREATE CLear-to-build FORMATED\n",
    "#********************************************************************************************************************************************\n",
    "#********************************************************************************************************************************************\n",
    "##############################################################################################################################\n",
    "# Looad Priority and floorstock\n",
    "##############################################################################################################################\n",
    "# Load the existing output workbook #New code 07/05\n",
    "try:\n",
    "    workbook = load_workbook(original_input)\n",
    "    #print(\"Output workbook loaded successfully.\")\n",
    "except FileNotFoundError as e:\n",
    "    print(f\"Output workbook not found: {e}\")\n",
    "    exit()\n",
    "\n",
    "'''\n",
    "# Get the active sheet\n",
    "active_sheet = workbook.active\n",
    "\n",
    "# Determine the name of the active sheet\n",
    "active_sheet_name = None\n",
    "for sheet_name in workbook.sheetnames:\n",
    "    if workbook[sheet_name] == active_sheet:\n",
    "        active_sheet_name = sheet_name\n",
    "        break\n",
    "\n",
    "# Print the active sheet name\n",
    "if active_sheet_name:\n",
    "    print(f\"Active sheet: {active_sheet_name}\")\n",
    "else:\n",
    "    print(\"No active sheet selected (workbook.active = None)\")\n",
    "'''\n",
    "\n",
    "priority_file_name = os.path.join(Path, 'CM_Priority_Database.xlsx')\n",
    "Floorstock_input = os.path.join(Path,'Floor-Stock-Items.xlsx')\n",
    "\n",
    "##############################################################################################################################\n",
    "#########################   Copying filtered file into original input while keeping first tab file      #####################\n",
    "###########################################################################################################################\n",
    "# Load the Excel file into pandas dataframes\n",
    "try:\n",
    "    df_CM_BOM = pd.read_excel(original_input, sheet_name='CM-BOM')\n",
    "    df_CTB_updated = pd.read_excel(original_input, sheet_name='Clear-to-Build')\n",
    "    df_CTB = pd.read_excel(input_file_filtered, sheet_name='Clear-to-Build')\n",
    "    df_Priority = pd.read_excel(priority_file_name, sheet_name='CM-Priority')\n",
    "    #print(\"Input files loaded successfully.\")\n",
    "except FileNotFoundError:\n",
    "    print(\"File not found. Please check the file path or name.\")\n",
    "    exit()\n",
    "###########################################################################################################################\n",
    "###########################################################################################################################\n",
    "#Update 09/09\n",
    "# Convert ['Remain. crit. Qty'] from df_Priority as integer as the file 'CM_Priority_Database.xlsx' contain a formulla instead of a number that is not properlly copied in CM-Priority \n",
    "df_Priority['Remain. crit. Qty'] = df_Priority['Remain. crit. Qty'].astype(int)\n",
    "\n",
    "# Print the 'Remain. crit. Qty' column\n",
    "#print(df_Priority['Remain. crit. Qty'])\n",
    "\n",
    "######################################  \n",
    "####     Tab Clear-to-Build    ###\n",
    "###################################### \n",
    "################################################################################################################################\n",
    "### Exploiting tab clear-to-build \n",
    "###############################################################################################################################\n",
    "#######Filtering the tab 'Clear-to-Build' to keep a single 'IDD Component' in [J] to avoid duplicate and faciliate the shortage report keeping in priority the component with 'inventory status' to 'GS', then 'R-INSP' then 'MRB' then anything else \n",
    "# Define the priority order for inventory statuses\n",
    "#New 08/07 --> Some IDD Component has to be duplicated because appear several time on the BOM and are used several time for different Make part -->  Sum 'BOM Qty' for these duplicate and keep a single row instead of erasing the row\n",
    "###########################################################################################################################\n",
    "# New code 08/08\n",
    "# Define priority order for inventory statuses\n",
    "priority_order = ['GS', 'FG', 'R-INSP', 'MRB', 'RTV', 'GIT2', 'Hold', 'Component not in Inventory']\n",
    "\n",
    "# Define a function to select the row with the highest priority inventory status for each 'IDD Top Level' and 'IDD Component'\n",
    "def select_row_with_priority(group):\n",
    "    max_priority_row = None\n",
    "    for _, row in group.iterrows():\n",
    "        status = row['Inventory Status']\n",
    "        if pd.notna(status) and status in priority_order:\n",
    "            if max_priority_row is None or priority_order.index(status) < priority_order.index(max_priority_row['Inventory Status']):\n",
    "                max_priority_row = row\n",
    "    return max_priority_row\n",
    "\n",
    "# Group by 'IDD Top Level' and 'IDD Component' and apply the function to select the row with the highest priority inventory status\n",
    "#df_CTB_updated = df_CTB_updated.groupby(['IDD Top Level', 'IDD Component']).apply(select_row_with_priority).reset_index(drop=True) # Replaced 09/24 to avoid warning\n",
    "############################# 09/24 update #############################\n",
    "# Group by 'IDD Top Level' and 'IDD Component', apply the function\n",
    "df_CTB_updated = df_CTB_updated.groupby(['IDD Top Level', 'IDD Component'], as_index=False).apply(select_row_with_priority)\n",
    "\n",
    "# Reset index to ensure proper formatting (this will keep the grouping columns intact)\n",
    "df_CTB_updated = df_CTB_updated.reset_index(drop=True)\n",
    "###########################################################################\n",
    "\n",
    "\n",
    "\n",
    "##################################\n",
    "#Update df_CTB_updated['BOM Qty'] with the sum of 'BOM Qty' from CM_BOM for a combinaison of   'IDD Top Level', 'IDD Component'\n",
    "#################################\n",
    "# Compute the sum of 'BOM Qty' from CM_BOM for each combination of 'IDD Top Level' and 'IDD Component'\n",
    "bom_qty_sum = CM_BOM.groupby(['IDD Top Level', 'IDD Component'])['BOM Qty'].sum().reset_index()\n",
    "\n",
    "# Merge the summed BOM quantities with df_CTB_updated\n",
    "df_CTB_updated = df_CTB_updated.merge(bom_qty_sum, on=['IDD Top Level', 'IDD Component'], how='left', suffixes=('', '_new'))\n",
    "\n",
    "# Update the existing 'BOM Qty' column with the new values\n",
    "df_CTB_updated['BOM Qty'] = df_CTB_updated['BOM Qty_new']\n",
    "\n",
    "# Drop the temporary 'BOM Qty_new' column\n",
    "df_CTB_updated.drop(columns=['BOM Qty_new'], inplace=True)\n",
    "\n",
    "#########################\n",
    "# Load workbook\n",
    "#########################\n",
    "with pd.ExcelWriter(original_input, engine='openpyxl') as writer:\n",
    "    # Write the DataFrame df_CTB_updated to the 'Clear-to-Build' tab\n",
    "    df_CTB_updated.to_excel(writer, sheet_name='Clear-to-Build', index=False)\n",
    "\n",
    "    # Copy other sheets from the input Excel file to the output Excel file\n",
    "    with pd.ExcelFile(input_file_filtered) as xls:\n",
    "        for sheet_name in xls.sheet_names:\n",
    "            if sheet_name != 'Clear-to-Build':\n",
    "                df = pd.read_excel(xls, sheet_name)\n",
    "                df.to_excel(writer, sheet_name=sheet_name, index=False)\n",
    "    \n",
    "    # Save the updated workbook\n",
    "    writer.book.save(original_input)\n",
    "\n",
    "# Update num_rows after saving\n",
    "num_rows = df_CTB_updated.shape[0]\n",
    "print(\"Number of rows in df_CTB_updated after keeping only unique 'IDD Component' per 'IDD Top Level':\", num_rows)\n",
    "\n",
    "#############################################################################################################\n",
    "#### Define the new columns in DataFrame df_CTB_updated should have the new columns inserted at the end ####\n",
    "#############################################################################################################\n",
    "new_columns = ['Max Qty (GS)', 'Max Qty Top-Level', 'Cost cancelation impact', 'Top Level sharing Components','Parent Components On Hand']\n",
    "#new_columns = ['Max Qty (GS)', 'Max Qty Top-Level', 'Cost cancelation impact', 'Top Level sharing Components']\n",
    "\n",
    "# Get the number of columns in the DataFrame\n",
    "num_columns = len(df_CTB_updated.columns)\n",
    "\n",
    "# Insert the new columns at the end of the DataFrame\n",
    "for column_name in new_columns:\n",
    "    df_CTB_updated.insert(loc=num_columns, column=column_name, value=None)\n",
    "    num_columns += 1  # Increment the number of columns\n",
    "\n",
    "#######################################################################################################################\n",
    "##############                Include IDD floor stock item in the clear-to-build tab              ################\n",
    "#######################################################################################################################\n",
    "# Load workbook\n",
    "with pd.ExcelWriter(original_input, engine='openpyxl') as writer:\n",
    "    # Write the DataFrame df_CTB_updated to the 'Clear-to-Build' tab\n",
    "    df_CTB_updated.to_excel(writer, sheet_name='Clear-to-Build', index=False)\n",
    "\n",
    "    # Copy other sheets from the input Excel file to the output Excel file\n",
    "    with pd.ExcelFile(input_file_filtered) as xls:\n",
    "        for sheet_name in xls.sheet_names:\n",
    "            if sheet_name != 'Clear-to-Build':\n",
    "                df = pd.read_excel(xls, sheet_name)\n",
    "                df.to_excel(writer, sheet_name=sheet_name, index=False)\n",
    "    \n",
    "    # Load the Excel file into pandas dataframes\n",
    "    df_floorstock = pd.read_excel(Floorstock_input, sheet_name='Floor-Stock')\n",
    "\n",
    "    # Merge df_floorstock with df_CTB_updated on IDD Component to update 'Max Qty (GS)' with 'Floor stock item'\n",
    "    df_CTB_updated['Max Qty (GS)'] = np.where(df_CTB_updated['IDD Component'].isin(df_floorstock['IDD Component']), 'Floor stock item', df_CTB_updated['Max Qty (GS)'])\n",
    "\n",
    "###############################################################\n",
    "####### Create new columns on the 'Clear-to-Build' tab     #########################################################################################\n",
    "######[T] Max Qty (GS) - Only considering 'GS' only from [C], while part in [C] = 'R-INSP' are excluded from this calculation and set as 'N/A' in [T] and with  [T] Max Qty = Qty on hand [G] / BOM Qty [L]\n",
    "# For setting values in 'Max Qty (GS)' column only considering integer as the not integer seems to be 'floor stock'\n",
    "####################################################################################################################################################\n",
    "'''\n",
    "    # New 09/23 - Check if 'BOM Qty' is a float and has a decimal part, return 'Floor stock item CUU'\n",
    "    bom_qty = row['BOM Qty']\n",
    "    if pd.notnull(bom_qty) and not float(bom_qty).is_integer():\n",
    "        return 'Floor stock item CUU' # Handles BOM quantities with decimal parts that are not present on the IDD floor-stock file\n",
    "'''\n",
    "def calculate_max_qty(row):\n",
    "    # If 'Max Qty (GS)' already contains 'Floor stock item', leave it unchanged\n",
    "    if row['Max Qty (GS)'] == 'Floor stock item':\n",
    "        return 'Floor stock item'  # If 'Max Qty (GS)' already contains 'Floor stock item', leave it unchanged\n",
    "    \n",
    "    if pd.notnull(row['Qty On Hand']) and pd.notnull(row['BOM Qty']):\n",
    "        qty_on_hand = row['Qty On Hand']\n",
    "        bom_qty = row['BOM Qty']\n",
    "        \n",
    "        # Check if 'BOM Qty' is zero or float \n",
    "        if bom_qty == 0:\n",
    "            return 'Floor stock item'\n",
    "        \n",
    "        # Check if both 'Qty On Hand' and 'BOM Qty' are integers or have a .0 decimal part\n",
    "        elif qty_on_hand == int(qty_on_hand) and bom_qty == int(bom_qty):\n",
    "            # Check if 'Inventory Status' is 'GS' or 'FG'\n",
    "            if row['Inventory Status'] in ['GS', 'FG']:\n",
    "                return int(qty_on_hand // bom_qty)\n",
    "            else:\n",
    "                return 0  # If 'Inventory Status' is not 'GS' or 'FG', return 0 -- \n",
    "        else:\n",
    "            return 'Floor stock item'  # Return None if either 'Qty On Hand' or 'BOM Qty' is not integer\n",
    "    else:\n",
    "        return 'Floor stock item'  # Return None if either 'Qty On Hand' or 'BOM Qty' is null\n",
    "\n",
    "# Apply the function to calculate values for the 'Max Qty (GS)' \n",
    "df_CTB_updated['Max Qty (GS)'] = df_CTB_updated.apply(calculate_max_qty, axis=1)\n",
    "\n",
    " # Print a message indicating the completion of the process\n",
    "print('Max Qty (GS) filled.')\n",
    "\n",
    "########################################################################################################################################################\n",
    "###[W] Shared Components - Listing of the Top-Level using the component to managed the potential shared component by listing in [W] all the top level from [M] using this 'IDD component' from [J]\n",
    "# Define a function to list shared components   #########################################################################################################\n",
    "##########################################################\n",
    "#08/09 - Keep the code to avoid changing the order of column \n",
    "# Define the function to list shared components\n",
    "def list_shared_components(row, df):\n",
    "    component = row['IDD Component']\n",
    "    # Filter the DataFrame using boolean indexing\n",
    "    filtered_df = df[df['IDD Component'] == component]\n",
    "    # Select the desired columns\n",
    "    top_levels = filtered_df[['IDD Top Level', 'Pty Indice']]\n",
    "    # Drop duplicates\n",
    "    top_levels.drop_duplicates(inplace=True)\n",
    "    # Check if top_levels is empty\n",
    "    if not top_levels.empty:\n",
    "        # Return all shared top levels as a list\n",
    "        #return list(top_levels.apply(lambda x: f\"{x['IDD Top Level']} [{x['Pty Indice']}]\", axis=1))\n",
    "        return list(top_levels.apply(lambda x: f\"{x['Pty Indice']}\", axis=1))\n",
    "    return None\n",
    "\n",
    "# Assuming df_CTB_Updated is already defined and loaded\n",
    "# Apply the function to create 'Top Level sharing Components' column using a lambda function\n",
    "df_CTB_updated['Top Level sharing Components'] = df_CTB_updated.apply(lambda row: list_shared_components(row, df_CTB_updated), axis=1)\n",
    "\n",
    "# Now we have lists of shared components, let's concatenate them into a single string separated by ;\n",
    "df_CTB_updated['Top Level sharing Components'] = df_CTB_updated['Top Level sharing Components'].apply(lambda x: '; '.join(x) if x is not None else None)\n",
    "\n",
    "# Save the updated Clear-to-Build tab to an Excel file\n",
    "df_CTB_updated.to_excel(original_input, sheet_name='Clear-to-Build', index=False)\n",
    "\n",
    "# Print a message indicating the completion of the process\n",
    "print(\"Top Level sharing Components filled and saved to\", original_input)\n",
    "\n",
    "########################################################################################################################################################\n",
    "###[V] Cost impact if cancelation - Calculate the impact for IDD of the the cancelation of an order by calculating the total cost of the inventory on hand that won't be used if Top Level is canceled \n",
    "# Define a function to calculate 'Cost cancelaation impact'  \n",
    "##########################################################\n",
    "# Calculation should be IF ('Remaining critical Qty' < 'Qty On Hand', 'Remaining critical Qty' * 'Unit cost', 'Qty On Hand' *  'Unit cost')\n",
    "# Define a function to calculate 'Cost impact if cancellation'\n",
    "\n",
    "# Define a function to calculate 'Cost impact if cancellation'\n",
    "def calculate_cancellation_impact(row):\n",
    "    remaining_critical_qty = pd.to_numeric(row['Remain. crit. Qty'], errors='coerce')\n",
    "    qty_on_hand = pd.to_numeric(row['Qty On Hand'], errors='coerce')\n",
    "    unit_cost = pd.to_numeric(row['Unit cost'], errors='coerce')\n",
    "    \n",
    "    if pd.notnull(remaining_critical_qty) and pd.notnull(qty_on_hand) and pd.notnull(unit_cost):\n",
    "        if remaining_critical_qty < qty_on_hand:\n",
    "            return remaining_critical_qty * unit_cost\n",
    "        else:\n",
    "            return qty_on_hand * unit_cost\n",
    "    else:\n",
    "        return 'N/A'  # Return 'N/A' if any of the required columns have missing or non-numeric values\n",
    "\n",
    "# Apply the function to create the 'Cost impact if cancellation' [V] column\n",
    "df_CTB_updated['Cost cancelation impact'] = df_CTB_updated.apply(calculate_cancellation_impact, axis=1)\n",
    "\n",
    "# Print a message indicating the completion of the process\n",
    "print('Cost cancelation impact filled.')\n",
    "\n",
    "#######################################################################################################################\n",
    "##############             Include missing component to tab Clear-to-Build tab from tab CM-BOM          ################\n",
    "#######################################################################################################################\n",
    "### This section should include the 'IDD Component' from tab 'CM-BOM' with column 'M/P/F' = 'P' missing in tab 'Clear-to-Build' for a given 'IDD Top Level' \n",
    "## Additionnaly, considering tab CM-BOM, for a given 'IDD Top Level', we need to excluded for this list of missing component, the 'IDD Component' which has a upper 'Level' with 'M/F/P' = 'P'\n",
    "# For example: 'IDD Component' 100-230909-003 is 'Level' = 4 but for a given 'IDD Top Level', there is a 340-000811-001 with 'Level' = 3 and 'M/P/F' = P menaning that it is a purchase part so 100-230909-003 should be exluded \n",
    "# --> We need to ensure that if a lower-level component is marked as 'M', then all its parent components up to the root level should be included in the missing components list\n",
    "\n",
    "# Define a mapping dictionary to map column names from CM-BOM to Clear-to-Build\n",
    "column_mapping = {\n",
    "    'Priority':'Priority',\n",
    "    'Pty Indice': 'Pty Indice',\n",
    "    'Inventory Status': 'Inventory Status',  # Add the 'Inventory Status' column mapping\n",
    "    'Site':'Site',  # Add the 'Site' column mapping\n",
    "    'M/P/F':'Pur/Mfg', \n",
    "    'Description Component':'Description',\n",
    "    'Qty On Hand':'Qty On Hand', # Add the 'Qty on Hand' column mapping\n",
    "    'Unit cost':'Unit cost', # Add the 'Site' column mapping\n",
    "    'Cost Total':'Cost Total', # Add the 'Cost Total' column mapping\n",
    "    'IDD Component': 'IDD Component',\n",
    "    'Level': 'Level',\n",
    "    'BOM Qty':'BOM Qty',\n",
    "    'IDD Top Level':'IDD Top Level',\n",
    "    'SEDA Top Level':'SEDA Top Level',\n",
    "    'Critical Qty':'Critical Qty', # Add the 'Critical Qty' column mapping\n",
    "    'Shipped':'Shipped', # Add the 'Shipped' column mapping\n",
    "    'Remain. crit. Qty':'Remain. crit. Qty', # Add the 'Remaining critical Qty' column mapping\n",
    "    'BOM Index':'BOM Index',\n",
    "    'Last update':'Last update' # Add the 'Last Update' column mapping\n",
    "}\n",
    "\n",
    "#***********************************************\n",
    "# ---->>> INCLUDE MAKE PART MISSING in addition to P parts\n",
    "#*************************************************\n",
    "# Identify missing components with 'M/P/F' = 'P'\n",
    "#missing_components = df_CM_BOM[(df_CM_BOM['M/P/F'] == 'P') & (~df_CM_BOM['IDD Component'].isin(df_CTB_updated['IDD Component']))]\n",
    "#missing_components = df_CM_BOM[((df_CM_BOM['M/P/F'] == 'P') | (df_CM_BOM['M/P/F'] == 'M')) & (~df_CM_BOM['IDD Component'].isin(df_CTB_updated['IDD Component']))]                    \n",
    "\n",
    "#Update 08/28 to include case incencive \n",
    "# Identify missing components with 'M/P/F' = 'P' or 'M' (case insensitive), excluding Level 0 components\n",
    "missing_components = df_CM_BOM[\n",
    "    ((df_CM_BOM['M/P/F'].str.upper() == 'P') | (df_CM_BOM['M/P/F'].str.upper() == 'M')) & \n",
    "    (~df_CM_BOM['IDD Component'].isin(df_CTB_updated['IDD Component'])) & \n",
    "    (df_CM_BOM['Level'] != 0)\n",
    "]\n",
    "\n",
    "# Get the IDs of missing components\n",
    "missing_component_ids = missing_components['IDD Component'].tolist()\n",
    "\n",
    "# Print the missing components\n",
    "num_missing_components = len(missing_component_ids)\n",
    "print('Number of missing components:', num_missing_components)\n",
    "\n",
    "# Display the missing components dataframe\n",
    "#print(\"Missing components from CM-BOM:\")\n",
    "#display(missing_components)\n",
    "\n",
    "# Append missing rows to df_CTB_updated with correct column values\n",
    "new_rows = []\n",
    "for index, row in missing_components.iterrows():\n",
    "    new_row = {}\n",
    "    for col_cm_bom, col_ctb in column_mapping.items():\n",
    "        if col_cm_bom in df_CM_BOM.columns:\n",
    "            new_row[col_ctb] = row[col_cm_bom]\n",
    "        else:\n",
    "            # Set default value for missing columns\n",
    "            if col_ctb == 'Inventory Status':\n",
    "                new_row[col_ctb] = 'Component not in Inventory'\n",
    "            elif col_ctb == 'Qty On Hand':\n",
    "                new_row[col_ctb] = 0\n",
    "            else:\n",
    "                # Set default value based on your requirement\n",
    "                new_row[col_ctb] = None  # You can replace None with appropriate default values if needed\n",
    "    new_rows.append(new_row)\n",
    "\n",
    "# Convert the list of dictionaries to a DataFrame\n",
    "new_rows_df = pd.DataFrame(new_rows)\n",
    "\n",
    "# Get the updated number of rows in df_CTB_updated\n",
    "num_rows = df_CTB_updated.shape[0]\n",
    "print(\"Number of rows in |Clear-to-Build| before including missing component:\", num_rows)\n",
    "\n",
    "# Concatenate the new rows DataFrame with df_CTB_updated\n",
    "# df_CTB_updated = pd.concat([df_CTB_updated, new_rows_df], ignore_index=True) # Updated 09/24 to avoid warning\n",
    "\n",
    "##### update 09/24 ##################\n",
    "# Ensure no empty or all-NA columns in new_rows_df\n",
    "new_rows_df = new_rows_df.dropna(axis=1, how='all')\n",
    "# Concatenate the DataFrames\n",
    "df_CTB_updated = pd.concat([df_CTB_updated, new_rows_df], ignore_index=True)\n",
    "####################################\n",
    "\n",
    "# Get the updated number of rows in df_CTB_updated\n",
    "num_rows = df_CTB_updated.shape[0]\n",
    "\n",
    "# Print the shape of the DataFrame after appending missing components\n",
    "print(\"Number of rows in |Clear-to-Build| after appending missing components - Including Make Part:\", df_CTB_updated.shape[0])\n",
    "\n",
    "#########################################################################################\n",
    "# Save the updated Clear-to-Build tab\n",
    "try:\n",
    "    with pd.ExcelWriter(original_input, engine='openpyxl') as writer:\n",
    "        df_CTB_updated.to_excel(writer, sheet_name='Clear-to-Build', index=False)\n",
    "    print('Missing components from |CM-BOM| have been included in |Clear-to-Build|.')\n",
    "except PermissionError:\n",
    "    print(\"Permission denied. Please make sure the file is not open and try again.\")\n",
    "    exit()\n",
    "\n",
    "# Save the updated workbook\n",
    "workbook.save(original_input)\n",
    "workbook.close()\n",
    "\n",
    "#################################################################\n",
    "### Based on BOM Index reordering \n",
    "##############################################################\n",
    "# Reordering 'Clear-to-Build' based on BOM Index and IDD Top level\n",
    "df_CTB_updated = df_CTB_updated.sort_values(by=['IDD Top Level', 'BOM Index'])\n",
    "\n",
    "##############################################\n",
    "# [T] Max Qty (GS) to N/A if BOM Qty = 0\n",
    "###############################################\n",
    "# Update 'Max Qty (GS)' to 'N/A' if 'BOM Qty' is 0, only if 'Max Qty (GS)' is NaN\n",
    "condition = (df_CTB_updated['BOM Qty'] == 0) & (df_CTB_updated['Max Qty (GS)'].isna())\n",
    "\n",
    "df_CTB_updated.loc[condition, 'Max Qty (GS)'] = 'N/A'\n",
    "\n",
    "####################################################################\n",
    "## [V] Cost Cancelation impact for 'Component not in inventory' to N/A \n",
    "## #################################################################\n",
    "# Update 'Cost cancelation impact' to 'N/A' if 'Inventory Status' is 'Component not in Inventory'\n",
    "# but retain 'Floor stock item' where it already exists\n",
    "condition = (df_CTB_updated['Inventory Status'] == 'Component not in Inventory') & \\\n",
    "            (df_CTB_updated['Cost cancelation impact'] != 'Floor stock item')\n",
    "\n",
    "df_CTB_updated.loc[condition, 'Cost cancelation impact'] = 'N/A'\n",
    "\n",
    "###############################################################\n",
    "####### Create new columns on the 'Clear-to-Build' tab     #########################################################################################\n",
    "######[X] Parent component On Hand' - In order to define if we are clear to build, for a given component we need to consider the potential 'M' component which is a parent component to a 'P' component (upper Level) that we might have in 'GS' \n",
    "#### The 'Max Qty Top-Level' should include the 'M' parent component on hand instead of the lower level component if > to the 'Max Qty (GS) of this given component \n",
    "#### In order to find the Qty of 'M' parent component in 'GS' we need to use the tab 'CM-Iventory' to get the Qty on hand, combined with 'CM-BOM' to get the architecture from\n",
    "####################################################################################################################################################\n",
    "#Sorting: Ensure the DataFrame is sorted by 'Pty Indice' and 'BOM Index' for proper sequential processing.\n",
    "#Filtering by Pty Indice: Iterate over each unique 'Pty Indice' and filter the DataFrame for the selected 'Pty Indice'.\n",
    "#Sub-group Creation: Within each 'Pty Indice', detect sub-groups by identifying 'Level 1' components and their ranges.\n",
    "#Parent Component Detection: For each row in the sub-group, find parent components within the same sub-group that have a lower 'Level' and a non-zero 'Qty On Hand'.\n",
    "###########################################################################\n",
    "###################### REQUIREMENTS  ######################################\n",
    "###########################################################################\n",
    "'''\n",
    "This code defines a function called process_subgroup and then iterates over each group in the DataFrame df_CTB_updated, where the groups are defined based on the 'Pty Indice' column. For each group, it performs the following steps:\n",
    "1. Initializes variables to keep track of the previous parent component information, the start index of the subgroup, and iterates over each row in the group DataFrame.\n",
    "2. Checks if the current row is a Level 1 component. If it is, it processes the previous subgroup (if any) using the process_subgroup function and updates the start index to the current index.\n",
    "3. Updates the previous parent component information.\n",
    "4. Processes the last subgroup in the group by calling the process_subgroup function with the start index, end index (maximum index in the group), and previous parent component information.\n",
    "\n",
    "The process_subgroup function takes a DataFrame, start index, end index, and previous parent component information as input. Within this function, it:\n",
    "1. Prints a message indicating the start and end indices of the subgroup being processed.\n",
    "2. Obtains the subgroup DataFrame based on the start and end indices.\n",
    "3. Iterates over each row in the subgroup and checks if the 'BOM Index' is not NaN.\n",
    "4. Finds parent components within the subgroup by filtering the DataFrame based on conditions such as the index being less than the current index, the 'Level' being lower than the current row's level, and the 'Qty On Hand' being greater than 0.\n",
    "5. If parent components are found, it updates the 'Parent Components On Hand' column in the original DataFrame with information about the parent component(s) found.\n",
    "--> Overall, this code aims to find parent components for each row in the DataFrame within subgroups defined by the Level 1 components and update the 'Parent Components On Hand' column accordingly.\n",
    "\n",
    "The subgroup creation logic is implemented within the main loop iterating over each group in the DataFrame based on the 'Pty Indice' column. Here's how the subgroup creation works within the code:\n",
    "1. The iteration begins over each row in the group DataFrame.\n",
    "2. When encountering a Level 1 component, it starts a new subgroup. The start index of the subgroup is updated to the index of the Level 1 component.\n",
    "3. For each row after the start of a subgroup and before the next Level 1 component, it processes the previous subgroup.\n",
    "4. The end index of the subgroup is set to the maximum index in the group DataFrame when reaching the next Level 1 component or the end of the DataFrame.\n",
    "5 The process_subgroup function is called for each subgroup, passing the start index, end index, and previous parent component information.\n",
    "6. The process_subgroup function processes each row within the subgroup to find and update the parent component information.\n",
    "--> Overall, the subgroup creation is implicitly defined by the logic of starting a new subgroup when encountering a Level 1 component and ending it before the next Level 1 component. This ensures that each subgroup contains all the rows between two consecutive Level 1 components.\n",
    "\n",
    "The issue might be within the process_subgroup function, where it searches for and updates the parent component information. Let's break down what the function does:\n",
    "1. Subgroup Selection: It takes the start and end indices to define the subgroup within the DataFrame.\n",
    "2. Iteration Over Rows: It iterates over each row within the subgroup.\n",
    "3. Parent Component Search:\n",
    "- For each row, it checks if the 'BOM Index' is not NaN, indicating a component.\n",
    "    -- Then, it filters the DataFrame to find potential parent components within the same subgroup:\n",
    "    -- Rows with an index less than the current row's index.\n",
    "    -- Rows with a 'Level' lower than the current row's 'Level'.\n",
    "    -- Rows with a positive 'Qty On Hand'.\n",
    "- If parent components are found, it selects the one with the smallest 'Level' (Level 1 over Level 2 etc). The function selects the parent component with the highest 'Level' (= lowest value) to ensure it's the closest parent to the current component in the hierarchy) and updates the 'Parent Components On Hand' column for the current row.\n",
    "\n",
    "\n",
    "Restrict the search for parent components within the same subgroup only, which means we should not consider Level 1 components from other subgroups as potential parent components\n",
    "--> Ensures that each subgroup contains ONLY ONE Level 1 --  strictly limit the search for parent components within the same subgroup, we'll add a condition to reset the start index whenever we encounter a Level 1 component. This will effectively partition the data into subgroups based on Level 1 components and ensure that parent-child relationships are only established within these subgroups\n",
    "\n",
    "##### UPDATE\n",
    "1. Wihtin the existing sub-group function (based on level == 1), create a new function sub-subgroup to define the Make architecture of this sub-group (starts with a M part and finish at the last 'P' part before the next 'M' part)\n",
    "2. A parent component is necessary a 'M' part of a child which is also a 'M' Part \n",
    "3. A parent component is necessary a 'P' part of a child which is a 'P' Part AND within the same sub-subgroup \n",
    "\n",
    "##### UPDATE 2\n",
    "1. Phantomed component ['Phantom'] = 'Oui' have to be identified on the BOM and the row skiped from the search as it will never be in GS but remaing important to define the sub-subgroup function\n",
    "2. Wihtin the existing sub-group function (based on level == 1), create a new function sub-subgroup to define the Make architecture of this sub-group (starts with a M part and finish at the last 'P' part before the next 'M' part)\n",
    " a. A parent component is necessary a 'M' part of a child which is also a 'M' Part \n",
    " b a 'phantom' part \n",
    " a. A 'P' part always goes on a 'M' Part with higher level (Level = 3 goes in level = 2 or 1)\n",
    " b. A 'P' parts can be parent only of a 'M' part with a higher level within the same sub-subgroup \n",
    "\n",
    "'''\n",
    "# Additional requirements:\n",
    "# 09/20 - Pur/Mfg == 'D' mean that this is a Make Part build at CUU --> D should be treated as a M part meaning that if we have some stock of a 'D' part we don't need the lower level because transfered from CUU to RED.\n",
    "# If 'Inventory Status' = 'Component not in Inventory' and the there is a row containing 'Pur/Mfg' = 'D' within the subgroupd at a upper level of a given 'IDD Component' then this component should be return in the 'Parent Components On Hand' column \n",
    "## Datafram Example: 100-400798-002 should be return as a 'Parent component' for 100-400798-002\n",
    "# Pty Indice\tInventory Status\tSite\tPur/Mfg\tDescription\tQty On Hand\tUnit cost\tCost Total\tIDD Component\tLevel\n",
    "# P17A\tGS\t100\tD\tCIRCUIT BOARD\t335\t2.927483334\t980.7069168\t100-400798-002\t2\n",
    "# P17A\tComponent not in Inventory\t\tP\t.031 FIBERGLASS SHEET\t0\t\t\t100-400753-001\t3\n",
    "\n",
    "###########################################################################\n",
    "######################    CODE WIP   ######################################\n",
    "###########################################################################\n",
    "# Remove duplicates based on relevant columns\n",
    "df_CTB_updated.drop_duplicates(subset=['Pty Indice', 'BOM Index', 'Level', 'IDD Component', 'Qty On Hand'], keep='first', inplace=True)\n",
    "\n",
    "# Create a new column 'Parent Components On Hand' with default value \"No parent component on hand\"\n",
    "df_CTB_updated['Parent Components On Hand'] = \"No parent component on hand\"\n",
    "\n",
    "# Sort the DataFrame by 'Pty Indice' and 'BOM Index' to ensure proper processing\n",
    "df_CTB_updated.sort_values(by=['Pty Indice', 'BOM Index'], inplace=True)\n",
    "\n",
    "# Function to identify and process sub-subgroups\n",
    "def identify_subsubgroup(subgroup_df):\n",
    "    subsubgroups = []\n",
    "    current_subsubgroup = []\n",
    "    m_part_found = False\n",
    "    \n",
    "    for index, row in subgroup_df.iterrows():\n",
    "        if row['Level'] == 1:\n",
    "            if m_part_found and current_subsubgroup:\n",
    "                subsubgroups.append(current_subsubgroup)\n",
    "                current_subsubgroup = []\n",
    "            current_subsubgroup.append(index)\n",
    "            m_part_found = True\n",
    "        elif m_part_found and row['Level'] == 2:\n",
    "            current_subsubgroup.append(index)\n",
    "    \n",
    "    # Append the last sub-subgroup\n",
    "    if current_subsubgroup:\n",
    "        subsubgroups.append(current_subsubgroup)\n",
    "    \n",
    "    return subsubgroups\n",
    "\n",
    "# Updated 09/03 as upper code was returning an error \n",
    "# Function to process each subgroup\n",
    "def process_subgroup(df, start_index, end_index):\n",
    "    # Obtain the subgroup DataFrame\n",
    "    if isinstance(start_index, int) and isinstance(end_index, int):\n",
    "        subgroup_df = df.iloc[start_index:end_index+1]\n",
    "    else:\n",
    "        print(f\"Invalid indices: {start_index}, {end_index}\")\n",
    "        return\n",
    "    \n",
    "    parent_updates_count = 0  # To store the count of parent component updates\n",
    "    \n",
    "    # Check if subgroup DataFrame is not empty and contains exactly one Level 1 component\n",
    "    if not subgroup_df.empty and subgroup_df['Level'].eq(1).sum() == 1:\n",
    "        # Get the Pty Indice value for the subgroup\n",
    "        pty_indice_value = subgroup_df.iloc[0]['Pty Indice']\n",
    "        \n",
    "        # Identify and process each sub-subgroup\n",
    "        subsubgroups = identify_subsubgroup(subgroup_df)\n",
    "        \n",
    "        for subsubgroup_indices in subsubgroups:\n",
    "            # Extract sub-subgroup DataFrame\n",
    "            subsubgroup_df = df.loc[subsubgroup_indices]\n",
    "            m_part_found = False\n",
    "            parent_component_info = None\n",
    "            \n",
    "            # Iterate over each row in the sub-subgroup\n",
    "            for index, row in subsubgroup_df.iterrows():\n",
    "                if row['Level'] == 1:\n",
    "                    m_part_found = True\n",
    "                elif m_part_found and row['Level'] == 2:\n",
    "                    # Find parent components that are 'M' parts and closest based on 'BOM Index'\n",
    "                    parent_components_rows = subgroup_df[\n",
    "                        (subgroup_df.index < index) &  # Exclude current row\n",
    "                        (subgroup_df['Level'] < row['Level']) &\n",
    "                        (subgroup_df['Qty On Hand'] > 0) &  # Filter for components with Qty > 0\n",
    "                        (subgroup_df['Pty Indice'] == pty_indice_value) &  # Ensure same Pty Indice\n",
    "                        (subgroup_df['IDD Component'].str.startswith('M'))  # Filter for 'M' parts\n",
    "                    ]\n",
    "                    \n",
    "                    # If parent component(s) are found, select the one with closest BOM Index\n",
    "                    if not parent_components_rows.empty:\n",
    "                        closest_parent = parent_components_rows.loc[\n",
    "                            parent_components_rows['BOM Index'].idxmin()  # Select the row with the smallest BOM Index\n",
    "                        ]\n",
    "                        if parent_component_info is not None:\n",
    "                            parent_component_info += \", \"\n",
    "                        else:\n",
    "                            parent_component_info = \"\"\n",
    "                        parent_component_info += (\n",
    "                            f\"{closest_parent['IDD Component']} (Level {int(closest_parent['Level'])}): Qty = {int(closest_parent['Qty On Hand'])}\"\n",
    "                        )\n",
    "                        parent_updates_count += 1\n",
    "            \n",
    "            # Update 'Parent Components On Hand' column in the original DataFrame\n",
    "            if parent_component_info:\n",
    "                df.loc[subsubgroup_df.index, 'Parent Components On Hand'] = parent_component_info\n",
    "    \n",
    "    # Summary print statement for the subgroup\n",
    "    # print(f\"Processed Subgroup from index {start_index} to {end_index} with {parent_updates_count} parent updates.\")\n",
    "\n",
    "# Group the DataFrame by 'Pty Indice'\n",
    "grouped = df_CTB_updated.groupby('Pty Indice')\n",
    "\n",
    "# Iterate over each group\n",
    "for group_name, group_df in grouped:\n",
    "    # Initialize the start index of the subgroup\n",
    "    start_index = None\n",
    "    \n",
    "    # Iterate over each row in the group\n",
    "    for index, row in group_df.iterrows():\n",
    "        # Check if the current row is a Level 1 component and Level is not 0\n",
    "        if row['Level'] == 1 and row['Level'] != 0:\n",
    "            # Process the previous subgroup if it exists\n",
    "            if start_index is not None:\n",
    "                end_index = index - 1\n",
    "                process_subgroup(df_CTB_updated, start_index, end_index)\n",
    "            # Reset the start index for the new subgroup\n",
    "            start_index = index\n",
    "    \n",
    "    # Process the last subgroup if start_index is not None\n",
    "    if start_index is not None:\n",
    "        end_index = len(group_df) - 1\n",
    "        process_subgroup(df_CTB_updated, start_index, end_index)\n",
    "\n",
    "# Display the updated DataFrame\n",
    "#display(df_CTB_updated)\n",
    "## End of update 09/03\n",
    "\n",
    "###########################################################################\n",
    "##########################################################################\n",
    "## Update Max Qty (GS) base on Parent component (GS) \n",
    "    ## Read Parent component (GS) on exctrat the higest number, for example:\n",
    "        ## 100-280013-1 (Level 2): Qty = 6, 100-280113-1 (Level 2): Qty = 13, 100-280195-1 (Level 1): Qty = 7 --> extract 7 \n",
    "            ## Fill Max Qty (GS) with the current value + the extracting value \n",
    "########################################################\n",
    "# Initialize a dictionary to store the maximum Qty On Hand for each parent component\n",
    "max_qty_dict = {}\n",
    "\n",
    "# Iterate over each row in df_CTB_updated\n",
    "for _, row in df_CTB_updated.iterrows():\n",
    "    # Extract the parent components on hand from the 'Parent Components On Hand' column\n",
    "    parent_components_on_hand = row['Parent Components On Hand'].split(', ')\n",
    "    \n",
    "    # Iterate over each parent component\n",
    "    for parent_component_info in parent_components_on_hand:\n",
    "        # Split the parent component info to extract quantity and unit\n",
    "        parent_info_split = parent_component_info.split('=')\n",
    "        if len(parent_info_split) >= 2:\n",
    "            parent_qty_info = parent_info_split[1].strip().split()\n",
    "            if len(parent_qty_info) >= 2:\n",
    "                parent_qty_on_hand = int(parent_qty_info[1])\n",
    "                \n",
    "                # Extract the parent component number\n",
    "                parent_component_number = parent_info_split[0].split('(')[0].strip()\n",
    "                \n",
    "                # Update the maximum quantity for the parent component in the max_qty_dict\n",
    "                if parent_component_number in max_qty_dict:\n",
    "                    max_qty_dict[parent_component_number] = max(max_qty_dict[parent_component_number], parent_qty_on_hand)\n",
    "                else:\n",
    "                    max_qty_dict[parent_component_number] = parent_qty_on_hand\n",
    "\n",
    "# Update the 'Max Qty (GS)' column based on the maximum quantity from parent components\n",
    "for index, row in df_CTB_updated.iterrows():\n",
    "    max_qty = row['Max Qty (GS)']\n",
    "    \n",
    "    # Extract parent component numbers from the 'Parent Components On Hand' column\n",
    "    parent_components_on_hand = row['Parent Components On Hand'].split(', ')\n",
    "    \n",
    "    # Iterate over each parent component and its maximum quantity\n",
    "    for parent_component_info in parent_components_on_hand:\n",
    "        # Split the parent component info to extract quantity and unit\n",
    "        parent_info_split = parent_component_info.split('=')\n",
    "        if len(parent_info_split) >= 2:\n",
    "            parent_qty_info = parent_info_split[1].strip().split()\n",
    "            if len(parent_qty_info) >= 2:\n",
    "                parent_component_number = parent_info_split[0].split('(')[0].strip()\n",
    "                parent_qty_on_hand = max_qty_dict.get(parent_component_number, 0)\n",
    "                max_qty = max(max_qty, parent_qty_on_hand)\n",
    "    \n",
    "    # Update the 'Max Qty (GS)' column with the new maximum quantity\n",
    "    df_CTB_updated.at[index, 'Max Qty (GS)'] = max_qty\n",
    "\n",
    "# Print a message indicating the completion of the process\n",
    "print('Max Qty (GS) updated.')\n",
    "\n",
    "############################################################################################\n",
    "## Updated Max Qty (GS) with floor stock Itemp to consider 'Component not in Inventory' \n",
    "############################################################################################\n",
    "# If Inventory Status = 'Component not in Inventory' AND 'IDD Component' part of floor-stock file, then update the Max Qty (GS) with 'Floor stock item'\n",
    "#df_floorstock = pd.read_excel('Floor-Stock-Items.xlsx', sheet_name='Floor-Stock')\n",
    "\n",
    "# Check if 'IDD Component' is in the floor-stock file and 'Inventory Status' is 'Component not in Inventory'\n",
    "mask = (df_CTB_updated['IDD Component'].isin(df_floorstock['IDD Component'])) & (df_CTB_updated['Inventory Status'] == 'Component not in Inventory')\n",
    "\n",
    "# Update 'Max Qty (GS)' with 'Floor stock item' where the condition is met\n",
    "df_CTB_updated.loc[mask, 'Max Qty (GS)'] = 'Floor stock item'\n",
    "\n",
    "#################################################################################################################################################################################\n",
    "# Updated 09/23 - Updated Max Qty (GS) with 'Make Part CUU' --> To not considered rows where Pur/Mfg' == 'D' to define 'Max Qty Top-Level' --> Write 'Make Part CUU' on 'Max Qty (GS)' so it won't be considered in df_Summary\n",
    "#################################################################################################################################################################################\n",
    "# Update 'Max Qty (GS)' with 'Make Part CUU' where 'Pur/Mfg' is 'D'\n",
    "df_CTB_updated.loc[df_CTB_updated['Pur/Mfg'] == 'D', 'Max Qty (GS)'] = 'Make Part CUU'\n",
    "\n",
    "print('Max Qty (GS) updated with Floor stock Item and Make Part from CUU')\n",
    "\n",
    "##############################################################\n",
    "### for a given IDD Top Level put [T] Max (GS) to 'Upper level on hand' if: \n",
    "    ## 'Inventory status' = 'Component not in Inventory' \n",
    "        ##********** OR 'Inventory status' = 'GS' & 'Max Qty (GS)' = 0  ************\n",
    "##############################################################\n",
    "# Iterate over each row in df_CTB_updated --> # Update 09/23 to not consider 'BOM Qty' not integer in the 'Max Qty Top-Level' calculation \n",
    "for idx, row in df_CTB_updated.iterrows():\n",
    "    # Check if 'BOM Qty' is an integer\n",
    "    if pd.notnull(row['BOM Qty']) and row['BOM Qty'] == int(row['BOM Qty']):\n",
    "        # Check Upper Levels based on 'Parent Components On Hand' and BOM Qty > 0\n",
    "        if ((row['Inventory Status'] == 'Component not in Inventory' or \n",
    "             (row['Inventory Status'] == 'GS' and row['Max Qty (GS)'] == 0)) and \n",
    "             isinstance(row['Parent Components On Hand'], str) and row['BOM Qty'] > 0):\n",
    "            if row['Parent Components On Hand'] == 'No parent component on hand':\n",
    "                if row['Max Qty (GS)'] != 'Floor stock item':  # Check if the current value is not 'Floor stock item'\n",
    "                    df_CTB_updated.at[idx, 'Max Qty (GS)'] = 0\n",
    "            else:\n",
    "                if row['Max Qty (GS)'] != 'Floor stock item':  # Check if the current value is not 'Floor stock item'\n",
    "                    df_CTB_updated.at[idx, 'Max Qty (GS)'] = row['Parent Components On Hand']\n",
    "\n",
    "\n",
    "''' SAVED 09/23\n",
    "for idx, row in df_CTB_updated.iterrows():\n",
    "    # Check Upper Levels based on 'Parent Components On Hand' and BOM Qty > 0 \n",
    "    if ((row['Inventory Status'] == 'Component not in Inventory' or \n",
    "         (row['Inventory Status'] == 'GS' and row['Max Qty (GS)'] == 0)) and \n",
    "         isinstance(row['Parent Components On Hand'], str) and row['BOM Qty'] > 0):\n",
    "        if row['Parent Components On Hand'] == 'No parent component on hand':\n",
    "            if row['Max Qty (GS)'] != 'Floor stock item':  # Check if the current value is not 'Floor stock item'\n",
    "                df_CTB_updated.at[idx, 'Max Qty (GS)'] = 0\n",
    "        else:\n",
    "            if row['Max Qty (GS)'] != 'Floor stock item':  # Check if the current value is not 'Floor stock item'\n",
    "                df_CTB_updated.at[idx, 'Max Qty (GS)'] = row['Parent Components On Hand']\n",
    "'''\n",
    "##############################################\n",
    "#### [U] Max Qty Top-Level to N/A if Max Qty (GS) = 'N/A, to 0 if Max Qty (GS) = 0 and to 'Make Part' if this is a M part \n",
    "## And update Max Qty Top-Level to 0 for Top-Levels where condition_zero is met\n",
    "###############################################\n",
    "# 09/20 - Pur/Mfg == 'D' mean that this is a Make Part build at CUU --> D should be treated as a M part meaning that if we have some stock of a 'D' part we don't need the lower level because transfered from CUU to RED.\n",
    "\n",
    "# Initial update of 'Max Qty Top-Level' based on conditions\n",
    "df_CTB_updated['Max Qty Top-Level'] = df_CTB_updated['Max Qty (GS)']\n",
    "df_CTB_updated.loc[df_CTB_updated['Pur/Mfg'] == 'M', 'Max Qty Top-Level'] = 'Make part'\n",
    "df_CTB_updated.loc[df_CTB_updated['Max Qty (GS)'].notna() & df_CTB_updated['Max Qty (GS)'].astype(str).str.contains('Qty =', na=False), 'Max Qty Top-Level'] = 'Upper level on Hand'\n",
    "df_CTB_updated.loc[df_CTB_updated['Max Qty (GS)'] == 'Floor stock item', 'Max Qty Top-Level'] = 'N/A'\n",
    "\n",
    "# Function to extract numeric quantity from 'Max Qty (GS)'\n",
    "def extract_numeric_qty(value):\n",
    "    if isinstance(value, str):\n",
    "        # Using regular expression to find numeric values directly or 'Qty =' pattern\n",
    "        match = re.search(r'(\\d+)', value)\n",
    "        if match:\n",
    "            return int(match.group())  # Extracting the numeric value found\n",
    "    return None\n",
    "\n",
    "# Apply function to create 'Numeric Qty' column, excluding rows where 'Pur/Mfg' == 'M' or non-numeric values - Update 09/23 to exlude 'BOM Qty' none integer\n",
    "#df_CTB_updated['Numeric Qty'] = df_CTB_updated.apply(lambda row: extract_numeric_qty(row['Max Qty (GS)']) if row['Pur/Mfg'] != 'M' else np.nan, axis=1)\n",
    "df_CTB_updated['Numeric Qty'] = df_CTB_updated.apply(\n",
    "    lambda row: extract_numeric_qty(row['Max Qty (GS)']) \n",
    "    if pd.notnull(row['BOM Qty']) and row['BOM Qty'] == int(row['BOM Qty']) \n",
    "    else np.nan, \n",
    "    axis=1\n",
    ")\n",
    "\n",
    "# Fill 'Numeric Qty' column with numeric values from 'Max Qty (GS)' where 'Max Qty (GS)' is already numeric excluding rows where 'Pur/Mfg' == 'M' or non-numeric values\n",
    "numeric_mask = df_CTB_updated['Max Qty (GS)'].apply(lambda x: isinstance(x, (int, float)))\n",
    "#df_CTB_updated.loc[numeric_mask & (df_CTB_updated['Pur/Mfg'] != 'M'), 'Numeric Qty'] = df_CTB_updated.loc[numeric_mask & (df_CTB_updated['Pur/Mfg'] != 'M'), 'Max Qty (GS)'] # Update 09/24 to avoid warning\n",
    "df_CTB_updated.loc[numeric_mask & (df_CTB_updated['Pur/Mfg'] != 'M'), 'Numeric Qty'] = pd.to_numeric(df_CTB_updated.loc[numeric_mask & (df_CTB_updated['Pur/Mfg'] != 'M'), 'Max Qty (GS)'], errors='coerce')\n",
    "\n",
    "# Calculate minimum numeric values for each 'Pty Indice'\n",
    "min_values = df_CTB_updated[df_CTB_updated['Numeric Qty'].notna()].groupby('Pty Indice')['Numeric Qty'].min().to_dict()\n",
    "\n",
    "# Update condition 09/23 - Check if 'BOM Qty' is an integer and exclude 'BOM Qty' containing a float \n",
    "# Function to update 'Max Qty Top-Level' with minimum values for each 'Pty Indice'\n",
    "def update_max_qty_top_level(row):\n",
    "    if row['Pty Indice'] in min_values:\n",
    "        return min_values[row['Pty Indice']]\n",
    "    return row['Max Qty Top-Level']\n",
    "\n",
    "# Apply the update function to rows with numeric values in 'Numeric Qty'\n",
    "df_CTB_updated['Max Qty Top-Level'] = df_CTB_updated.apply(update_max_qty_top_level, axis=1)\n",
    "\n",
    "#Drop |Numeric Qty|\n",
    "df_CTB_updated = df_CTB_updated.drop('Numeric Qty', axis =1) \n",
    "\n",
    "# Print the updated DataFrame\n",
    "print(\"|Clear-to-Build| after updating Max Qty (GS) and handling Pur/Mfg == 'M' condition.\")\n",
    "\n",
    "##################################################################################################################\n",
    "#### Fill Remain. crit. Qty for Inventory Status = 'Component not in Inventory' by checking the 'Pty Indice' #### \n",
    "################################################################################################################\n",
    "#Update on 08/09 -- Does not work for PN witn ONLY 'Component not in Inventory'\n",
    "#Create a mapping dictionary from df_Priority on 'Pty Indice'\n",
    "priority_mapping = df_Priority.set_index('Pty Indice')['Remain. crit. Qty'].to_dict()\n",
    "\n",
    "# Step 2: Define the function to fill 'Remain. crit. Qty' using the mapping\n",
    "def fill_remaining_critical_qty(row):\n",
    "    # Check if 'Remain. crit. Qty' is NaN and 'Inventory Status' is 'Component not in Inventory'\n",
    "    if pd.isna(row['Remain. crit. Qty']) and row['Inventory Status'] == 'Component not in Inventory':\n",
    "        # Use the mapping if the 'Pty Indice' exists in the dictionary\n",
    "        return priority_mapping.get(row['Pty Indice'], row['Remain. crit. Qty'])\n",
    "    # Return the existing value if the conditions are not met\n",
    "    return row['Remain. crit. Qty']\n",
    "\n",
    "# Apply the function to fill remaining critical quantity\n",
    "df_CTB_updated['Remain. crit. Qty'] = df_CTB_updated.apply(fill_remaining_critical_qty, axis=1)\n",
    "\n",
    "# Print a message indicating the completion of the process\n",
    "print(\"Remaining critical quantity filled for inventory status 'Component not in Inventory'.\")\n",
    "\n",
    "#######################################################################################################################\n",
    "# New 09/23 - Function to check if 'BOM Qty' is a float with a decimal part, and return 'Floor stock item CUU' if true\n",
    "#######################################################################################################################\n",
    "def check_bom_qty(row):\n",
    "    bom_qty = row['BOM Qty']\n",
    "    \n",
    "    # Check if 'Inventory Status' is 'Component not in Inventory'\n",
    "    if row['Inventory Status'] == 'Component not in Inventory':\n",
    "        # Check if BOM Qty is not null and has a decimal value\n",
    "        if pd.notnull(bom_qty) and not float(bom_qty).is_integer():\n",
    "            return 'Floor stock item CUU'  # Mark as floor stock CUU if BOM Qty has a decimal part\n",
    "    \n",
    "    # Return existing value if conditions are not met\n",
    "    return row['Max Qty (GS)']\n",
    "\n",
    "# Apply the function to the DataFrame\n",
    "df_CTB_updated['Max Qty (GS)'] = df_CTB_updated.apply(check_bom_qty, axis=1)\n",
    "\n",
    "# Print a message indicating the completion of the process\n",
    "print(\"Floor-stock CUU identified for relevant rows.\")\n",
    "\n",
    "#########################################################################\n",
    "# New code 08/09 -- Code need some work, it is not working\n",
    "#########################################################################\n",
    "''' TO BE UPDATED \n",
    "#################################################################################################################################################\n",
    "#### Update 'Top Level sharing Component' for Inventory Status = 'Component not in Inventory' by checking the 'Pty Indice' AND 'IDD Component' #### \n",
    "################################################################################################################################################\n",
    "def Update_Top_Level_Sharing_Components(df):\n",
    "    \"\"\"\n",
    "    Update the 'Top Level sharing Components' column for rows where\n",
    "    'Inventory Status' is 'Component not in Inventory'.\n",
    "    \n",
    "    Args:\n",
    "        df (pd.DataFrame): The DataFrame to be updated.\n",
    "        \n",
    "    Returns:\n",
    "        pd.DataFrame: The updated DataFrame.\n",
    "    \"\"\"\n",
    "    def list_shared_components(component, df):\n",
    "        filtered_df = df[df['IDD Component'] == component]\n",
    "        top_levels = filtered_df[['IDD Top Level', 'Pty Indice']].drop_duplicates()\n",
    "        return '; '.join(top_levels['Pty Indice']) if not top_levels.empty else None\n",
    "    \n",
    "    # Update 'Top Level sharing Components' for rows where Inventory Status is 'Component not in Inventory'\n",
    "    mask = df['Inventory Status'] == 'Component not in Inventory'\n",
    "    df.loc[mask, 'Top Level sharing Components'] = df.loc[mask, 'IDD Component'].apply(lambda x: list_shared_components(x, df))\n",
    "    \n",
    "    return df\n",
    "\n",
    "# Assuming df_CTB_updated is already defined and loaded\n",
    "# Call the function to update the DataFrame\n",
    "df_CTB_updated = Update_Top_Level_Sharing_Components(df_CTB_updated)\n",
    "\n",
    "# Save the updated DataFrame to an Excel file\n",
    "df_CTB_updated.to_excel(original_input, sheet_name='Clear-to-Build', index=False)\n",
    "#################################################################################################################################################\n",
    "'''\n",
    "#***********************************\n",
    "# Sort by BOM Index\n",
    "#***********************************\n",
    "# Sort df_CTB_updated by 'BOM Index'\n",
    "df_CTB_updated.sort_values(by='BOM Index', inplace=True)\n",
    "\n",
    "# Display the updated DataFrame\n",
    "#display(df_CTB_updated)\n",
    "\n",
    "####################################################################################################################\n",
    "##########################################     SAVING sheet_CTB                  ##################################\n",
    "###################################################################################################################\n",
    "# Load workbook\n",
    "workbook = load_workbook(original_input)\n",
    "\n",
    "# Replace the 'Clear-to-Build' tab with df_CTB_updated\n",
    "if 'Clear-to-Build' in workbook.sheetnames:\n",
    "    worksheet = workbook['Clear-to-Build']\n",
    "    worksheet.delete_rows(2, worksheet.max_row)  # Delete all rows starting from row 2\n",
    "    \n",
    "    # Write headers\n",
    "    for c_idx, header in enumerate(df_CTB_updated.columns, start=1):\n",
    "        worksheet.cell(row=1, column=c_idx, value=header)\n",
    "\n",
    "    # Write data\n",
    "    for r_idx, row in enumerate(df_CTB_updated.values, start=2):  # Start from row 2\n",
    "        for c_idx, value in enumerate(row, start=1):\n",
    "            worksheet.cell(row=r_idx, column=c_idx, value=value)\n",
    "else:\n",
    "    print(\"Error: 'Clear-to-Build' tab not found in the input file.\")\n",
    "\n",
    "# Save the updated workbook\n",
    "workbook.save(original_input)\n",
    "# Close the workbook\n",
    "workbook.close()\n",
    "\n",
    "####################################################################################################################\n",
    "##########################################     Copying Priotity Database                 ##########################\n",
    "###################################################################################################################\n",
    "# --> New code 06/28/2024\n",
    "# Load workbook and sheet if it exists, otherwise create a new sheet\n",
    "try:\n",
    "    workbook = load_workbook(original_input)\n",
    "    existing_sheet = True\n",
    "except FileNotFoundError:\n",
    "    workbook = None\n",
    "    existing_sheet = False\n",
    "\n",
    "if existing_sheet:\n",
    "    if 'CM-Priority' in workbook.sheetnames:\n",
    "        sheet_Priority = workbook['CM-Priority']\n",
    "    else:\n",
    "        sheet_Priority = workbook.create_sheet(title='CM-Priority', index=4)\n",
    "else:\n",
    "    sheet_Priority = workbook.create_sheet(title='CM-Priority', index=4)\n",
    "\n",
    "# Clear existing data in the sheet (optional step)\n",
    "if existing_sheet and 'CM-Priority' in workbook.sheetnames:\n",
    "    sheet_Priority.delete_rows(sheet_Priority.min_row + 1, sheet_Priority.max_row)\n",
    "\n",
    "# Convert 'Earliest Due Date' and 'SO Modified' columns to datetime format\n",
    "df_Priority['Earliest Due Date'] = pd.to_datetime(df_Priority['Earliest Due Date'], errors='coerce', format='%m/%d/%Y')\n",
    "df_Priority['SO Modified'] = pd.to_datetime(df_Priority['SO Modified'], errors='coerce', format='%m/%d/%Y')\n",
    "\n",
    "# update 09/09\n",
    "# Convert column to string to prevent automatic date parsing\n",
    "#df_Priority['Remain. crit. Qty'] = df_Priority['Remain. crit. Qty'].astype(str)\n",
    "df_Priority['Remain. crit. Qty'] = df_Priority['Remain. crit. Qty'].fillna(0)\n",
    "df_Priority['Remain. crit. Qty'] = df_Priority['Remain. crit. Qty'].astype(int)\n",
    "\n",
    "#print('df_Priority')\n",
    "#display(df_Priority)\n",
    "\n",
    "# Ensure the column is treated as an object type - Removed 09/09\n",
    "#df_Priority['Remain. crit. Qty'] = df_Priority['Remain. crit. Qty'].astype(object)\n",
    "\n",
    "# Replace 'nan' strings with empty string - Update 09/09\n",
    "#df_Priority['Remain. crit. Qty'] = df_Priority['Remain. crit. Qty'].replace('nan', '')\n",
    "\n",
    "# Convert 'Earliest Due Date' and 'SO Modified' format to short date format (mm/dd/yyyy)\n",
    "df_Priority['SO Modified'] = df_Priority['SO Modified'].dt.strftime('%m/%d/%Y')\n",
    "df_Priority['Earliest Due Date'] = df_Priority['Earliest Due Date'].dt.strftime('%m/%d/%Y')\n",
    "\n",
    "# Write headers\n",
    "header = list(df_Priority.columns)  # Convert Index to list\n",
    "sheet_Priority.append(header)\n",
    "\n",
    "# Write data\n",
    "for r in dataframe_to_rows(df_Priority, index=False, header=False):\n",
    "    sheet_Priority.append(r)\n",
    "\n",
    "# Save workbook\n",
    "workbook.save(original_input)\n",
    "# Close the workbook\n",
    "workbook.close()\n",
    "\n",
    "print(f\"Priority database added successfully as |CM-Priority| in {original_input}\")\n",
    "\n",
    "#End of NEw Code\n",
    "\n",
    "########################################################################################################################\n",
    "###############################################     FORMATING  output file          ####################################\n",
    "#######################################################################################################################\n",
    "##### load the formatted workbook\n",
    "workbook = load_workbook(original_input) \n",
    "# Define sheet_CTB\n",
    "sheet_CTB =  workbook['Clear-to-Build']\n",
    "max_row_CTB = sheet_CTB.max_row\n",
    "\n",
    "###########################################################################################################################################\n",
    "###Formatting tab 1 sheet_CTB  ### CLEAR TO BUILD\n",
    "###########################################################################################################################################\n",
    "\n",
    "#Last update column S\n",
    "content_S_CTB = {\n",
    "    1: \"Last update\",\n",
    "    2: date.today().strftime(\"%m-%d-%y\"),\n",
    "    3: \"Clear to build report: Based on IDD's Inventory & existing BOM\"\n",
    "}\n",
    "\n",
    "# Apply sorting to column I (assuming column I is column 9)\n",
    "##sheet_CTB.sort('I2:I' + str(max_row_CTB))  # Sort column I\n",
    "\n",
    "# Apply formatting to the header row\n",
    "header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')\n",
    "header_font = Font(color='FFFFFF', bold=True)\n",
    "header_alignment = Alignment(horizontal='left', vertical='center')\n",
    "header_border = Border(\n",
    "    top=Side(style='medium'),\n",
    "    bottom=Side(style='medium'),\n",
    "    left=Side(style='medium'),\n",
    "    right=Side(style='medium')\n",
    ")\n",
    "\n",
    "for cell in sheet_CTB[1]:\n",
    "    cell.fill = header_fill\n",
    "    cell.font = header_font\n",
    "    cell.alignment = header_alignment\n",
    "    cell.border = header_border\n",
    "\n",
    "# Add filters to the first row of the sheet_CTB worksheet\n",
    "sheet_CTB.auto_filter.ref = sheet_CTB.dimensions\n",
    "\n",
    "# Set column widths and text alignment for columns A to R\n",
    "for column in sheet_CTB.iter_cols(min_col=1, max_col=18):\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "    \n",
    "    column_letter = column[0].column_letter\n",
    "    if column_letter in ['O', 'P', 'Q','R']:\n",
    "        sheet_CTB.column_dimensions[column_letter].width = 15\n",
    "    elif column_letter in ['M', 'N','J','S']:\n",
    "        sheet_CTB.column_dimensions[column_letter].width = 20\n",
    "    elif column_letter in ['C', 'F']:\n",
    "        sheet_CTB.column_dimensions[column_letter].width = 30\n",
    "    else:\n",
    "        sheet_CTB.column_dimensions[column_letter].width = 10\n",
    "\n",
    "    # Apply alignment and border to cells in the current column\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "\n",
    "# Set column widths and text alignment for columns S\n",
    "for column in sheet_CTB.iter_cols(min_col=19, max_col=19):\n",
    "    for cell in column:\n",
    "        cell.alignment = Alignment(horizontal='left' if cell.row == 1 else 'center', vertical='center')\n",
    "    \n",
    "    if column[0].column_letter == 'S':\n",
    "        sheet_CTB.column_dimensions['S'].width = 15 \n",
    "\n",
    "#####################################################\n",
    "### Set formatting for new columns [T] to [X]    ###\n",
    "####################################################\n",
    "for column in sheet_CTB.iter_cols(min_col=20, max_col=24):\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "    \n",
    "    column_letter = column[0].column_letter\n",
    "    if column_letter in ['W']:\n",
    "        sheet_CTB.column_dimensions[column_letter].width = 60\n",
    "        sheet_CTB.column_dimensions[column_letter].alignment = Alignment(horizontal='left', vertical='center', wrap_text=True)  # Set alignment for column [W] and [X] to left\n",
    "    elif column_letter in ['T','X']:\n",
    "        sheet_CTB.column_dimensions[column_letter].width = 35\n",
    "    else:\n",
    "        sheet_CTB.column_dimensions[column_letter].width = 20\n",
    "\n",
    "    # Apply alignment and border to cells in the current column\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "######################################\n",
    "######## Color formating   ###########\n",
    "### Formating [T] 'Max Qty (GS)' ##############################\n",
    "# Custom conditional formatting for column T (Max Qty (GS))  ##\n",
    "###############################################################\n",
    "for row in range(2, max_row_CTB + 1):\n",
    "    cell_T = sheet_CTB.cell(row=row, column=20)  # Assuming 'Max Qty (GS)' is in column T\n",
    "    cell_O = sheet_CTB.cell(row=row, column=15)  # Assuming column O contains the comparison value\n",
    "    cell_Q = sheet_CTB.cell(row=row, column=17)  # Assuming column Q contains the comparison value\n",
    "    \n",
    "    if cell_O.value not in ['Completed', 'Canceled', 'TBD', 'To be Canceled']:\n",
    "        if isinstance(cell_T.value, (int, float)) and isinstance(cell_O.value, (int, float)):\n",
    "            if cell_T.value == 'N/A' or cell_T.value == 'Floor stock item':\n",
    "                continue  # Skip N/A and Floor stock items\n",
    "\n",
    "            # Convert cell_T.value to numerical type for comparison\n",
    "            if isinstance(cell_T.value, str):\n",
    "                cell_T_value = 0  # Or any default value that makes sense in your context\n",
    "            else:\n",
    "                cell_T_value = cell_T.value\n",
    "\n",
    "            # Convert cell_Q.value to numerical type for comparison\n",
    "            if cell_Q.value is None:\n",
    "                cell_Q_value = 0  # Or any default value that makes sense in your context\n",
    "            elif isinstance(cell_Q.value, str):\n",
    "                cell_Q_value = 0  # Or any default value that makes sense in your context\n",
    "            else:\n",
    "                cell_Q_value = cell_Q.value\n",
    "\n",
    "            if cell_T_value > cell_Q_value:\n",
    "                fill_color = 'C6EFCE'  # Green\n",
    "            elif cell_T_value < cell_Q_value:\n",
    "                # Check if [T] is the lowest number for a given Top-Level [M]\n",
    "                top_level = sheet_CTB.cell(row=row, column=13).value  # Assuming 'IDD Top Level' is in column M\n",
    "                # Extract numerical values for comparison\n",
    "                top_level_values = [sheet_CTB.cell(row=r, column=20).value for r in range(2, max_row_CTB + 1) if sheet_CTB.cell(row=r, column=13).value == top_level and isinstance(sheet_CTB.cell(row=r, column=20).value, (int, float))]\n",
    "                if top_level_values:\n",
    "                    min_value_T = min(top_level_values)\n",
    "                    if cell_T.value == min_value_T:\n",
    "                        fill_color = 'FFC7CE'  # Red\n",
    "                    else:\n",
    "                        fill_color = 'FFEB9C'  # Yellow\n",
    "                else:\n",
    "                    fill_color = 'FFEB9C'  # Yellow\n",
    "            else:\n",
    "                fill_color = None\n",
    "\n",
    "            if fill_color:\n",
    "                cell_T.fill = PatternFill(start_color=fill_color, end_color=fill_color, fill_type='solid')\n",
    "\n",
    "#############################################################\n",
    "# Set column width and text alignment for column S from row 3\n",
    "############################################################\n",
    "for cell in sheet_CTB.iter_rows(min_row=3, min_col=19, max_col=19):\n",
    "    cell[0].alignment = Alignment(horizontal='left', vertical='center')\n",
    "\n",
    "# Apply borders for rows 1 and 2 in column S\n",
    "for row in range(1, 3):\n",
    "    sheet_CTB.cell(row=row, column=19).border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "# Set background color for cell S2 and S3 left align\n",
    "sheet_CTB.cell(row=2, column=19).fill = PatternFill(start_color='E2EFDA', end_color='E2EFDA', fill_type='solid')\n",
    "\n",
    "# Define the grey fill color for rows related to Component not in Inventory\n",
    "grey_fill = PatternFill(start_color='F2F2F2', end_color='F2F2F2', fill_type='solid')\n",
    "\n",
    "# Define the red fill color for column 19 (T)\n",
    "red_fill_color = 'FFC7CE' \n",
    "blue_fill_color = '92CDDC' \n",
    "\n",
    "# Iterate through each row in the sheet_CTB worksheet\n",
    "for row in sheet_CTB.iter_rows(min_row=2, max_row=max_row_CTB, min_col=1, max_col=20):  # Adjust max_col to 20\n",
    "    inventory_status_cell = row[2]  # Assuming 'Inventory Status' is in column C (index 2)\n",
    "    floor_stock_cell = row[19]      # Assuming column T is the 20th column (index 19)\n",
    "    \n",
    "    if inventory_status_cell.value == 'Component not in Inventory':\n",
    "        # Apply grey fill color to columns 1 to 18\n",
    "        for cell in row[:18]:  \n",
    "            cell.fill = grey_fill\n",
    "        # Apply red fill color to column 20 (T)\n",
    "        if floor_stock_cell.value is not None and floor_stock_cell.value not in ['Floor stock item', 'N/A']: # Check if it's not a floor stock item or N/A\n",
    "            row[19].fill = PatternFill(start_color=red_fill_color, end_color=red_fill_color, fill_type='solid')\n",
    "        # Apply blue fill color to column 20 (T) if 'Level' is in the value\n",
    "        if isinstance(floor_stock_cell.value, str) and 'Level' in floor_stock_cell.value:  # Check if 'Level' is present in the value\n",
    "            row[19].fill = PatternFill(start_color=blue_fill_color, end_color=blue_fill_color, fill_type='solid')\n",
    "       \n",
    "# Custom conditional formatting for column K 'Level' (Assuming data starts from row 2)\n",
    "min_row = 2\n",
    "col_K = 11\n",
    "\n",
    "# Initialize fill_color outside of the loop\n",
    "fill_color = None\n",
    "\n",
    "for row in range(min_row, max_row_CTB + 1):\n",
    "    cell_value = sheet_CTB.cell(row=row, column=col_K).value\n",
    "    \n",
    "    if cell_value is not None:\n",
    "        if cell_value == 0:\n",
    "            fill_color = '63BE7B'  # Green\n",
    "        elif cell_value == 1:\n",
    "            fill_color = 'A2C075'  # Lighter Green\n",
    "        elif cell_value == 2:\n",
    "            fill_color = 'FFEB84'  # Yellow\n",
    "        elif cell_value == 3:\n",
    "            fill_color = 'FFD166'  # Orange\n",
    "        elif cell_value == 4:\n",
    "            fill_color = 'F88E5B'  # Darker Orange\n",
    "        elif cell_value == 5:\n",
    "            fill_color = 'F8696B'  # Red\n",
    "        elif cell_value == 6:\n",
    "            fill_color = '8B0000'  # Darker Red\n",
    "    else:\n",
    "        fill_color = None  # Reset fill_color when cell value is None\n",
    "            \n",
    "    # Check if fill_color is not None before applying PatternFill\n",
    "    if fill_color is not None:\n",
    "        fill = PatternFill(start_color=fill_color, end_color=fill_color, fill_type='solid')\n",
    "        sheet_CTB.cell(row=row, column=col_K).fill = fill\n",
    "\n",
    "# Write the date to a specific cell\n",
    "sheet_CTB.cell(row=2, column=19, value=file_date_inventory)  # S2 cell\n",
    "\n",
    "######################################################################################################################################################\n",
    "####     Tab 2 - CM-Inventory      ### CM-INVENTORY\n",
    "###################################################################################################################################################\n",
    "sheet_Inventory = workbook['CM-Inventory']\n",
    "\n",
    "# Apply formatting to the header row\n",
    "header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')\n",
    "header_font = Font(color='FFFFFF', bold=True)\n",
    "header_alignment = Alignment(horizontal='left', vertical='center')\n",
    "header_border = Border(\n",
    "    top=Side(style='medium'),\n",
    "    bottom=Side(style='medium'),\n",
    "    left=Side(style='medium'),\n",
    "    right=Side(style='medium')\n",
    ")\n",
    "\n",
    "for cell in sheet_Inventory[1]:\n",
    "    cell.fill = header_fill\n",
    "    cell.font = header_font\n",
    "    cell.alignment = header_alignment\n",
    "    cell.border = header_border\n",
    "\n",
    "# Add filters to the first row\n",
    "sheet_Inventory.auto_filter.ref = sheet_Inventory.dimensions\n",
    "\n",
    "# Set column widths and text alignment for columns A to R\n",
    "for column in sheet_Inventory.iter_cols(min_col=1, max_col=18):\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "    \n",
    "    column_letter = column[0].column_letter\n",
    "    if column_letter in ['G','J','M','N']:\n",
    "        sheet_Inventory.column_dimensions[column_letter].width = 20\n",
    "    elif column_letter in ['O','P','Q']:\n",
    "        sheet_Inventory.column_dimensions[column_letter].width = 15\n",
    "    elif column_letter in ['D']:\n",
    "        sheet_Inventory.column_dimensions[column_letter].width = 30\n",
    "    else:\n",
    "        sheet_Inventory.column_dimensions[column_letter].width = 10\n",
    "\n",
    "    # Apply alignment and border to cells in the current column\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "# Set column width and text alignment for column S from row 3\n",
    "for cell in sheet_Inventory.iter_rows(min_row=3, min_col=19, max_col=19):\n",
    "    cell[0].alignment = Alignment(horizontal='left', vertical='center')\n",
    "\n",
    "# Apply borders for rows 1 and 2 in column S\n",
    "for row in range(1, 3):\n",
    "    sheet_Inventory.cell(row=row, column=19).border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "# Set background color for cell S2 and S3 left align\n",
    "sheet_Inventory.cell(row=2, column=19).fill = PatternFill(start_color='E2EFDA', end_color='E2EFDA', fill_type='solid')\n",
    "\n",
    "# Custom conditional formatting for column K (Assuming data starts from row 2)Remain. crit. Qty\n",
    "min_row = 2\n",
    "max_row = sheet_Inventory.max_row\n",
    "col_K = 11\n",
    "\n",
    "for row in range(min_row, max_row + 1):\n",
    "    cell_value = sheet_Inventory.cell(row=row, column=col_K).value\n",
    "    \n",
    "    if cell_value is not None:\n",
    "        if cell_value == 0:\n",
    "            fill_color = '63BE7B'  # Green\n",
    "        elif cell_value == 1:\n",
    "            fill_color = 'A2C075'  # Lighter Green\n",
    "        elif cell_value == 2:\n",
    "            fill_color = 'FFEB84'  # Yellow\n",
    "        elif cell_value == 3:\n",
    "            fill_color = 'FFD166'  # Orange\n",
    "        elif cell_value == 4:\n",
    "            fill_color = 'F88E5B'  # Darker Orange\n",
    "        elif cell_value == 5:\n",
    "            fill_color = 'F8696B'  # Red\n",
    "        elif cell_value == 6:\n",
    "            fill_color = '8B0000'  # Darker Red\n",
    "        \n",
    "        fill = PatternFill(start_color=fill_color, end_color=fill_color, fill_type='solid')\n",
    "        sheet_Inventory.cell(row=row, column=col_K).fill = fill\n",
    "\n",
    "################################################################################################################################################ \n",
    "####     Tab 3 - CM-BOM            ### CM-BOM\n",
    "#################################################################################################################################################\n",
    "sheet_BOM = workbook['CM-BOM']\n",
    "\n",
    "# Apply formatting to the header row\n",
    "header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')\n",
    "header_font = Font(color='FFFFFF', bold=True)\n",
    "header_alignment = Alignment(horizontal='left', vertical='center')\n",
    "header_border = Border(\n",
    "    top=Side(style='medium'),\n",
    "    bottom=Side(style='medium'),\n",
    "    left=Side(style='medium'),\n",
    "    right=Side(style='medium')\n",
    ")\n",
    "\n",
    "for cell in sheet_BOM[1]:\n",
    "    cell.fill = header_fill\n",
    "    cell.font = header_font\n",
    "    cell.alignment = header_alignment\n",
    "    cell.border = header_border\n",
    "\n",
    "# Add filters to the first row\n",
    "sheet_BOM.auto_filter.ref = sheet_BOM.dimensions\n",
    "\n",
    "# Set column widths and text alignment for columns A to L\n",
    "for column in sheet_BOM.iter_cols(min_col=1, max_col=11):\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "    \n",
    "    column_letter = column[0].column_letter\n",
    "    if column_letter in ['C', 'G', 'H']:\n",
    "        sheet_BOM.column_dimensions[column_letter].width = 20\n",
    "    elif column_letter in ['F']:\n",
    "        sheet_BOM.column_dimensions[column_letter].width = 30\n",
    "    else:\n",
    "        sheet_BOM.column_dimensions[column_letter].width = 10\n",
    "\n",
    "    # Apply alignment and border to cells in the current column\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "# Set column width and text alignment for column L from row 3\n",
    "for cell in sheet_BOM.iter_rows(min_row=3, min_col=12, max_col=12):\n",
    "    cell[0].alignment = Alignment(horizontal='left', vertical='center')\n",
    "\n",
    "# Apply borders for rows 1 and 2 in column L\n",
    "for row in range(1, 3):\n",
    "    sheet_BOM.cell(row=row, column=12).border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "# Set background color for cell L2 and L3 left align\n",
    "sheet_BOM.cell(row=2, column=12).fill = PatternFill(start_color='E2EFDA', end_color='E2EFDA', fill_type='solid')\n",
    "\n",
    "# Custom conditional formatting for column D (Assuming data starts from row 2)\n",
    "min_row = 2\n",
    "max_row = sheet_BOM.max_row\n",
    "col_D = 4\n",
    "\n",
    "for row in range(min_row, max_row + 1):\n",
    "    cell_value = sheet_BOM.cell(row=row, column=col_D).value\n",
    "    \n",
    "    if cell_value is not None:\n",
    "        if cell_value == 0:\n",
    "            fill_color = '63BE7B'  # Green\n",
    "        elif cell_value == 1:\n",
    "            fill_color = 'A2C075'  # Lighter Green\n",
    "        elif cell_value == 2:\n",
    "            fill_color = 'FFEB84'  # Yellow\n",
    "        elif cell_value == 3:\n",
    "            fill_color = 'FFD166'  # Orange\n",
    "        elif cell_value == 4:\n",
    "            fill_color = 'F88E5B'  # Darker Orange\n",
    "        elif cell_value == 5:\n",
    "            fill_color = 'F8696B'  # Red\n",
    "        elif cell_value == 6:\n",
    "            fill_color = '8B0000'  # Darker Red\n",
    "         \n",
    "        fill = PatternFill(start_color=fill_color, end_color=fill_color, fill_type='solid')\n",
    "        sheet_BOM.cell(row=row, column=col_D).fill = fill\n",
    "\n",
    "#####################################################################\n",
    "### Save the changes to the Excel file \n",
    "#####################################################################\n",
    "workbook.save(original_input)\n",
    "# Close the workbook\n",
    "workbook.close()\n",
    "\n",
    "#***************************************************************************************************************************\n",
    "#############################################################################################################################\n",
    "##  #######  ########  ########  ##   ##   ##       ########  ########\n",
    "##  ##   ##  ##    ##  ##        ##  ##    ##       ##    ##  ##\n",
    "##  ######   ########  ##        ####      ##       ##    ##  ##  #####\n",
    "##  ##   ##  ##    ##  ##        ##  ##    ##       ##    ##  ##     ##\n",
    "##  #######  ##    ##  ########  ##   ###  #######  ########  #########\n",
    "##############################################################################################################################\n",
    "#***************************************************************************************************************************\n",
    "# Define date and path\n",
    "input_backlog_formatted = os.path.join(Path, f'CM_IDD_Backlog-{file_date_inventory}_Formatted.xlsx') \n",
    "\n",
    "##############################################################################################################################\n",
    "# Load workbook\n",
    "##############################################################################################################################\n",
    "# Load the existing output workbook\n",
    "try:\n",
    "    workbook = load_workbook(original_input)\n",
    "    #print(\"Output workbook loaded successfully.\")\n",
    "except FileNotFoundError as e:\n",
    "    print(f\"Output workbook not found: {e}\")\n",
    "    exit()\n",
    "\n",
    "# Print the sheet names\n",
    "print(\"Tabs in the workbook:\")\n",
    "print(workbook.sheetnames)\n",
    "print('Processing |CM-Backlog| ...')\n",
    "    \n",
    "# Load the Excel files into pandas DataFrames\n",
    "try:\n",
    "    df_backlog = pd.read_excel(input_backlog_formatted, sheet_name=0)\n",
    "    print(\"Backlog files loaded successfully.\")\n",
    "except FileNotFoundError as e:\n",
    "    print(f\"Input backlog file not found: {e}\")\n",
    "    exit()\n",
    "\n",
    "# Convert 'SO Modified' column to datetime format\n",
    "df_backlog['SO Modified'] = pd.to_datetime(df_backlog['SO Modified'], errors='coerce', format='%m-%d-%Y')\n",
    "\n",
    "# Convert datetime format to short date format (mm/dd/yyyy)\n",
    "df_backlog['SO Modified'] = df_backlog['SO Modified'].dt.strftime('%m/%d/%Y')\n",
    "\n",
    "#New 08/20\n",
    "#######################################################################################\n",
    "# -->> CREATE 'Month', 'Product Category', and 'Complexity' in |CM-Backlog| + 'Month Requested'\n",
    "######################################################################################\n",
    "# Creating column 'Month'\n",
    "############################\n",
    "# Ensure 'Due date' is in datetime format\n",
    "df_backlog['Due Date'] = pd.to_datetime(df_backlog['Due Date'])\n",
    "\n",
    "# Directly create 'Month' in the desired format (e.g., Jan 23, Feb 23, ...)\n",
    "df_backlog['Month'] = df_backlog['Due Date'].dt.strftime('%b %y')\n",
    "\n",
    "# Ensure 'Requested Date' is in datetime format\n",
    "df_backlog['Requested Date'] = pd.to_datetime(df_backlog['Requested Date'])\n",
    "\n",
    "# Directly create 'Month Requested' in the desired format (e.g., Jan 23, Feb 23, ...)\n",
    "df_backlog['Month Requested'] = df_backlog['Requested Date'].dt.strftime('%b %y')\n",
    "\n",
    "# Convert 'Due date' back to short date format (e.g., MM/DD/YYYY)\n",
    "df_backlog['Due Date'] = df_backlog['Due Date'].dt.strftime('%m/%d/%Y')\n",
    "\n",
    "# Convert 'Requested Date' back to short date format (e.g., MM/DD/YYYY)\n",
    "df_backlog['Requested Date'] = df_backlog['Requested Date'].dt.strftime('%m/%d/%Y')\n",
    "\n",
    "##########################################################################################################################################\n",
    "# Creating column 'Complexity' with the function to define the familly based on 'General Description' + new function to assign a complecity level\n",
    "###########################################################################################################################################\n",
    "# Define the 'Product Category' base on 'General Description' \n",
    "#######################################################\n",
    "# Define the 'Product Category' based on 'General Description'\n",
    "def determine_category(description):\n",
    "    if not isinstance(description, str):\n",
    "        return 'Others'\n",
    "    if description == 'Rototellite':\n",
    "        return 'Rototellite'\n",
    "    elif 'Indicator' in description or 'CPA' in description:\n",
    "        return 'CPA'\n",
    "    elif 'Lightplate' in description:\n",
    "        return 'Lightplate'\n",
    "    elif 'ISP' in description or 'Keyboard' in description:\n",
    "        return 'ISP'\n",
    "    elif 'Module' in description:\n",
    "        return 'CPA'\n",
    "    elif 'optics' in description:\n",
    "        return 'Fiber Optics'\n",
    "    else:\n",
    "        return 'Others'\n",
    "\n",
    "# Create 'Product_Category' column based on the 'General Description'\n",
    "df_backlog['Product_Category'] = df_backlog['General Description'].apply(determine_category)\n",
    "\n",
    "###################################################\n",
    "# Assigne a complexity Level base on the familly \n",
    "##################################################\n",
    "# 'Kit' = 0, 'Rototellite' and 'Lightplete' = 1, 'CPA' = 2, 'ISP' = 3\n",
    "# Assign a complexity level based on the category\n",
    "def determine_complexity(category):\n",
    "    if not isinstance(category, str):\n",
    "        return 0\n",
    "    if category == 'Rototellite':\n",
    "        return 0.50\n",
    "    elif category == 'Lightplate':\n",
    "        return 0.25\n",
    "    elif category == 'CPA':\n",
    "        return 0.75\n",
    "    elif category == 'ISP':\n",
    "        return 1\n",
    "    elif category == 'Fiber Optics':\n",
    "        return 0.50\n",
    "    elif category == 'Others':\n",
    "        return 0\n",
    "    else:\n",
    "        return 0\n",
    "    \n",
    "# Create 'Complexity' column based on 'Product Category'\n",
    "df_backlog['Complexity'] = df_backlog['Product_Category'].apply(determine_complexity)\n",
    "\n",
    "#print('df_Historic')\n",
    "#display(df_Historic)\n",
    "\n",
    "####################################################################################################################\n",
    "##########################################     Creating Backlog                            #########################\n",
    "###################################################################################################################\n",
    "# Check if \"CM-Backlog\" sheet already exists and delete it if it does\n",
    "if \"CM-Backlog\" in workbook.sheetnames:\n",
    "    del workbook[\"CM-Backlog\"]\n",
    "\n",
    "# Create new \"CM-Backlog\" sheet\n",
    "backlog_sheet = workbook.create_sheet(title='CM-Backlog')\n",
    "\n",
    "# Write headers\n",
    "for c_idx, header in enumerate(df_backlog.columns, start=1):\n",
    "    backlog_sheet.cell(row=1, column=c_idx, value=header)\n",
    "\n",
    "# Write data\n",
    "for r_idx, row in enumerate(df_backlog.values, start=2):  # Start from row 2\n",
    "    for c_idx, value in enumerate(row, start=1):\n",
    "        backlog_sheet.cell(row=r_idx, column=c_idx, value=value)\n",
    "\n",
    "####################################################################################################################\n",
    "##########################################     Formating Backlog                            #########################\n",
    "###################################################################################################################\n",
    "# Apply formatting to the header row\n",
    "header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')\n",
    "header_font = Font(color='FFFFFF', bold=True)\n",
    "header_alignment = Alignment(horizontal='left', vertical='center')\n",
    "header_border = Border(\n",
    "    top=Side(style='medium'),\n",
    "    bottom=Side(style='medium'),\n",
    "    left=Side(style='medium'),\n",
    "    right=Side(style='medium')\n",
    ")\n",
    "\n",
    "for cell in backlog_sheet[1]:\n",
    "    cell.fill = header_fill\n",
    "    cell.font = header_font\n",
    "    cell.alignment = header_alignment\n",
    "    cell.border = header_border\n",
    "\n",
    "# Add filters to the first row\n",
    "backlog_sheet.auto_filter.ref = backlog_sheet.dimensions\n",
    "\n",
    "############################################################\n",
    "# Set column widths and text alignment for columns A to V\n",
    "#############################################################\n",
    "for column in backlog_sheet.iter_cols(min_col=1, max_col=22):\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "    \n",
    "    column_letter = column[0].column_letter\n",
    "    if column_letter in ['C', 'D','H', 'F', 'G', 'T', 'U']:\n",
    "        backlog_sheet.column_dimensions[column_letter].width = 15\n",
    "    elif column_letter in ['I', 'N', 'P']:\n",
    "        backlog_sheet.column_dimensions[column_letter].width = 40\n",
    "    elif column_letter in ['N', 'O', 'U', 'V', 'Q']:\n",
    "        backlog_sheet.column_dimensions[column_letter].width = 20\n",
    "    else:\n",
    "        backlog_sheet.column_dimensions[column_letter].width = 10\n",
    "\n",
    "    # Apply alignment and border to cells in the current column\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "# Erase contents in column W (assuming W is column 23)\n",
    "for row in range(2, backlog_sheet.max_row + 1):\n",
    "    backlog_sheet.cell(row=row, column=23).value = None\n",
    "\n",
    "# Apply borders for rows 1 and 2 in column W\n",
    "for row in range(1, 3):\n",
    "    backlog_sheet.cell(row=row, column=23).border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "# Set background color for cell W2 and W3 left align\n",
    "backlog_sheet.cell(row=2, column=23).fill = PatternFill(start_color='E2EFDA', end_color='E2EFDA', fill_type='solid')\n",
    "backlog_sheet.cell(row=2, column=23).alignment = Alignment(horizontal='left', vertical='center')\n",
    "\n",
    "# Set the date of column W2 to {date}\n",
    "backlog_sheet.cell(row=2, column=23, value=file_date_inventory)\n",
    "\n",
    "# Set the width of column W (23th column)\n",
    "backlog_sheet.column_dimensions[get_column_letter(23)].width = 20\n",
    "\n",
    "############################################################################\n",
    "# Set column widths and text alignment for columns after W --> X to AA\n",
    "############################################################################\n",
    "for column in backlog_sheet.iter_cols(min_col=24, max_col=28):\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        \n",
    "        cell.border = Border(\n",
    "            top=Side(style='thin'),\n",
    "            right=Side(style='thin'),\n",
    "            bottom=Side(style='thin'),\n",
    "            left=Side(style='thin')\n",
    "        )\n",
    "\n",
    "# Set the width of column X (24th column)\n",
    "backlog_sheet.column_dimensions[get_column_letter(24)].width = 20\n",
    "# Set the width of column AA (27th column)\n",
    "backlog_sheet.column_dimensions[get_column_letter(27)].width = 20\n",
    "        \n",
    "#**#############################################################################################################**\n",
    "# Color formating based on |Production status| from CM-Priority --> Refering to |CM-Priority| formatting \n",
    "#**############################################################################################################**\n",
    "# Define the fills and fonts for conditional formatting\n",
    "green_fill = PatternFill(start_color='D8E4BC', end_color='D8E4BC', fill_type='solid')\n",
    "blue_fill = PatternFill(start_color='DAEEF3', end_color='DAEEF3', fill_type='solid')\n",
    "dark_red_font = Font(color='C00000')\n",
    "light_yellow_fill = PatternFill(start_color='FFFFCC', end_color='FFFFCC', fill_type='solid')\n",
    "red_fill = PatternFill(start_color='F2DCDB', end_color='F2DCDB', fill_type='solid')\n",
    "grey_fill = PatternFill(start_color='F2F2F2', end_color='F2F2F2', fill_type='solid')\n",
    "grey_font_color = Font(color='BFBFBF')\n",
    "font_color = Font(color='000000')  # Black font color\n",
    "\n",
    "border_color = '000000'  # Black color for the border\n",
    "thin_black_side = Side(style='thin', color=border_color)\n",
    "border_grey = Border(\n",
    "    left=Side(border_style=None),\n",
    "    right=Side(border_style=None),\n",
    "    top=Side(border_style=None),\n",
    "    bottom=Side(border_style=None),\n",
    "    diagonal=Side(border_style='thin', color='D9D9D9'),\n",
    "    diagonalDown=True,\n",
    "    diagonalUp=True\n",
    ")\n",
    "\n",
    "# Load the workbook and sheets\n",
    "sheet_Priority = workbook[\"CM-Priority\"]\n",
    "\n",
    "# Get the column indices (1-based)\n",
    "col_idd_top_level_priority = [cell.value for cell in sheet_Priority[1]].index(\"IDD Top Level\") + 1\n",
    "col_idd_top_level_backlog = [cell.value for cell in backlog_sheet[1]].index(\"IDD Top Level\") + 1\n",
    "col_production_status = [cell.value for cell in sheet_Priority[1]].index(\"Production Status\") + 1\n",
    "\n",
    "# Create a mapping of IDD Top Level values to their respective formatting in the Priority sheet\n",
    "formatting_map = {}\n",
    "redlist_map = {}\n",
    "completed_map = {}\n",
    "\n",
    "for row in sheet_Priority.iter_rows(min_row=2, max_row=sheet_Priority.max_row):\n",
    "    idd_value = row[col_idd_top_level_priority - 1].value  # Adjust for zero-based index\n",
    "    production_status = row[col_production_status - 1].value\n",
    "\n",
    "    if production_status == 'Industrialized':\n",
    "        formatting_map[idd_value] = green_fill\n",
    "    elif 'WIP' in str(production_status):\n",
    "        formatting_map[idd_value] = blue_fill\n",
    "\n",
    "    # Redlist criteria\n",
    "    value_in_O = row[14].value  # Column O is the 15th column\n",
    "    if value_in_O and ('transferred' in str(value_in_O).lower() or 'canceled' in str(value_in_O).lower()):\n",
    "        redlist_map[idd_value] = red_fill\n",
    "\n",
    "    # Completed PN\n",
    "    value_in_I = row[8].value  # Column I is the 9th column\n",
    "    if value_in_I == 'Completed':\n",
    "        completed_map[idd_value] = (grey_fill, grey_font_color)\n",
    "\n",
    "# Apply the formatting to the Backlog sheet based on the mappings\n",
    "for row in backlog_sheet.iter_rows(min_row=2, max_row=backlog_sheet.max_row):\n",
    "    idd_value = row[col_idd_top_level_backlog - 1].value  # Adjust for zero-based index\n",
    "    if idd_value in formatting_map:\n",
    "        fill = formatting_map[idd_value]\n",
    "        for cell in row[:backlog_sheet.max_column - 6]:  # Iterate up to max_column - 6\n",
    "            cell.fill = fill\n",
    "            cell.font = font_color\n",
    "\n",
    "    if idd_value in redlist_map:\n",
    "        fill = redlist_map[idd_value]\n",
    "        for cell in row[:backlog_sheet.max_column - 6]:  # Iterate up to max_column - 6\n",
    "            cell.fill = fill\n",
    "            if cell.col_idx == 1 or cell.col_idx == backlog_sheet.max_column:\n",
    "                cell.border = Border(left=thin_black_side if cell.col_idx == 1 else None,\n",
    "                                     right=thin_black_side if cell.col_idx == backlog_sheet.max_column else None,\n",
    "                                     top=thin_black_side, bottom=thin_black_side,\n",
    "                                     diagonal=border_grey.diagonal, diagonalDown=border_grey.diagonalDown,\n",
    "                                     diagonalUp=border_grey.diagonalUp)\n",
    "\n",
    "    if idd_value in completed_map:\n",
    "        fill, font = completed_map[idd_value]\n",
    "        for cell in row[:backlog_sheet.max_column - 6]:  # Iterate up to max_column - 6\n",
    "            cell.fill = fill\n",
    "            cell.font = font\n",
    "\n",
    "#################################################\n",
    "# Formatting SO Modified and Due date\n",
    "###############################################\n",
    "# Define column indices\n",
    "due_date_column_index = 17  # Column Q\n",
    "so_modified_column_index = 20  # Column T\n",
    "\n",
    "# Define the orange fill color\n",
    "orange_fill = PatternFill(start_color='FCD5B4', end_color='FCD5B4', fill_type='solid')\n",
    "\n",
    "# Define the yellow fill color and dark red font for the target date\n",
    "light_yellow_fill = PatternFill(start_color='FFFFCC', end_color='FFFFCC', fill_type='solid')\n",
    "dark_red_font = Font(color='C00000')\n",
    "\n",
    "# Loop through the rows in the backlog_sheet\n",
    "for row in range(2, backlog_sheet.max_row + 1):\n",
    "    due_date_cell = backlog_sheet.cell(row=row, column=due_date_column_index)\n",
    "    so_modified_cell = backlog_sheet.cell(row=row, column=so_modified_column_index)\n",
    "\n",
    "    due_date_value = due_date_cell.value\n",
    "    so_modified_value = so_modified_cell.value\n",
    "\n",
    "    # If SO Modified is NaN (None), just continue without applying any fill\n",
    "    if so_modified_value is None or pd.isna(so_modified_value):\n",
    "        continue\n",
    "\n",
    "    # Apply orange fill if dates are different\n",
    "    if due_date_value != so_modified_value:\n",
    "        due_date_cell.fill = orange_fill\n",
    "        so_modified_cell.fill = orange_fill\n",
    "        # Optionally, apply dark red font\n",
    "        due_date_cell.font = dark_red_font\n",
    "        so_modified_cell.font = dark_red_font\n",
    "        \n",
    "# Additional formatting based on SO Modified/Due date date in column S 'Due Date' \n",
    "target_dates = {datetime(2026, 12, 31), datetime(2026, 12, 24)}  # 12/31/2026 or 12/24/2026\n",
    "for row in range(2, backlog_sheet.max_row + 1):\n",
    "    value_in_S = backlog_sheet.cell(row=row, column=so_modified_column_index).value  # Column S is the 19th column for |CM-Backlog|\n",
    "    if isinstance(value_in_S, datetime) and value_in_S.date() == target_dates.date():\n",
    "        cell = backlog_sheet.cell(row=row, column=so_modified_column_index)\n",
    "        cell.fill = light_yellow_fill\n",
    "        cell.font = dark_red_font\n",
    "\n",
    "############################################################################\n",
    "# Highlight NC orders in yellow for entire row when 'Order' contains 'NC'\n",
    "#############################################################################\n",
    "yellow_fill = PatternFill(start_color='FFFF99', end_color='FFFF99', fill_type='solid')\n",
    "\n",
    "for row in backlog_sheet.iter_rows(min_row=2, max_row=backlog_sheet.max_row):\n",
    "    order_cell = row[11]  # Column L (12th column, zero-indexed is 11)\n",
    "    if order_cell.value and 'NC' in order_cell.value:\n",
    "        for cell in row[:backlog_sheet.max_column - 5]:  # Iterate up to max_column - 1\n",
    "            cell.fill = yellow_fill\n",
    "\n",
    "#####################################################################################################\n",
    "# Fill cell color based on condition for 'Order' column\n",
    "#####################################################################################################\n",
    "\n",
    "# Define the fill color for 'Order' column\n",
    "light_purple_fill = PatternFill(start_color='E4DFEC', end_color='E4DFEC', fill_type='solid')\n",
    "\n",
    "# Iterate through rows and fill 'Order' column based on condition\n",
    "for row in range(2, backlog_sheet.max_row + 1):\n",
    "    order_cell = backlog_sheet.cell(row=row, column=12)  # Column L (1-based index)\n",
    "    if order_cell.value and str(order_cell.value).startswith('D'):\n",
    "        order_cell.fill = light_purple_fill\n",
    "        \n",
    "####################################################################\n",
    "# Save the updated workbook\n",
    "###################################################################\n",
    "workbook.save(original_input)\n",
    "# Close the workbook\n",
    "workbook.close()\n",
    "\n",
    "print(f\"Backlog added successfully as |CM-Backlog| in {original_input}\")\n",
    "\n",
    "#***************************************************************************************************************************\n",
    "#############################################################################################################################\n",
    "## ##############  ###########     #########\n",
    "##       ##        ##       ##     ##      ##\n",
    "##       ##        ##       ##     ##########\n",
    "##       ##        ##       ##     ##   ###\n",
    "##       ## URN    ###########VER  ##     ### EPORT \n",
    "##############################################################################################################################\n",
    "#***************************************************************************************************************************\n",
    "# Define date and path\n",
    "input_TurnoverReport_formatted = os.path.join(Path, f'CM_IDD_TurnoverReport-{file_date_inventory}_Formatted.xlsx') \n",
    "\n",
    "##############################################################################################################################\n",
    "# Load workbook\n",
    "##############################################################################################################################\n",
    "# Load the existing output workbook\n",
    "try:\n",
    "    workbook = load_workbook(original_input)\n",
    "    #print(\"Output workbook loaded successfully.\")\n",
    "except FileNotFoundError as e:\n",
    "    print(f\"Output workbook not found: {e}\")\n",
    "    exit()\n",
    "\n",
    "# Print the sheet names\n",
    "print(\"Tabs in the workbook:\")\n",
    "print(workbook.sheetnames)\n",
    "print('Processing |CM-TurnoverReport| ...')\n",
    "\n",
    "# Load the Excel files into pandas DataFrames\n",
    "try:\n",
    "    df_TurnoverReport = pd.read_excel(input_TurnoverReport_formatted, sheet_name=0)\n",
    "    #print(\"TurnoverReport files loaded successfully.\")\n",
    "except FileNotFoundError as e:\n",
    "    print(f\"Input TurnoverReport file not found: {e}\")\n",
    "    exit()\n",
    "\n",
    "# Convert 'SO Modified' column to datetime format\n",
    "df_TurnoverReport['SO Modified'] = pd.to_datetime(df_TurnoverReport['SO Modified'], errors='coerce', format='%m-%d-%Y')\n",
    "\n",
    "# Convert datetime format to short date format (mm/dd/yyyy)\n",
    "df_TurnoverReport['SO Modified'] = df_TurnoverReport['SO Modified'].dt.strftime('%m/%d/%Y')\n",
    "\n",
    "#Rename column ['Flight/AWB'] and convert to number to avoid the format  Number+11\n",
    "df_TurnoverReport = df_TurnoverReport.rename(columns={'Flight/AWB': 'Tracking#'})\n",
    "\n",
    "# Convert 'Tracking#' column to string\n",
    "df_TurnoverReport['Tracking#'] = df_TurnoverReport['Tracking#'].astype(str)\n",
    "\n",
    "# Remove '.0' from the string if it exists\n",
    "df_TurnoverReport['Tracking#'] = df_TurnoverReport['Tracking#'].str.replace('.0', '', regex=False)\n",
    "\n",
    "####################################################################################################################\n",
    "##########################################     Creating TurnoverReport                   #########################\n",
    "###################################################################################################################\n",
    "# Check if \"CM-TurnoverReport\" sheet already exists and delete it if it does\n",
    "if \"CM-TurnoverReport\" in workbook.sheetnames:\n",
    "    del workbook[\"CM-TurnoverReport\"]\n",
    "\n",
    "# Create new \"CM-TurnoverReport\" sheet\n",
    "TurnoverReport_sheet = workbook.create_sheet(title='CM-TurnoverReport')\n",
    "\n",
    "# Write headers\n",
    "for c_idx, header in enumerate(df_TurnoverReport.columns, start=1):\n",
    "    TurnoverReport_sheet.cell(row=1, column=c_idx, value=header)\n",
    "\n",
    "# Write data\n",
    "for r_idx, row in enumerate(df_TurnoverReport.values, start=2):  # Start from row 2\n",
    "    for c_idx, value in enumerate(row, start=1):\n",
    "        TurnoverReport_sheet.cell(row=r_idx, column=c_idx, value=value)\n",
    "\n",
    "####################################################################################################################\n",
    "##########################################     Formating TurnoverReport                            #########################\n",
    "###################################################################################################################\n",
    "# Apply formatting to the header row\n",
    "header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')\n",
    "header_font = Font(color='FFFFFF', bold=True)\n",
    "header_alignment = Alignment(horizontal='left', vertical='center')\n",
    "header_border = Border(\n",
    "    top=Side(style='medium'),\n",
    "    bottom=Side(style='medium'),\n",
    "    left=Side(style='medium'),\n",
    "    right=Side(style='medium')\n",
    ")\n",
    "\n",
    "for cell in TurnoverReport_sheet[1]:\n",
    "    cell.fill = header_fill\n",
    "    cell.font = header_font\n",
    "    cell.alignment = header_alignment\n",
    "    cell.border = header_border\n",
    "\n",
    "# Add filters to the first row\n",
    "TurnoverReport_sheet.auto_filter.ref = TurnoverReport_sheet.dimensions\n",
    "\n",
    "# Set column widths and text alignment for columns A to W\n",
    "for column in TurnoverReport_sheet.iter_cols(min_col=1, max_col=22):\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "    \n",
    "    column_letter = column[0].column_letter\n",
    "    if column_letter in ['A', 'B', 'F', 'G', 'M', 'P', 'I', 'Q', 'S', 'R']:\n",
    "        TurnoverReport_sheet.column_dimensions[column_letter].width = 15\n",
    "    elif column_letter in ['H', 'L', 'N']:\n",
    "        TurnoverReport_sheet.column_dimensions[column_letter].width = 40\n",
    "    elif column_letter in ['C', 'D', 'N', 'T', 'U', 'V', 'R']:\n",
    "        TurnoverReport_sheet.column_dimensions[column_letter].width = 20\n",
    "    else:\n",
    "        backlog_sheet.column_dimensions[column_letter].width = 10\n",
    "\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "# Apply borders for rows 1 and 2 in column W\n",
    "for row in range(1, 3):\n",
    "    TurnoverReport_sheet.cell(row=row, column=23).border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "# Set background color for cell W2 and W3 left align\n",
    "TurnoverReport_sheet.cell(row=2, column=23).fill = PatternFill(start_color='E2EFDA', end_color='E2EFDA', fill_type='solid')\n",
    "TurnoverReport_sheet.cell(row=2, column=23).alignment = Alignment(horizontal='left', vertical='center')\n",
    "\n",
    "#**#############################################################################################################**\n",
    "# Color formating based on |Production status| from CM-Priority --> Refering to |CM-Priority| formatting \n",
    "#**############################################################################################################**\n",
    "# Define the fills and fonts for conditional formatting\n",
    "green_fill = PatternFill(start_color='D8E4BC', end_color='D8E4BC', fill_type='solid')\n",
    "blue_fill = PatternFill(start_color='DAEEF3', end_color='DAEEF3', fill_type='solid')\n",
    "dark_red_font = Font(color='C00000')\n",
    "light_yellow_fill = PatternFill(start_color='FFFFCC', end_color='FFFFCC', fill_type='solid')\n",
    "red_fill = PatternFill(start_color='F2DCDB', end_color='F2DCDB', fill_type='solid')\n",
    "grey_fill = PatternFill(start_color='F2F2F2', end_color='F2F2F2', fill_type='solid')\n",
    "grey_font_color = Font(color='BFBFBF')\n",
    "font_color = Font(color='000000')  # Black font color\n",
    "\n",
    "border_color = '000000'  # Black color for the border\n",
    "thin_black_side = Side(style='thin', color=border_color)\n",
    "border_grey = Border(\n",
    "    left=Side(border_style=None),\n",
    "    right=Side(border_style=None),\n",
    "    top=Side(border_style=None),\n",
    "    bottom=Side(border_style=None),\n",
    "    diagonal=Side(border_style='thin', color='D9D9D9'),\n",
    "    diagonalDown=True,\n",
    "    diagonalUp=True\n",
    ")\n",
    "\n",
    "# Load the workbook and sheets\n",
    "sheet_Priority = workbook[\"CM-Priority\"]\n",
    "\n",
    "# Get the column indices (1-based)\n",
    "col_idd_top_level_priority = [cell.value for cell in sheet_Priority[1]].index(\"IDD Top Level\") + 1\n",
    "col_idd_top_level_TurnoverReport = [cell.value for cell in TurnoverReport_sheet[1]].index(\"IDD Top Level\") + 1\n",
    "col_production_status = [cell.value for cell in sheet_Priority[1]].index(\"Production Status\") + 1\n",
    "\n",
    "# Create a mapping of IDD Top Level values to their respective formatting in the Priority sheet\n",
    "formatting_map = {}\n",
    "redlist_map = {}\n",
    "completed_map = {}\n",
    "\n",
    "for row in sheet_Priority.iter_rows(min_row=2, max_row=sheet_Priority.max_row):\n",
    "    idd_value = row[col_idd_top_level_priority - 1].value  # Adjust for zero-based index\n",
    "    production_status = row[col_production_status - 1].value  # Adjust for zero-based index\n",
    "\n",
    "    if production_status == 'Industrialized':\n",
    "        formatting_map[idd_value] = green_fill\n",
    "    elif 'WIP' in str(production_status):\n",
    "        formatting_map[idd_value] = blue_fill\n",
    "\n",
    "    # Redlist criteria\n",
    "    value_in_O = row[14].value  # Column O is the 15th column\n",
    "    if value_in_O and ('transferred' in str(value_in_O).lower() or 'canceled' in str(value_in_O).lower()):\n",
    "        redlist_map[idd_value] = red_fill\n",
    "\n",
    "    # Completed PN\n",
    "    value_in_I = row[8].value  # Column I is the 9th column\n",
    "    if value_in_I == 'Completed':\n",
    "        completed_map[idd_value] = (grey_fill, grey_font_color)\n",
    "\n",
    "# Apply the formatting to the TurnoverReport sheet based on the mappings\n",
    "for row in TurnoverReport_sheet.iter_rows(min_row=2, max_row=TurnoverReport_sheet.max_row):\n",
    "    idd_value = row[col_idd_top_level_TurnoverReport - 1].value  # Adjust for zero-based index\n",
    "    \n",
    "    # Apply formatting based on formatting_map\n",
    "    if idd_value in formatting_map:\n",
    "        fill = formatting_map[idd_value]\n",
    "        for cell in row[:backlog_sheet.max_column - 1]:  # Iterate up to max_column - 1\n",
    "            cell.fill = fill\n",
    "            cell.font = font_color\n",
    "    \n",
    "    # Apply formatting based on redlist_map\n",
    "    if idd_value in redlist_map:\n",
    "        fill = redlist_map[idd_value]\n",
    "        for cell in row[:backlog_sheet.max_column - 1]:  # Iterate up to max_column - 1\n",
    "            cell.fill = fill\n",
    "            if cell.col_idx == 1 or cell.col_idx == TurnoverReport_sheet.max_column:\n",
    "                cell.border = Border(\n",
    "                    left=thin_black_side if cell.col_idx == 1 else None,\n",
    "                    right=thin_black_side if cell.col_idx == TurnoverReport_sheet.max_column else None,\n",
    "                    top=thin_black_side, bottom=thin_black_side,\n",
    "                    diagonal=border_grey.diagonal, diagonalDown=border_grey.diagonalDown,\n",
    "                    diagonalUp=border_grey.diagonalUp\n",
    "                )\n",
    "    \n",
    "    # Apply formatting based on completed_map\n",
    "    if idd_value in completed_map:\n",
    "        fill, font = completed_map[idd_value]\n",
    "        for cell in row[:backlog_sheet.max_column - 1]:  # Iterate up to max_column - 1\n",
    "            cell.fill = fill\n",
    "            cell.font = font\n",
    "\n",
    "############################\n",
    "# Higlight NC order in yellow for column J 'Order'\n",
    "#############################\n",
    "# Highlight NC orders in yellow for entire row when 'Order' contains 'NC'\n",
    "yellow_fill = PatternFill(start_color='FFFF99', end_color='FFFF99', fill_type='solid')\n",
    "\n",
    "# Iterate through rows starting from the second row (index 1 in Python)\n",
    "for row in range(2, TurnoverReport_sheet.max_row + 1):\n",
    "    order_value = TurnoverReport_sheet.cell(row=row, column=10).value  # Assuming 'Order' is in column J (10th column)\n",
    "    if order_value and 'NC' in str(order_value):  # Check if 'NC' is in the 'Order' cell\n",
    "        # Iterate through all cells in the current row (columns A to W)\n",
    "        for col in range(1, 23):  # Adjust max_col based on your actual number of columns\n",
    "            cell = TurnoverReport_sheet.cell(row=row, column=col)\n",
    "            cell.fill = yellow_fill\n",
    "\n",
    "####################################################################\n",
    "# Save the updated workbook\n",
    "###################################################################\n",
    "workbook.save(original_input)\n",
    "# Close the workbook\n",
    "workbook.close()\n",
    "\n",
    "print(f\"TurnoverReport added successfully as |CM-TurnoverReport| in {original_input}\")\n",
    "\n",
    "#***************************************************************************************************************************\n",
    "#############################################################################################################################\n",
    "## ##                ##    ####     ##########\n",
    "##  ##      ##      ##      ##      ##      ##\n",
    "##   ##    ## ##   ##       ##      ##########\n",
    "##     ## ##   ## ##        ##      ##\n",
    "##       ###     ##        ####     ##\n",
    "##############################################################################################################################\n",
    "#***************************************************************************************************************************\n",
    "# Define date and path\n",
    "input_WIP_formatted = os.path.join(Path, f'CM_IDD_WIP-{file_date_inventory}_Formatted.xlsx') \n",
    "\n",
    "##############################################################################################################################\n",
    "# Load workbook\n",
    "##############################################################################################################################\n",
    "# Load the existing output workbook\n",
    "try:\n",
    "    workbook = load_workbook(original_input)\n",
    "    #print(\"Output workbook loaded successfully.\")\n",
    "except FileNotFoundError as e:\n",
    "    print(f\"Output workbook not found: {e}\")\n",
    "    exit()\n",
    "\n",
    "# Print the sheet names\n",
    "print(\"Tabs in the workbook:\")\n",
    "print(workbook.sheetnames)\n",
    "print('Processing |CM-WIP| ...')\n",
    "\n",
    "# Load the Excel files into pandas DataFrames\n",
    "try:\n",
    "    df_WIP = pd.read_excel(input_WIP_formatted, sheet_name=0)\n",
    "    print(\"WIP files loaded successfully.\")\n",
    "except FileNotFoundError as e:\n",
    "    print(f\"Input WIP file not found: {e}\")\n",
    "    exit()\n",
    "\n",
    "######################################################################################################\n",
    "##########################################     Creating WIP                  #########################\n",
    "######################################################################################################\n",
    "# Check if \"CM-TurnoverReport\" sheet already exists and delete it if it does\n",
    "if 'CM-WIP' in workbook.sheetnames:\n",
    "    del workbook['CM-WIP']\n",
    "\n",
    "# Create new \"CM-TurnoverReport\" sheet\n",
    "sheet_WIP = workbook.create_sheet(title='CM-WIP')\n",
    "\n",
    "#####################################################\n",
    "#Formating of the datafram before writing into Excel \n",
    "#####################################################\n",
    "# Ensure 'Last movement' is in datetime format\n",
    "df_WIP['Last movement'] = pd.to_datetime(df_WIP['Last movement'])\n",
    "\n",
    "# Make a copy of df_WIP for processing\n",
    "df_WIP_Temp = df_WIP.copy()\n",
    "\n",
    "# Get today's date\n",
    "today = pd.Timestamp(datetime.today().date())\n",
    "\n",
    "# Calculate the absolute difference between 'Last movement' and today's date in df_WIP_Temp\n",
    "df_WIP_Temp['Date Difference'] = abs(df_WIP_Temp['Last movement'] - today)\n",
    "\n",
    "# Define a function to select the row with the smallest date difference for each group\n",
    "def select_closest_to_today(group):\n",
    "    return group.sort_values('Date Difference').head(1)\n",
    "\n",
    "# Apply the function to each group defined by 'WO' and 'Pty Indice'\n",
    "#df_WIP_Temp = df_WIP_Temp.groupby(['WO', 'Pty Indice']).apply(select_closest_to_today).reset_index(drop=True) # Update 09/24 to avoid warning\n",
    "#df_WIP_Temp = df_WIP_Temp.groupby(['WO', 'Pty Indice']).apply(select_closest_to_today).reset_index(drop=True).copy() # Update 10/28\n",
    "df_WIP_Temp = df_WIP_Temp.groupby(['WO', 'Pty Indice'], group_keys=False).apply(select_closest_to_today).reset_index(drop=True)\n",
    "\n",
    "\n",
    "# Add or update 'OP Status' column with 'Most recent Op'\n",
    "df_WIP_Temp['OP Status'] = 'Most recent Op'\n",
    "\n",
    "# Create a mapping of ('WO', 'Pty Indice', 'Op', 'Last movement') to 'OP Status'\n",
    "op_status_mapping = df_WIP_Temp.set_index(['WO', 'Pty Indice', 'Op', 'Last movement'])['OP Status']\n",
    "\n",
    "# Map 'OP Status' based on the created mapping to update df_WIP\n",
    "df_WIP['OP Status'] = df_WIP.set_index(['WO', 'Pty Indice', 'Op', 'Last movement']).index.map(op_status_mapping)\n",
    "\n",
    "# Apply a lambda function to fill 'OP Status' with 'Most recent Op' where applicable\n",
    "df_WIP['OP Status'] = df_WIP.apply(\n",
    "    lambda row: 'Most recent Op' if (row['WO'], row['Pty Indice'], row['Op'], row['Last movement']) in op_status_mapping.index else row['OP Status'],\n",
    "    axis=1\n",
    ")\n",
    "\n",
    "# Convert 'Last movement' back to short format date sorting\n",
    "df_WIP['Last movement'] = df_WIP['Last movement'].dt.strftime('%m/%d/%Y')\n",
    "\n",
    "# Remove duplicate lines\n",
    "df_WIP = df_WIP.drop_duplicates()\n",
    "\n",
    "#print('df_WIP_Temp after processing:')\n",
    "#display(df_WIP_Temp)\n",
    "\n",
    "#print('df_WIP after processing:')\n",
    "#display(df_WIP)\n",
    "\n",
    "#############################################################################\n",
    "# Droping duplicates 'WO' for a given 'Pty Indice' to faciliate the reading\n",
    "#############################################################################\n",
    "# Retain only unique 'WO' values on column [F] - Identify the duplicates in the 'WO' column\n",
    "#df_WIP['WO'] = df_WIP['WO'].where(~df_WIP['WO'].duplicated(), np.nan)\n",
    "\n",
    "# Get all unique 'Pty Indice' values\n",
    "unique_p_indices = df_WIP['Pty Indice'].unique()\n",
    "\n",
    "# Iterate over each unique 'Pty Indice'\n",
    "for pty_indice in unique_p_indices:\n",
    "    # Filter DataFrame for the current 'Pty Indice'\n",
    "    df_filtered = df_WIP[df_WIP['Pty Indice'] == pty_indice].copy()\n",
    "    \n",
    "    # Identify duplicates in 'WO' column within the filtered DataFrame\n",
    "    df_filtered['WO'] = df_filtered['WO'].where(~df_filtered['WO'].duplicated(), np.nan)\n",
    "    \n",
    "    # Update the original DataFrame with the modified 'WO' column\n",
    "    df_WIP.loc[df_WIP['Pty Indice'] == pty_indice, 'WO'] = df_filtered['WO']\n",
    "\n",
    "#######################################################\n",
    "# Write headers\n",
    "for c_idx, header in enumerate(df_WIP.columns, start=1):\n",
    "    sheet_WIP.cell(row=1, column=c_idx, value=header)\n",
    "\n",
    "# Write data\n",
    "for r_idx, row in enumerate(df_WIP.values, start=2):  # Start from row 2\n",
    "    for c_idx, value in enumerate(row, start=1):\n",
    "        sheet_WIP.cell(row=r_idx, column=c_idx, value=value)\n",
    "\n",
    "####################################################################################################################\n",
    "##########################################     Formating WIP                          #########################\n",
    "###################################################################################################################\n",
    "# Apply formatting to the header row\n",
    "header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')\n",
    "header_font = Font(color='FFFFFF', bold=True)\n",
    "header_alignment = Alignment(horizontal='left', vertical='center')\n",
    "header_border = Border(\n",
    "    top=Side(style='medium'),\n",
    "    bottom=Side(style='medium'),\n",
    "    left=Side(style='medium'),\n",
    "    right=Side(style='medium')\n",
    ")\n",
    "\n",
    "for cell in sheet_WIP[1]:\n",
    "    cell.fill = header_fill\n",
    "    cell.font = header_font\n",
    "    cell.alignment = header_alignment\n",
    "    cell.border = header_border\n",
    "\n",
    "# Add filters to the first row\n",
    "sheet_WIP.auto_filter.ref = workbook.active.dimensions\n",
    "\n",
    "# Set column widths and text alignment for columns A to Z\n",
    "for column in sheet_WIP.iter_cols(min_col=1, max_col=30):\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "    \n",
    "    column_letter = column[0].column_letter\n",
    "    if column_letter in ['M', 'N']:\n",
    "        sheet_WIP.column_dimensions[column_letter].width = 15\n",
    "    elif column_letter in ['C', 'D', 'E', 'P', 'V', 'Z', 'AA', 'AB']:\n",
    "        sheet_WIP.column_dimensions[column_letter].width = 20\n",
    "    elif column_letter in ['L', 'W', 'H']:\n",
    "        sheet_WIP.column_dimensions[column_letter].width = 30\n",
    "    else:\n",
    "        sheet_WIP.column_dimensions[column_letter].width = 10\n",
    "\n",
    "    # Apply alignment and border to cells in the current column\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "# Set column width and text alignment for column AA from row 3\n",
    "for cell in sheet_WIP.iter_rows(min_row=3, min_col=31, max_col=31):\n",
    "    cell[0].alignment = Alignment(horizontal='left', vertical='center')\n",
    "\n",
    "# Apply borders for rows 1 and 2 in column \n",
    "for row in range(1, 3):\n",
    "    sheet_WIP.cell(row=row, column=31).border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "# Set background color for cell AA2 and AA3 left align\n",
    "sheet_WIP.cell(row=2, column=31).fill = PatternFill(start_color='E2EFDA', end_color='E2EFDA', fill_type='solid')\n",
    "\n",
    "# Custom conditional formatting for column J 'Level' (Assuming data starts from row 2)\n",
    "min_row = 2\n",
    "max_row = sheet_WIP.max_row\n",
    "col_J = 10\n",
    "\n",
    "for row in range(min_row, max_row + 1):\n",
    "    cell_value = sheet_WIP.cell(row=row, column=col_J).value\n",
    "\n",
    "    # Define default fill color in case cell_value is not in expected range\n",
    "    fill_color = None\n",
    "    \n",
    "    if cell_value is not None:\n",
    "        if cell_value == 0:\n",
    "            fill_color = '63BE7B'  # Green\n",
    "        elif cell_value == 1:\n",
    "            fill_color = 'A2C075'  # Lighter Green\n",
    "        elif cell_value == 2:\n",
    "            fill_color = 'FFEB84'  # Yellow\n",
    "        elif cell_value == 3:\n",
    "            fill_color = 'FFD166'  # Orange\n",
    "        elif cell_value == 4:\n",
    "            fill_color = 'F88E5B'  # Darker Orange\n",
    "        elif cell_value == 5:\n",
    "            fill_color = 'F8696B'  # Red\n",
    "        elif cell_value == 6:\n",
    "            fill_color = '8B0000'  # Darker Red\n",
    "        \n",
    "       # Create PatternFill object only if fill_color is defined\n",
    "        if fill_color:\n",
    "            fill = PatternFill(start_color=fill_color, end_color=fill_color, fill_type='solid')\n",
    "            sheet_WIP.cell(row=row, column=col_J).fill = fill\n",
    "\n",
    "#####################\n",
    "#Formating row of WOs\n",
    "######################\n",
    "# Define thick borders\n",
    "thick_border = Border(top=Side(style='thick'), bottom=Side(style='thick'))\n",
    "\n",
    "# Define bold font\n",
    "bold_font = Font(bold=True)\n",
    "\n",
    "# Highlight color\n",
    "bleu_fill = PatternFill(start_color='DAEEF3', end_color='DAEEF3', fill_type='solid')\n",
    "# Define fill for dark blue\n",
    "dark_blue_fill = PatternFill(start_color='92CDDC', end_color='92CDDC', fill_type='solid')\n",
    "\n",
    "# Iterate through rows starting from the second row\n",
    "for row in range(2, sheet_WIP.max_row + 1):  # Make sure to include the last row\n",
    "    wo_value = sheet_WIP.cell(row=row, column=6).value  # 'WO' column is F (6th column)\n",
    "    \n",
    "    # Check if 'WO' value is not None or NaN\n",
    "    if wo_value is not None and not pd.isna(wo_value):  \n",
    "        # Highlight entire row except column J 'Level'\n",
    "        for col in range(1, sheet_WIP.max_column):  # change 07/30\n",
    "            if col != 10:  # Skip column J (10th column)\n",
    "                cell = sheet_WIP.cell(row=row, column=col)\n",
    "                cell.fill = bleu_fill\n",
    "                cell.border = thick_border\n",
    "        \n",
    "        # Make the 'WO' value bold and dark bleu in column F\n",
    "        wo_cell = sheet_WIP.cell(row=row, column=6)  # 'WO' column is F (6th column)\n",
    "        wo_cell.font = bold_font\n",
    "        wo_cell.fill = dark_blue_fill\n",
    "        \n",
    "######################################################################\n",
    "# Formating row of 'WO status' and 'Area' to highlight the current WC  \n",
    "######################################################################\n",
    "# Column indices for 'Op Status', 'WO', and 'Last Movement'\n",
    "op_status_col_index = 22  # 'Op Status' column is V (22nd column)\n",
    "wo_status_col_index = 7  # 'WO Status' column is G (7th column)\n",
    "wo_col_index = 6 # 'WO' column is F (6th column)\n",
    "area_col_index = 8 # 'Area' column is H (8th column)\n",
    "last_movement_col_index = 28  # 'Last Movement' column is AB (28th column)\n",
    "\n",
    "# Iterate through the rows to find and highlight the rows where 'Op Status' contains 'Most recent Op'\n",
    "for row in range(2, sheet_WIP.max_row + 1):\n",
    "    op_status = sheet_WIP.cell(row=row, column=op_status_col_index).value  # 'Op Status' column\n",
    "\n",
    "    # Check if 'Op Status' is a string and contains 'Most recent Op'\n",
    "    if isinstance(op_status, str) and 'Most recent Op' in op_status:\n",
    "        # Highlight the 'Last Movement' cell\n",
    "        cell = sheet_WIP.cell(row=row, column=last_movement_col_index)\n",
    "        cell.fill = dark_blue_fill\n",
    "        cell.font = bold_font  # Make the text bold\n",
    "        \n",
    "        # Highlight the 'WO status' cell\n",
    "        cell = sheet_WIP.cell(row=row, column=wo_status_col_index)\n",
    "        cell.fill = dark_blue_fill\n",
    "        cell.font = bold_font  # Make the text bold\n",
    "\n",
    "        # Highlight the 'Area' cell\n",
    "        cell = sheet_WIP.cell(row=row, column=area_col_index)\n",
    "        cell.fill = dark_blue_fill\n",
    "        cell.font = bold_font  # Make the text bold\n",
    "\n",
    "############################\n",
    "# Higlight NC order in yellow for column F 'WO'\n",
    "#############################\n",
    "# Highlight NC orders in yellow for entire row when 'Order' contains 'NC'\n",
    "yellow_fill = PatternFill(start_color='FFFF99', end_color='FFFF99', fill_type='solid')\n",
    "\n",
    "# Iterate through rows starting from the second row (index 1 in Python)\n",
    "for row in range(2, max_row + 1):\n",
    "    order_value = sheet_WIP.cell(row=row, column=6).value  # Assuming 'WO' is in column F (6th column)\n",
    "    if order_value and 'NC' in str(order_value):  # Check if 'NC' is in the 'WO' cell\n",
    "        # Iterate through all cells in the current row (columns A to Z)\n",
    "        for col in range(1, 31):  # Adjust max_col based on your actual number of columns\n",
    "            if col == 10:  # Skip column J (10th column)\n",
    "                continue\n",
    "            cell = sheet_WIP.cell(row=row, column=col)\n",
    "            cell.fill = yellow_fill\n",
    "            \n",
    "####################################################################\n",
    "# Save the updated workbook\n",
    "###################################################################\n",
    "workbook.save(original_input)\n",
    "# Close the workbook\n",
    "workbook.close()\n",
    "\n",
    "print(f\"WIP added successfully as |CM-WIP| in {original_input}\")\n",
    "\n",
    "#***************************************************************************************************************************\n",
    "#############################################################################################################################\n",
    "## ##########            #########\n",
    "## ##      ##            ##     ##\n",
    "## ##########            #########\n",
    "## ##                    #####\n",
    "## ##         ENDING     ##  #### EPORT\n",
    "##############################################################################################################################\n",
    "#***************************************************************************************************************************\n",
    "# Define date and path\n",
    "input_PendingReport_formatted = os.path.join(Path, f'CM_IDD_PendingReport_Formatted.xlsx') \n",
    "\n",
    "##############################################################################################################################\n",
    "# Load workbook\n",
    "##############################################################################################################################\n",
    "# Load the existing output workbook\n",
    "try:\n",
    "    workbook = load_workbook(original_input)\n",
    "    #print(\"Output workbook loaded successfully.\")\n",
    "except FileNotFoundError as e:\n",
    "    print(f\"Output workbook not found: {e}\")\n",
    "    exit()\n",
    "\n",
    "# Print the sheet names\n",
    "print(\"Tabs in the workbook:\")\n",
    "print(workbook.sheetnames)\n",
    "print('Processing |PendingReport| ...')\n",
    "\n",
    "# Load the Excel files into pandas DataFrames\n",
    "try:\n",
    "    df_PendingReport = pd.read_excel(input_PendingReport_formatted, sheet_name=0)\n",
    "    #print(\"Pending Report files loaded successfully.\")\n",
    "except FileNotFoundError as e:\n",
    "    print(f\"Input PendingReport file not found: {e}\")\n",
    "    exit()\n",
    "\n",
    "####################################################################################################################\n",
    "##########################################     Creating |PendingReport|                    #########################\n",
    "###################################################################################################################\n",
    "# Check if \"CM-TurnoverReport\" sheet already exists and delete it if it does\n",
    "if 'PendingReport' in workbook.sheetnames:\n",
    "    del workbook['PendingReport']\n",
    "\n",
    "# Create new \"CM-TurnoverReport\" sheet\n",
    "sheet_PendingReport = workbook.create_sheet(title='PendingReport')\n",
    "\n",
    "# Convert 'S.O. Date' and 'Rel Date' to datetime format (if they are not already)\n",
    "df_PendingReport['S.O. Date'] = pd.to_datetime(df_PendingReport['S.O. Date'], errors='coerce')\n",
    "df_PendingReport['Rel Date'] = pd.to_datetime(df_PendingReport['Rel Date'], errors='coerce')\n",
    "\n",
    "####################################################################################################################################################################\n",
    "# Including additionnal column based on CM-Priority ['Agile expected status'], and based on BOM ['Description Component'] based on ['Item Number'] from pending report\n",
    "####################################################################################################################################################################\n",
    "### Create column ['Agile expected status'] based on ['IDD Top Level'] and mapping with ['IDD Top Level'] from df_Priority \n",
    "# Merge to include 'Agile expected status' while keeping all existing columns\n",
    "# Remove duplicates in df_Priority before merging for 'Agile expected status'\n",
    "df_Priority_unique = df_Priority[['IDD Top Level', 'Agile expected status']].drop_duplicates()\n",
    "\n",
    "#Create a temporary datafram df_PendingReport_temp\n",
    "df_PendingReport_temp = df_PendingReport.copy()\n",
    "\n",
    "# Merge to include 'Agile expected status'\n",
    "df_PendingReport_temp = df_PendingReport_temp.merge(\n",
    "    df_Priority_unique,\n",
    "    on='IDD Top Level',\n",
    "    how='left'\n",
    ")\n",
    "\n",
    "# Check if 'Agile expected status' is present after the merge\n",
    "#print('Check if Agile expected status is part of the datafram After merging with df_Priority:')\n",
    "#print(df_PendingReport_temp.head())\n",
    "\n",
    "# Remove duplicates in df_CM_BOM before merging for 'Description Component'\n",
    "df_CM_BOM_unique = df_CM_BOM[['IDD Component', 'Description Component']].drop_duplicates()\n",
    "\n",
    "# Merge to include 'Description Component'\n",
    "df_PendingReport_temp = df_PendingReport_temp.merge(\n",
    "    df_CM_BOM_unique,\n",
    "    left_on='Item Number',\n",
    "    right_on='IDD Component',\n",
    "    how='left'\n",
    ")\n",
    "\n",
    "#Drop 'IDD Component' and 'Description Component'  to avoid dupliacted column later\n",
    "df_PendingReport_temp.drop(columns=['IDD Component', 'Description Component'], inplace=True)\n",
    "\n",
    "#print('Check if Agile expected status is part of the datafram After merging with df_CM_BOM_unique:')\n",
    "#print(df_PendingReport_temp.head())\n",
    "\n",
    "### Create column ['Description Component'] based on ['Item Number'] from pending report\n",
    "## Mapping of ['Item Number'] from df_PendingReport on ['IDD Component'] from df_CM_BOM and retuning ['Description Component']\n",
    "# Remove duplicates before next merge\n",
    "df_CM_BOM_unique = df_CM_BOM[['IDD Component', 'Description Component']].drop_duplicates()\n",
    "\n",
    "# Merge to include 'Description Component' while keeping all existing columns\n",
    "df_PendingReport_temp = df_PendingReport_temp.merge(\n",
    "    df_CM_BOM_unique,\n",
    "    left_on='Item Number',\n",
    "    right_on='IDD Component',\n",
    "    how='left'\n",
    ")\n",
    "\n",
    "#print('df_PendingReport_temp BEFORE merging on Production status')\n",
    "#display(df_PendingReport_temp)\n",
    "\n",
    "### Create column ['Production Status'] based on mapping with ['IDD Top Level'] from df_Priority and fill the 'Legacy' PN with 'Industrilalized' and the Not Transfer PN with 'Not Transfer'\n",
    "# Merge to include 'Production Status' while keeping all existing columns\n",
    "# Remove duplicates in df_Priority before merging for 'Production Status'\n",
    "df_Priority_unique = df_Priority[['IDD Top Level', 'Production Status']].drop_duplicates(subset=['IDD Top Level'])\n",
    "\n",
    "#df_Priority_unique = df_Priority.groupby('IDD Top Level').agg({'Production Status': 'first'}).reset_index()\n",
    "\n",
    "# Merge to include 'Production Status'\n",
    "df_PendingReport_temp = df_PendingReport_temp.merge(\n",
    "    df_Priority_unique,\n",
    "    on='IDD Top Level',\n",
    "    how='left'\n",
    ")\n",
    "\n",
    "# Function to determine 'Production Status'\n",
    "def determine_production_status(row):\n",
    "    if row['Program'] in ['Legacy', 'Legacy CUU', 'SIKORSKY', 'COMAC', 'EMBRAER']:\n",
    "        return 'Industrialized'\n",
    "    elif row['Program'] == 'Not Transfer':\n",
    "        return 'Not Transfer'\n",
    "    return row['Production Status']  # Keep the existing value\n",
    "\n",
    "# Apply function to update 'Production Status'\n",
    "df_PendingReport_temp['Production Status'] = df_PendingReport_temp.apply(determine_production_status, axis=1)\n",
    "\n",
    "\n",
    "####################################################################################################################################\n",
    "# Function to order the list based on type of order DO/DX ['S.O. #'], ['Production Status'], and Expected Release date ['Rel Date']\n",
    "###################################################################################################################################\n",
    "## Order is defined as follow: Collumn ['ENG Priority']\n",
    "#1. Industrialized PN - 'Legacy' are considered Industrialized, 'Not Tranfer' are also considered Industrialized due to lack of info\n",
    "#2. DO/DX order \n",
    "#3. Expected released date\n",
    "# --> Top priority is ['ENG Priority'] = Industrialized with ['S.O. #'] start with 'D' and ['Rel Date'] most in the past \n",
    "\n",
    "# Step 1: Create helper columns to classify Industrialized and Phase 4 industrialized and DO/DX orders\n",
    "df_PendingReport_temp['Is Industrialized'] = df_PendingReport_temp['Production Status'].isin(['Industrialized', 'Not Transfer'])\n",
    "df_PendingReport_temp['Phase 4 Industrialized'] = (df_PendingReport_temp['Program'] == 'Phase 4') & (df_PendingReport_temp['Production Status'].isin(['Industrialized']))\n",
    "df_PendingReport_temp['S.O. # Starts with D'] = df_PendingReport_temp['S.O. #'].apply(lambda x: str(x).startswith('D'))\n",
    "\n",
    "# Step 2: Define the sorting criteria\n",
    "df_PendingReport_temp['Sort Key'] = (\n",
    "    df_PendingReport_temp['Phase 4 Industrialized'].astype(int) * 1000 +  # Phase 4 Industrialized first\n",
    "    df_PendingReport_temp['Is Industrialized'].astype(int) * 100 +  # Other Industrialized next\n",
    "    df_PendingReport_temp['S.O. # Starts with D'].astype(int) * 10 +  # S.O. # starts with D within above groups\n",
    "    (df_PendingReport_temp['Rel Date'].max() - df_PendingReport_temp['Rel Date']).dt.days  # Earliest Rel Date\n",
    ")\n",
    "\n",
    "# Adjust the sorting criteria to handle 'S.O. # Starts with D' within each group\n",
    "df_PendingReport_temp['Sort Key'] = (\n",
    "    df_PendingReport_temp['Phase 4 Industrialized'].astype(int) * 1000 +\n",
    "    df_PendingReport_temp['Is Industrialized'].astype(int) * 100 +\n",
    "    df_PendingReport_temp['S.O. # Starts with D'].astype(int) * 10 +\n",
    "    df_PendingReport_temp['Rel Date'].rank(ascending=True, method='first')  # Rank Rel Date within each group\n",
    ")\n",
    "\n",
    "# Step 3: Sort the DataFrame based on the Sort Key\n",
    "df_PendingReport_temp = df_PendingReport_temp.sort_values(by=['Sort Key'], ascending=True)\n",
    "\n",
    "# Step 4: Assign sequential ENG Priority based on the sorted DataFrame\n",
    "df_PendingReport_temp['ENG Priority'] = range(1, len(df_PendingReport_temp ) + 1)\n",
    "\n",
    "#print('df_PendingReport_temp before droping the extra column used for sorting and after seting priority numbers in [ENG Priority] based on sorting criteria')\n",
    "#display(df_PendingReport_temp)\n",
    "\n",
    "# step 5: Sort dataframe back in the original order based on the index.\n",
    "df_PendingReport_temp = df_PendingReport_temp.sort_index()\n",
    "\n",
    "#print('df_PendingReport_temp after sorting back to original order of df_PendingReport but with [ENG Priority] filled')\n",
    "#display(df_PendingReport_temp)\n",
    "\n",
    "\n",
    "####################################################################################################################\n",
    "# Creating |PendingReport|\n",
    "#####################################################################################################################\n",
    "#Create df_PendingReport with relevant column after sortung back to original order basec on the original index\n",
    "df_PendingReport = df_PendingReport_temp.drop(columns=['Is Industrialized', 'S.O. # Starts with D', 'Sort Key', 'Phase 4 Industrialized'])\n",
    "\n",
    "# Format dates as short dates\n",
    "df_PendingReport['S.O. Date'] = df_PendingReport['S.O. Date'].dt.strftime('%m/%d/%Y')  # MM/DD/YYYY format\n",
    "df_PendingReport['Rel Date'] = df_PendingReport['Rel Date'].dt.strftime('%m/%d/%Y')  # MM/DD/YYYY format\n",
    "\n",
    "# Write headers to Excel\n",
    "for c_idx, header in enumerate(df_PendingReport.columns, start=1):\n",
    "    sheet_PendingReport.cell(row=1, column=c_idx, value=header)\n",
    "\n",
    "# Write data to Excel\n",
    "for r_idx, row in enumerate(df_PendingReport.values, start=2):\n",
    "    for c_idx, value in enumerate(row, start=1):\n",
    "        sheet_PendingReport.cell(row=r_idx, column=c_idx, value=value)\n",
    "    \n",
    "####################################################################################################################\n",
    "##########################################     Formating |PendingReport|                  #########################\n",
    "###################################################################################################################\n",
    "# Apply formatting to the header row\n",
    "header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')\n",
    "header_font = Font(color='FFFFFF', bold=True)\n",
    "header_alignment = Alignment(horizontal='left', vertical='center')\n",
    "header_border = Border(\n",
    "    top=Side(style='medium'),\n",
    "    bottom=Side(style='medium'),\n",
    "    left=Side(style='medium'),\n",
    "    right=Side(style='medium')\n",
    ")\n",
    "\n",
    "for cell in sheet_PendingReport[1]:\n",
    "    cell.fill = header_fill\n",
    "    cell.font = header_font\n",
    "    cell.alignment = header_alignment\n",
    "    cell.border = header_border\n",
    "\n",
    "# Add filters to the first row\n",
    "sheet_PendingReport.auto_filter.ref = sheet_PendingReport.dimensions\n",
    "\n",
    "# Set column widths and text alignment for columns A to S\n",
    "for column in sheet_PendingReport.iter_cols(min_col=1, max_col=19):\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "    \n",
    "    column_letter = column[0].column_letter\n",
    "    if column_letter in ['A', 'B', 'F']:\n",
    "        sheet_PendingReport.column_dimensions[column_letter].width = 15\n",
    "    elif column_letter in ['G', 'Q', 'O']:\n",
    "        sheet_PendingReport.column_dimensions[column_letter].width = 30\n",
    "    elif column_letter in ['P']:\n",
    "        sheet_PendingReport.column_dimensions[column_letter].width = 40\n",
    "    elif column_letter in ['C', 'D', 'H' , 'I', 'N', 'R', 'S']:\n",
    "        sheet_PendingReport.column_dimensions[column_letter].width = 20\n",
    "    else:\n",
    "        sheet_PendingReport.column_dimensions[column_letter].width = 10\n",
    "\n",
    "    # Apply alignment and border to cells in the current column\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "# Erase contents in column T (assuming T is column 20)\n",
    "for row in range(2, sheet_PendingReport.max_row + 1):\n",
    "    sheet_PendingReport.cell(row=row, column=10).value = None\n",
    "\n",
    "# Apply borders for rows 1 and 2 in column T\n",
    "for row in range(1, 3):\n",
    "    sheet_PendingReport.cell(row=row, column=20).border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "# Set background color for cell T2 and T3 left align\n",
    "sheet_PendingReport.cell(row=2, column=20).fill = PatternFill(start_color='E2EFDA', end_color='E2EFDA', fill_type='solid')\n",
    "sheet_PendingReport.cell(row=2, column=20).alignment = Alignment(horizontal='left', vertical='center')\n",
    "\n",
    "#############################################################################################################################\n",
    "# Formatting added column ['Agile expected status'], ['Description Component'], ['IDD Component'] and ['Production Status']\n",
    "############################################################################################################################\n",
    "# Set the width for column T (20)\n",
    "sheet_PendingReport.column_dimensions['T'].width = 20\n",
    "    \n",
    "# Set column widths and text alignment for columns U to Y (21 to 25)\n",
    "for column in sheet_PendingReport.iter_cols(min_col=21, max_col=25):\n",
    "    column_letter = column[0].column_letter  # Get the column letter\n",
    "\n",
    "    # Set the width based on the column letter\n",
    "    if column_letter in ['U', 'V', 'X']:\n",
    "        sheet_PendingReport.column_dimensions[column_letter].width = 20\n",
    "    elif column_letter == 'W':\n",
    "        sheet_PendingReport.column_dimensions[column_letter].width = 30\n",
    "    else:\n",
    "        sheet_PendingReport.column_dimensions[column_letter].width = 10\n",
    "\n",
    "    # Apply alignment and border to each cell in the current column\n",
    "    for cell in column:\n",
    "        if cell.row == 1:  # Header\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:  # Data rows\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "\n",
    "        # Set borders for the cells in the current column\n",
    "        cell.border = Border(\n",
    "            top=Side(style='thin'),\n",
    "            right=Side(style='thin'),\n",
    "            bottom=Side(style='thin'),\n",
    "            left=Side(style='thin')\n",
    "        )\n",
    "        \n",
    "########################################\n",
    "# Formatting based on 'Rel Date'\n",
    "#########################################\n",
    "# Convert 'S.O. Date' and 'Rel Date' to datetime format (if they are not already) for the formatting based on date\n",
    "df_PendingReport['S.O. Date'] = pd.to_datetime(df_PendingReport['S.O. Date'], errors='coerce')\n",
    "df_PendingReport['Rel Date'] = pd.to_datetime(df_PendingReport['Rel Date'], errors='coerce')\n",
    "\n",
    "# Define colors\n",
    "light_green = PatternFill(start_color='EBF1DE', end_color='EBF1DE', fill_type='solid')\n",
    "light_orange = PatternFill(start_color='FDE9D9', end_color='FDE9D9', fill_type='solid')\n",
    "\n",
    "# Get today's date\n",
    "today = datetime.today().date()\n",
    "\n",
    "# Apply formatting based on 'Rel Date'\n",
    "for row in range(len(df_PendingReport)):  # Iterate over the DataFrame rows\n",
    "    rel_date_value = df_PendingReport.iloc[row]['Rel Date']  # Access the 'Rel Date'\n",
    "\n",
    "    if isinstance(rel_date_value, pd.Timestamp):\n",
    "        rel_date_value_date = rel_date_value.date()  # Convert to date for comparison\n",
    "\n",
    "        # Apply the formatting logic\n",
    "        for col in range(3, 13):  # Columns C (3) to L (12)\n",
    "            cell = sheet_PendingReport.cell(row=row + 2, column=col)  # Adjust row index for Excel\n",
    "\n",
    "            if rel_date_value_date > today:\n",
    "                cell.fill = light_green\n",
    "            elif rel_date_value_date < today:\n",
    "                cell.fill = light_orange\n",
    "\n",
    "#####################################################\n",
    "# Formating on DO/DX Order ['S.O. #'] \n",
    "####################################################\n",
    "# Define the fill color for 'Order' column\n",
    "light_purple_fill = PatternFill(start_color='E4DFEC', end_color='E4DFEC', fill_type='solid')\n",
    "\n",
    "# Iterate through rows and fill 'S.O. #' column based on condition\n",
    "for row in range(2, sheet_PendingReport.max_row + 1):\n",
    "    order_cell = sheet_PendingReport.cell(row=row, column=5)  # Column E (1-based index)\n",
    "    if order_cell.value and str(order_cell.value).startswith('D'):\n",
    "        order_cell.fill = light_purple_fill\n",
    "\n",
    "#################################################################################################################\n",
    "# Formating ['Pty Indice'], ['Where Used Top Level']  and ['Action Needed] in bold with thick left and right border\n",
    "####################################################################################################################\n",
    "# Define the column indices for 'Action Needed', column C, and column A\n",
    "action_needed_col_index = 12  # Column L\n",
    "column_c_index = 3  # Column C\n",
    "column_a_index = 1  # Column A\n",
    "\n",
    "# Define the thick border style for left and right\n",
    "thick_left_right_border = Border(\n",
    "    left=Side(style='thick'),\n",
    "    right=Side(style='thick')\n",
    ")\n",
    "\n",
    "# Function to apply formatting\n",
    "def apply_formatting(column_index):\n",
    "    for row in range(2, sheet_PendingReport.max_row + 1):  # Starting from row 2\n",
    "        cell = sheet_PendingReport.cell(row=row, column=column_index)\n",
    "        cell.font = Font(bold=True)\n",
    "        \n",
    "        # Preserve existing top and bottom borders\n",
    "        current_border = cell.border\n",
    "        cell.border = Border(\n",
    "            left=thick_left_right_border.left,\n",
    "            right=thick_left_right_border.right,\n",
    "            top=current_border.top,\n",
    "            bottom=current_border.bottom\n",
    "        )\n",
    "\n",
    "# Apply formatting to columns A, C, and L\n",
    "apply_formatting(action_needed_col_index)\n",
    "apply_formatting(column_c_index)\n",
    "apply_formatting(column_a_index)\n",
    "\n",
    "##################################################################################################\n",
    "# Color formating based on mapping from |CM_Priority| on df_PendingReport ['Production Status']\n",
    "##################################################################################################\n",
    "#Color already defined in BACKLOG section\n",
    "col_idd_top_level_PendingReport = [cell.value for cell in sheet_PendingReport[1]].index(\"IDD Top Level\") + 1\n",
    "\n",
    "# Using the mapping of IDD Top Level values to their respective formatting in the Priority sheet (see section BACKLOG)\n",
    "# Apply the formatting to the PendingReport sheet based on the mappings\n",
    "# Define column indices for A and X (1-based index)\n",
    "col_A_index = 1  # Column A is the 1st column (1-based index)\n",
    "col_X_index = 24 # Column X is the 24th column (1-based index)\n",
    "\n",
    "# Convert to zero-based indices for Python list handling\n",
    "col_A_index_zero_based = col_A_index - 1\n",
    "col_X_index_zero_based = col_X_index - 1\n",
    "\n",
    "# Iterate over rows starting from the second row (assuming the first row is headers)\n",
    "for row in sheet_PendingReport.iter_rows(min_row=2, max_row=sheet_PendingReport.max_row):\n",
    "    idd_value = row[col_idd_top_level_PendingReport - 1].value  # Adjust for zero-based index\n",
    "    \n",
    "    if idd_value in formatting_map:\n",
    "        fill = formatting_map[idd_value]\n",
    "        # Apply formatting only to columns A and X\n",
    "        if row[col_A_index_zero_based].value is not None:\n",
    "            row[col_A_index_zero_based].fill = fill\n",
    "            row[col_A_index_zero_based].font = font_color\n",
    "        \n",
    "        if row[col_X_index_zero_based].value is not None:\n",
    "            row[col_X_index_zero_based].fill = fill\n",
    "            row[col_X_index_zero_based].font = font_color\n",
    "\n",
    "    if idd_value in completed_map:\n",
    "        fill, font = completed_map[idd_value]\n",
    "        # Apply formatting only to columns A and X\n",
    "        if row[col_A_index_zero_based].value is not None:\n",
    "            row[col_A_index_zero_based].fill = fill\n",
    "            row[col_A_index_zero_based].font = font\n",
    "        \n",
    "        if row[col_X_index_zero_based].value is not None:\n",
    "            row[col_X_index_zero_based].fill = fill\n",
    "            row[col_X_index_zero_based].font = font\n",
    "\n",
    "################################################################\n",
    "# Save the updated workbook\n",
    "################################################################\n",
    "workbook.save(original_input)\n",
    "# Close the workbook\n",
    "workbook.close()\n",
    "\n",
    "print(f\"Pending Report added successfully as |PendingReport| in {original_input}\")\n",
    "\n",
    "#***************************************************************************************************************************\n",
    "######################################################################################################################################################################################\n",
    "##  ##    ##  ######  ########  ########## #########  #########  ######  #########\n",
    "##  ##    ##    ##    ##            ##     ##     ##  ##     ##    ##    ##\n",
    "##  ########    ##    ########      ##     ##     ##  #########    ##    ##\n",
    "##  ##    ##    ##          ##      ##     ##     ##  ##  ###      ##    ##\n",
    "##  ##    ##  ######  ########      ##     #########  ##    ###  ######  #########\n",
    "######################################################################################################################################################################################\n",
    "#***************************************************************************************************************************\n",
    "#***************************************************************************************************************************\n",
    "# Define date and path\n",
    "input_historic_formatted = os.path.join(Path, f'CM_IDD_TurnoverReport_Historic_Formatted.xlsx') \n",
    "\n",
    "##############################################################################################################################\n",
    "# Load workbook\n",
    "##############################################################################################################################\n",
    "# Load the existing output workbook\n",
    "try:\n",
    "    workbook = load_workbook(original_input)\n",
    "    #print(\"Output workbook loaded successfully.\")\n",
    "except FileNotFoundError as e:\n",
    "    print(f\"Output workbook not found: {e}\")\n",
    "    exit()\n",
    "\n",
    "# Print the sheet names\n",
    "print(\"Tabs in the workbook:\")\n",
    "print(workbook.sheetnames)\n",
    "print('Processing |Historic| ...')\n",
    "\n",
    "# Load the Excel files into pandas DataFrames\n",
    "try:\n",
    "    df_Historic = pd.read_excel(input_historic_formatted, sheet_name=0)\n",
    "    #print(\"Pending Report files loaded successfully.\")\n",
    "except FileNotFoundError as e:\n",
    "    print(f\"Input PendingReport file not found: {e}\")\n",
    "    exit()\n",
    "\n",
    "################################################\n",
    "# Formatting 'Tracking#'\n",
    "#################################################\n",
    "# Replace NaN with empty string\n",
    "df_Historic['Tracking#'] = df_Historic['Tracking#'].fillna('')\n",
    "\n",
    "# Convert 'Tracking#' column to string\n",
    "df_Historic['Tracking#'] = df_Historic['Tracking#'].astype(str)\n",
    "\n",
    "# Remove '.0' from the string if it exists\n",
    "df_Historic['Tracking#'] = df_Historic['Tracking#'].str.replace('.0', '', regex=False)\n",
    "\n",
    "#######################################\n",
    "# Create a column 'IDD Marge Standard'\n",
    "######################################\n",
    "#Fill the blank\n",
    "''' Update 09/23 to avoid warning\n",
    "df_Historic['Currency turnover ex.VAT'].fillna(0, inplace=True)\n",
    "df_Historic['Standard amount USD'].fillna(0, inplace=True)\n",
    "'''\n",
    "df_Historic['Currency turnover ex.VAT'] = df_Historic['Currency turnover ex.VAT'].fillna(0)\n",
    "df_Historic['Standard amount USD'] = df_Historic['Standard amount USD'].fillna(0)\n",
    "\n",
    "#Format to numeric \n",
    "df_Historic['Currency turnover ex.VAT'] = pd.to_numeric(df_Historic['Currency turnover ex.VAT'], errors='coerce')\n",
    "df_Historic['Standard amount USD'] = pd.to_numeric(df_Historic['Standard amount USD'], errors='coerce')\n",
    "\n",
    "#Calculation of the marge standard \n",
    "df_Historic['IDD Marge Standard'] = df_Historic['Currency turnover ex.VAT'] - df_Historic['Standard amount USD']\n",
    "\n",
    "#############################\n",
    "# Creating column 'Month'\n",
    "############################\n",
    "# Ensure 'Invoice date' is in datetime format\n",
    "df_Historic['Invoice date'] = pd.to_datetime(df_Historic['Invoice date'])\n",
    "\n",
    "# Directly create 'Month' in the desired format (e.g., Jan 23, Feb 23, ...)\n",
    "df_Historic['Month'] = df_Historic['Invoice date'].dt.strftime('%b %y')\n",
    "\n",
    "# Convert 'Invoice date' back to short date format (e.g., MM/DD/YYYY)\n",
    "df_Historic['Invoice date'] = df_Historic['Invoice date'].dt.strftime('%m/%d/%Y')\n",
    "#\n",
    "##########################################################################################################################################\n",
    "# Creating column 'Complexity' with the function to define the familly based on 'Description' + new function to assign a complecity level\n",
    "###########################################################################################################################################\n",
    "# Define the 'Product Category' base on 'Description' \n",
    "#######################################################\n",
    "# Define the 'Product Category' based on 'General Description'\n",
    "def determine_category(description):\n",
    "    if not isinstance(description, str):\n",
    "        return 'Others'\n",
    "    if description == 'Rototellite':\n",
    "        return 'Rototellite'\n",
    "    elif 'Indicator' in description or 'CPA' in description:\n",
    "        return 'CPA'\n",
    "    elif 'Lightplate' in description:\n",
    "        return 'Lightplate'\n",
    "    elif 'ISP' in description or 'Keyboard' in description:\n",
    "        return 'ISP'\n",
    "    elif 'Module' in description:\n",
    "        return 'CPA'\n",
    "    elif 'optics' in description:\n",
    "        return 'Fiber Optics'\n",
    "    else:\n",
    "        return 'Others'\n",
    "\n",
    "# Create 'Product Category' column based on the 'Description'\n",
    "df_Historic['Product Category'] = df_Historic['Description'].apply(determine_category)\n",
    "\n",
    "###################################################\n",
    "# Assigne a complexity Level base on the familly \n",
    "##################################################\n",
    "# 'Kit' = 0, 'Rototellite' and 'Lightplete' = 1, 'CPA' = 2, 'ISP' = 3\n",
    "# Assign a complexity level based on the category\n",
    "def determine_complexity(category):\n",
    "    if not isinstance(category, str):\n",
    "        return 0\n",
    "    if category == 'Rototellite':\n",
    "        return 0.50\n",
    "    elif category == 'Lightplate':\n",
    "        return 0.25\n",
    "    elif category == 'CPA':\n",
    "        return 0.75\n",
    "    elif category == 'ISP':\n",
    "        return 1\n",
    "    elif category == 'Fiber Optics':\n",
    "        return 0.50\n",
    "    elif category == 'Others':\n",
    "        return 0\n",
    "    else:\n",
    "        return 0\n",
    "    \n",
    "# Create 'Complexity' column based on 'Product Category'\n",
    "df_Historic['Complexity'] = df_Historic['Product Category'].apply(determine_complexity)\n",
    "\n",
    "#print('df_Historic')\n",
    "#display(df_Historic)\n",
    "\n",
    "####################################################################################################################\n",
    "##########################################         Creating |Historic|                    #########################\n",
    "###################################################################################################################\n",
    "# Check if \"CM-TurnoverReport\" sheet already exists and delete it if it does\n",
    "if 'Historic' in workbook.sheetnames:\n",
    "    del workbook['Historic']\n",
    "\n",
    "# Create new \"CM-TurnoverReport\" sheet\n",
    "sheet_Historic = workbook.create_sheet(title='Historic')\n",
    "\n",
    "# Write headers to Excel\n",
    "for c_idx, header in enumerate(df_Historic.columns, start=1):\n",
    "    sheet_Historic.cell(row=1, column=c_idx, value=header)\n",
    "\n",
    "# Write data to Excel\n",
    "for r_idx, row in enumerate(df_Historic.values, start=2):\n",
    "    for c_idx, value in enumerate(row, start=1):\n",
    "        sheet_Historic.cell(row=r_idx, column=c_idx, value=value)\n",
    "\n",
    "###############################################################################################################\n",
    "################################################ Formatting |Historic|  ########################################\n",
    "###############################################################################################################\n",
    "# Apply formatting to the header row\n",
    "header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')\n",
    "header_font = Font(color='FFFFFF', bold=True)\n",
    "header_alignment = Alignment(horizontal='left', vertical='center')\n",
    "header_border = Border(\n",
    "    top=Side(style='medium'),\n",
    "    bottom=Side(style='medium'),\n",
    "    left=Side(style='medium'),\n",
    "    right=Side(style='medium')\n",
    ")\n",
    "\n",
    "for cell in sheet_Historic[1]:\n",
    "    cell.fill = header_fill\n",
    "    cell.font = header_font\n",
    "    cell.alignment = header_alignment\n",
    "    cell.border = header_border\n",
    "\n",
    "# Add filters to the first row\n",
    "sheet_Historic.auto_filter.ref = sheet_Historic.dimensions\n",
    "\n",
    "##########################################################\n",
    "# Set column widths and text alignment for columns A to V\n",
    "#############################################################\n",
    "for column in sheet_Historic.iter_cols(min_col=1, max_col=21):\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "    \n",
    "    column_letter = column[0].column_letter\n",
    "    if column_letter in ['A', 'B', 'F', 'G', 'M', 'P', 'I', 'Q', 'R', 'U']:\n",
    "        sheet_Historic.column_dimensions[column_letter].width = 15\n",
    "    elif column_letter in ['H', 'L', 'N']:\n",
    "        sheet_Historic.column_dimensions[column_letter].width = 40\n",
    "    elif column_letter in ['C', 'D', 'N', 'S', 'T']:\n",
    "        sheet_Historic.column_dimensions[column_letter].width = 20\n",
    "    else:\n",
    "        sheet_Historic.column_dimensions[column_letter].width = 10\n",
    "\n",
    "    # Apply alignment and border to cells in the current column\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "# Apply borders for rows 1 and 2 in column V\n",
    "for row in range(1, 3):\n",
    "    sheet_Historic.cell(row=row, column=22).border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "# Set the width of column V and Y\n",
    "sheet_Historic.column_dimensions['V'].width = 15\n",
    "sheet_Historic.column_dimensions['Y'].width = 20\n",
    "\n",
    "# Set background color for cell V2 and V3 left align\n",
    "sheet_Historic.cell(row=2, column=22).fill = PatternFill(start_color='E2EFDA', end_color='E2EFDA', fill_type='solid')\n",
    "sheet_Historic.cell(row=2, column=22).alignment = Alignment(horizontal='left', vertical='center')\n",
    "\n",
    "############################################################################\n",
    "# Set column widths and text alignment for columns after V --> W to Z\n",
    "############################################################################\n",
    "for column in sheet_Historic.iter_cols(min_col=23, max_col=26):\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        \n",
    "        cell.border = Border(\n",
    "            top=Side(style='thin'),\n",
    "            right=Side(style='thin'),\n",
    "            bottom=Side(style='thin'),\n",
    "            left=Side(style='thin')\n",
    "        )\n",
    "        \n",
    "##################################################################################################\n",
    "# Color formating based on mapping from |CM_Priority| on df_Historic ['Production Status']\n",
    "##################################################################################################\n",
    "gray_fill = PatternFill(start_color='F2F2F2', end_color='DAEEF3', fill_type='solid')\n",
    "\n",
    "# Create a mapping of IDD Top Level values to their respective formatting\n",
    "formatting_map = {}\n",
    "completed_map = {}\n",
    "\n",
    "# Populate formatting_map based on 'Production Status'\n",
    "for row in sheet_Historic.iter_rows(min_row=2, max_row=sheet_Historic.max_row):\n",
    "    idd_value = row[2].value  # Column C (3rd column, zero-based index 2)\n",
    "    production_status = row[19].value  # Column T (20th column, zero-based index 19)\n",
    "\n",
    "    if production_status == 'Industrialized':\n",
    "        formatting_map[idd_value] = (green_fill,)\n",
    "    elif 'WIP' in str(production_status):\n",
    "        formatting_map[idd_value] = (blue_fill,)\n",
    "    elif production_status == 'Completed':\n",
    "        formatting_map[idd_value] = (gray_fill,)\n",
    "\n",
    "# Apply the formatting based on formatting_map\n",
    "start_col_index_zero_based = 0  # Column A (0-based index)\n",
    "end_col_index_zero_based = 20  # Column U (0-based index)\n",
    "\n",
    "for row in sheet_Historic.iter_rows(min_row=2, max_row=sheet_Historic.max_row):\n",
    "    idd_value = row[2].value  # Column C (zero-based index 2)\n",
    "\n",
    "    if idd_value in formatting_map:\n",
    "        fill = formatting_map[idd_value][0]\n",
    "        for col_index in range(start_col_index_zero_based, end_col_index_zero_based + 1):\n",
    "            if row[col_index].value is not None:  # Ensure cell is not empty\n",
    "                row[col_index].fill = fill\n",
    "\n",
    "############################\n",
    "# Higlight NC order in yellow for column J 'Order'\n",
    "#############################\n",
    "# Highlight NC orders in yellow for entire row when 'Order' contains 'NC'\n",
    "yellow_fill = PatternFill(start_color='FFFF99', end_color='FFFF99', fill_type='solid')\n",
    "\n",
    "# Iterate through rows starting from the second row (index 1 in Python)\n",
    "for row in range(2, sheet_Historic.max_row + 1):\n",
    "    order_value = sheet_Historic.cell(row=row, column=10).value  # Assuming 'Order' is in column J (10th column)\n",
    "    if order_value and 'NC' in str(order_value):  # Check if 'NC' is in the 'Order' cell\n",
    "        # Iterate through all cells in the current row (columns A to V)\n",
    "        for col in range(1, 22):  # Adjust max_col based on your actual number of columns\n",
    "            cell = sheet_Historic.cell(row=row, column=col)\n",
    "            cell.fill = yellow_fill\n",
    "\n",
    "#####################################################\n",
    "# Formating on DO/DX Order on ['Order'] \n",
    "####################################################\n",
    "# Iterate through rows and fill 'Order' column based on condition\n",
    "for row in range(2, sheet_Historic.max_row + 1):\n",
    "    order_cell = sheet_Historic.cell(row=row, column=9)  # Column J (1-based index)\n",
    "    if order_cell.value and str(order_cell.value).startswith('D'):\n",
    "        order_cell.fill = light_purple_fill\n",
    "\n",
    "################################################################\n",
    "# Rename the sheet\n",
    "sheet_Historic.title = 'CM-Historic'\n",
    "\n",
    "#### NOTE ON 07/31 -->> Gantt is still the workbook active here \n",
    "\n",
    "################################################\n",
    "# Save the updated workbook\n",
    "################################################################\n",
    "workbook.save(original_input)\n",
    "# Close the workbook\n",
    "workbook.close()\n",
    "\n",
    "print(f\"Historic added successfully as |CM-Historic| in {original_input}\")\n",
    "\n",
    "# -->> update 08/27\n",
    "#///////////////////////////////////////////\n",
    "#####################################################################################################\n",
    "## Update ['Shipped'] and ['Remain. crit. Qty']from df_Priority based on df_Historic & df_TurnoverReport \n",
    "###################################################################################################\n",
    "#//////////////////////////////////////////\n",
    "#loaad a copy of df_Priority \n",
    "df_Priority_updated = df_Priority.copy()\n",
    "\n",
    "#Update df_Priority_updated['Shipped'] based on df_Historic['Quantity'] and df_TurnoverReport['TurnoverReport row Qty'] by \n",
    "# 1. looking at the dates df_Historic['Invoice date'] & df_TurnoverReport['Invoice date'] \n",
    "# 2. looking at the order df_Historic['Order'] & df_TurnoverReport['Order'] \n",
    "# 3. Summing for a given Pty Indice df_Historic['Quantity'] & df_TurnoverReport['TurnoverReport row Qty'] ensuring to no compte several time the same line \n",
    "\n",
    "# Group and summarize the quantities by 'Pty Indice', 'Invoice date', 'Order', and 'Tracking#']\n",
    "# For df_Historic\n",
    "df_Historic_grouped = df_Historic.groupby(['Pty Indice', 'Invoice date', 'Order', 'Tracking#'])['Quantity'].sum().reset_index()\n",
    "\n",
    "# For df_TurnoverReport\n",
    "df_Turnover_grouped = df_TurnoverReport.groupby(['Pty Indice', 'Invoice date', 'Order', 'Tracking#'])['TurnoverReport row Qty'].sum().reset_index()\n",
    "\n",
    "# Filter out rows where 'Order' contains 'NC'\n",
    "df_Historic_grouped = df_Historic_grouped[~df_Historic_grouped['Order'].str.contains('NC', na=False)]\n",
    "df_Turnover_grouped = df_Turnover_grouped[~df_Turnover_grouped['Order'].str.contains('NC', na=False)]\n",
    "\n",
    "# Concatenate the two dataframes\n",
    "combined_df = pd.concat([\n",
    "    df_Historic_grouped.rename(columns={'Quantity': 'Shipped'}),\n",
    "    df_Turnover_grouped.rename(columns={'TurnoverReport row Qty': 'Shipped'})\n",
    "])\n",
    "\n",
    "#Update on 08/29 \n",
    "# Replace the string 'nan' with an empty string\n",
    "''' SAVED 09/24 to avoid warning\n",
    "combined_df['Tracking#'].replace('nan', '', inplace=True)\n",
    "# Replace empty strings and None with NaN, then fill NaN with 'N/A'\n",
    "combined_df['Tracking#'].replace([\"\", None, np.nan], \"N/A\", inplace=True)\n",
    "'''\n",
    "combined_df['Tracking#'] = combined_df['Tracking#'].replace('nan', '')\n",
    "combined_df['Tracking#'] = combined_df['Tracking#'].replace([\"\", None, np.nan], \"N/A\")\n",
    "\n",
    "\n",
    "# Drop duplicates to avoid double counting\n",
    "combined_df = combined_df.drop_duplicates(subset=['Pty Indice', 'Invoice date', 'Order', 'Tracking#', 'Shipped'])\n",
    "\n",
    "#print('combined_df filtered on P5')\n",
    "# Filter the DataFrame\n",
    "#filtered_combined_df = combined_df[combined_df['Pty Indice'] == 'P5']\n",
    "#display(filtered_combined_df) \n",
    "\n",
    "# Convert 'Shipped' to integers\n",
    "combined_df['Shipped'] = combined_df['Shipped'].astype(int)\n",
    "\n",
    "# Group by 'Pty Indice' to sum 'Shipped' values only (NOT across all combinations of 'Invoice date', 'Order', and 'Tracking#')\n",
    "df_Priority_updated = combined_df.groupby('Pty Indice', as_index=False)['Shipped'].sum()\n",
    "\n",
    "# Convert 'Shipped' to integer\n",
    "df_Priority_updated['Shipped'] = df_Priority_updated['Shipped'].astype(int)\n",
    "\n",
    "#print('df_Priority_updated')\n",
    "#display(df_Priority_updated)\n",
    "\n",
    "# 08/23\n",
    "######/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n",
    "###########################################################################################################################################################\n",
    "#####  ------------->>> Modifiction of |CM-Priority|  <<<<-----------------------\n",
    "##### Mapping of df_Priority_updated['Shipped'] into Excel tab |CM-Priority| only if df_Priority_updated['Shipped'] > existing value df_Priority['Shipped'] \n",
    "###########################################################################################################################################################\n",
    "######/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n",
    "### Updating the Excel sheet ['Shipped'] and ['Remain. crit. Qty']\n",
    "######################################################################\n",
    "# Load workbook and sheet CM-Priority \n",
    "sheet_Priority = workbook['CM-Priority']\n",
    "\n",
    "# load headers\n",
    "header = list(df_Priority.columns)  # Convert Index to list\n",
    "\n",
    "#Updated 08/29\n",
    "# Iterate through the rows in df_Priority_updated\n",
    "for index, row in df_Priority_updated.iterrows():\n",
    "    pty_indice = row['Pty Indice']\n",
    "    new_shipped = row['Shipped']\n",
    "\n",
    "    # Find the corresponding row in the Excel sheet\n",
    "    for excel_row in sheet_Priority.iter_rows(min_row=2, max_row=sheet_Priority.max_row, values_only=False):\n",
    "        if excel_row[header.index('Pty Indice')].value == pty_indice:\n",
    "            # Update the 'Shipped' value\n",
    "            excel_row[header.index('Shipped')].value = new_shipped\n",
    "            \n",
    "            # Calculate 'Remain. Crit. Qty'\n",
    "            crit_qty = excel_row[header.index('Critical Qty')].value\n",
    "            \n",
    "            # Ensure new_shipped and crit_qty are treated as integers before subtraction\n",
    "            remain_crit_qty = max(int(crit_qty) - int(new_shipped), 0)\n",
    "\n",
    "            # Explicitly set the value as an integer\n",
    "            remain_crit_qty_cell = excel_row[header.index('Remain. crit. Qty')]\n",
    "            remain_crit_qty_cell.value = remain_crit_qty\n",
    "            remain_crit_qty_cell.number_format = '0'  # Format the cell to show integers only\n",
    "\n",
    "            break\n",
    "\n",
    "########################################################################\n",
    "#### Apply formating on CM-Priority after modifying the sheet \n",
    "##########################################################################\n",
    "# Get the maximum row number\n",
    "max_row = sheet_Priority.max_row\n",
    "\n",
    "# Apply formatting to the header row\n",
    "header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')\n",
    "header_font = Font(color='FFFFFF', bold=True)\n",
    "header_alignment = Alignment(horizontal='left', vertical='center')\n",
    "header_border = Border(\n",
    "    top=Side(style='medium'),\n",
    "    bottom=Side(style='medium'),\n",
    "    left=Side(style='medium'),\n",
    "    right=Side(style='medium')\n",
    ")\n",
    "\n",
    "for cell in sheet_Priority[1]:\n",
    "    cell.fill = header_fill\n",
    "    cell.font = header_font\n",
    "    cell.alignment = header_alignment\n",
    "    cell.border = header_border\n",
    "\n",
    "# Add filters to the first row\n",
    "sheet_Priority.auto_filter.ref = sheet_Priority.dimensions\n",
    "\n",
    "############################################################\n",
    "# Set column widths and text alignment for columns A to T\n",
    "##############################################################\n",
    "for column in sheet_Priority.iter_cols(min_col=1, max_col=20):\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "    \n",
    "    column_letter = column[0].column_letter\n",
    "    if column_letter in ['B', 'C', 'F', 'G', 'H', 'I', 'J','K', 'L', 'M', 'N', 'R', 'T']:\n",
    "        sheet_Priority.column_dimensions[column_letter].width = 20\n",
    "    elif column_letter in ['A', 'E']:\n",
    "        sheet_Priority.column_dimensions[column_letter].width = 15\n",
    "    elif column_letter in ['D', 'Q', 'O', 'P']:\n",
    "        sheet_Priority.column_dimensions[column_letter].width = 35\n",
    "    elif column_letter in ['Q']:\n",
    "        sheet_Priority.column_dimensions[column_letter].width = 50\n",
    "    else:\n",
    "        sheet_Priority.column_dimensions[column_letter].width = 10\n",
    "\n",
    "    # Apply alignment and border to cells in the current column\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "############################################################\n",
    "# Set column widths and text alignment for columns V to Z\n",
    "##############################################################\n",
    "for column in sheet_Priority.iter_cols(min_col=22, max_col=26):\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "    \n",
    "    column_letter = column[0].column_letter\n",
    "    if column_letter in ['V', 'W', 'X', 'Y', 'Z']:\n",
    "        sheet_Priority.column_dimensions[column_letter].width = 20\n",
    "    else:\n",
    "        sheet_Priority.column_dimensions[column_letter].width = 10\n",
    "\n",
    "    # Apply alignment and border to cells in the current column\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "##############################################################\n",
    "# Set column width and text alignment for column U from row 3\n",
    "#################################################################\n",
    "for cell in sheet_Priority.iter_rows(min_row=3, min_col=21, max_col=21):\n",
    "    cell[0].alignment = Alignment(horizontal='left', vertical='center')\n",
    "\n",
    "# Set the width of column U to 15mm\n",
    "column_letter = get_column_letter(21)  # Column T is the 21th column\n",
    "sheet_Priority.column_dimensions[column_letter].width = 15\n",
    "\n",
    "# Apply borders for rows 1 and 2 in column U\n",
    "for row in range(1, 3):\n",
    "    sheet_Priority.cell(row=row, column=21).border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "# Set background color for cell U2 and U3 left align\n",
    "sheet_Priority.cell(row=2, column=21).fill = PatternFill(start_color='E2EFDA', end_color='E2EFDA', fill_type='solid')\n",
    "\n",
    "# Format cell U2 as a short date\n",
    "sheet_Priority.cell(row=2, column=21).number_format = 'mm-dd-yyyy'\n",
    "\n",
    "# Set short date format for columns K, L, N and M starting from row 2 up to max_row\n",
    "for column_letter in ['L', 'M', 'N']:\n",
    "    for row in range(2, sheet_Priority.max_row + 1):\n",
    "        cell = sheet_Priority[f'{column_letter}{row}']\n",
    "        cell.number_format = 'mm-dd-yyyy'\n",
    "\n",
    "###############################\n",
    "#### Industrialized and WIP PN\n",
    "###############################\n",
    "# Define the fill for the conditional formatting\n",
    "green_fill = PatternFill(start_color='D8E4BC', end_color='D8E4BC', fill_type='solid')\n",
    "blue_fill = PatternFill(start_color='DAEEF3', end_color='DAEEF3', fill_type='solid')\n",
    "\n",
    "# Define the font color\n",
    "font_color = Font(color='000000')  # Black font color\n",
    "\n",
    "# Iterate over each row in column O\n",
    "for row in range(2, max_row + 1):  # Start from row 2 since row 1 contains headers\n",
    "    # Get the value in the current cell in column O\n",
    "    value_in_o = sheet_Priority.cell(row=row, column=15).value  # Column O is the 15th column (1-based index)\n",
    "    \n",
    "    # Determine the fill color based on the value in column O\n",
    "    if value_in_o == 'Industrialized':\n",
    "        fill_color = green_fill\n",
    "    elif 'WIP' in str(value_in_o):\n",
    "        fill_color = blue_fill\n",
    "    else:\n",
    "        fill_color = None\n",
    "    \n",
    "    # Apply the fill and font color to columns A to T and V to Z\n",
    "    if fill_color:\n",
    "        for col in list(range(1, 21)) + list(range(22, 27)):  # Columns A-T (1-20) and V-Z (22-26)\n",
    "            cell = sheet_Priority.cell(row=row, column=col)\n",
    "            cell.fill = fill_color\n",
    "            cell.font = font_color\n",
    "      \n",
    "###################################\n",
    "#### SO Modified red if pushed-out to 12/31/2026 or 12/24/2026\n",
    "##################################\n",
    "# Define the font color for dark red\n",
    "dark_red_font = Font(color='C00000')\n",
    "\n",
    "# Define the fill color for light yellow\n",
    "light_yellow_fill = PatternFill(start_color='FFFFCC', end_color='FFFFCC', fill_type='solid')\n",
    "\n",
    "# Get the maximum row number in column M (SO Modified)\n",
    "max_row_M = sheet_Priority.max_row\n",
    "\n",
    "# Define the target dates as strings\n",
    "target_dates = ['12/31/2026', '12/24/2026']\n",
    "\n",
    "# Iterate over each row in column M\n",
    "max_row_M = sheet_Priority.max_row\n",
    "for row in range(2, max_row_M + 1):  # Start from row 2 since row 1 contains headers\n",
    "    # Get the value in the current cell in column M\n",
    "    value_in_m = sheet_Priority.cell(row=row, column=13).value  # Column M is the 13th column\n",
    "    \n",
    "    # Check if the value in column M matches the target dates\n",
    "    if value_in_m in target_dates:\n",
    "        # Apply the light yellow fill and dark red font color to the cell\n",
    "        cell = sheet_Priority.cell(row=row, column=13)\n",
    "        cell.fill = light_yellow_fill\n",
    "        cell.font = dark_red_font\n",
    "\n",
    "############################################################################################\n",
    "#### Redlist - If |Production Status| contain something else then a number or 'TBD' apply red fill\n",
    "############################################################################################\n",
    "# Define the fill for the conditional formatting\n",
    "red_fill = PatternFill(start_color='F2DCDB', end_color='F2DCDB', fill_type='solid')\n",
    "border_color = '000000'  # Black color for the border\n",
    "\n",
    "# Define thin black border style for top and bottom sides\n",
    "thin_black_side = Side(style='thin', color=border_color)\n",
    "\n",
    "# Define diagonal cross-border style (grey color)\n",
    "border_grey = Border(\n",
    "    left=Side(border_style=None),\n",
    "    right=Side(border_style=None),\n",
    "    top=Side(border_style=None),\n",
    "    bottom=Side(border_style=None),\n",
    "    diagonal=Side(border_style='thin', color='D9D9D9'),\n",
    "    diagonalDown=True,\n",
    "    diagonalUp=True\n",
    ")\n",
    "\n",
    "# Iterate over each row\n",
    "for row in range(2, max_row + 1):  # Start from row 2 since row 1 contains headers\n",
    "    # Get the value in column O\n",
    "    value_in_O = sheet_Priority.cell(row=row, column=15).value  # Column O is the 15th column (1-based index)\n",
    "\n",
    "    # Check if the value in column O contains 'Transfer' or 'Canceled'\n",
    "    if value_in_O and ('transferred' in str(value_in_O).lower() or 'canceled' in str(value_in_O).lower()):\n",
    "        # Apply red fill and border styles to columns A to T and V to Z\n",
    "        for col in list(range(1, 21)) + list(range(22, 27)):  # Columns A-T (1-20) and V-Z (22-26)\n",
    "            cell = sheet_Priority.cell(row=row, column=col)\n",
    "            cell.fill = red_fill\n",
    "\n",
    "            # Apply border styles\n",
    "            if col == 1 or col == sheet_Priority.max_column:\n",
    "                # Apply black border to leftmost and rightmost columns\n",
    "                cell.border = Border(\n",
    "                    left=thin_black_side if col == 1 else None,\n",
    "                    right=thin_black_side if col == sheet_Priority.max_column else None,\n",
    "                    top=thin_black_side,\n",
    "                    bottom=thin_black_side,\n",
    "                    diagonal=border_grey.diagonal,\n",
    "                    diagonalDown=border_grey.diagonalDown,\n",
    "                    diagonalUp=border_grey.diagonalUp\n",
    "                )\n",
    "            else:\n",
    "                # Apply grey diagonal cross-border to other columns\n",
    "                cell.border = border_grey\n",
    "\n",
    "###########################\n",
    "#### Completed PN\n",
    "###########################\n",
    "# Define the fill for the conditional formatting\n",
    "grey_fill = PatternFill(start_color='F2F2F2', end_color='F2F2F2', fill_type='solid')\n",
    "\n",
    "# Define the font color\n",
    "grey_font_color = Font(color='BFBFBF')\n",
    "\n",
    "# Iterate over each row in column I\n",
    "for row in range(2, max_row + 1):  # Start from row 2 since row 1 contains headers\n",
    "    # Get the value in the current cell in column I\n",
    "    value_in_i = sheet_Priority.cell(row=row, column=9).value  # Column I is the 9th column (1-based index)\n",
    "    \n",
    "    # Check if the value in column I is 'Completed'\n",
    "    if value_in_i == 'Completed':\n",
    "        # Apply the grey fill and font color to columns A-T and V-Z\n",
    "        for col in list(range(1, 21)) + list(range(22, 27)):  # Columns A-T (1-20) and V-Z (22-26)\n",
    "            cell = sheet_Priority.cell(row=row, column=col)\n",
    "            cell.fill = grey_fill\n",
    "            cell.font = grey_font_color\n",
    "\n",
    "###########################\n",
    "#### 'Pty Indice', 'Qty clear to build' & 'Production status' Bold and font color formatting\n",
    "###########################\n",
    "# Define the font for bold text\n",
    "bold_font = Font(bold=True)\n",
    "\n",
    "# Define font colors\n",
    "font_color_industrialized = \"008000\"  # Dark Green\n",
    "font_color_completed = \"808080\"  # Grey\n",
    "font_color_wip = \"1F497D\"  # Dark Blue\n",
    "font_color_transfer = \"C00000\"  # Dark Red\n",
    "\n",
    "# Iterate over each row\n",
    "for row in range(2, max_row + 1):  # Assuming max_row is already defined\n",
    "    # Get the cells in columns E, F, and O for the current row\n",
    "    cell_E = sheet_Priority.cell(row=row, column=5)  # Column E is the 5th column\n",
    "    cell_F = sheet_Priority.cell(row=row, column=6)  # Column F is the 6th column\n",
    "    cell_O = sheet_Priority.cell(row=row, column=15)  # Column O is the 15th column\n",
    "    \n",
    "    # Set the font to bold for cells in columns E and O\n",
    "    cell_E.font = bold_font\n",
    "    cell_O.font = bold_font\n",
    "    \n",
    "    # Convert cell_O.value to a string to handle NoneType values\n",
    "    cell_O_value_str = str(cell_O.value)\n",
    "    \n",
    "    # Set the font color for column E based on the value in column O\n",
    "    if cell_O_value_str == \"Industrialized\":\n",
    "        cell_E.font = Font(color=font_color_industrialized, bold=True)\n",
    "    elif cell_O_value_str == \"Completed\":\n",
    "        cell_E.font = Font(color=font_color_completed, bold=True)\n",
    "    elif \"WIP\" in cell_O_value_str:  # Checking if \"WIP\" is contained in the value\n",
    "        cell_E.font = Font(color=font_color_wip, bold=True)\n",
    "    elif \"transferred\" in cell_O_value_str or \"Canceled\" in cell_O_value_str:\n",
    "        cell_E.font = Font(color=font_color_transfer, bold=True)\n",
    "    \n",
    "    # Set the font color for column O to match column E\n",
    "    cell_O.font = Font(color=cell_E.font.color, bold=True)\n",
    "    \n",
    "###########################\n",
    "#### Applied thick border to |Pty Indice|Clear to build| ... |Production Status|\n",
    "###########################\n",
    "# Define thick border style for left and right sides\n",
    "thick_side = Side(style='thick')\n",
    "\n",
    "# Define thin black border style for top and bottom sides\n",
    "thin_black_side = Side(style='thin', color='000000')\n",
    "\n",
    "# Define the column indices for the range\n",
    "column_indices = [5, 6, 15]  # Columns E, F, and O\n",
    "\n",
    "# Iterate over each row and apply the defined border style to the specified columns\n",
    "for row in range(2, max_row + 1):  # Assuming max_row is already defined\n",
    "    for col_index in column_indices:\n",
    "        cell = sheet_Priority.cell(row=row, column=col_index)\n",
    "        cell.border = Border(\n",
    "            left=thick_side,\n",
    "            right=thick_side,\n",
    "            top=thin_black_side,\n",
    "            bottom=thin_black_side\n",
    "        )\n",
    "\n",
    "#####################################################################\n",
    "### Save the changes to the Excel file \n",
    "#####################################################################\n",
    "# Save and close workbook\n",
    "workbook.save(original_input)\n",
    "workbook.close()\n",
    "\n",
    "#***************************************************************************************************************************\n",
    "############################################################################################################################\n",
    "##  ##        ############  ###########    #############  ##############             \n",
    "##  ##        ##        ##  ##        ##   ##         ##  ##           ##\n",
    "##  ##        ##        ##  ##        ##   ##         ##  ##           ##\n",
    "##  ##        ############  ###########    ##         ##  ##############\n",
    "##  ##        ##        ##  ##        ##   ##         ##  ##     ###\n",
    "##  ##        ##        ##  ##        ##   ##         ##  ##       ###\n",
    "##  ########  ##        ##  ###########    #############  ##          ###\n",
    "############################################################################################################################\n",
    "#***************************************************************************************************************************\n",
    "#***************************************************************************************************************************\n",
    "# Define date and path\n",
    "input_LaborReport_formatted = os.path.join(Path, f'CM_IDD_LaborReport_Historic_Formatted.xlsx') \n",
    "\n",
    "##############################################################################################################################\n",
    "# Load workbook\n",
    "##############################################################################################################################\n",
    "# Load the existing output workbook\n",
    "try:\n",
    "    workbook = load_workbook(original_input)\n",
    "    #print(\"Output workbook loaded successfully.\")\n",
    "except FileNotFoundError as e:\n",
    "    print(f\"Output workbook not found: {e}\")\n",
    "    exit()\n",
    "\n",
    "# Print the sheet names\n",
    "print(\"Tabs in the workbook:\")\n",
    "print(workbook.sheetnames)\n",
    "print('Processing |CM-LaborReport| ...')\n",
    "\n",
    "# Load the Excel files into pandas DataFrames\n",
    "try:\n",
    "    df_LaborReport = pd.read_excel(input_LaborReport_formatted, sheet_name=0)\n",
    "    #print(\"Pending Report files loaded successfully.\")\n",
    "except FileNotFoundError as e:\n",
    "    print(f\"Input PendingReport file not found: {e}\")\n",
    "    exit()\n",
    "\n",
    "######################################################\n",
    "# Create column 'Actual vs Expected (%)'\n",
    "########################################################\n",
    "# Convert ['Actual Time (hours)'] will set 'Inaccurate data' to NaN\n",
    "df_LaborReport['Actual Time (hours)'] = pd.to_numeric(df_LaborReport['Actual Time (hours)'], errors='coerce')\n",
    "\n",
    "#Drop NaN values \n",
    "df_LaborReport.dropna(subset=['Actual Time (hours)', 'Expected Time (hours)'], inplace=True)\n",
    "\n",
    "# Calculation \n",
    "df_LaborReport['Actual vs Expected (%)'] = (df_LaborReport['Actual Time (hours)'] / df_LaborReport['Expected Time (hours)']) * 100\n",
    "df_LaborReport['Actual vs Expected (%)'] = df_LaborReport['Actual vs Expected (%)'].round(2)\n",
    "\n",
    "# Convert to string and append '%' symbol\n",
    "df_LaborReport['Actual vs Expected (%)'] = df_LaborReport['Actual vs Expected (%)'].astype(str) + '%'\n",
    "\n",
    "####################################################################################################################\n",
    "##########################################         Creating |CM-LaborReport|                    ####################\n",
    "###################################################################################################################\n",
    "# Check if \"CM-TurnoverReport\" sheet already exists and delete it if it does\n",
    "if 'CM-LaborReport' in workbook.sheetnames:\n",
    "    del workbook['CM-LaborReport']\n",
    "\n",
    "# Create new \"CM-LaborReport\" sheet\n",
    "sheet_LaborReport = workbook.create_sheet(title='CM-LaborReport')\n",
    "\n",
    "# Write headers to Excel\n",
    "for c_idx, header in enumerate(df_LaborReport.columns, start=1):\n",
    "    sheet_LaborReport.cell(row=1, column=c_idx, value=header)\n",
    "\n",
    "# Write data to Excel\n",
    "for r_idx, row in enumerate(df_LaborReport.values, start=2):\n",
    "    for c_idx, value in enumerate(row, start=1):\n",
    "        sheet_LaborReport.cell(row=r_idx, column=c_idx, value=value)\n",
    "\n",
    "###############################################################################################################\n",
    "################################################ Formatting |CM-LaborReport|  #################################\n",
    "###############################################################################################################\n",
    "# Apply formatting to the header row\n",
    "header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')\n",
    "header_font = Font(color='FFFFFF', bold=True)\n",
    "header_alignment = Alignment(horizontal='left', vertical='center')\n",
    "header_border = Border(\n",
    "    top=Side(style='medium'),\n",
    "    bottom=Side(style='medium'),\n",
    "    left=Side(style='medium'),\n",
    "    right=Side(style='medium')\n",
    ")\n",
    "\n",
    "for cell in sheet_LaborReport[1]:\n",
    "    cell.fill = header_fill\n",
    "    cell.font = header_font\n",
    "    cell.alignment = header_alignment\n",
    "    cell.border = header_border\n",
    "\n",
    "# Add filters to the first row\n",
    "sheet_LaborReport.auto_filter.ref = sheet_LaborReport.dimensions\n",
    "\n",
    "# Set column widths and text alignment for columns A to U\n",
    "for column in sheet_LaborReport.iter_cols(min_col=1, max_col=20):\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "    \n",
    "    column_letter = column[0].column_letter\n",
    "    if column_letter in ['A', 'B', 'F']:\n",
    "        sheet_LaborReport.column_dimensions[column_letter].width = 15\n",
    "    elif column_letter in ['D']:\n",
    "        sheet_LaborReport.column_dimensions[column_letter].width = 40\n",
    "    elif column_letter in ['C', 'I', 'J', 'K']:\n",
    "        sheet_LaborReport.column_dimensions[column_letter].width = 20\n",
    "    else:\n",
    "        sheet_LaborReport.column_dimensions[column_letter].width = 10\n",
    "\n",
    "    # Apply alignment and border to cells in the current column\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "    \n",
    "# Apply borders for rows 1 and 2 in column U\n",
    "for row in range(1, 3):\n",
    "    sheet_LaborReport.cell(row=row, column=21).border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "# Set background color for cell U2 and U3 left align\n",
    "sheet_LaborReport.cell(row=2, column=21).fill = PatternFill(start_color='E2EFDA', end_color='E2EFDA', fill_type='solid')\n",
    "sheet_LaborReport.cell(row=2, column=21).alignment = Alignment(horizontal='left', vertical='center')\n",
    "    \n",
    "########################################################\n",
    "# Higlight NC order in yellow for column F 'WO NR'\n",
    "##########################################################\n",
    "#Update 08/26\n",
    "# Highlight NC orders in yellow for entire row when 'Order' contains 'NC'\n",
    "yellow_fill = PatternFill(start_color='FFFF99', end_color='FFFF99', fill_type='solid')\n",
    "\n",
    "# Iterate through rows starting from the second row (index 1 in Python)\n",
    "for row in range(2, sheet_LaborReport.max_row + 1):\n",
    "    order_value = sheet_LaborReport.cell(row=row, column=6).value  # Assuming 'Order' is in column F (6th column)\n",
    "    if order_value and 'NC' in str(order_value).upper():  # Convert to uppercase and check if 'NC' is in the 'Order' cell\n",
    "        # Iterate through all cells in the current row (columns A to T)\n",
    "        for col in range(1, 21):  # Adjust max_col based on your actual number of columns\n",
    "            cell = sheet_LaborReport.cell(row=row, column=col)\n",
    "            cell.fill = yellow_fill\n",
    "\n",
    "###############################################\n",
    "# Coloring column 'Level' \n",
    "################################################\n",
    "# Custom conditional formatting for column J 'Level' (Assuming data starts from row 2)\n",
    "min_row = 2\n",
    "max_row = sheet_LaborReport.max_row\n",
    "col_E = 5\n",
    "\n",
    "for row in range(min_row, max_row + 1):\n",
    "    cell_value = sheet_LaborReport.cell(row=row, column=col_E).value\n",
    "\n",
    "    # Define default fill color in case cell_value is not in expected range\n",
    "    fill_color = None\n",
    "    \n",
    "    if cell_value is not None:\n",
    "        if cell_value == 0:\n",
    "            fill_color = '63BE7B'  # Green\n",
    "        elif cell_value == 1:\n",
    "            fill_color = 'A2C075'  # Lighter Green\n",
    "        elif cell_value == 2:\n",
    "            fill_color = 'FFEB84'  # Yellow\n",
    "        elif cell_value == 3:\n",
    "            fill_color = 'FFD166'  # Orange\n",
    "        elif cell_value == 4:\n",
    "            fill_color = 'F88E5B'  # Darker Orange\n",
    "        elif cell_value == 5:\n",
    "            fill_color = 'F8696B'  # Red\n",
    "        elif cell_value == 6:\n",
    "            fill_color = '8B0000'  # Darker Red\n",
    "        \n",
    "       # Create PatternFill object only if fill_color is defined\n",
    "        if fill_color:\n",
    "            fill = PatternFill(start_color=fill_color, end_color=fill_color, fill_type='solid')\n",
    "            sheet_LaborReport.cell(row=row, column=col_E).fill = fill\n",
    "\n",
    "###########################################################\n",
    "# Set column widths and text alignment for columns V to AB\n",
    "############################################################\n",
    "# set width of U\n",
    "sheet_LaborReport.column_dimensions['U'].width = 15\n",
    "\n",
    "# Set column widths and text alignment for columns V to AA\n",
    "for column in sheet_LaborReport.iter_cols(min_col=22, max_col=28):\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "    \n",
    "    column_letter = column[0].column_letter\n",
    "    if column_letter in ['U', 'V']:\n",
    "        sheet_LaborReport.column_dimensions[column_letter].width = 15\n",
    "    elif column_letter in ['Y']:\n",
    "        sheet_LaborReport.column_dimensions[column_letter].width = 40\n",
    "    elif column_letter in ['W', 'X', 'Z', 'AA', 'AB']:\n",
    "        sheet_LaborReport.column_dimensions[column_letter].width = 20\n",
    "    else:\n",
    "        sheet_LaborReport.column_dimensions[column_letter].width = 10\n",
    "\n",
    "    # Apply alignment and border to cells in the current column\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "\n",
    "#########################################################################################################################\n",
    "# Higlight in orange or bleu row related to Prototype and FAI unit --> Those row are filtered-out from the the 'Avg Actual Time'\n",
    "# Higlight in gray row related to 'Phantom' part -->  row where ['Phantom'] = 'Oui'\n",
    "# If sheet_LaborReport['Remarks'] contain 'FA' or 'PROTO' higlitgh row in orange #FCE4D6\n",
    "#########################################################################################################################\n",
    "# Updated 08/28\n",
    "# Define the fill for highlighting\n",
    "orange_fill = PatternFill(start_color='FCE4D6', end_color='FCE4D6', fill_type='solid')\n",
    "blue_fill = PatternFill(start_color='ADD8E6', end_color='ADD8E6', fill_type='solid')\n",
    "gray_fill = PatternFill(start_color='D3D3D3', end_color='D3D3D3', fill_type='solid')\n",
    "\n",
    "# Iterate through rows starting from the second row\n",
    "for row in range(2, sheet_LaborReport.max_row + 1):\n",
    "    remarks_value = sheet_LaborReport.cell(row=row, column=25).value  # Assuming 'Remarks' is in column Y (25th column)\n",
    "    phantom_value = sheet_LaborReport.cell(row=row, column=13).value  # Assuming 'Phamtom' is in column M (13th column)\n",
    "\n",
    "    if phantom_value and phantom_value.lower() == 'oui':\n",
    "        fill = gray_fill\n",
    "    elif remarks_value:\n",
    "        remarks_value_lower = str(remarks_value).lower()\n",
    "\n",
    "        if 'proto' in remarks_value_lower:\n",
    "            fill = orange_fill\n",
    "        elif 'fa' in remarks_value_lower:\n",
    "            fill = blue_fill\n",
    "        else:\n",
    "            continue  # Skip rows without \"PROTO\" or \"FA\"\n",
    "\n",
    "    else:\n",
    "        continue  # Skip rows with no relevant remarks or phantom status\n",
    "\n",
    "    # Apply the fill color to all cells in the current row (columns A to T), except column E\n",
    "    for col in range(1, 21):  # Adjust max_col based on your actual number of columns\n",
    "        if col != 5:  # Skip column E (5th column)\n",
    "            cell = sheet_LaborReport.cell(row=row, column=col)\n",
    "            cell.fill = fill\n",
    "\n",
    "################################################\n",
    "# Save the updated workbook\n",
    "################################################\n",
    "workbook.save(original_input)\n",
    "# Close the workbook\n",
    "workbook.close()\n",
    "\n",
    "print(f\"LaborReport added successfully as |CM-LaborReport| in {original_input}\")\n",
    "\n",
    "\n",
    "#New 08/21\n",
    "#***************************************************************************************************************************\n",
    "############################################################################################################################\n",
    "##  ####       ####       ############             \n",
    "##  ## ##    ##  ##       ##        ##  \n",
    "##  ##  ## ##    ##       ##        ##  \n",
    "##  ##    #      ##       ############  \n",
    "##  ##           ##       ##        ##  \n",
    "##  ##           ##       ##        ##  \n",
    "##  ##           ##Ake    ##        ## Rchitecture\n",
    "############################################################################################################################\n",
    "#***************************************************************************************************************************\n",
    "#***************************************************************************************************************************\n",
    "# Print the sheet names\n",
    "print(\"Tabs in the workbook:\")\n",
    "print(workbook.sheetnames)\n",
    "print('Processing |CM-MakeArchitecutre| ...')\n",
    "\n",
    "#update 08/28 to include case incensitive \n",
    "# Create df_Make_architure based on |CM-BOM| datyafram df_CM_BOM where M/P/F = 'M'\n",
    "df_Make_architure = df_CM_BOM[df_CM_BOM['M/P/F'].str.upper() == 'M']\n",
    "\n",
    "###########################################################################################################################\n",
    "# Create 'Make Architecture' from |CM-BOM| with the Avrage Expected and Average Actual time per unit from |CM-LaborReport|\n",
    "###########################################################################################################################\n",
    "# Combine the row to keep a single row for a conbinaison of 'Pty Indice' and 'IDD Component' and return the 'Average count WO' \n",
    "# sum the Actual and Expected time and create [Actual Time (unit)] and [Expected Time (unit)] \n",
    "# Filter-out row where 'Remarks' contain either 'FAI' or 'PROTO' when calculating the Average times to reduce bias\n",
    "#############################################################################################################################\n",
    "#Update 08/28 \n",
    "# Filter out rows where 'Remarks' contain 'PROTO' (case insensitive) - Sometimes a lot of WO are tag FA without a reason, so it might be better to keep the 'FA'\n",
    "# and rows where 'WO#' contain 'NC' (case insensitive)\n",
    "# and rows where 'Phantom' is 'Oui'\n",
    "df_LaborReport_filtered = df_LaborReport[\n",
    "    ~df_LaborReport['Remarks'].fillna('').str.contains('PROTO', case=False) &  # Filter out 'PROTO'\n",
    "    ~df_LaborReport['WO#'].fillna('').str.contains('NC', case=False) &         # Filter out 'NC'\n",
    "    ~(df_LaborReport['Phantom'].fillna('').str.lower() == 'oui')               # Filter out 'Phantom' = 'Oui'\n",
    "]\n",
    "\n",
    "# Update 09/20 \n",
    "# Filter out rows where 'Actual Time (unit)' & 'Expected Time (unit)' are 0 - Update 09/20 to not filter where 'Expected Time (unit)'  = 0\n",
    "# df_LaborReport_filtered = df_LaborReport_filtered[(df_LaborReport_filtered['Actual Time (unit)'] > 0) &(df_LaborReport_filtered['Expected Time (unit)'] > 0)]\n",
    "df_LaborReport_filtered = df_LaborReport_filtered[(df_LaborReport_filtered['Actual Time (unit)'] > 0)]\n",
    "\n",
    "# Only keep components where 'ACTUAL_RUN_TIME' > 1 hourQty_Count\n",
    "#df_LaborReport_filtered = df_LaborReport_filtered[df_LaborReport_filtered['ACTUAL_RUN_TIME'] > 1]\n",
    "\n",
    "#############################################################################################################\n",
    "# New 09/11 - Erase 'ACTUAL_RUN_TIME' (set to NaN) for abberent values in order to get realistic AVG Actual Time\n",
    "#############################################################################################################\n",
    "#Define a function to remove aberrant values based on IQR \n",
    "# Identify aberrant values: This could be based on statistical measures like z-scores, interquartile range (IQR), or other criteria.\n",
    "# Define a threshold for the minimum number of values required\n",
    "MIN_VALUES_REQUIRED = 6\n",
    "\n",
    "# Define a function to remove aberrant values based on IQR\n",
    "def remove_aberrant_values(df, column_name):\n",
    "    Q1 = df[column_name].quantile(0.25)\n",
    "    Q3 = df[column_name].quantile(0.75)\n",
    "    IQR = Q3 - Q1\n",
    "\n",
    "    lower_bound = Q1 # set as 25% quantille \n",
    "    upper_bound = Q3 + 1.5 * IQR\n",
    "\n",
    "    return df[(df[column_name] >= lower_bound) & (df[column_name] <= upper_bound)]\n",
    "\n",
    "'''\n",
    "# Function to process each group\n",
    "def process_group(group):\n",
    "    if len(group) >= MIN_VALUES_REQUIRED:\n",
    "        return remove_aberrant_values(group, 'ACTUAL_RUN_TIME')\n",
    "    else:\n",
    "        return group\n",
    "'''\n",
    "\n",
    "# Function to process each group -> Function to be applied to 'Actual Time (unit)' not 'ACTUAL_RUN_TIME'\n",
    "def process_group(group):\n",
    "    if len(group) >= MIN_VALUES_REQUIRED:\n",
    "        return remove_aberrant_values(group, 'Actual Time (unit)')\n",
    "    else:\n",
    "        return group\n",
    "        \n",
    "# Group by 'Pty Indice', 'IDD Component', and 'Level', and apply the function\n",
    "# Group by the desired columns\n",
    "grouped = df_LaborReport_filtered.groupby(['Pty Indice', 'IDD Component', 'Level'])\n",
    "\n",
    "# Apply the function to each group to get  df_filtered 'Actual Time (unit)' with aberrant values removed\n",
    "# df_filtered = grouped.apply(process_group).reset_index(drop=True) - Replaced 09/24 to avoid warning\n",
    "df_filtered = grouped.apply(process_group).reset_index(drop=True).copy()\n",
    "\n",
    "#############################################################################\n",
    "# df_filtered is a filtered df_LaborReport_filtered without aberrant values\n",
    "#############################################################################\n",
    "# Only keep relevant columns from df_filtered\n",
    "df_filtered = df_filtered[['Priority', 'Pty Indice', 'IDD Component', 'Actual Time (unit)', 'Expected Time (unit)', 'WO#', 'WO Qty']]\n",
    "\n",
    "# Convert to numeric to avoid merging issues - Update 09/11\n",
    "#df_LaborReport_filtered['Expected Time (unit)'] = pd.to_numeric(df_LaborReport_filtered['Expected Time (unit)'], errors='coerce')\n",
    "#df_LaborReport_filtered['Actual Time (unit)'] = pd.to_numeric(df_LaborReport_filtered['Actual Time (unit)'], errors='coerce')\n",
    "# Convert to numeric to avoid merging issues\n",
    "df_filtered['Expected Time (unit)'] = pd.to_numeric(df_filtered['Expected Time (unit)'], errors='coerce')\n",
    "df_filtered['Actual Time (unit)'] = pd.to_numeric(df_filtered['Actual Time (unit)'], errors='coerce')\n",
    "\n",
    " # Updated 09/11 to replace  df_LaborReport_filtered by df_filtered to erase abberant values for the calculatation of Actual Time (unit)\n",
    "# --> |CM-LaborReport| still contain all the values, while |CM-MakeArchitecture| calculation are based on a filtered datafram df_LaborReport_filtered. Apply color formating in red of the row filtered out from the datafram.\n",
    "# Perform the merge and keep all columns from both dataframes\n",
    "df_Make_architure = df_Make_architure.merge(\n",
    "    df_filtered,\n",
    "    on=['IDD Component', 'Pty Indice'],\n",
    "    how='left',\n",
    "    suffixes=('', '_from_LaborReport')\n",
    ")\n",
    "\n",
    "# Drop any unnecessary columns\n",
    "df_Make_architure.drop(columns=['BOM Index_from_LaborReport'], inplace=True, errors='ignore')\n",
    "\n",
    "#Remove duplicates based on 'WO#' to ensure each 'WO#' is counted only once\n",
    "unique_wo_data = df_Make_architure.drop_duplicates(subset='WO#')\n",
    "\n",
    "# Group by 'Pty Indice' and 'IDD Component' and perform the aggregation\n",
    "final_aggregated = unique_wo_data.groupby(['Pty Indice', 'IDD Component']).agg(\n",
    "    WO_Count=('WO#', 'nunique'),  # Count the number of unique 'WO#' for each group\n",
    "    Qty_Count=('WO Qty', 'sum'),  # Sum the 'WO Qty' for each group\n",
    "    Avg_Expected_Time=('Expected Time (unit)', 'mean'),  # Mean of 'Expected Time (unit)'\n",
    "    Avg_Actual_Time=('Actual Time (unit)', 'mean'),  # Mean of 'Actual Time (unit)'\n",
    "    Var_Actual_Time=('Actual Time (unit)', 'var'),  # Variance of 'Actual Time (unit)'\n",
    "    Max_Expected_Time=('Expected Time (unit)', 'last')  # Maximum 'Expected Time (unit)' --> Update 09/16 to get the 'last' instead of the 'max' as the most recent WO with the most updated BOM is the last for a given PN\n",
    ").reset_index()\n",
    "\n",
    "# Calculate standard deviation based on variance\n",
    "final_aggregated['Standard Deviation [hour]'] = np.sqrt(final_aggregated['Var_Actual_Time'])\n",
    "\n",
    "# Rename columns in the aggregated dataframe to match the final output\n",
    "final_aggregated.rename(columns={\n",
    "    'Avg_Expected_Time': 'Avg Expected Time (unit)[hour]',\n",
    "    'Avg_Actual_Time': 'Avg Actual Time (unit)[hour]',\n",
    "    'Var_Actual_Time': 'Variance Actual Time [hour²]',\n",
    "    'Max_Expected_Time': 'Max Expected Time (unit)[hour]',\n",
    "}, inplace=True)\n",
    "\n",
    "# Calculate 'Actual vs Standard time [%]'\n",
    "final_aggregated['Actual vs Standard time [%]'] = np.where(\n",
    "    final_aggregated['Max Expected Time (unit)[hour]'].fillna(0) == 0,\n",
    "    'N/A',  # Handle division by zero\n",
    "    (\n",
    "        (((final_aggregated['Avg Actual Time (unit)[hour]'] / \n",
    "           final_aggregated['Max Expected Time (unit)[hour]']) - 1) * 100)\n",
    "        .replace([np.inf, -np.inf], np.nan)  # Replace infinity values\n",
    "        .fillna(0)  # Replace NaN values with 0\n",
    "        .round(0)  # Round the result\n",
    "        .astype(int)  # Convert to integer\n",
    "        .astype(str) + '%'  # Convert to string and append '%'\n",
    "    )\n",
    ")\n",
    "\n",
    "# Merge the aggregated data with the original make architecture\n",
    "df_Make_architure_final = pd.merge(\n",
    "    final_aggregated,\n",
    "    df_Make_architure,\n",
    "    on=['Pty Indice', 'IDD Component'],\n",
    "    how='left'\n",
    ").drop_duplicates()\n",
    "\n",
    "# Convert 'BOM Qty' and 'BOM Index' to numeric, coercing errors to NaN\n",
    "df_Make_architure_final['BOM Qty'] = pd.to_numeric(df_Make_architure_final['BOM Qty'], errors='coerce')\n",
    "df_Make_architure_final['BOM Index'] = pd.to_numeric(df_Make_architure_final['BOM Index'], errors='coerce')\n",
    "\n",
    "# Fill NaN values with appropriate placeholders\n",
    "'''\n",
    "Updated 10/15 to avoid FutureWarning:\n",
    "1. Removed inplace=True as it will no longer work in future pandas versions.\n",
    "2. Directly assign the result of fillna() back to the columns.\n",
    "'''\n",
    "df_Make_architure_final['BOM Qty'] = df_Make_architure_final['BOM Qty'].fillna(1)\n",
    "df_Make_architure_final['BOM Index'] = df_Make_architure_final['BOM Index'].fillna(0)\n",
    "\n",
    "\n",
    "# Convert to integer\n",
    "df_Make_architure_final['BOM Qty'] = df_Make_architure_final['BOM Qty'].astype(int)\n",
    "df_Make_architure_final['BOM Index'] = df_Make_architure_final['BOM Index'].astype(int)\n",
    "\n",
    "# Filter out rows where 'Qty_Count' is 0\n",
    "df_Make_architure_final = df_Make_architure_final[df_Make_architure_final['Qty_Count'] > 0]\n",
    "\n",
    "# Keep only relevant columns in the final dataframe\n",
    "df_Make_architure_final = df_Make_architure_final[['Priority', 'Pty Indice', 'IDD Component', 'Level', 'BOM Qty', 'Description Component', 'IDD Top Level', 'SEDA Top Level', 'M/P/F', 'Phantom', 'BOM Index', 'Avg Expected Time (unit)[hour]', 'Max Expected Time (unit)[hour]', 'Avg Actual Time (unit)[hour]', 'Variance Actual Time [hour²]', 'Standard Deviation [hour]', 'Actual vs Standard time [%]', 'WO_Count', 'Qty_Count']]\n",
    "\n",
    "# Drop any duplicates\n",
    "df_Make_architure_final.drop_duplicates(inplace=True)\n",
    "\n",
    "# Round 'Avg Expected Time (unit)' and 'Avg Actual Time (unit)' to 2 decimal places\n",
    "df_Make_architure_final['Avg Expected Time (unit)[hour]'] = df_Make_architure_final['Avg Expected Time (unit)[hour]'].round(2)\n",
    "df_Make_architure_final['Max Expected Time (unit)[hour]'] = df_Make_architure_final['Max Expected Time (unit)[hour]'].round(2)\n",
    "df_Make_architure_final['Avg Actual Time (unit)[hour]'] = df_Make_architure_final['Avg Actual Time (unit)[hour]'].round(2)\n",
    "df_Make_architure_final['Variance Actual Time [hour²]'] = df_Make_architure_final['Variance Actual Time [hour²]'].round(2)\n",
    "df_Make_architure_final['Standard Deviation [hour]'] = df_Make_architure_final['Standard Deviation [hour]'].round(2)\n",
    "\n",
    "# Groupby 'Pty Indice' and sort by 'BOM Index' for a given 'Pty Indice', then sort datafram by 'Priority' (non-numeric at the end) while keeping the previous grouping\n",
    "# Define a sorting function for 'Priority' that places non-numeric values at the end\n",
    "def priority_sort_key(value):\n",
    "    try:\n",
    "        # For numeric values, return a tuple where the second element is the integer value\n",
    "        return (0, int(value))\n",
    "    except ValueError:\n",
    "        # For non-numeric values, return a tuple where the second element is a large number (e.g., 99)\n",
    "        return (1, 99)  # Ensuring non-numeric values are sorted at the end\n",
    "\n",
    "# Apply sorting within each group defined by 'Pty Indice'\n",
    "df_Make_architure_final['Priority_Sort'] = df_Make_architure_final['Priority'].map(priority_sort_key)\n",
    "\n",
    "# Print and display the DataFrame with the Priority_Sort column\n",
    "#print('df_Make_architure_final with Priority_Sort')\n",
    "#display(df_Make_architure_final)\n",
    "\n",
    "# Sort the DataFrame by 'Priority' first\n",
    "df_Make_architure_final_sorted_by_priority = df_Make_architure_final.sort_values(\n",
    "    by='Priority_Sort',\n",
    "    ascending=True\n",
    ")\n",
    "\n",
    "# Group by 'Pty Indice' and sort by 'BOM Index' within each group\n",
    "df_Make_architure_final_sorted = df_Make_architure_final_sorted_by_priority.sort_values(\n",
    "    by=['Pty Indice', 'BOM Index'],\n",
    "    ascending=[True, True]\n",
    ")\n",
    "\n",
    "\n",
    "# Drop the temporary 'Priority_Sort' column\n",
    "df_Make_architure_final_sorted.drop(columns=['Priority_Sort'], inplace=True)\n",
    "\n",
    "#Create column 'Last Update' and fill the first row with the value of the first row of df_LaborReport['Last Update']\n",
    "last_update_value = df_LaborReport['Last Update'].iloc[0]  # Get the value from the first row\n",
    "\n",
    "# Create 'Last Update' column and fill it\n",
    "''' Updated 10/15 to avoid warning\n",
    "df_Make_architure_final_sorted['Last Update'] = np.nan  # Initialize column with NaN\n",
    "df_Make_architure_final_sorted.loc[0, 'Last Update'] = last_update_value  # Fill the first row \n",
    "'''\n",
    "df_Make_architure_final_sorted['Last Update'] = np.nan  # Initialize column with NaN\n",
    "df_Make_architure_final_sorted['Last Update'] = df_Make_architure_final_sorted['Last Update'].astype(str)  # Cast to string\n",
    "df_Make_architure_final_sorted.loc[0, 'Last Update'] = last_update_value  # Fill the first row with actual value\n",
    "\n",
    "\n",
    "# Print and display the final dataframe\n",
    "#print('df_Make_architure_final_sorted')\n",
    "#display(df_Make_architure_final_sorted)\n",
    "\n",
    "# New 09/11 \n",
    "###############################################################################################################\n",
    "################################################ Red Formatting of |CM-LaborReport|  ##########################\n",
    "###############################################################################################################\n",
    "# --> |CM-LaborReport| still contain all the values, while |CM-MakeArchitecture| calculation are based on a filtered datafram df_LaborReport_filtered. Apply color formating in red of the row filtered out from the datafram.\n",
    "# Create a mapping of the row that have been filtered-out between df_LaborReport_filtered and df_filtered and color them in red in |CM-LaborReport| \n",
    "# --> Create a boolean mask indicating which rows in df_LaborReport_filtered were kept in df_filtered\n",
    "\n",
    "# Define the red fill for rows that were filtered out\n",
    "red_fill = PatternFill(start_color='FC8F84', end_color='FC8F84', fill_type='solid')\n",
    "\n",
    "# Identify the rows that were filtered out in your DataFrame\n",
    "df_LaborReport_filtered['is_filtered_out'] = ~df_LaborReport_filtered['WO#'].isin(df_filtered['WO#'])\n",
    "# Create a dictionary mapping WO# to is_filtered_out status\n",
    "filtered_out_map = df_LaborReport_filtered.set_index('WO#')['is_filtered_out'].to_dict()\n",
    "\n",
    "# Iterate over rows in the existing Excel sheet\n",
    "for r_idx, row in enumerate(sheet_LaborReport.iter_rows(min_row=2, max_row=sheet_LaborReport.max_row, values_only=True), start=2):\n",
    "    wo_number = row[5]  # Assuming 'WO#' is the 6th column (index 5)\n",
    "    if wo_number in filtered_out_map and filtered_out_map[wo_number]:\n",
    "        # Apply red fill to columns F through T (indices 6 to 20)\n",
    "        for c_idx in range(6, 21):  # 6 is F and 21 is T + 1\n",
    "            cell = sheet_LaborReport.cell(row=r_idx, column=c_idx)\n",
    "            cell.fill = red_fill\n",
    "        \n",
    "        # Apply red fill to columns V through AB (indices 22 to 28)\n",
    "        for c_idx in range(22, 29):  # 22 is V and 29 is AB + 1\n",
    "            cell = sheet_LaborReport.cell(row=r_idx, column=c_idx)\n",
    "            cell.fill = red_fill\n",
    "        \n",
    "'''\n",
    "# Iterate over rows in the existing Excel sheet\n",
    "for r_idx, row in enumerate(sheet_LaborReport.iter_rows(min_row=2, max_row=sheet_LaborReport.max_row, values_only=True), start=2):\n",
    "    wo_number = row[5]  # Assuming 'WO#' is the 6th column (index 5)\n",
    "    if wo_number in filtered_out_map and filtered_out_map[wo_number]:\n",
    "        # Apply red fill to the entire row if it was filtered out\n",
    "        for c_idx in range(1, len(row) + 1):\n",
    "            cell = sheet_LaborReport.cell(row=r_idx, column=c_idx)\n",
    "            cell.fill = red_fill\n",
    "'''\n",
    "\n",
    "#Save workbook\n",
    "workbook.save(original_input)\n",
    "# Close the workbook\n",
    "workbook.close()\n",
    "\n",
    "###################################################################################################################\n",
    "##########################################         Creating |CM-MakeArchitecture|              ####################\n",
    "###################################################################################################################\n",
    "# Check if \"CM-TurnoverReport\" sheet already exists and delete it if it does\n",
    "if 'CM-MakeArchitecture' in workbook.sheetnames:\n",
    "    del workbook['CM-MakeArchitecture']\n",
    "\n",
    "# Create new \"CM-MakeArchitecture\" sheet\n",
    "sheet_MakeArchi = workbook.create_sheet(title='CM-MakeArchitecture')\n",
    "\n",
    "# Write headers to Excel\n",
    "for c_idx, header in enumerate(df_Make_architure_final_sorted.columns, start=1):\n",
    "    sheet_MakeArchi.cell(row=1, column=c_idx, value=header)\n",
    "\n",
    "# Write data to Excel\n",
    "for r_idx, row in enumerate(df_Make_architure_final_sorted.values, start=2):\n",
    "    for c_idx, value in enumerate(row, start=1):\n",
    "        sheet_MakeArchi.cell(row=r_idx, column=c_idx, value=value)\n",
    "\n",
    "\n",
    "###############################################################################################################\n",
    "################################################ Formatting |CM-MakeArchitecture|  ############################\n",
    "###############################################################################################################\n",
    "\n",
    "# Apply formatting to the header row\n",
    "header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')\n",
    "header_font = Font(color='FFFFFF', bold=True)\n",
    "header_alignment = Alignment(horizontal='left', vertical='center')\n",
    "header_border = Border(\n",
    "    top=Side(style='medium'),\n",
    "    bottom=Side(style='medium'),\n",
    "    left=Side(style='medium'),\n",
    "    right=Side(style='medium')\n",
    ")\n",
    "\n",
    "for cell in sheet_MakeArchi[1]:\n",
    "    cell.fill = header_fill\n",
    "    cell.font = header_font\n",
    "    cell.alignment = header_alignment\n",
    "    cell.border = header_border\n",
    "\n",
    "# Add filters to the first row\n",
    "sheet_MakeArchi.auto_filter.ref = sheet_MakeArchi.dimensions\n",
    "\n",
    "# Set column widths and text alignment for columns A to S\n",
    "for column in sheet_MakeArchi.iter_cols(min_col=1, max_col=19):\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "    \n",
    "    column_letter = column[0].column_letter\n",
    "    if column_letter in ['A', 'B']:\n",
    "        sheet_MakeArchi.column_dimensions[column_letter].width = 15\n",
    "    elif column_letter in ['F']:\n",
    "        sheet_MakeArchi.column_dimensions[column_letter].width = 40\n",
    "    elif column_letter in ['C', 'G', 'H', 'L', 'M', 'N', 'O', 'P', 'Q']:\n",
    "        sheet_MakeArchi.column_dimensions[column_letter].width = 20\n",
    "    else:\n",
    "        sheet_MakeArchi.column_dimensions[column_letter].width = 10\n",
    "\n",
    "    # Apply alignment and border to cells in the current column\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "###############################################\n",
    "# Set background color for Last Update cell T2 \n",
    "###############################################\n",
    "sheet_MakeArchi.cell(row=2, column=20).fill = PatternFill(start_color='E2EFDA', end_color='E2EFDA', fill_type='solid')\n",
    "\n",
    "###############################################\n",
    "# Coloring column 'Level' \n",
    "################################################\n",
    "# Custom conditional formatting for column D 'Level' (Assuming data starts from row 2)\n",
    "min_row = 2\n",
    "max_row = sheet_MakeArchi.max_row\n",
    "col_D = 4\n",
    "\n",
    "for row in range(min_row, max_row + 1):\n",
    "    cell_value = sheet_MakeArchi.cell(row=row, column=col_D).value\n",
    "\n",
    "    # Define default fill color in case cell_value is not in expected range\n",
    "    fill_color = None\n",
    "    \n",
    "    if cell_value is not None:\n",
    "        if cell_value == 0:\n",
    "            fill_color = '63BE7B'  # Green\n",
    "        elif cell_value == 1:\n",
    "            fill_color = 'A2C075'  # Lighter Green\n",
    "        elif cell_value == 2:\n",
    "            fill_color = 'FFEB84'  # Yellow\n",
    "        elif cell_value == 3:\n",
    "            fill_color = 'FFD166'  # Orange\n",
    "        elif cell_value == 4:\n",
    "            fill_color = 'F88E5B'  # Darker Orange\n",
    "        elif cell_value == 5:\n",
    "            fill_color = 'F8696B'  # Red\n",
    "        elif cell_value == 6:\n",
    "            fill_color = '8B0000'  # Darker Red\n",
    "        \n",
    "       # Create PatternFill object only if fill_color is defined\n",
    "        if fill_color:\n",
    "            fill = PatternFill(start_color=fill_color, end_color=fill_color, fill_type='solid')\n",
    "            sheet_MakeArchi.cell(row=row, column=col_D).fill = fill\n",
    "\n",
    "\n",
    "################################################\n",
    "# Save the updated workbook\n",
    "################################################\n",
    "workbook.save(original_input)\n",
    "# Close the workbook\n",
    "workbook.close()\n",
    "\n",
    "print(f\"Make Architecture added successfully as |CM-MakeArchi| in {original_input}\")\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "#****************************************************************************************************************************************************************************************\n",
    "######################################################################################################################################################################################\n",
    "###   ######  ##    ##   ####      ####  ####      ####  #########  #########  ##     ##       #######  ###    ##  ########  ########  #########  ##    ##  #########  ############\n",
    "##    ##      ##    ##   ######   #####  ######   #####  ##     ##  ##     ##   ##  ##         ##       ## ##  ##  ##    ##  ##    ##  ##         ##    ##  ##     ##       ##\n",
    "###   #####   ##    ##   ##  ##  ##  ##  ##  ##  ##  ##  #########  #########    ####      +   #######  ##  ## ##  ########  ########  #########  ########  ##     ##       ##\n",
    "##       ##   ##    ##   ##   ####   ##  ##   ####   ##  ##     ##  ##  ###       ##                ##  ##   ####  ##    ##  ##               ##  ##    ##  ##     ##       ##\n",
    "##   ######   ########   ##          ##  ##          ##  ##     ##  ##    ###     ##           #######  ##    ###  ##    ##  ##        #########  ##    ##  #########       ##\n",
    "######################################################################################################################################################################################\n",
    "#****************************************************************************************************************************************************************************************\n",
    "# Load the existing output workbook\n",
    "try:\n",
    "    workbook = load_workbook(original_input)\n",
    "    #print(\"Output workbook loaded successfully.\")\n",
    "except FileNotFoundError as e:\n",
    "    print(f\"Output workbook not found: {e}\")\n",
    "    exit()\n",
    "\n",
    "# Print the sheet names \n",
    "print(\"Tabs in the workbook:\")\n",
    "print(workbook.sheetnames)\n",
    "print('Processing |Summary| ...')\n",
    "\n",
    "# Define date and path\n",
    "#input_file_formatted = original_input\n",
    "supplier_file_name = os.path.join(Path, '100_item_site_settings.xlsx')\n",
    "\n",
    "##############################################################################################################################\n",
    "# Load workbook\n",
    "##############################################################################################################################\n",
    "# Load the Excel files into pandas DataFrames\n",
    "try:\n",
    "    #df_CTB = pd.read_excel(input_file_formatted, sheet_name='Clear-to-Build')\n",
    "    df_CTB = pd.read_excel(original_input, sheet_name='Clear-to-Build')\n",
    "    \n",
    "    # Load the supplier file with renamed columns\n",
    "    df_supplier = pd.read_excel(supplier_file_name, sheet_name=0, usecols=['Item Number', 'Name'])\n",
    "    df_supplier.rename(columns={'Item Number': 'IDD Component', 'Name': 'Supplier'}, inplace=True)\n",
    "    #print(\"Input files loaded successfully.\")\n",
    "except FileNotFoundError as e:\n",
    "    print(f\"File not found: {e}\")\n",
    "    exit()\n",
    "\n",
    "########################################################\n",
    "### Filtering data from input file df_CTB_formatted ###\n",
    "###################################################################################################\n",
    "##### Create a tab 'Summary' sumarizing the Top-Level clear-to-build and shortages on a table ######\n",
    "    ### 1. Create a table with the following headers from tab from tab Clear-to-Build: \n",
    "        ## |Pty Indice | Priority | IDD Component | Level | BOM Qty | Description | IDD Top Level | SEDA Top Level | Qty On Hand | Remain. crit. Qty | Max Qty (GS) | Max Qty Top-Level | Top Level sharing Components\n",
    "    ### 2. Create a new column in position 0: | Top-Level Status | to fille with 'Clear-to-build' or 'Shortage' AND second position | Supplier | \n",
    "    ### 3. Fill the table with the information from df_CTB:\n",
    "            ## Based on df_CTB, |Top-Level Status | is clear-to-build for |Max Qty Top-Level| > 0 \n",
    "                # fill |status| with 'Clear-to-Build' for all component of a given Top-Level only if this given component |Max Qty (GS)| < |Remain. crit. Qty|\n",
    "            ## Based on df_CTB, |Top-Level Status | is shortage for |Max Qty Top-Level| = 0\n",
    "                #fill |status| with 'shortage' for all component of a given Top-Level only if this given component |Max Qty (GS)| < |Remain. crit. Qty|\n",
    "    \n",
    "    ### 4. The colum | Supplier | should be filled based on the info from df_supplier \n",
    "    ### 5. Create a new row for the Top-Level with |Level| = 0 on top of each subset/list of component related to a given Top-Level to facilitate the reading \n",
    "\n",
    "##############################################################################################################################\n",
    "# Filtering data from input file df_CTB_formatted\n",
    "##############################################################################################################################\n",
    "# Define the columns to be filtered from df_CTB\n",
    "filtered_columns = ['Pty Indice', 'Priority', 'IDD Component', 'Level', 'BOM Qty', 'Description',\n",
    "                    'IDD Top Level', 'SEDA Top Level', 'Qty On Hand', 'Remain. crit. Qty', 'Max Qty (GS)',\n",
    "                    'Max Qty Top-Level', 'Top Level sharing Components', 'Pur/Mfg']\n",
    "\n",
    "# Filter relevant columns and create a copy\n",
    "df_summary = df_CTB[filtered_columns].copy()\n",
    "\n",
    "# Convert 'Max Qty Top-Level' column to numeric, coercing errors to NaN\n",
    "df_summary['Max Qty Top-Level'] = pd.to_numeric(df_summary['Max Qty Top-Level'], errors='coerce')\n",
    "\n",
    "# Create 'Top-Level Status' column based on comparison\n",
    "df_summary['Top-Level Status'] = np.where(df_summary['Max Qty Top-Level'] > 0, 'Clear-to-Build', 'Shortage')\n",
    "\n",
    "# Merge information from df_supplier\n",
    "df_summary = df_summary.merge(df_supplier, how='left', on='IDD Component')\n",
    "\n",
    "# Fill NaN values in the 'Supplier' column with 'Supplier TBD' initially\n",
    "# df_summary['Supplier'].fillna('Supplier TBD', inplace=True) - Replaced 09/24 to avoid warning\n",
    "df_summary['Supplier'] = df_summary['Supplier'].fillna('Supplier TBD')\n",
    "\n",
    "# Update 'Supplier' to 'Make Part' if 'Pur/Mfg' is 'M' and 'Supplier' is 'Supplier TBD'\n",
    "#df_summary.loc[(df_summary['Pur/Mfg'] == 'M') & (df_summary['Supplier'] == 'Supplier TBD'), 'Supplier'] = 'Make Part'\n",
    "\n",
    "# Update 'Supplier' to 'Make Part' if 'Pur/Mfg' is 'M' \n",
    "df_summary.loc[df_summary['Pur/Mfg'] == 'M', 'Supplier'] = 'Make Part'\n",
    "\n",
    "###################################################################################\n",
    "#########   New 09/20                                                    ##########\n",
    "###################################################################################\n",
    "# Update Supplier to 'Make Part CUU' if 'Pur/Mfg' is 'D' \n",
    "df_summary.loc[df_summary['Pur/Mfg'] == 'D', 'Supplier'] = 'Make Part CUU'\n",
    "\n",
    "# Convert 'BOM Qty' to numeric, coercing errors to NaN\n",
    "df_summary['BOM Qty'] = pd.to_numeric(df_summary['BOM Qty'], errors='coerce')\n",
    "\n",
    "# Filter out rows where 'BOM Qty' is a float (keep NaN and integers intact)\n",
    "df_summary = df_summary[df_summary['BOM Qty'].apply(lambda x: x.is_integer() if pd.notna(x) else True)]\n",
    "###################################################################################\n",
    "# Updated 09/23 to not considered rows where Pur/Mfg' == 'D' to define 'Max Qty Top-Level' --> Write 'Make Part CUU' on 'Max Qty (GS)' so it won't be considered in df_Summary\n",
    "###################################################################################\n",
    "# Drop the 'Pur/Mfg' column as it is no longer needed\n",
    "df_summary.drop(columns=['Pur/Mfg'], inplace=True)\n",
    "\n",
    "# Filter out rows where 'Remain. crit. Qty' is 'Completed'\n",
    "df_summary_filtered = df_summary[df_summary['Remain. crit. Qty'] != 'Completed']\n",
    "\n",
    "# Convert 'Max Qty (GS)' column to numeric, coercing errors to NaN\n",
    "df_summary_filtered.loc[:, 'Max Qty (GS)'] = pd.to_numeric(df_summary_filtered['Max Qty (GS)'], errors='coerce')\n",
    "\n",
    "# Filter the DataFrame to keep only rows where 'Max Qty Top-Level' is not empty\n",
    "df_summary_filtered = df_summary_filtered[df_summary_filtered['Max Qty Top-Level'].notnull()]\n",
    "\n",
    "# Convert 'Remain. crit. Qty' and 'Max Qty (GS)' columns to numeric, coercing errors to NaN for non-numeric values\n",
    "df_summary_filtered['Remain. crit. Qty'] = pd.to_numeric(df_summary_filtered['Remain. crit. Qty'], errors='coerce')\n",
    "df_summary_filtered['Max Qty (GS)'] = pd.to_numeric(df_summary_filtered['Max Qty (GS)'], errors='coerce')\n",
    "\n",
    "# Create a mask to filter out non-numeric values - Updated on 08/09 to include PN where Remain. crit. Qty is NaN if 'Max Qty (GS)' is >= 0\n",
    "#numeric_mask = ~df_summary_filtered['Remain. crit. Qty'].isna() & ~df_summary_filtered['Max Qty (GS)'].isna()\n",
    "\n",
    "# New 08/09 - Create the mask including PN where Remain. crit. Qty is NaN if 'Max Qty (GS)' is >= 0 --> Follow-up order for a PN with an existing BOM \n",
    "numeric_mask = (\n",
    "    ((df_summary_filtered['Max Qty (GS)'] >= 0)) |\n",
    "    (~df_summary_filtered['Remain. crit. Qty'].isna() & ~df_summary_filtered['Max Qty (GS)'].isna())\n",
    ")\n",
    "\n",
    "\n",
    "# Filter the DataFrame to keep only rows where both 'Max Qty (GS)' and 'Remain. crit. Qty' are numeric\n",
    "df_summary_filtered = df_summary_filtered[numeric_mask]\n",
    "\n",
    "#################################################################\n",
    "# PN with Backlog - Hidden on 08/09 to include PN with Backlog \n",
    "####################################################################\n",
    "'''\n",
    "# Filter the DataFrame to keep only rows where 'Max Qty (GS)' is lower than 'Remain. crit. Qty' - Update 07/30 to include PN where 'Remain. crit. Qty' = 0 but IDD Backlog exists (from df_backlog)\n",
    "df_summary_filtered = df_summary_filtered[df_summary_filtered['Max Qty (GS)'] < df_summary_filtered['Remain. crit. Qty']]\n",
    "\n",
    "#New code 07/30\n",
    "#Filter df_summary_filtered based on 'Max Qty (GS)' < 'Remain. crit. Qty'\n",
    "df_summary_filtered = df_summary_filtered[df_summary_filtered['Max Qty (GS)'] < df_summary_filtered['Remain. crit. Qty']]\n",
    "\n",
    "# Identify 'Pty Indice' in df_backlog with 'Order' starting with 'S' or 'D' (filter out NC) -- Only PN for wich IDD has a backlog\n",
    "valid_indices = df_backlog[df_backlog['Order'].str.startswith(('S', 'D'))]['Pty Indice'].unique() -- Update 08/08 to include PN NOT in IDD backlog \n",
    "\n",
    "# Include rows in df_summary_filtered where 'Remain. crit. Qty' is not 0, or 'Pty Indice' is in valid_indices -- CHanged 08/08 'Remain. crit. Qty' can be 0\n",
    "df_summary_filtered_with_backlog = df_summary_filtered[\n",
    "    (df_summary_filtered['Remain. crit. Qty'] != 0) |\n",
    "    (df_summary_filtered['Pty Indice'].isin(valid_indices))\n",
    "]\n",
    "\n",
    "\n",
    "# Include rows in df_summary_filtered where 'Remain. crit. Qty' is not 0, or 'Pty Indice' is in valid_indices -- Changed 08/08 'Remain. crit. Qty' can be 0 so we can see the follow-up order\n",
    "#df_summary_filtered_with_backlog = df_summary_filtered[(df_summary_filtered['Pty Indice'].isin(valid_indices))]\n",
    "\n",
    "# Copy df_summary_filtered_with_backlog as df_summary_filtered\n",
    "df_summary_filtered = df_summary_filtered_with_backlog\n",
    "'''\n",
    "######################################################################\n",
    "\n",
    "# Reorder columns with \"Top-Level Status\" and \"Supplier\" as the first two columns\n",
    "df_summary = df_summary_filtered[['Top-Level Status', 'Supplier'] + [col for col in df_summary_filtered.columns if col not in ['Top-Level Status', 'Supplier']]]\n",
    "\n",
    "#print('df_summary:')\n",
    "# Display or further process df_summary\n",
    "#display(df_summary)\n",
    "\n",
    "##############################################################################################################################\n",
    "# Include fully clear to build Top-Level & Display a row for every given Top-Level\n",
    "##############################################################################################################################\n",
    "# Get unique top-level components\n",
    "top_levels = df_summary['IDD Top Level'].unique()\n",
    "\n",
    "# Create rows for top-level components\n",
    "top_level_rows = []\n",
    "for top_level in top_levels:\n",
    "    subcomponents = df_summary[df_summary['IDD Top Level'] == top_level]\n",
    "    remain_crit_qty = subcomponents['Remain. crit. Qty'].iloc[0]\n",
    "    max_qty_top_level = subcomponents['Max Qty Top-Level'].iloc[0]\n",
    "    # Create a row with the necessary columns\n",
    "    row = {\n",
    "        'Top-Level Status': top_level,\n",
    "        'Supplier': '',\n",
    "        'Pty Indice': subcomponents['Pty Indice'].iloc[0],\n",
    "        'Priority': subcomponents['Priority'].iloc[0],\n",
    "        'IDD Component': top_level,\n",
    "        'Level': 0,\n",
    "        'BOM Qty': np.nan,\n",
    "        'Description': '',\n",
    "        'IDD Top Level': top_level,\n",
    "        'SEDA Top Level': '',\n",
    "        'Qty On Hand': np.nan,\n",
    "        'Remain. crit. Qty': remain_crit_qty,\n",
    "        'Max Qty (GS)': np.nan,\n",
    "        'Max Qty Top-Level': max_qty_top_level,\n",
    "        'Top Level sharing Components': ''\n",
    "    }\n",
    "    top_level_rows.append(row)\n",
    "\n",
    "# Convert the list of dictionaries to a DataFrame\n",
    "df_top_levels = pd.DataFrame(top_level_rows)\n",
    "\n",
    "# Append the top-level rows to the filtered DataFrame\n",
    "df_summary_final = pd.concat([df_top_levels, df_summary], ignore_index=True)\n",
    "\n",
    "#print('df_summary_final:')\n",
    "#display(df_top_levels) \n",
    "\n",
    "#########################################################\n",
    "# Include Top-Level fully clear to build based on df_CTB\n",
    "########################################################\n",
    "# Convert 'Max Qty Top-Level' and 'Remain. crit. Qty' to numeric, coercing errors to NaN\n",
    "df_CTB['Max Qty Top-Level'] = pd.to_numeric(df_CTB['Max Qty Top-Level'], errors='coerce')\n",
    "df_CTB['Remain. crit. Qty'] = pd.to_numeric(df_CTB['Remain. crit. Qty'], errors='coerce')\n",
    "\n",
    "# Filter the DataFrame to include only rows where 'Max Qty Top-Level' is greater than 'Remain. crit. Qty' - Update 08/08, I want to see pty indice with follow-up order \n",
    "#df_clear_to_build = df_CTB[df_CTB['Max Qty Top-Level'] > df_CTB['Remain. crit. Qty']]\n",
    "#Updated 08/08: \n",
    "# Filter the DataFrame where 'Max Qty Top-Level' is not NaN and is >= 0 --> Should include ALL PN (clear and short) from |Clear-to-Build| meanning PN with an existing BOM in |Summary| \n",
    "df_clear_to_build = df_CTB[pd.notna(df_CTB['Max Qty Top-Level']) & (df_CTB['Max Qty Top-Level'] >= 0)]\n",
    "\n",
    "# Drop duplicates to ensure only one row per top-level component\n",
    "df_clear_to_build = df_clear_to_build.drop_duplicates(subset=['IDD Top Level'])\n",
    "\n",
    "# Create a new DataFrame for the top-level components based on the components\n",
    "top_level_columns = ['Pty Indice', 'Priority', 'IDD Component', 'IDD Top Level', 'Remain. crit. Qty', 'Max Qty Top-Level']\n",
    "\n",
    "# Initialize df_top_level with columns from df_clear_to_build\n",
    "df_top_level = df_clear_to_build[top_level_columns].copy()\n",
    "\n",
    "# Set the 'Level' column to 0 only where IDD Component matches IDD Top Level\n",
    "df_top_level.loc[df_top_level['IDD Component'] == df_top_level['IDD Top Level'], 'Level'] = 0 \n",
    "\n",
    "# Set the 'Top-Level Status' column to the value of 'IDD Top Level'\n",
    "df_top_level['Top-Level Status'] = df_top_level['IDD Top Level']\n",
    "\n",
    "# Filter out rows where 'Max Qty (GS)' is empty and 'Level' is not 0\n",
    "df_summary_final = df_summary_final[~((df_summary_final['Max Qty (GS)'].isna()) & (df_summary_final['Level'] != 0))]\n",
    "\n",
    "# Concatenate the top-level rows with the existing summary DataFrame\n",
    "df_summary_with_top_level = pd.concat([df_summary_final, df_top_level], ignore_index=True)\n",
    "\n",
    "# Ensure no row has Max Qty (GS) empty if Level is not 0 in the final DataFrame\n",
    "df_summary_with_top_level = df_summary_with_top_level[~((df_summary_with_top_level['Max Qty (GS)'].isna()) & (df_summary_with_top_level['Level'] != 0))]\n",
    "\n",
    "#Delete potentiel duplicate component for a given Pty Indice - Some component appears several time on the BOM and on the |clear-to-build| tab\n",
    "df_summary_with_top_level = df_summary_with_top_level.drop_duplicates(subset=['Pty Indice', 'IDD Component'])\n",
    "\n",
    "###################################################################################\n",
    "### Sorting dataframe by 'Pty Indice' and then by 'Level'  within 'Pty Indice' ###\n",
    "##################################################################################\n",
    "# df_summary_sorted = df_summary_with_top_level.groupby('Pty Indice', group_keys=False).apply(lambda x: x.sort_values(by=['Level']).sort_values(by='Priority')) # Replaced 09/24 to avoid warning\n",
    "\n",
    "#########################################################\n",
    "################### Update 09/24 ###################\n",
    "# Apply the sorting while keeping the grouping columns\n",
    "df_summary_sorted = (df_summary_with_top_level\n",
    "                     .groupby('Pty Indice', group_keys=False)\n",
    "                     .apply(lambda x: x.sort_values(by='Level').sort_values(by='Priority'))\n",
    "                    )\n",
    "\n",
    "# Resetting the index to keep the grouping columns and remove any warnings\n",
    "df_summary_sorted = df_summary_sorted.reset_index(drop=True)\n",
    "############################\n",
    "\n",
    "\n",
    "\n",
    "####################################################################################################################\n",
    "##########################################     Creating SUMMARY                            #########################\n",
    "###################################################################################################################\n",
    "# Check if \"Summary\" sheet already exists\n",
    "if \"Summary\" in workbook.sheetnames:\n",
    "    # Remove the existing \"Summary\" sheet\n",
    "    workbook.remove(workbook[\"Summary\"])\n",
    "\n",
    "# Create a new \"Summary\" sheet\n",
    "Summary_sheet = workbook.create_sheet(title='Summary', index=0)  # Add as the 1st sheet (index 0)\n",
    "\n",
    "# Write headers\n",
    "for c_idx, header in enumerate(df_summary_sorted.columns, start=1):\n",
    "    Summary_sheet.cell(row=1, column=c_idx, value=header)\n",
    "\n",
    "# Write data\n",
    "for r_idx, row in enumerate(df_summary_sorted.values, start=2):  # Start from row 2\n",
    "    for c_idx, value in enumerate(row, start=1):\n",
    "        Summary_sheet.cell(row=r_idx, column=c_idx, value=value)\n",
    "\n",
    "# Save the updated workbook\n",
    "workbook.save(original_input)\n",
    "# Close the workbook\n",
    "workbook.close()\n",
    "\n",
    "print(f\"Summary added successfully as |Summary| in {original_input}\")\n",
    "\n",
    "################################################################################################################\n",
    "#***************************************************************************************************************\n",
    "# Creating tab 'Snapshot' in first position \n",
    "#***************************************************************************************************************\n",
    "################################################################################################################\n",
    "##### load the formatted workbook & print sheet names\n",
    "print(\"Tabs in the workbook:\")\n",
    "print(workbook.sheetnames)\n",
    "print('Processing |Snapshot| ...')\n",
    "\n",
    "df_summary = pd.read_excel(original_input, sheet_name='Summary')\n",
    "df_priority = pd.read_excel(original_input, sheet_name='CM-Priority')\n",
    "df_backlog = pd.read_excel(original_input, sheet_name='CM-Backlog')\n",
    "df_CTB = pd.read_excel(original_input, sheet_name='Clear-to-Build')\n",
    "df_WIP = pd.read_excel(original_input, sheet_name='CM-WIP')\n",
    "\n",
    "########################################################\n",
    "### Filtering data from input tab SUMMARY & CM-Priority\n",
    "########################################################\n",
    "# Create a summary table with required columns\n",
    "df_snapshot = df_summary[['Top-Level Status', 'Pty Indice', 'Priority', 'IDD Top Level', 'SEDA Top Level', 'Remain. crit. Qty', 'Max Qty Top-Level']]\n",
    "\n",
    "''' To be deleted \n",
    "# Merge with 'CM-Priority' to get 'Production Status' and 'Description'\n",
    "df_snapshot = pd.merge(df_snapshot, df_priority[['Pty Indice', 'Description', 'Shipped','Production Status',  'Start date target', 'IDD Sale Price', 'SEDA Sale Price']], on='Pty Indice', how='inner')\n",
    "\n",
    "# Exclude rows where 'Production Status' is 'To be transferred' or 'Not phase 4'\n",
    "df_snapshot = df_snapshot[~df_snapshot['Production Status'].isin(['To be transferred', 'Not phase 4','Canceled'])]\n",
    "''' \n",
    "\n",
    "# Ensure 'Pty Indice' in df_priority is unique\n",
    "df_priority_unique = df_priority.drop_duplicates(subset='Pty Indice', keep='first')\n",
    "\n",
    "# Merge df_snapshot with df_priority to get all necessary columns\n",
    "df_snapshot = pd.merge(df_snapshot, df_priority_unique[['Pty Indice', 'Description', 'Shipped', 'Production Status', 'Start date target', 'IDD Sale Price', 'SEDA Sale Price']], on='Pty Indice', how='left')\n",
    "\n",
    "# Exclude rows where 'Production Status' is 'To be transferred', 'Not phase 4', or 'Canceled' - update 08/09, line not needed as this part are now included on df_Summary\n",
    "#df_snapshot = df_snapshot[~df_snapshot['Production Status'].isin(['To be transferred', 'Not phase 4', 'Canceled'])]\n",
    "\n",
    "###############################################################################################\n",
    "# Include fully clear-to-build PN\n",
    "# Mostly necesseary for lightplate as very fiew P Part and most of the work is at a Top-Level \n",
    "#############################################################################################\n",
    "# --->>> #New code 07/24/24 <--\n",
    "# Convert columns to numeric, coercing errors to NaN\n",
    "df_CTB['Max Qty (GS)'] = pd.to_numeric(df_CTB['Max Qty (GS)'], errors='coerce')\n",
    "df_CTB['Remain. crit. Qty'] = pd.to_numeric(df_CTB['Remain. crit. Qty'], errors='coerce')\n",
    "\n",
    "# Filter df_CTB to remove rows with NaN in 'Max Qty (GS)' and apply custom filter\n",
    "filtered_ctb = df_CTB.dropna(subset=['Max Qty (GS)'])\n",
    "filtered_ctb = filtered_ctb[filtered_ctb['Max Qty (GS)'] > filtered_ctb['Remain. crit. Qty']]\n",
    "\n",
    "# Group by 'Pty Indice'\n",
    "grouped = filtered_ctb.groupby('Pty Indice')\n",
    "\n",
    "# Find the row with the lowest 'Max Qty (GS)' in each group\n",
    "#min_qty_rows = grouped.apply(lambda df: df.loc[df['Max Qty (GS)'].idxmin()]) - Replaced 09/24 to avoid warning\n",
    "min_qty_rows = grouped.apply(lambda df: df.loc[df['Max Qty (GS)'].idxmin()]).reset_index(drop=True)\n",
    "\n",
    "# Reset the index because the groupby + apply operation sets a multi-index\n",
    "#min_qty_rows = min_qty_rows.reset_index(drop=True) # No need to call reset_index again as it's already reset in the previous line\n",
    "\n",
    "# Concatenate these rows with df_snapshot\n",
    "df_snapshot = pd.concat([df_snapshot, min_qty_rows], ignore_index=True)\n",
    "\n",
    "# Print the result\n",
    "#print(\"Column names in df_snapshot:\")\n",
    "#print(df_snapshot.columns)\n",
    "#print(\"Updated df_snapshot:\")\n",
    "#display(df_snapshot)\n",
    "\n",
    "\n",
    "# Some part are not present on the backlog and won't appear on df_snapshot (P14B for example) --> Need to include the part that are not in the backlog but present in df_Historic and set backlog qty to 0\n",
    "#############################################################################################\n",
    "# Ensure 'Pty Indice' in df_priority is unique\n",
    "df_priority_unique = df_priority.drop_duplicates(subset='Pty Indice', keep='first')\n",
    "df_priority_unique.set_index('Pty Indice', inplace=True)\n",
    "\n",
    "# Fill 'Production Status' for new rows based on 'CM-Priority'\n",
    "df_snapshot['Production Status'] = df_snapshot['Pty Indice'].map(df_priority_unique['Production Status'])\n",
    "\n",
    "# Update 'Description' similarly\n",
    "df_snapshot['Description'] = df_snapshot['Pty Indice'].map(df_priority_unique['Description'])\n",
    "\n",
    "# Rename 'Max Qty Top-Level' to 'Qty clear to build'\n",
    "df_snapshot.rename(columns={'Max Qty Top-Level': 'Qty clear to build'}, inplace=True)\n",
    "\n",
    "#################################################################################################################\n",
    "# Create new rows in df_snapshot for missing PN (not in |Summary| because no Purchase Part) -- P14B for example \n",
    "#################################################################################################################\n",
    "# New code 07/29 \n",
    "######################\n",
    "### Include only missing PN related to Phase 4 as Summary is only showing Phase 4 at this point \n",
    "# Create new rows for missing 'Pty Indice' in Phase 4\n",
    "missing_pn_phase4 = df_priority[(df_priority['Program'] == 'Phase 4') & (~df_priority['Pty Indice'].isin(df_snapshot['Pty Indice']))]\n",
    "\n",
    "# Prepare the new rows with 'Clear-to-Build' status\n",
    "new_rows = missing_pn_phase4[['Pty Indice', 'Priority', 'IDD Top Level', 'SEDA Top Level', 'Shipped', 'Remain. crit. Qty', 'Description', 'Production Status']]\n",
    "\n",
    "#print('new_rows')\n",
    "#display(new_rows)\n",
    "\n",
    "################\n",
    "#New code 07/30 - Update 08/09, carefull to always have 'Remain. crit. Qty' filled on |clear-to-build| even though they are from the redlist 'To be transferred' or 'Canceled' \n",
    "# otherwise these PN will be filter-out and introduced later and consiedered as PN without any purchases parts (like some lightplate) and the 'Qty clear to build' will be set to the maximmun demand even though they might be short\n",
    "#######################################################################################\n",
    "# Filter out rows where 'Production Status' is in ['To be transferred', 'Canceled']\n",
    "# AND 'Remain. crit. Qty' is either empty OR 'Qty clear to build' = 0\n",
    "#########################################################################################\n",
    "filtered_new_rows = new_rows[\n",
    "    ~(\n",
    "        (new_rows['Production Status'].isin(['To be transferred', 'Canceled'])) &\n",
    "        (new_rows['Remain. crit. Qty'].isna() | (new_rows['Remain. crit. Qty'] == ''))\n",
    "    )\n",
    "]\n",
    "\n",
    "#print('filtered_new_rows')\n",
    "#display (filtered_new_rows) -- filtered_new_rows all the missing PN that should be included on Snapshot\n",
    "\n",
    "filtered_new_rows = filtered_new_rows.copy()\n",
    "\n",
    "# Merge new rows with the existing snapshot \n",
    "df_snapshot = pd.concat([df_snapshot, filtered_new_rows], ignore_index=True)\n",
    "\n",
    "#####################################################################################################\n",
    "#********************************************************************************\n",
    "# Update |Snapshot| based on |CM-Backlog| - Include after creation of Backlog\n",
    "#********************************************************************************\n",
    "###Row from |CM-Backlog| with 'Inv. Addr' = 10178-1 ('Invoice name' = 'IDD Aerospace Corporation') should be excluded, this is Labortest WO.\n",
    "# --> Filter out the specific row from CM-Backlog that are LABORTEST WO\n",
    "df_backlog = df_backlog[df_backlog['Inv. Addr'] != '10178-1']\n",
    "\n",
    "##############################################################################################\n",
    "# Create column |IDD Backlog Qty| to determine |Remaining Crit. Qty| vs. |IDD Backlog Qty|\n",
    "#|IDD Backlog Qty| = |Backlog row Qty| for each row for a given |IDD Top Leve| exept if |Order| contain 'NC'\n",
    "#############################################################################################\n",
    "# Load backlog data and calculate IDD Backlog Qty\n",
    "df_backlog['IDD Backlog Qty'] = df_backlog.apply(lambda row: row['Backlog row Qty'] if 'NC' not in row['Order'] else 0, axis=1)\n",
    "\n",
    "# Aggregate backlog quantities by 'IDD Top Level'\n",
    "df_backlog_agg = df_backlog.groupby('IDD Top Level')['IDD Backlog Qty'].sum().reset_index()\n",
    "\n",
    "# Merge backlog quantities with snapshot\n",
    "df_snapshot = pd.merge(df_snapshot, df_backlog_agg, on='IDD Top Level', how='left')\n",
    "\n",
    "# Replace NaN values in 'IDD Backlog Qty' with 0\n",
    "df_snapshot['IDD Backlog Qty'] = df_snapshot['IDD Backlog Qty'].fillna(0)\n",
    "\n",
    "# New 08/08  - Filter-out \n",
    "# Filter out rows where 'IDD Backlog Qty' is zero\n",
    "#df_snapshot = df_snapshot[df_snapshot['IDD Backlog Qty'] != 0]\n",
    "\n",
    "#####################################################\n",
    "# NEW 09/16 --> do not filter-out with completed PN\n",
    "######################################################\n",
    "# Filter out rows where 'IDD Backlog Qty' is zero and 'Production Status' is 'Completed'\n",
    "# df_snapshot = df_snapshot[~((df_snapshot['IDD Backlog Qty'] == 0) & (df_snapshot['Production Status'].isin(['Completed'])))] <-- Erased 09/16\n",
    "\n",
    "#filter-out 'Pty Indice' that are not on the df_CM_BOM as without BOM it should not be included\n",
    "df_snapshot = df_snapshot[df_snapshot['Pty Indice'].isin(df_CM_BOM['Pty Indice'])]\n",
    "\n",
    "# Optionally, reset the index after filtering\n",
    "df_snapshot.reset_index(drop=True, inplace=True)\n",
    "\n",
    "##############################################################################\n",
    "# Update 'Qty clear to build' based on 'IDD Backlog Qty' - Max of 'Qty clear to build' should be the Max of ('IDD Backlog Qty' and 'Remain. crit. Qty')\n",
    "############################################################################\n",
    "#New code 07/25\n",
    "# Ensure values are numerical\n",
    "df_snapshot['Remain. crit. Qty'] = pd.to_numeric(df_snapshot['Remain. crit. Qty'], errors='coerce')\n",
    "df_snapshot['IDD Backlog Qty'] = pd.to_numeric(df_snapshot['IDD Backlog Qty'], errors='coerce')\n",
    "\n",
    "# Ensure 'Qty clear to build' is updated based on 'IDD Backlog Qty' and 'Remain. crit. Qty' only if it is initially greater than both - To avoid having to big of a number for lightplates\n",
    "df_snapshot['Qty clear to build'] = df_snapshot.apply(\n",
    "    lambda row: max(row['Remain. crit. Qty'], row['IDD Backlog Qty'])\n",
    "    if row['Qty clear to build'] > row['Remain. crit. Qty'] and row['Qty clear to build'] > row['IDD Backlog Qty']\n",
    "    else row['Qty clear to build'],\n",
    "    axis=1\n",
    ")\n",
    "\n",
    "# New code 07/30 - 08/08 --> Carefull that ALL PN related to Phase4 from CM-Priority have a 'Critical qty' set to some number to avoid filling these PN with an completly innacurate 'Qty CTB' \n",
    "# At this point, only the PN without any purchased part on the BOM will have Qty clear to build' empty (mainly lightplates) \n",
    "#If 'Qty clear to build' is empty, fill 'Qty clear to build'  with the biggest value between 'Remain. crit. Qty' and 'IDD Backlog Qty'\n",
    "df_snapshot['Qty clear to build'] = df_snapshot['Qty clear to build'].fillna(\n",
    "    df_snapshot[['Remain. crit. Qty', 'IDD Backlog Qty']].max(axis=1)\n",
    ")\n",
    "\n",
    "#Update 07/30 --- change position of code bellow\n",
    "# Set 'Top-Level Status' based on the 'Qty clear to build'\n",
    "df_snapshot['Top-Level Status'] = df_snapshot.apply(lambda row: 'Clear-to-Build' if row['Qty clear to build'] > 0 else 'Short', axis=1)\n",
    "\n",
    "# Drop duplicates of 'Pty Indice' and keep the row where 'SEDA Top Level' is not empty\n",
    "# If 'SEDA Top Level' is empty for all duplicates, keep the first occurrence\n",
    "df_snapshot = df_snapshot.sort_values(by=['Pty Indice', 'SEDA Top Level'], ascending=[True, False])\n",
    "df_snapshot = df_snapshot.drop_duplicates(subset='Pty Indice', keep='first')\n",
    "\n",
    "# Keep only the necessary columns\n",
    "df_snapshot = df_snapshot[['Top-Level Status', 'Pty Indice', 'Priority', 'IDD Top Level', 'SEDA Top Level', 'Shipped', 'Remain. crit. Qty', 'Qty clear to build', 'Description', 'Production Status', 'Start date target', 'IDD Backlog Qty']]\n",
    "\n",
    "# Convert and format 'Start date target' in one step\n",
    "df_snapshot['Start date target'] = pd.to_datetime(df_snapshot['Start date target'], format='%m/%d/%Y', errors='coerce').dt.strftime('%m/%d/%Y')\n",
    "\n",
    "############################################\n",
    "# Function to determine the product category\n",
    "############################################\n",
    "# Define the 'Product Category' based on 'General Description'\n",
    "def determine_category(description):\n",
    "    if not isinstance(description, str):\n",
    "        return 'Others'\n",
    "    if description == 'Rototellite':\n",
    "        return 'Rototellite'\n",
    "    elif 'Indicator' in description or 'CPA' in description:\n",
    "        return 'CPA'\n",
    "    elif 'Lightplate' in description:\n",
    "        return 'Lightplate'\n",
    "    elif 'ISP' in description or 'Keyboard' in description:\n",
    "        return 'ISP'\n",
    "    elif 'Module' in description:\n",
    "        return 'CPA'\n",
    "    elif 'optics' in description:\n",
    "        return 'Fiber Optics'\n",
    "    else:\n",
    "        return 'Others'\n",
    "\n",
    "# Create 'Product Category' column based on the 'Description'\n",
    "df_snapshot['Product Category'] = df_snapshot['Description'].apply(determine_category)\n",
    "\n",
    "########################################################################################\n",
    "# Determine 'IDD Marge Standard (unit)' & 'IDD Sale Price' from CM-Backlog\n",
    "#######################################################################################\n",
    "''' SAVED 10/07 to be updated to avoid getting $0 as 'IDD Sale Price'\n",
    "# Group by 'IDD Top Level' and calculate required values from df_backlog\n",
    "df_backlog_grouped = df_backlog.groupby('IDD Top Level').agg({\n",
    "    'Marge standard': 'first', \n",
    "    'Backlog row Qty': 'first',\n",
    "    'Currency net amount': 'first' \n",
    "}).reset_index()\n",
    "\n",
    "df_backlog_grouped['IDD Marge Standard (unit)'] = (df_backlog_grouped['Marge standard'] / df_backlog_grouped['Backlog row Qty']).round(1)\n",
    "df_backlog_grouped['IDD Sale Price'] = (df_backlog_grouped['Currency net amount'] / df_backlog_grouped['Backlog row Qty']).round(1)\n",
    "\n",
    "# Merge these calculated columns back to the df_snapshot\n",
    "df_snapshot = pd.merge(df_snapshot, df_backlog_grouped[['IDD Top Level', 'IDD Marge Standard (unit)', 'IDD Sale Price']], on='IDD Top Level', how='left')\n",
    "'''\n",
    "\n",
    "#Update 10/07 to filter-out 'Order' containg NC --> To avoid getting $0 as 'IDD Sale Price' because of NC at the beggining of the Backlog.\n",
    "# Step 1: Filter out rows where 'Order' contains 'NC'\n",
    "df_backlog_filtered_without_NC = df_backlog[~df_backlog['Order'].str.contains('NC', na=False)]\n",
    "\n",
    "# Step 2: Determine 'IDD Marge Standard (unit)' & 'IDD Sale Price' from CM-Backlog\n",
    "# Group by 'IDD Top Level' and calculate required values from the filtered df_backlog\n",
    "df_backlog_grouped = df_backlog_filtered_without_NC.groupby('IDD Top Level').agg({\n",
    "    'Marge standard': 'first', \n",
    "    'Backlog row Qty': 'first',\n",
    "    'Currency net amount': 'first' \n",
    "}).reset_index()\n",
    "\n",
    "df_backlog_grouped['IDD Marge Standard (unit)'] = (df_backlog_grouped['Marge standard'] / df_backlog_grouped['Backlog row Qty']).round(1)\n",
    "df_backlog_grouped['IDD Sale Price'] = (df_backlog_grouped['Currency net amount'] / df_backlog_grouped['Backlog row Qty']).round(1)\n",
    "\n",
    "# Merge these calculated columns back to the df_snapshot\n",
    "df_snapshot = pd.merge(df_snapshot, df_backlog_grouped[['IDD Top Level', 'IDD Marge Standard (unit)', 'IDD Sale Price']], on='IDD Top Level', how='left')\n",
    "\n",
    "#--> \n",
    "################################\n",
    "# WIP 09/17 \n",
    "###################################################################################################################################################################\n",
    "### Update Snapshot (only rows for the parts that are completed without follow-up order for analysis purposes) by calculating Financial KPI based on df_Historic & set the backlog/production KPI to 0 [P2's, P14B ...]\n",
    "## Update KPI metrics based on df_Historic for the PN present on df_snapshot but not in the backlog for wich 'IDD Current Margin (%)' = 'N/A' due to missing financial metrics from the backlog (only possible if present on df_Historic) [P14A]\n",
    "###################################################################################################################################################################\n",
    "### Apply this to the row in df_snapshot with 'Pty Indice' not present in df_backlog but present in df_Historic \n",
    "### Set 'Top-Level Status' to 'Completed - No Backlog' as the current status should be 'Shortage' which make sense as there is not backlog --> Deferiencation for this specific rows \n",
    "## Calculation of the KPI metrics for a given 'Pty Indice': \n",
    "# --> Keep last row on df_Historic and calculate df_snapshot['IDD Marge Standard (unit)'] = (df_Historic['Currency turnover ex.VAT'] - df_Historic['Standard amount USD')]/df_Historic['Quantity'], \n",
    "# --> Keep last row on df_Historic and set df_snapshot['IDD Sale Price'] = df_Historic['Currency turnover ex.VAT']/df_Historic['Quantity']\n",
    "# df_snapshot['IDD Current Margin (%)'] is calculated later on the code\n",
    "# df_snapshot['IDD Expected ROI (Total)'] is calculated later on the code\n",
    "\n",
    "# Create a boolean mask for each 'Pty Indice' indicating whether all 'Order' values from the backlog contain 'NC'\n",
    "backlog_nc_only_mask = df_backlog.groupby('Pty Indice')['Order'].apply(lambda x: (x.str.contains('NC', na=False).all()))\n",
    "\n",
    "# Filter 'Pty Indice' that have only 'NC' in their 'Order'\n",
    "backlog_nc_only = backlog_nc_only_mask[backlog_nc_only_mask].index\n",
    "\n",
    "# Convert the index to a list of unique 'Pty Indice'\n",
    "backlog_nc_only = backlog_nc_only.tolist()\n",
    "\n",
    "# Identify `Pty Indice` in df_snapshot that are not in df_backlog but are present in df_Historic\n",
    "df_snapshot_missing = df_snapshot[\n",
    "    (~df_snapshot['Pty Indice'].isin(df_backlog['Pty Indice']) | df_snapshot['Pty Indice'].isin(backlog_nc_only)) &\n",
    "    df_snapshot['Pty Indice'].isin(df_Historic['Pty Indice'])\n",
    "]\n",
    "\n",
    "print(\"Pty Indice to update:\", df_snapshot_missing['Pty Indice'].unique())\n",
    "\n",
    "#############################################################################\n",
    "# Update 09/20 - Ensure that only a few rows are updated with df_Historic \n",
    "#############################################################################\n",
    "# Check if there are rows to update\n",
    "if df_snapshot_missing.empty:\n",
    "    print(\"No rows to update in df_snapshot_missing.\")\n",
    "else:\n",
    "    # Count the number of rows to be updated\n",
    "    num_rows_to_update = len(df_snapshot_missing)\n",
    "\n",
    "    # Exclude rows in df_Historic where 'Order' contains 'NC'\n",
    "    df_Historic_filtered = df_Historic[~df_Historic['Order'].str.contains('NC', na=False)]\n",
    "\n",
    "    # Fetch the last row from the filtered df_Historic for each 'Pty Indice' present in df_snapshot_missing - Nope, the most recent not the last\n",
    "    #df_Historic_last = df_Historic_filtered[df_Historic_filtered['Pty Indice'].isin(df_snapshot_missing['Pty Indice'])].groupby('Pty Indice').last().reset_index()\n",
    "\n",
    "    # Convert 'Invoice date' in df_Historic to datetime\n",
    "    df_Historic['Invoice date'] = pd.to_datetime(df_Historic['Invoice date'], errors='coerce')  # Handle any invalid dates\n",
    "\n",
    "    # Sort df_Historic_filtered by 'Pty Indice' and 'Invoice date' in descending order to get the most recent row for each 'Pty Indice'\n",
    "    df_Historic_filtered = df_Historic_filtered.sort_values(by=['Pty Indice', 'Invoice date'], ascending=[True, False])\n",
    "\n",
    "    # Fetch the most recent row for each 'Pty Indice' based on 'Invoice date'\n",
    "    df_Historic_mostrecent = df_Historic_filtered.groupby('Pty Indice').first().reset_index()\n",
    "\n",
    "    # Merge df_snapshot_missing with df_Historic_mostrecent based on 'Pty Indice' to get corresponding financial metrics\n",
    "    df_snapshot_missing_updated = df_snapshot_missing.merge(\n",
    "        df_Historic_mostrecent[['Pty Indice', 'Currency turnover ex.VAT', 'Standard amount USD', 'Quantity']],\n",
    "        on='Pty Indice',\n",
    "        how='left'\n",
    "    )\n",
    "\n",
    "    # Calculate 'IDD Marge Standard (unit)' and 'IDD Sale Price' for these rows\n",
    "    df_snapshot_missing_updated['IDD Marge Standard (unit)'] = (\n",
    "        (df_snapshot_missing_updated['Currency turnover ex.VAT'] - df_snapshot_missing_updated['Standard amount USD']) / \n",
    "        df_snapshot_missing_updated['Quantity']\n",
    "    )\n",
    "    \n",
    "    df_snapshot_missing_updated['IDD Sale Price'] = (\n",
    "        df_snapshot_missing_updated['Currency turnover ex.VAT'] / df_snapshot_missing_updated['Quantity']\n",
    "    )\n",
    "\n",
    "    # Update the specific rows in df_snapshot that are in df_snapshot_missing\n",
    "    df_snapshot.loc[df_snapshot['Pty Indice'].isin(df_snapshot_missing_updated['Pty Indice']), \n",
    "                    ['IDD Marge Standard (unit)', 'IDD Sale Price']] = df_snapshot_missing_updated[\n",
    "                    ['IDD Marge Standard (unit)', 'IDD Sale Price']].values\n",
    "\n",
    "    print(f\"{num_rows_to_update} rows from df_snapshot updated with df_Historic\")\n",
    "\n",
    "    '''\n",
    "    # Set 'Top-Level Status' to 'Completed - No Backlog' for the PN part of df_snapshot_missing only if 'IDD Sale Price' > 0 & only if Remain. crit. Qty = 0 \n",
    "    df_snapshot.loc[\n",
    "        (df_snapshot['Pty Indice'].isin(df_snapshot_missing['Pty Indice'])) &\n",
    "        (df_snapshot['IDD Sale Price'] > 0), \n",
    "        'Top-Level Status'\n",
    "    ] = 'Completed - No Backlog'\n",
    "\n",
    "    # Print the number of rows updated\n",
    "    print(f\"{num_rows_to_update} rows from df_snapshot updated with df_Historic\")\n",
    "    '''\n",
    "    \n",
    "    ##########################################################################################\n",
    "    # Set 'Top-Level Status' to 'Completed - No Backlog' or  'Not completed - No Backlog'\n",
    "    ##########################################################################################\n",
    "    # Condition 1: Set 'Completed - No Backlog' if 'IDD Sale Price' > 0 and 'Remain. crit. Qty' = 0\n",
    "    rows_to_update_completed = (\n",
    "        (df_snapshot['Pty Indice'].isin(df_snapshot_missing['Pty Indice'])) &\n",
    "        (df_snapshot['IDD Sale Price'] > 0) &\n",
    "        (df_snapshot['Remain. crit. Qty'] == 0)\n",
    "    )\n",
    "    \n",
    "    df_snapshot.loc[rows_to_update_completed, 'Top-Level Status'] = 'Completed - No Backlog'\n",
    "    \n",
    "    # Condition 2: Set 'Not completed - No Backlog' if 'IDD Sale Price' > 0 and 'Remain. crit. Qty' > 0\n",
    "    rows_to_update_not_completed = (\n",
    "        (df_snapshot['Pty Indice'].isin(df_snapshot_missing['Pty Indice'])) &\n",
    "        (df_snapshot['IDD Sale Price'] > 0) &\n",
    "        (df_snapshot['Remain. crit. Qty'] > 0)\n",
    "    )\n",
    "    \n",
    "    df_snapshot.loc[rows_to_update_not_completed, 'Top-Level Status'] = 'Not completed - No Backlog'\n",
    "    \n",
    "    # Print the number of rows updated for each condition\n",
    "    num_rows_completed = rows_to_update_completed.sum()\n",
    "    num_rows_not_completed = rows_to_update_not_completed.sum()\n",
    "    \n",
    "    print(f\"{num_rows_completed} rows updated with 'Completed - No Backlog'\")\n",
    "    print(f\"{num_rows_not_completed} rows updated with 'Not completed - No Backlog'\")\n",
    "\n",
    "############################\n",
    "# Create column '% Margin'\n",
    "###########################\n",
    "#New code 07/24/24\n",
    "# Fill missing values if needed\n",
    "'''\n",
    "df_snapshot['IDD Marge Standard (unit)'].fillna(0, inplace=True)\n",
    "df_snapshot['IDD Sale Price'].fillna(0, inplace=True)\n",
    "''' \n",
    "# Replaced 09/23 to avoid warning \n",
    "df_snapshot['IDD Marge Standard (unit)'] = df_snapshot['IDD Marge Standard (unit)'].fillna(0)\n",
    "df_snapshot['IDD Sale Price'] = df_snapshot['IDD Sale Price'].fillna(0)\n",
    "\n",
    "\n",
    "# Calculate '% Margin' with handling for division by zero - Updated 08/16, this return inacurates values\n",
    "df_snapshot['IDD Current Margin (%)'] = df_snapshot.apply(\n",
    "    lambda row: round(row['IDD Marge Standard (unit)'] / row['IDD Sale Price'], 3) if row['IDD Sale Price'] != 0 else None,\n",
    "    axis=1\n",
    ")\n",
    "\n",
    "# Convert any `-0` to `0`\n",
    "df_snapshot['IDD Current Margin (%)'] = df_snapshot['IDD Current Margin (%)'].apply(lambda x: 0 if x == -0 else x)\n",
    "\n",
    "#print('df_snapshot[IDD Current Margin (%)] BEFORE convertion to string')\n",
    "#display(df_snapshot['IDD Current Margin (%)'])\n",
    "\n",
    "# Format '% Margin' as a percentage string with a '%' sign \n",
    "df_snapshot['IDD Current Margin (%)'] = df_snapshot['IDD Current Margin (%)'].apply(lambda x: f\"{x * 100:.2f}%\" if pd.notna(x) else 'N/A')\n",
    "\n",
    "#print('df_snapshot[IDD Current Margin (%)] ATFER convertion to string')\n",
    "#display(df_snapshot['IDD Current Margin (%)'])\n",
    "\n",
    "\n",
    "###################################################################################################\n",
    "# Create column 'Production Cost' as average of 'Actual amount -standard' from the current backlog \n",
    "###################################################################################################\n",
    "#New code 07/25\n",
    "# Calculate 'Production Cost (unit)' for each row in df_backlog\n",
    "df_backlog['IDD Production Cost (unit)'] = df_backlog.apply(\n",
    "    lambda row: round(row['Actual amount -standard'] / row['Backlog row Qty'], 1) if row['Backlog row Qty'] != 0 else None,\n",
    "    axis=1\n",
    ")\n",
    "\n",
    "# Group by 'IDD Top Level' and aggregate 'IDD Production Cost (unit)' if needed\n",
    "# Here we assume you need the average or another aggregate measure\n",
    "df_backlog_grouped = df_backlog.groupby('IDD Top Level').agg({\n",
    "    'IDD Production Cost (unit)': 'mean'  # Or use 'first' if you just need the first non-null value\n",
    "}).reset_index()\n",
    "\n",
    "# Merge 'IDD Production Cost (unit)' back into df_snapshot\n",
    "df_snapshot = pd.merge(df_snapshot, df_backlog_grouped, on='IDD Top Level', how='left')\n",
    "\n",
    "# If 'IDD production Cost (unit)' is NaN in df_snapshot, you may choose to fill with a default value or leave as is\n",
    "df_snapshot.loc[:, 'IDD Production Cost (unit)'] = df_snapshot['IDD Production Cost (unit)'].fillna(0)\n",
    "\n",
    "# Display updated df_snapshot\n",
    "#print(\"Updated df_snapshot with Production Cost:\")\n",
    "#display(df_snapshot)\n",
    "\n",
    "\n",
    "#--> \n",
    "######################################################################################################################################################################\n",
    "# WIP 19/17 - update for row not in backlog with df_Histroic - Update 09/23\n",
    "########################################################################################################################################################################\n",
    "# --> Keep most recent row on df_Historic and set df_snapshot['IDD Production Cost (unit)'] = df_Historic['Standard amount USD']/df_Historic['Quantity']\n",
    "# For rows missing from backlog but present in df_Historic, calculate 'IDD Production Cost (unit)'\n",
    "# Calculate 'IDD Production Cost (unit)' based on last row in df_Historic\n",
    "df_Historic_mostrecent['IDD Production Cost (unit)'] = df_Historic_mostrecent['Standard amount USD'] / df_Historic_mostrecent['Quantity']\n",
    "\n",
    "# Filter df_Historic_mostrecent to include only the 'Pty Indice' present in df_snapshot_missing\n",
    "df_Historic_mostrecent_filtered = df_Historic_mostrecent[df_Historic_mostrecent['Pty Indice'].isin(df_snapshot_missing['Pty Indice'])]\n",
    "\n",
    "# Create a mapping of 'Pty Indice' to 'IDD Production Cost (unit)'\n",
    "production_cost_mapping = df_Historic_mostrecent_filtered.set_index('Pty Indice')['IDD Production Cost (unit)'].to_dict()\n",
    "\n",
    "# Update 'IDD Production Cost (unit)' in df_snapshot where 'Pty Indice' is in the production cost mapping\n",
    "df_snapshot.loc[df_snapshot['Pty Indice'].isin(production_cost_mapping.keys()), 'IDD Production Cost (unit)'] = df_snapshot['Pty Indice'].map(production_cost_mapping)\n",
    "\n",
    "# Print the number of rows updated\n",
    "print(f\"{len(df_snapshot[df_snapshot['Pty Indice'].isin(production_cost_mapping.keys())])} rows updated with production costs.\")\n",
    "############################\n",
    "# End WIP 09/17\n",
    "############################\n",
    "#--> \n",
    "\n",
    "#######################\n",
    "# Create column 'ROI'\n",
    "#######################\n",
    "#New code 07/25/24\n",
    "#'ROI' depend on the 'Production Status', the 'Product Category', IDD Marge Standard (unit) and 'Total critical Qty' which is 'Shipped' + 'Remain. crit. Qty'\n",
    "\n",
    "#Development Costs - Assuming no major problems:\n",
    "# 80 Engineering Man-hours-Irvine: $8000\n",
    "# 40 Engineering man-hours-Red:  $4000\n",
    "# Procurement: $600\n",
    "# FTB – routings, PBS, ATP/ATR, etc: $4000\n",
    "# Prototype First Time Build: $6000.\n",
    "\n",
    "#Define Engineering Cost based on 'Product Category' and 'Production Status'\n",
    "Engineering_cost_Proto_FTB_RED = 14600\n",
    "Engineering_cost_FTB_only_RED = 8600\n",
    "\n",
    "#######################################################################\n",
    "# The Engineering Cost depend on ['Production Effort'] from CM-Priority \n",
    "########################################################################\n",
    "# Define a function to determine Engineering Cost based on 'Production Effort'\n",
    "def determine_engineering_cost(production_effort):\n",
    "    if production_effort == 'Proto + FTB':\n",
    "        return Engineering_cost_Proto_FTB_RED\n",
    "    elif production_effort == 'FTB':\n",
    "        return Engineering_cost_FTB_only_RED\n",
    "    else:\n",
    "        \n",
    "        return 0  # Default value if no match\n",
    "\n",
    "########################################################################################################################\n",
    "# Expected ROI - Based on total Crit. Qty or backlog whatever is the biggest\n",
    "#######################################################################################################################\n",
    "##################################\n",
    "# Merge 'Critical Qty' from df_priority into df_snapshot\n",
    "##################################\n",
    "# Merge df_priority with df_snapshot\n",
    "df_snapshot = pd.merge(df_snapshot, df_priority[['Pty Indice', 'Critical Qty', 'Production Effort']], on='Pty Indice', how='left')\n",
    "\n",
    "# Display the updated df_snapshot\n",
    "#print(\"Updated df_snapshot with Production Effort:\")\n",
    "#display(df_snapshot)\n",
    "\n",
    "#########################################################################################################\n",
    "# Create 'IDD Manufacturing Cost (unit)' = 'IDD Production Cost (unit)' + 'IDD Engineering Cost (Unit)' \n",
    "##########################################################################################################\n",
    "# Ensure 'IDD Production Cost (unit)' is numeric\n",
    "df_snapshot['IDD Production Cost (unit)'] = pd.to_numeric(df_snapshot['IDD Production Cost (unit)'], errors='coerce')\n",
    "df_snapshot['Critical Qty'] = pd.to_numeric(df_snapshot['Critical Qty'], errors='coerce')\n",
    "\n",
    "# Define a function to calculate max_qty for each row\n",
    "def calculate_max_qty(row):\n",
    "    # Handle possible NaN values\n",
    "    critical_qty = row.get('Critical Qty', 0)\n",
    "    backlog_qty = row.get('IDD Backlog Qty', 0)\n",
    "    \n",
    "    return max(row['Critical Qty'], row['IDD Backlog Qty'])\n",
    "\n",
    "# Apply the function to calculate max_qty and add it as a new column\n",
    "df_snapshot['Max Qty'] = df_snapshot.apply(calculate_max_qty, axis=1)\n",
    "\n",
    "# Calculate 'Engineering Cost' and 'IDD Manufacturing Cost (unit)'\n",
    "df_snapshot.loc[:, 'Engineering Cost'] = df_snapshot['Production Effort'].apply(determine_engineering_cost)\n",
    "\n",
    "# Calculate 'IDD Manufacturing Cost (unit)' using the Max Qty\n",
    "#df_snapshot.loc[:, 'IDD Manufacturing Cost (unit)'] = df_snapshot['IDD Production Cost (unit)'] + (df_snapshot['Engineering Cost'] / df_snapshot['Max Qty'])\n",
    "\n",
    "# Convert columns to numeric, forcing errors to NaN\n",
    "df_snapshot['Engineering Cost'] = pd.to_numeric(df_snapshot['Engineering Cost'], errors='coerce')\n",
    "#df_snapshot['IDD Manufacturing Cost (unit)'] = pd.to_numeric(df_snapshot['IDD Production Cost (unit)'], errors='coerce')\n",
    "\n",
    "# Calculate total ROI directly\n",
    "def calculate_total_roi(row):\n",
    "    # Ensure Engineering Cost is not zero to avoid division by zero\n",
    "    if row['Engineering Cost'] != 0:\n",
    "        # Calculate ROI as a percentage\n",
    "        roi = (row['IDD Marge Standard (unit)'] * row['Max Qty']) / row['Engineering Cost'] * 100\n",
    "        return roi\n",
    "    else:\n",
    "        return None\n",
    "        \n",
    "# Apply the ROI calculation\n",
    "df_snapshot['IDD Expected ROI (Total)'] = df_snapshot.apply(calculate_total_roi, axis=1)\n",
    "\n",
    "# Format ROI to two decimal places and append a percentage sign, or 'N/A' for NaN\n",
    "df_snapshot['IDD Expected ROI (Total)'] = df_snapshot['IDD Expected ROI (Total)'].apply(\n",
    "    lambda x: f\"{round(x, 2)}%\" if pd.notna(x) else 'N/A'\n",
    ")\n",
    "\n",
    "# Remove 'Production Effort' and 'Engineering Cost' columns from df_snapshot\n",
    "#df_snapshot.drop(columns=['Production Effort', 'Engineering Cost'], errors='ignore', inplace=True)\n",
    "df_snapshot.drop(columns=['Production Effort', 'Max Qty'], errors='ignore', inplace=True)\n",
    "\n",
    "# Display the updated df_snapshot\n",
    "#print(\"Updated df_snapshot with ROI:\")\n",
    "#display(df_snapshot)\n",
    "\n",
    "#######################################################################\n",
    "# Create column 'Qty WIP' for each 'IDD Top-Level' from tab |CM-WIP|\n",
    "######################################################################\n",
    "#New code 07/30\n",
    "# Filter df_WIP where Level is 0\n",
    "df_WIP_filtered = df_WIP[df_WIP['Level'] == 0].copy()\n",
    "\n",
    "# Convert 'WO' to string\n",
    "df_WIP_filtered['WO'] = df_WIP_filtered['WO'].astype(str)\n",
    "\n",
    "# Replace string 'nan' with np.nan for better handling\n",
    "#df_WIP_filtered['WO'].replace('nan', np.nan, inplace=True) # Replaced 09/24 to avoid warning\n",
    "df_WIP_filtered['WO'] = df_WIP_filtered['WO'].replace('nan', np.nan) \n",
    "\n",
    "# Drop rows where 'WO' is NaN or empty\n",
    "df_WIP_filtered = df_WIP_filtered.dropna(subset=['WO'])\n",
    "df_WIP_filtered = df_WIP_filtered[df_WIP_filtered['WO'].str.strip() != '']\n",
    "\n",
    "# Drop rows where 'WO' contains 'NC'\n",
    "df_WIP_filtered = df_WIP_filtered[~df_WIP_filtered['WO'].str.contains('NC')]\n",
    "\n",
    "# Drop duplicate rows based on 'WO' + 'Pty Indice'\n",
    "df_WIP_filtered = df_WIP_filtered.drop_duplicates(subset=['WO', 'Pty Indice'])\n",
    "\n",
    "# Display 'Pty Indice' and 'WO' values in the filtered DataFrame\n",
    "#print('display df_WIP_filtered')\n",
    "#display(df_WIP_filtered[['Pty Indice', 'WO', 'Qty Ordered']])\n",
    "\n",
    "# Sum 'Qty Ordered' for each unique 'Pty Indice'\n",
    "df_WIP_aggregated = df_WIP_filtered.groupby('Pty Indice')['Qty Ordered'].sum().reset_index()\n",
    "\n",
    "# Rename 'Qty Ordered' to 'Qty WIP' for clarity\n",
    "df_WIP_aggregated.rename(columns={'Qty Ordered': 'Qty WIP'}, inplace=True)\n",
    "\n",
    "# Fill 'Qty WIP' with 0 when NaN - Does not work\n",
    "#df_WIP_aggregated['Qty WIP'].fillna(0, inplace=True) # # Replaced 09/24 to avoid warning\n",
    "df_WIP_aggregated['Qty WIP'] = df_WIP_aggregated['Qty WIP'].fillna(0)\n",
    "\n",
    "# Merge the aggregated data with df_snapshot\n",
    "df_snapshot = pd.merge(df_snapshot, df_WIP_aggregated, on='Pty Indice', how='left')\n",
    "\n",
    "# Fill 'Qty WIP' with 0 when NaN - Introduced 08/21\n",
    "#df_snapshot['Qty WIP'].fillna(0, inplace=True) # Replaced 09/24 to avoid warning\n",
    "df_snapshot['Qty WIP'] = df_snapshot['Qty WIP'].fillna(0)\n",
    "\n",
    "# Print the results\n",
    "#print('df_WIP_filtered including only unique WO+Pty Indice without NC:')\n",
    "#display(df_WIP_filtered)\n",
    "\n",
    "#print('df_WIP_aggregated with summed Qty WIP for unique WO+Pty Indice per IDD Top Level:')\n",
    "#display(df_WIP_aggregated)\n",
    "\n",
    "#New 08/14\n",
    "############################################################################################\n",
    "# Create column 'Program' with mapping from df_Priority on Pty Indice\n",
    "#############################################################################################\n",
    "program_mapping = df_Priority.set_index('Pty Indice')['Program'].to_dict()\n",
    "df_snapshot['Program'] = df_snapshot['Pty Indice'].map(program_mapping)\n",
    "\n",
    "#print('df_snapshot BEFORE inclding new columns')\n",
    "#display(df_snapshot)\n",
    "\n",
    "#New 08/22\n",
    "###################################################################################################################################################\n",
    "# Create column 'Avg Expected Time (unit)', 'Avg Actual Time (unit)', 'WO_Count' and 'Actual vs Expected time (%)' based on |CM-MakeArchitecture|\n",
    "####################################################################################################################################################\n",
    "# Create df_MakeArchi from df_Make_architure_final_sorted\n",
    "df_MakeArchi = df_Make_architure_final_sorted.copy()\n",
    "\n",
    "# The 'BOM Qty' needs to be taken into account in the calculation 'Avg Actual Time (unit)[hour]'*'BOM Qty'* for a given 'IDD Component'\n",
    "# Group by 'Pty Indice' and calculate the required aggregations\n",
    "df_aggregated_MakeArchi = df_MakeArchi.groupby('Pty Indice').agg(\n",
    "    Max_Expected_Time=('Max Expected Time (unit)[hour]', 'sum'), \n",
    "    Sum_Weighted_Actual_Time=('Avg Actual Time (unit)[hour]', lambda x: (x * df_MakeArchi.loc[x.index, 'BOM Qty']).sum()),\n",
    "    WO_Count=('WO_Count', 'sum'),\n",
    "    Max_Standard_dev=('Standard Deviation [hour]', 'max'),  #New 08/26\n",
    ").reset_index()\n",
    "\n",
    "# Rename columns to match the desired format\n",
    "df_aggregated_MakeArchi.rename(columns={\n",
    "    'Max_Expected_Time': 'Max Expected Time (full ASSY)[hour]',\n",
    "    'Sum_Weighted_Actual_Time': 'Avg Actual Time (full ASSY)[hour]',\n",
    "    'Max_Standard_dev': 'Max Standard Deviation [hour]', #New 08/26\n",
    "    'WO_Count': 'Total WO Count',\n",
    "}, inplace=True)\n",
    "\n",
    "# Round the 'Max Expected Time (unit)' and 'Avg Actual Time (unit)' columns to 2 decimal places\n",
    "df_aggregated_MakeArchi['Max Expected Time (full ASSY)[hour]'] = df_aggregated_MakeArchi['Max Expected Time (full ASSY)[hour]'].round(2)\n",
    "df_aggregated_MakeArchi['Avg Actual Time (full ASSY)[hour]'] = df_aggregated_MakeArchi['Avg Actual Time (full ASSY)[hour]'].round(2)\n",
    "\n",
    "#print('df_aggregated_MakeArchi')\n",
    "#display(df_aggregated_MakeArchi)\n",
    "\n",
    "# Merge aggregated data into df_MakeArchi\n",
    "df_snapshot = df_snapshot.merge(\n",
    "    df_aggregated_MakeArchi,\n",
    "    on='Pty Indice',\n",
    "    how='left',\n",
    "    suffixes=('', '_aggregated')\n",
    ")\n",
    "\n",
    "\n",
    "# Update 09/25\n",
    "df_snapshot['Actual vs Standard time [%]'] = np.where(\n",
    "    df_snapshot['Max Expected Time (full ASSY)[hour]'].fillna(0) == 0,\n",
    "    'N/A',  # Handle division by zero\n",
    "    (\n",
    "        (((df_snapshot['Avg Actual Time (full ASSY)[hour]'] / \n",
    "           df_snapshot['Max Expected Time (full ASSY)[hour]']) - 1) * 100)\n",
    "        .replace([np.inf, -np.inf], np.nan)  # Replace infinity values\n",
    "        .fillna(0)  # Replace NaN values with 0\n",
    "        .round(0)  # Round the result\n",
    "        .astype(int)  # Convert to integer\n",
    "        .astype(str) + '%'  # Convert to string and append '%'\n",
    "    )\n",
    ")\n",
    "\n",
    "# New 09/25 \n",
    "# Fill 'Max Standard Deviation [hour]' with 0 if empty and 'Total WO Count' = 1\n",
    "df_snapshot['Max Standard Deviation [hour]'] = np.where((df_snapshot['Max Standard Deviation [hour]'].isna()) & (df_snapshot['Total WO Count'] == 1), 0, df_snapshot['Max Standard Deviation [hour]']) # Keep the original values if condition not met\n",
    "\n",
    "\n",
    "# Print the final DataFrame to verify results\n",
    "#print('df_snapshot')\n",
    "#display(df_snapshot)\n",
    "\n",
    "########################################################\n",
    "# New 09/24 -  Create new column 'Deviation vs Actual [%]'\n",
    "########################################################\n",
    "df_snapshot['Deviation vs Actual [%]'] = np.where(\n",
    "    df_snapshot['Max Standard Deviation [hour]'].fillna(0) == 0, \n",
    "    'N/A',  # Handle division by zero\n",
    "    (\n",
    "        ((df_snapshot['Max Standard Deviation [hour]'] / \n",
    "           df_snapshot['Avg Actual Time (full ASSY)[hour]']) * 100)\n",
    "        .replace([np.inf, -np.inf], np.nan)  # Replace infinity values\n",
    "        .fillna(0)  # Replace NaN values with 0\n",
    "        .round(0)  # Round the result\n",
    "        .astype(int)  # Convert to integer\n",
    "        .astype(str) + '%'  # Convert to string and append '%'\n",
    "    )\n",
    ")\n",
    "\n",
    "#New 09/20\n",
    "#######################################################################################################################################################################################\n",
    "# Create news columns 'Gap Actual vs Standard [USD]', 'IDD Corrected Margin Standard (unit)[USD]', 'IDD Corrected Cost [USD]' & 'IDD Corrected Margin [%]' \n",
    "# based on the Direct labor rate, Burden (indirect rate) = Fully burdened rate\n",
    "####################################################################################################################################################################################\n",
    "# To calculate the impact in USD of the differences between standard time and actual time, the formula is: (Actual time − Standard time) × labor + burden rate (Actual time−Standard time)×labor + burden rate\n",
    "# The rate usually depends on where the part is produced. For example, if it's produced in the 6444 location, the CPA rate applies, but for other locations, there will be a different rate.\n",
    "# By default, let's use the global rate for Redmond, which is $79.58 for 2024 : Direct labor rate: $41.20, Burden (indirect rate): $38.38, Fully burdened rate: $79.58.\n",
    "################################################################################################################################################################################\n",
    "# df_snapshot['Max Expected Time (full ASSY)[hour]'] represents the most recent 'Standard Time' of the full ASSY \n",
    "# df_snapshot['Avg Actual Time (full ASSY)[hour]'] represents the all time AVG 'Actual Time' with the filtering function applied; abberante values has been filtered-out \n",
    "# df_snapshot['IDD Production Cost (unit)'] represents the current labor cost used to calculate the Margin  \n",
    "# df_snapshot['IDD Sale Price'] represents the sales price \n",
    "\n",
    "# Fully_Burden_Rate_2024 represents the labor cost - Define the Fully burdened rate in USD\n",
    "Fully_Burden_Rate_2024 = 79.58\n",
    "\n",
    "# Calculate df_snapshot['Gap Actual vs Standard [USD]'] =  (df_snapshot['Avg Actual Time (full ASSY)[hour]'] - df_snapshot['Max Expected Time (full ASSY)[hour]'])*Fully_Burden_Rate_2024\n",
    "df_snapshot['Gap Actual vs Standard [USD]'] = (\n",
    "    df_snapshot['Avg Actual Time (full ASSY)[hour]'] - df_snapshot['Max Expected Time (full ASSY)[hour]']\n",
    ") * Fully_Burden_Rate_2024\n",
    "\n",
    "# Calculate df_snapshot['IDD Corrected Cost [USD]'] = df_snapshot['IDD Production Cost (unit)'] + df_snapshot['Gap Actual vs Standard [USD]'] \n",
    "df_snapshot['IDD Corrected Cost [USD]'] = (\n",
    "    df_snapshot['IDD Production Cost (unit)'] + df_snapshot['Gap Actual vs Standard [USD]']\n",
    ")\n",
    "\n",
    "# Calculate df_snapshot['IDD Corrected Margin Standard (unit)[USD]'] = df_snapshot['IDD Sale Price'] - df_snapshot['IDD Corrected Cost [USD]']\n",
    "df_snapshot['IDD Corrected Margin Standard (unit) [USD]'] = (\n",
    "    df_snapshot['IDD Sale Price'] - df_snapshot['IDD Corrected Cost [USD]']\n",
    ")\n",
    "\n",
    "#Calculate  df_snapshot['IDD Corrected Margin [%]'] = df_snapshot['IDD Sale Price'] - df_snapshot['IDD Corrected Cost [USD]'] with handling for division by zero - Updated 08/16, this return inacurates values\n",
    "df_snapshot['IDD Corrected Margin [%]'] = df_snapshot.apply(\n",
    "    lambda row: round(row['IDD Corrected Margin Standard (unit) [USD]'] / row['IDD Sale Price'], 3) \n",
    "    if row['IDD Sale Price'] != 0 else None, \n",
    "    axis=1\n",
    ")\n",
    "\n",
    "# Convert any `-0` to `0`\n",
    "df_snapshot['IDD Corrected Margin [%]'] = df_snapshot['IDD Corrected Margin [%]'].apply(lambda x: 0 if x == -0 else x)\n",
    "\n",
    "# Format '% Margin' as a percentage string with a '%' sign \n",
    "df_snapshot['IDD Corrected Margin [%]'] = df_snapshot['IDD Corrected Margin [%]'].apply(\n",
    "    lambda x: f\"{x * 100:.2f}%\" if pd.notna(x) else 'N/A'\n",
    ")\n",
    "\n",
    "\n",
    "# Round and add $ sign to 'Gap Actual vs Standard [USD]', 'IDD Corrected Cost [USD]', 'IDD Corrected Margin Standard (unit) [USD]'\n",
    "df_snapshot['Gap Actual vs Standard [USD]'] = df_snapshot['Gap Actual vs Standard [USD]'].apply(lambda x: f\"${round(x, 2):,.2f}\" if pd.notna(x) else 'N/A')\n",
    "df_snapshot['IDD Corrected Cost [USD]'] = df_snapshot['IDD Corrected Cost [USD]'].apply(lambda x: f\"${round(x, 2):,.2f}\" if pd.notna(x) else 'N/A')\n",
    "df_snapshot['IDD Corrected Margin Standard (unit) [USD]'] = df_snapshot['IDD Corrected Margin Standard (unit) [USD]'].apply(lambda x: f\"${round(x, 2):,.2f}\" if pd.notna(x) else 'N/A')\n",
    "\n",
    "\n",
    "######################################################################################################################\n",
    "## New 09/23                                                                                     #####################\n",
    "######################################################################################################################\n",
    "# --> Updated 09/23 to use df_Historic instead of df_Snapshot to calculate the 'Realized sales' and 'Realized Margin' \n",
    "# The calculation should be based on the real data from the df_Historic trunover Report including the change of price over time \n",
    "# Need to create 'IDD AVG realized sales price [USD]' & ['IDD AVG realized Margin[%]']\n",
    "######################################################################################################################\n",
    "# df_snapshot['IDD AVG realized sales price [USD]'] = Average of (df_Historic['Currency turnover ex.VAT']/df_Historic['Quantity']) for a given Pty Indice \n",
    "# df_snapshot['IDD AVG realized Margin Standard [USD]'] = Average of (df_Historic['Currency turnover ex.VAT'] - df_Historic['Standard amount USD'])/['Quantity']\n",
    "# df_snapshot['IDD AVG realized Margin [%]'] = df_snapshot['IDD AVG realized Margin Standard [USD]']/['IDD AVG realized sales price [USD]']*100\n",
    "\n",
    "# 1. Filter out rows where 'Order' contains 'NC'\n",
    "df_Historic_filtered = df_Historic[~df_Historic['Order'].str.contains('NC', na=False)].copy()\n",
    "\n",
    "# 2. Calculate the average realized sales price for each 'Pty Indice'\n",
    "df_Historic_filtered.loc[:, 'Realized Sales Price [USD]'] = df_Historic_filtered['Currency turnover ex.VAT'] / df_Historic_filtered['Quantity']\n",
    "avg_realized_sales_price = df_Historic_filtered.groupby('Pty Indice')['Realized Sales Price [USD]'].mean().reset_index()\n",
    "\n",
    "# 3. Calculate the average realized margin standard [USD]\n",
    "df_Historic_filtered.loc[:, 'Realized Margin Standard [USD]'] = (\n",
    "    (df_Historic_filtered['Currency turnover ex.VAT'] - df_Historic_filtered['Standard amount USD']) / df_Historic_filtered['Quantity']\n",
    ")\n",
    "avg_realized_margin_standard = df_Historic_filtered.groupby('Pty Indice')['Realized Margin Standard [USD]'].mean().reset_index()\n",
    "\n",
    "# 4. Merge the average sales price and margin back to df_snapshot\n",
    "df_snapshot = df_snapshot.merge(avg_realized_sales_price, on='Pty Indice', how='left')\n",
    "df_snapshot = df_snapshot.merge(avg_realized_margin_standard, on='Pty Indice', how='left')\n",
    "\n",
    "# Rename columns for clarity\n",
    "df_snapshot.rename(columns={\n",
    "    'Realized Sales Price [USD]': 'IDD AVG realized sales price [USD]',\n",
    "    'Realized Margin Standard [USD]': 'IDD AVG realized Margin Standard [USD]'\n",
    "}, inplace=True)\n",
    "\n",
    "# 5. Calculate the realized margin [%]\n",
    "df_snapshot['IDD AVG realized Margin [%]'] = (\n",
    "    df_snapshot['IDD AVG realized Margin Standard [USD]'] / df_snapshot['IDD AVG realized sales price [USD]'] * 100\n",
    ").fillna(0)  # Fill NaN with 0 if there's no sales price\n",
    "\n",
    "# 6. Format the results\n",
    "df_snapshot['IDD AVG realized sales price [USD]'] = df_snapshot['IDD AVG realized sales price [USD]'].apply(lambda x: f\"${round(x, 2):,.2f}\" if pd.notna(x) else 'N/A')\n",
    "df_snapshot['IDD AVG realized Margin Standard [USD]'] = df_snapshot['IDD AVG realized Margin Standard [USD]'].apply(lambda x: f\"${round(x, 2):,.2f}\" if pd.notna(x) else 'N/A')\n",
    "df_snapshot['IDD AVG realized Margin [%]'] = df_snapshot['IDD AVG realized Margin [%]'].apply(lambda x: f\"{round(x, 2):,.2f}%\" if pd.notna(x) else 'N/A')\n",
    "\n",
    "\n",
    "######################################################################################################################\n",
    "# New 10/14 - Update 'Remain. crit. Qty' if different from |CM-Priority| in order consider the unit shipped recently. \n",
    "# 'Remain. crit. Qty' is set based on |CM-Inventory| which won't be update until the new generation of inputs\n",
    "# To have a corrected 'Remain. crit. Qty'  in |Snapshot|, the value has to be update based on |CM-priority|\n",
    "######################################################################################################################\n",
    "# Create a mapping from on 'Pty Indice' with the updated |CM-Priority|\n",
    "remaining_qty_mapping = df_Priority.set_index('Pty Indice')['Remain. crit. Qty'].to_dict()\n",
    "\n",
    "# Update 'Remain. crit. Qty' only if different from the current value in df_snapshot\n",
    "df_snapshot['Remain. crit. Qty'] = df_snapshot.apply(\n",
    "    lambda row: remaining_qty_mapping.get(row['Pty Indice'], row['Remain. crit. Qty']) \n",
    "    if row['Remain. crit. Qty'] != remaining_qty_mapping.get(row['Pty Indice'], row['Remain. crit. Qty']) \n",
    "    else row['Remain. crit. Qty'], axis=1\n",
    ")\n",
    "\n",
    "#***********************************************************************************************************\n",
    "######################################################################################################################\n",
    "### *** 4 PN rule maximum: Rule to be applied to both 'Start target date' & 'Industrialization target date' ***\n",
    "####################################################################################################################\n",
    "#***********************************************************************************************************\n",
    "#########################\n",
    "# Sort the final dataframe by 'Pty Indice' and 'Priority'\n",
    "#########################\n",
    "df_snapshot = df_snapshot.sort_values(by=['Priority','Pty Indice'])\n",
    "\n",
    "#####################################################\n",
    "#########   Creating SNAPSHOT    ####################\n",
    "#####################################################\n",
    "# Check if \"Snapshot\" sheet already exists\n",
    "if \"Snapshot\" in workbook.sheetnames:\n",
    "    # Remove the existing \"Snapshot\" sheet\n",
    "    workbook.remove(workbook[\"Snapshot\"])\n",
    "\n",
    "# Create a new \"snapshot\" sheet\n",
    "snapshot_sheet = workbook.create_sheet(title='Snapshot', index=0)  # Add as the 1st sheet (index 0)\n",
    "\n",
    "# Write headers\n",
    "for c_idx, header in enumerate(df_snapshot.columns, start=1):\n",
    "   snapshot_sheet.cell(row=1, column=c_idx, value=header)\n",
    "\n",
    "# Write data\n",
    "for r_idx, row in enumerate(df_snapshot.values, start=2):  # Start from row 2\n",
    "    for c_idx, value in enumerate(row, start=1):\n",
    "       snapshot_sheet.cell(row=r_idx, column=c_idx, value=value)\n",
    "\n",
    "# Save the updated workbook\n",
    "workbook.save(original_input)\n",
    "# Close the workbook\n",
    "workbook.close()\n",
    "\n",
    "print(f\"Snapshot added successfully as |Snapshot| in {original_input}\")\n",
    "\n",
    "\n",
    "#*********************************************************************************************************************************************\n",
    "# UPDATE of CM-Priority based of SUMMARY and SNAPSHOT\n",
    "#*********************************************************************************************************************************************\n",
    "#sheet_CTB =  workbook['Clear-to-Build']\n",
    "#sheet_snapshot =  workbook['Snapshot']\n",
    "#####################################################################\n",
    "### Filling |Clear to build| from CM-Priority column based on SUMARRY \n",
    "#####################################################################\n",
    "# Fill Top Level sharing component\n",
    "\n",
    "#####################################################################\n",
    "### Filling |Clear to build| from CM-Priority column based on SNAPSHOT \n",
    "#####################################################################\n",
    "#Fill Clear to build & Start date target \n",
    "#print(f\"CM-Priority successfully updated in based on |Summary| and  |Snapshot| in {original_input}\")\n",
    "\n",
    "#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n",
    "########################################################################################################################\n",
    "####################                 --->>> FORMATING  SUMMARY & SNAPSHOT                          ######################\n",
    "#######################################################################################################################\n",
    "#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n",
    "##### load the formatted workbook\n",
    "workbook = load_workbook(original_input) \n",
    "# Define sheet_summary\n",
    "sheet_summary =  workbook['Summary']\n",
    "max_row_CTB = sheet_summary.max_row\n",
    "\n",
    "######################################\n",
    "###Formatting tab 1 sheet_summary  ###\n",
    "######################################\n",
    "# Last update column P\n",
    "content_P_CTB = {\n",
    "    1: \"Last update\",\n",
    "    2: file_date_inventory,  # Using the datetime object directly\n",
    "    3: \"Summary report: Based on IDD's Inventory & existing BOM\"\n",
    "}\n",
    "\n",
    "# Write the date to a specific cell\n",
    "sheet_summary.cell(row=1, column=16, value='Last Update')  # P2 cell\n",
    "sheet_summary.cell(row=2, column=16, value=file_date_inventory)  # P2 cell\n",
    "\n",
    "# Set column widths and text alignment for columns A to O)\n",
    "for column in sheet_summary.iter_cols(min_col=1, max_col=15):\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "    \n",
    "    column_letter = column[0].column_letter\n",
    "    if column_letter in ['A', 'C', 'D', 'E','I','J','K','L','M', 'N']:\n",
    "        sheet_summary.column_dimensions[column_letter].width = 20\n",
    "    elif column_letter in ['B','H', 'O']:\n",
    "        sheet_summary.column_dimensions[column_letter].width = 30\n",
    "    elif column_letter in ['Q']:\n",
    "        sheet_summary.column_dimensions[column_letter].width = 35\n",
    "    else:\n",
    "        sheet_summary.column_dimensions[column_letter].width = 10\n",
    "\n",
    "    # Apply alignment and border to cells in the current column\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "\n",
    "# Set column widths and text alignment for columns P\n",
    "for column in sheet_summary.iter_cols(min_col=16, max_col=16):\n",
    "    for cell in column:\n",
    "        cell.alignment = Alignment(horizontal='left' if cell.row == 1 else 'center', vertical='center')\n",
    "    \n",
    "    if column[0].column_letter == 'P':\n",
    "        sheet_summary.column_dimensions['P'].width = 15\n",
    "\n",
    "# Set left alignment for column O\n",
    "for row in sheet_summary.iter_rows(min_row=1, max_row=sheet_summary.max_row, min_col=15, max_col=15):  # Column O is the 15th column\n",
    "    for cell in row:\n",
    "        cell.alignment = Alignment(horizontal='right')\n",
    "        \n",
    "# Set column width and text alignment for column P from row 3\n",
    "for cell in sheet_summary.iter_rows(min_row=3, min_col=16, max_col=16):\n",
    "    cell[0].alignment = Alignment(horizontal='left', vertical='center')\n",
    "\n",
    "# Apply borders for rows 1 and 2 in column P\n",
    "for row in range(1, 3):\n",
    "    sheet_summary.cell(row=row, column=16).border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "# Apply conditional formatting for 'Max Qty (GS)' column when equal to 0\n",
    "# Define the red fill pattern\n",
    "fill_red = PatternFill(start_color='FFC7CE', end_color='FFC7CE', fill_type='solid')\n",
    "\n",
    "# Loop through the rows starting from row 2 to max_row_CTB\n",
    "for row in range(2, max_row_CTB + 1):  # Assuming data starts from row 2\n",
    "    max_qty_cell = sheet_summary.cell(row=row, column=13)  # 'Max Qty (GS)' is in column 13\n",
    "    if max_qty_cell.value == 0:\n",
    "        # Apply red fill to the 'Max Qty (GS)' cell\n",
    "        max_qty_cell.fill = fill_red\n",
    "        # Apply red fill to the cell in 'idd_component' column, which is column 5\n",
    "        idd_component_cell = sheet_summary.cell(row=row, column=5)\n",
    "        idd_component_cell.fill = fill_red\n",
    "\n",
    "#######################################################################################################\n",
    "### Apply conditional formatting for 'Make Part' & 'Make Part CUU' in 'Supplier' column - Upadte 09/20\n",
    "#######################################################################################################\n",
    "# Define light grey fill\n",
    "fill_grey = PatternFill(start_color='E0E0E0', end_color='E0E0E0', fill_type='solid')\n",
    "\n",
    "# Apply conditional formatting for 'Make Part' in 'Supplier' column (columns B to O)\n",
    "for row in range(2, max_row_CTB + 1):  # Assuming data starts from row 2\n",
    "    supplier_cell = sheet_summary.cell(row=row, column=2)  # Assuming 'Supplier' column is in column B (2)\n",
    "    if supplier_cell.value and 'Make Part' in supplier_cell.value:\n",
    "        for col in range(2, 15):  # Columns B to O (2 to 15)\n",
    "            cell = sheet_summary.cell(row=row, column=col)\n",
    "            cell.fill = fill_grey\n",
    "            \n",
    "##########################################################################\n",
    "# Apply conditional formatting for row dedicated to Top-Level (Level = 0)\n",
    "##########################################################################\n",
    "# Define fill color for Top-Level\n",
    "fill_TopLevel = PatternFill(start_color='5B9BD5', end_color='5B9BD5', fill_type='solid')  # Blue fill\n",
    "\n",
    "# Define font colors\n",
    "font_color_clear = \"FFFFFF\"  # White\n",
    "font_color_shortage = \"C00000\"  # Dark Red\n",
    "font_color_fullyClear = \"24CA77\"  # Green\n",
    "\n",
    "# Define thick border\n",
    "thick_border = Border(\n",
    "    top=Side(style='thick'),\n",
    "    bottom=Side(style='thick')\n",
    ")\n",
    "\n",
    "# Iterate through each row in the sheet\n",
    "for row in range(2, max_row_CTB + 1):\n",
    "    cell_level = sheet_summary.cell(row=row, column=6)  # Assuming 'Level' is in column 6 (F)\n",
    "    cell_max_qty = sheet_summary.cell(row=row, column=14)  # Assuming 'Max Qty Top-Level' is in column 14 (N)\n",
    "    cell_remain_crit_qty = sheet_summary.cell(row=row, column=12)  # Assuming 'Remain. crit. Qty' is in column 12 (L)\n",
    "    \n",
    "    if cell_level.value == 0:\n",
    "        # Determine the font color based on the value of 'Max Qty Top-Level' and 'Remain. crit. Qty'\n",
    "        font_color = font_color_clear  # Default font color\n",
    "        if cell_max_qty.value is not None and cell_remain_crit_qty.value is not None:\n",
    "            if cell_max_qty.value >= cell_remain_crit_qty.value:\n",
    "                font_color = font_color_fullyClear\n",
    "            elif cell_max_qty.value > 0:\n",
    "                font_color = font_color_clear\n",
    "            elif cell_max_qty.value == 0:\n",
    "                font_color = font_color_shortage\n",
    "\n",
    "        # Apply fill color, font color, bold, and border to each cell in the row\n",
    "        for col in range(1, 16):\n",
    "            cell = sheet_summary.cell(row=row, column=col)\n",
    "            cell.fill = fill_TopLevel\n",
    "            cell.font = Font(color=font_color, bold=True)\n",
    "            cell.border = thick_border\n",
    "\n",
    "#########################################################\n",
    "# Applying formating to most critical shortage component \n",
    "#######################################################\n",
    "light_purple_fill = PatternFill(start_color='E4DFEC', end_color='E4DFEC', fill_type='solid')\n",
    "\n",
    "# 'Max Qty (GS)' column M, 'Max Qty Top-Level' column N --> Apply purple fill from column B to column M\n",
    "for row in range(2, max_row_CTB + 1):\n",
    "    max_qty_gs = sheet_summary.cell(row=row, column=13).value\n",
    "    max_qty_top_level = sheet_summary.cell(row=row, column=14).value\n",
    "\n",
    "    # Update 08/08\n",
    "    ''' \n",
    "    if max_qty_gs == max_qty_top_level and max_qty_top_level > 0:\n",
    "        for col in range(2, 14):  # Columns B to M (2 to 13)\n",
    "            cell = sheet_summary.cell(row=row, column=col)\n",
    "            cell.fill = light_purple_fill  # Assuming green_fill is defined earlier\n",
    "    '''\n",
    "    if max_qty_gs is not None and max_qty_top_level is not None and max_qty_gs == max_qty_top_level and max_qty_top_level > 0:\n",
    "        for col in range(2, 14):  # Columns B to M (2 to 13)\n",
    "            cell = sheet_summary.cell(row=row, column=col)\n",
    "            cell.fill = light_purple_fill  # Assuming green_fill is defined earlier\n",
    "        \n",
    "######################################################################################\n",
    "# Custom conditional formatting for column F 'Level' (Assuming data starts from row 2)\n",
    "#####################################################################################\n",
    "min_row = 2\n",
    "col_F = 6\n",
    "\n",
    "# Initialize fill_color outside of the loop\n",
    "fill_color = None\n",
    "font_color_black = \"000000\"  # Black\n",
    "\n",
    "# Iterate through each row in the specified range\n",
    "for row in range(min_row, max_row_CTB + 1):\n",
    "    cell_value = sheet_summary.cell(row=row, column=col_F).value\n",
    "    \n",
    "    # Apply fill color based on the 'Level' value\n",
    "    if cell_value is not None:\n",
    "        if cell_value == 0:\n",
    "            fill_color = '63BE7B'  # Green\n",
    "        elif cell_value == 1:\n",
    "            fill_color = 'A2C075'  # Lighter Green\n",
    "        elif cell_value == 2:\n",
    "            fill_color = 'FFEB84'  # Yellow\n",
    "        elif cell_value == 3:\n",
    "            fill_color = 'FFD166'  # Orange\n",
    "        elif cell_value == 4:\n",
    "            fill_color = 'F88E5B'  # Darker Orange\n",
    "        elif cell_value == 5:\n",
    "            fill_color = 'F8696B'  # Red\n",
    "        elif cell_value == 6:\n",
    "            fill_color = '8B0000'  # Darker Red\n",
    "    else:\n",
    "        fill_color = None  # Reset fill_color when cell value is None\n",
    "            \n",
    "    # Apply font color to column F (Level) in each row\n",
    "    sheet_summary.cell(row=row, column=col_F).font = Font(color=font_color_black, bold=False)\n",
    "        \n",
    "    # Check if fill_color is not None before applying PatternFill\n",
    "    if fill_color is not None:\n",
    "        fill = PatternFill(start_color=fill_color, end_color=fill_color, fill_type='solid')\n",
    "        sheet_summary.cell(row=row, column=col_F).fill = fill\n",
    "\n",
    "###################################################################\n",
    "### Apply conditional formatting for 'Top-Level Status' column\n",
    "###################################################################\n",
    "fill_green = PatternFill(start_color='C6EFCE', end_color='C6EFCE', fill_type='solid')  # Green fill\n",
    "fill_red = PatternFill(start_color='FFC7CE', end_color='FFC7CE', fill_type='solid')   # Red fill\n",
    "fill_dark_green = PatternFill(start_color='6FAC46', end_color='6FAC46', fill_type='solid')   # Dark green fill\n",
    "fill_orange = PatternFill(start_color='ED7D31', end_color='ED7D31', fill_type='solid')   # orange fill\n",
    "\n",
    "for row in range(2, max_row_CTB + 1):\n",
    "    cell = sheet_summary.cell(row=row, column=1)  # Assuming 'Top-Level Status' is in column 1 (A)\n",
    "    if cell.value == 'Clear-to-Build':\n",
    "        cell.fill = fill_green\n",
    "    if cell.value == 'Completed - No Backlog':\n",
    "        cell.fill = fill_dark_green\n",
    "    if cell.value == 'Not completed - No Backlog':\n",
    "        cell.fill = fill_orange\n",
    "    elif cell.value == 'Shortage':\n",
    "        cell.fill = fill_red\n",
    "        \n",
    "###################################################################\n",
    "# Set background color for cell P2 and P3 left align\n",
    "###################################################################\n",
    "sheet_summary.cell(row=2, column=16).fill = PatternFill(start_color='E2EFDA', end_color='E2EFDA', fill_type='solid')\n",
    "\n",
    "################################################################################################\n",
    "# Create a new column [Comment] to identified potential interesting fact for a given component\n",
    "###############################################################################################\n",
    "#New 08/30 - Integrate a column 'BOM Index' \n",
    "# Step 1: Create a dictionary to map IDD Component to Inventory Status and Qty On Hand\n",
    "idd_to_inventory_status_qty = {row['IDD Component']: (row['Inventory Status'], int(row['Qty On Hand']))\n",
    "                               for _, row in Inventory.iterrows()}\n",
    "\n",
    "# Step 2: Merge df_summary_sorted with CM_BOM to get the BOM Index\n",
    "df_summary_sorted_with_bom_index = df_summary_sorted.merge(\n",
    "    CM_BOM[['IDD Component', 'Pty Indice', 'BOM Index']],\n",
    "    on=['IDD Component', 'Pty Indice'],\n",
    "    how='left'\n",
    ")\n",
    "\n",
    "# Define the starting column index and headers for the [Comment] and [BOM Index] columns\n",
    "comment_start_column_index = sheet_summary.max_column + 1  # Place the comment column to the right of the last column\n",
    "bom_index_column_index = comment_start_column_index + 1    # Place the BOM Index column right after the comment column\n",
    "comment_header = 'Comment'\n",
    "bom_index_header = 'BOM Index'\n",
    "\n",
    "# Step 3: Iterate through df_summary_sorted_with_bom_index to populate comments and BOM Index\n",
    "comments = []\n",
    "bom_indices = []\n",
    "for idx, row in df_summary_sorted_with_bom_index.iterrows():\n",
    "    idd_component = row['IDD Component']\n",
    "    if idd_component in idd_to_inventory_status_qty:\n",
    "        inventory_status, qty_on_hand = idd_to_inventory_status_qty[idd_component]\n",
    "        if inventory_status in ['R-INSP', 'RTV', 'MRB']:\n",
    "            comment = f\"({qty_on_hand}) component(s) in inventory, status: {inventory_status}\"\n",
    "        else:\n",
    "            comment = \"\"\n",
    "    else:\n",
    "        comment = \"\"\n",
    "    comments.append(comment)\n",
    "    \n",
    "    # Get the BOM Index from the merged DataFrame\n",
    "    bom_index = row['BOM Index'] if not pd.isna(row['BOM Index']) else \"\"\n",
    "    bom_indices.append(bom_index)\n",
    "\n",
    "# Step 4: Write comments and BOM Index to their respective columns in sheet_summary\n",
    "# Write the headers first\n",
    "sheet_summary.cell(row=1, column=comment_start_column_index, value=comment_header)\n",
    "sheet_summary.cell(row=1, column=bom_index_column_index, value=bom_index_header)\n",
    "\n",
    "# Write comments and BOM Index for each row\n",
    "for idx, (comment, bom_index) in enumerate(zip(comments, bom_indices)):\n",
    "    comment_cell = sheet_summary.cell(row=idx + 2, column=comment_start_column_index)\n",
    "    bom_index_cell = sheet_summary.cell(row=idx + 2, column=bom_index_column_index)\n",
    "    \n",
    "    comment_cell.value = comment.strip()  # Remove trailing whitespace\n",
    "    bom_index_cell.value = bom_index\n",
    "    \n",
    "    # Align the text in the comment and BOM Index cells to center\n",
    "    comment_cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)\n",
    "    bom_index_cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)\n",
    "\n",
    "    # Set border for the comment and BOM Index cells\n",
    "    comment_cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "    bom_index_cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "# Step 5: Set column widths and text alignment for 'Comment' and 'BOM Index' columns\n",
    "column_Q_width = 40\n",
    "column_R_width = 20  # Set this to a width appropriate for BOM Index\n",
    "for row in sheet_summary.iter_rows(min_row=1, max_row=max_row_CTB, min_col=comment_start_column_index, max_col=bom_index_column_index):\n",
    "    for cell in row:\n",
    "        # Set alignment to center\n",
    "        cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        # Set width for column Q ('Comment')\n",
    "        if cell.column_letter == sheet_summary.cell(row=1, column=comment_start_column_index).column_letter:\n",
    "            sheet_summary.column_dimensions[cell.column_letter].width = column_Q_width\n",
    "        # Set width for column R ('BOM Index')\n",
    "        elif cell.column_letter == sheet_summary.cell(row=1, column=bom_index_column_index).column_letter:\n",
    "            sheet_summary.column_dimensions[cell.column_letter].width = column_R_width\n",
    "\n",
    "# Display or further process df_summary_with_top_level\n",
    "#display(df_summary_with_top_level)\n",
    "\n",
    "######################################################################################################\n",
    "# Apply formatting to the header row\n",
    "header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')\n",
    "header_font = Font(color='FFFFFF', bold=True)\n",
    "header_alignment = Alignment(horizontal='left', vertical='center')\n",
    "header_border = Border(\n",
    "    top=Side(style='medium'),\n",
    "    bottom=Side(style='medium'),\n",
    "    left=Side(style='medium'),\n",
    "    right=Side(style='medium')\n",
    ")\n",
    "\n",
    "for cell in sheet_summary[1]:\n",
    "    cell.fill = header_fill\n",
    "    cell.font = header_font\n",
    "    cell.alignment = header_alignment\n",
    "    cell.border = header_border\n",
    "\n",
    "# Add filters to the first row of the sheet_summary worksheet\n",
    "sheet_summary.auto_filter.ref = sheet_summary.dimensions\n",
    "\n",
    "######################################################################################\n",
    "#***********************************************************************************\n",
    "# Formatting SNAPSHOT  \n",
    "#***********************************************************************************\n",
    "####################################################################################\n",
    "# Define sheet_snapshot\n",
    "sheet_snapshot =  workbook['Snapshot']\n",
    "max_row_snapshot = sheet_snapshot.max_row\n",
    "\n",
    "###################################\n",
    "###Formatting tab 1 Snapshot  \n",
    "##################################\n",
    "# Apply formatting to the header row\n",
    "header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')\n",
    "header_font = Font(color='FFFFFF', bold=True)\n",
    "header_alignment = Alignment(horizontal='left', vertical='center')\n",
    "header_border = Border(\n",
    "    top=Side(style='medium'),\n",
    "    bottom=Side(style='medium'),\n",
    "    left=Side(style='medium'),\n",
    "    right=Side(style='medium')\n",
    ")\n",
    "\n",
    "for cell in sheet_snapshot[1]:\n",
    "    cell.fill = header_fill\n",
    "    cell.font = header_font\n",
    "    cell.alignment = header_alignment\n",
    "    cell.border = header_border\n",
    "\n",
    "# Add filters to the first row of the sheet_snapshot worksheet\n",
    "sheet_snapshot.auto_filter.ref = sheet_snapshot.dimensions\n",
    "\n",
    "# Set column widths and text alignment for columns A to AI)\n",
    "for column in sheet_snapshot.iter_cols(min_col=1, max_col=35):\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "    \n",
    "    column_letter = column[0].column_letter\n",
    "    if column_letter in ['B', 'C', 'D', 'E', 'K', 'L', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI']:\n",
    "        sheet_snapshot.column_dimensions[column_letter].width = 20\n",
    "    elif column_letter in ['A','I','J', 'M']:\n",
    "        sheet_snapshot.column_dimensions[column_letter].width = 32\n",
    "    else:\n",
    "        sheet_snapshot.column_dimensions[column_letter].width = 10\n",
    "\n",
    "    # Apply alignment and border to cells in the current column\n",
    "    for cell in column:\n",
    "        if cell.row == 1:\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "\n",
    "###################################################################\n",
    "### Apply conditional formatting for |Top-Level Status| column\n",
    "###################################################################\n",
    "fill_green = PatternFill(start_color='C6EFCE', end_color='C6EFCE', fill_type='solid')  # Green fill\n",
    "fill_red = PatternFill(start_color='FFC7CE', end_color='FFC7CE', fill_type='solid')   # Red fill\n",
    "fill_dark_green = PatternFill(start_color='6FAC46', end_color='6FAC46', fill_type='solid')   # Dark green fill\n",
    "fill_orange = PatternFill(start_color='ED7D31', end_color='ED7D31', fill_type='solid')   # orange fill\n",
    "\n",
    "for row in range(2, max_row_CTB + 1):\n",
    "    cell = sheet_snapshot.cell(row=row, column=1)  # Assuming 'Top-Level Status' is in column 1 (A)\n",
    "    if cell.value == 'Clear-to-Build':\n",
    "        cell.fill = fill_green\n",
    "    if cell.value == 'Completed - No Backlog':\n",
    "        cell.fill = fill_dark_green\n",
    "    if cell.value == 'Not completed - No Backlog':\n",
    "        cell.fill = fill_orange\n",
    "    elif cell.value == 'Short':\n",
    "        cell.fill = fill_red\n",
    "        \n",
    "###################################################################\n",
    "### Apply conditional formatting for |Production Status| = Industrialized or contain WIP \n",
    "###################################################################\n",
    "# Define the fill for the conditional formatting\n",
    "green_fill = PatternFill(start_color='D8E4BC', end_color='D8E4BC', fill_type='solid')\n",
    "blue_fill = PatternFill(start_color='DAEEF3', end_color='DAEEF3', fill_type='solid')\n",
    "gray_fill = PatternFill(start_color='F2F2F2', end_color='DAEEF3', fill_type='solid')\n",
    "\n",
    "# Define the font color\n",
    "font_color = Font(color='000000')  # Black font color\n",
    "\n",
    "# Iterate over each row in column J\n",
    "for row in range(2, max_row_snapshot + 1):  # Start from row 2 since row 1 contains headers\n",
    "    # Get the value in the current cell in column J\n",
    "    value_in_J = sheet_snapshot.cell(row=row, column=10).value  # Column J is the 9th column\n",
    "    \n",
    "    # Check if the value in column J is 'Industrialized'\n",
    "    if value_in_J == 'Industrialized':\n",
    "        # Apply the green fill to the entire row and set the font color\n",
    "        for col in range(2, 22):  # Assuming 22 is the last column index\n",
    "            cell = sheet_snapshot.cell(row=row, column=col)\n",
    "            cell.fill = green_fill\n",
    "            cell.font = font_color\n",
    "    # Check if the value in column J contains 'WIP'\n",
    "    elif 'WIP' in str(value_in_J):\n",
    "        # Apply the blue fill to the entire row and set the font color\n",
    "        for col in range(2, 22):  # Assuming 22 is the last column index\n",
    "            cell = sheet_snapshot.cell(row=row, column=col)\n",
    "            cell.fill = blue_fill\n",
    "            cell.font = font_color\n",
    "\n",
    "    # Check if the value in column J contains 'Completed'\n",
    "    elif 'Completed' in str(value_in_J):\n",
    "        # Apply the blue fill to the entire row and set the font color\n",
    "        for col in range(2, 22):  # Assuming 22 is the last column index\n",
    "            cell = sheet_snapshot.cell(row=row, column=col)\n",
    "            cell.fill = gray_fill\n",
    "            cell.font = font_color\n",
    "\n",
    "##########################\n",
    "#### Applied thick border to |Top-Level Status|Pty Indice| ... |Production Status|\n",
    "###########################\n",
    "# Define thick border style for left and right sides\n",
    "thick_side = Side(style='thick')\n",
    "\n",
    "# Define thin black border style for top and bottom sides\n",
    "thin_black_side = Side(style='thin', color='000000')\n",
    "\n",
    "# Define the column indices for the range\n",
    "column_indices = [1, 2, 8, 10]  # Columns A, B, H, and J\n",
    "\n",
    "# Iterate over each row and apply the defined border style to the specified columns\n",
    "for row in range(2, max_row_snapshot + 1):  # Assuming max_row is already defined\n",
    "    for col_index in column_indices:\n",
    "        cell = sheet_snapshot.cell(row=row, column=col_index)\n",
    "        cell.border = Border(\n",
    "            left=thick_side,\n",
    "            right=thick_side,\n",
    "            top=thin_black_side,\n",
    "            bottom=thin_black_side\n",
    "        )\n",
    "   \n",
    "###########################\n",
    "#### |Pty Indice|..|Qty Clear to Build| ..|IDD Top Level| in bold\n",
    "###########################\n",
    "# Define font colors\n",
    "green_font_color = '24CA77'  # Green font color\n",
    "red_font_color = 'C00000'    # Red font color\n",
    "\n",
    "# Define font styles\n",
    "bold_font = Font(bold=True)\n",
    "green_font = Font(color=green_font_color, bold=True)  # Bold font with green color\n",
    "red_font = Font(color=red_font_color, bold=True)      # Bold font with red color\n",
    "\n",
    "# Apply bold font to 'Pty Indice' (Column B), 'IDD Top Level' (Column D), and 'Qty Clear to Build' (Column H)\n",
    "columns_to_bold = [2, 4, 8]  # Column B is 2, Column D is 4, Column H is 8\n",
    "\n",
    "for col_index in columns_to_bold:\n",
    "    for row in range(2, sheet_snapshot.max_row + 1):  # Start from row 2 to skip the header\n",
    "        cell = sheet_snapshot.cell(row=row, column=col_index)\n",
    "        cell.font = bold_font\n",
    "\n",
    "# Apply font color based on 'Top-Level Status' to 'Pty Indice' (Column B) and 'Qty Clear to Build' (Column H)\n",
    "for row in range(2, sheet_snapshot.max_row + 1):\n",
    "    top_level_status_cell = sheet_snapshot.cell(row=row, column=1)  # Assuming 'Top-Level Status' is in Column A\n",
    "    pty_indice_cell = sheet_snapshot.cell(row=row, column=2)  # Column B for 'Pty Indice'\n",
    "    qty_clear_to_build_cell = sheet_snapshot.cell(row=row, column=8)  # Column H for 'Qty Clear to Build'\n",
    "    top_level_status = top_level_status_cell.value\n",
    "\n",
    "    # Apply font color based on 'Top-Level Status'\n",
    "    if top_level_status == 'Clear-to-Build':\n",
    "        pty_indice_cell.font = green_font\n",
    "        qty_clear_to_build_cell.font = green_font\n",
    "    elif top_level_status == 'Short':\n",
    "        pty_indice_cell.font = red_font\n",
    "        qty_clear_to_build_cell.font = red_font\n",
    "    else:\n",
    "        # Reset font color to default (black) if neither condition is met\n",
    "        pty_indice_cell.font = Font(bold=True)\n",
    "        qty_clear_to_build_cell.font = Font(bold=True)\n",
    "\n",
    "####################################################################\n",
    "# Highlight discripency between |IDD Backlog| and |Remain. Crt. Qty.|\n",
    "#####################################################################\n",
    "# Define the fill for highlighting and font color\n",
    "highlight_fill = PatternFill(start_color=\"FFFFCC\", end_color=\"FFFFCC\", fill_type=\"solid\")  # Light yellow background\n",
    "highlight_font = Font(color=\"C00000\")  # Dark red text\n",
    "\n",
    "# Get the column index for 'IDD Backlog Qty' and 'Remain. crit. Qty'\n",
    "idd_backlog_col_idx = df_snapshot.columns.get_loc('IDD Backlog Qty') + 1  # Adding 1 because openpyxl is 1-indexed\n",
    "remain_crit_qty_col_idx = df_snapshot.columns.get_loc('Remain. crit. Qty') + 1  # Adding 1 because openpyxl is 1-indexed\n",
    "\n",
    "# Apply conditional formatting\n",
    "for row in range(2, len(df_snapshot) + 2):  # Starting from row 2 to skip header\n",
    "    idd_backlog_cell = sheet_snapshot.cell(row=row, column=idd_backlog_col_idx)\n",
    "    remain_crit_qty_cell = sheet_snapshot.cell(row=row, column=remain_crit_qty_col_idx)\n",
    "    \n",
    "    if idd_backlog_cell.value != remain_crit_qty_cell.value:\n",
    "        idd_backlog_cell.fill = highlight_fill\n",
    "        idd_backlog_cell.font = highlight_font\n",
    "\n",
    "##############################\n",
    "# Define the currency format & date format \n",
    "###############################\n",
    "currency_format = '$#,##0.00'\n",
    "\n",
    "# Apply the currency format to the specific columns (N and O)\n",
    "for row in range(2, max_row_snapshot + 1):\n",
    "    # Column N: IDD Marge Standard (unit)\n",
    "    cell = sheet_snapshot.cell(row=row, column=14)  # Column N is the 14th column\n",
    "    cell.number_format = currency_format\n",
    "    \n",
    "    # Column O: IDD Sale Price\n",
    "    cell = sheet_snapshot.cell(row=row, column=15)  # Column O is the 15th column\n",
    "    cell.number_format = currency_format\n",
    "\n",
    "    # Column Q: IDD Production Cost (unit)\n",
    "    cell = sheet_snapshot.cell(row=row, column=16)  # Column Q is the 16th column\n",
    "    cell.number_format = currency_format\n",
    "\n",
    "\n",
    "#########################################################################################################################\n",
    "# 09/23 - Apply color formating for [W] to [AA] in #DDEBF7, [AB] to [AE] in #FFF2CC and [AF] to [AH] in #E2EFDA\n",
    "########################################################################################################################\n",
    "# Define the fills for the different column ranges\n",
    "fill_w_ab = PatternFill(start_color='DDEBF7', end_color='DDEBF7', fill_type='solid')  # Light blue fill\n",
    "fill_ac_af = PatternFill(start_color='FFF2CC', end_color='FFF2CC', fill_type='solid')  # Light yellow fill\n",
    "fill_ag_ai = PatternFill(start_color='E2EFDA', end_color='E2EFDA', fill_type='solid')  # Light green fill\n",
    "\n",
    "# Define the column indices for each range\n",
    "range_w_ab = range(23, 29)\n",
    "range_ac_af = range(29, 33) \n",
    "range_ag_ai = range(33, 36)  \n",
    "\n",
    "# Apply the color formatting for each row and each range\n",
    "for row in range(2, max_row_snapshot + 1):  # Assuming max_row_snapshot is the maximum row number\n",
    "    # Apply fill for columns W to AB\n",
    "    for col in range_w_ab:\n",
    "        cell = sheet_snapshot.cell(row=row, column=col)\n",
    "        cell.fill = fill_w_ab\n",
    "    \n",
    "    # Apply fill for columns AC to AF\n",
    "    for col in range_ac_af:\n",
    "        cell = sheet_snapshot.cell(row=row, column=col)\n",
    "        cell.fill = fill_ac_af\n",
    "\n",
    "    # Apply fill for columns AG to AI\n",
    "    for col in range_ag_ai:\n",
    "        cell = sheet_snapshot.cell(row=row, column=col)\n",
    "        cell.fill = fill_ag_ai\n",
    "\n",
    "###################################################################\n",
    "### Save the changes to the Excel file \n",
    "###################################################################\n",
    "workbook.save(original_input)\n",
    "\n",
    "# Close the workbook\n",
    "workbook.close()\n",
    "\n",
    "\n",
    "# WIP 10/08\n",
    "#***************************************************************************************************************************\n",
    "############################################################################################################################\n",
    "##  ############  ###########    #############  ####         ##      \n",
    "##  ##        ##  ##        ##   ##             ##  ##       ##\n",
    "##  ##        ##  ##        ##   ##             ##    ##     ##\n",
    "##  ############# #         ##   ##             ##      ##   ##\n",
    "##  ##        ##  ##        ##   ##             ##       ##  ## \n",
    "##  ##        ##  ##        ##   ##             ##        #  ##\n",
    "##  ##        ##  ###########    #############  ##         ####\n",
    "############################################################################################################################\n",
    "#***************************************************************************************************************************\n",
    "#***************************************************************************************************************************\n",
    "Path_ADCN = 'Inputs\\IDD_ENG-Changes'\n",
    "\n",
    "# Define date and path\n",
    "input_ADCNReport_formatted = os.path.join(Path_ADCN, f'CM_IDD_ADCN-Report_Formatted.xlsx') \n",
    "\n",
    "##############################################################################################################################\n",
    "# Load workbook\n",
    "##############################################################################################################################\n",
    "# Load the existing output workbook\n",
    "try:\n",
    "    workbook = load_workbook(original_input)\n",
    "    #print(\"Output workbook loaded successfully.\")\n",
    "except FileNotFoundError as e:\n",
    "    print(f\"Output workbook not found: {e}\")\n",
    "    exit()\n",
    "\n",
    "# Print the sheet names\n",
    "print(\"Tabs in the workbook:\")\n",
    "print(workbook.sheetnames)\n",
    "print('Processing |CM-ADCNReport| ...')\n",
    "\n",
    "# Load the Excel files into pandas DataFrames\n",
    "try:\n",
    "    df_ADCNReport = pd.read_excel(input_ADCNReport_formatted, sheet_name=0)\n",
    "    #print(\"Pending Report files loaded successfully.\")\n",
    "except FileNotFoundError as e:\n",
    "    print(f\"Input ADCN Report file not found: {e}\")\n",
    "    exit()\n",
    "\n",
    "\n",
    "# Convert columns to datetime\n",
    "''' Replaced 10/15 to avoid warning\n",
    "df_ADCNReport['Created'] = pd.to_datetime(df_ADCNReport['Created'], errors='coerce')\n",
    "df_ADCNReport['Release Date'] = pd.to_datetime(df_ADCNReport['Release Date'], errors='coerce')\n",
    "'''\n",
    "# Assuming dates are in 'YYYY-MM-DD' format. Modify the format string if needed.\n",
    "df_ADCNReport['Created'] = pd.to_datetime(df_ADCNReport['Created'], format='%Y-%m-%d', errors='coerce')\n",
    "df_ADCNReport['Release Date'] = pd.to_datetime(df_ADCNReport['Release Date'], format='%Y-%m-%d', errors='coerce')\n",
    "\n",
    "####################################################################################################################\n",
    "##########################################         Creating |CM-LaborReport|                    ####################\n",
    "###################################################################################################################\n",
    "# Check if \"CM-TurnoverReport\" sheet already exists and delete it if it does\n",
    "if 'CM-ADCNReport' in workbook.sheetnames:\n",
    "    del workbook['CM-ADCNReport']\n",
    "\n",
    "# Create new \"CM-ADCNReport\" sheet\n",
    "sheet_ADCNReport = workbook.create_sheet(title='CM-ADCNReport')\n",
    "\n",
    "# Write headers to Excel\n",
    "for c_idx, header in enumerate(df_ADCNReport.columns, start=1):\n",
    "    sheet_ADCNReport.cell(row=1, column=c_idx, value=header)\n",
    "\n",
    "# Identify the columns for 'Created' and 'Release Date' (D and E correspond to 4 and 5 respectively)\n",
    "created_col = 4\n",
    "release_date_col = 5\n",
    "\n",
    "# Write data to Excel and apply date formatting\n",
    "for r_idx, row in enumerate(df_ADCNReport.values, start=2):\n",
    "    for c_idx, value in enumerate(row, start=1):\n",
    "        cell = sheet_ADCNReport.cell(row=r_idx, column=c_idx, value=value)\n",
    "\n",
    "        # Apply short date format to 'Created' and 'Release Date' columns\n",
    "        if c_idx in [created_col, release_date_col]:\n",
    "            # Use pd.Timestamp check for pandas datetime\n",
    "            if isinstance(value, pd.Timestamp) or isinstance(value, datetime):\n",
    "                cell.number_format = 'MM/DD/YYYY'  # Short date format\n",
    "\n",
    "###############################################################################################################\n",
    "################################################ Formatting |CM-ADCNReport|   #################################\n",
    "###############################################################################################################\n",
    "# Apply autofilter on headers\n",
    "sheet_ADCNReport.auto_filter.ref = sheet_ADCNReport.dimensions\n",
    "\n",
    "# Create a light green fill\n",
    "light_green_fill = PatternFill(start_color=\"E2EFDA\", end_color=\"E2EFDA\", fill_type=\"solid\")\n",
    "\n",
    "# Apply the light green fill to row 2 of column M (cell M2)\n",
    "sheet_ADCNReport.cell(row=2, column=19).fill = light_green_fill\n",
    "\n",
    "# Apply formatting to the header row\n",
    "header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')\n",
    "header_font = Font(color='FFFFFF', bold=True)\n",
    "header_alignment = Alignment(horizontal='left', vertical='center')\n",
    "header_border = Border(\n",
    "    top=Side(style='medium'),\n",
    "    bottom=Side(style='medium'),\n",
    "    left=Side(style='medium'),\n",
    "    right=Side(style='medium')\n",
    ")\n",
    "\n",
    "for cell in sheet_ADCNReport[1]:  # Header row\n",
    "    cell.fill = header_fill\n",
    "    cell.font = header_font\n",
    "    cell.alignment = header_alignment\n",
    "    cell.border = header_border\n",
    "\n",
    "# Set column widths and text alignment for relevant columns\n",
    "for column in sheet_ADCNReport.iter_cols(min_col=1, max_col=18):\n",
    "    for cell in column:\n",
    "        if cell.row == 1:  # Header row\n",
    "            cell.alignment = Alignment(horizontal='left', vertical='center')\n",
    "        else:\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "        cell.border = Border(top=Side(style='thin'), right=Side(style='thin'), bottom=Side(style='thin'), left=Side(style='thin'))\n",
    "    \n",
    "    # Adjust column widths\n",
    "    column_letter = column[0].column_letter\n",
    "    if column_letter in ['E', 'F', 'G']:\n",
    "        sheet_ADCNReport.column_dimensions[column_letter].width = 15\n",
    "    elif column_letter in ['A', 'B', 'D']:\n",
    "        sheet_ADCNReport.column_dimensions[column_letter].width = 20\n",
    "    elif column_letter in ['J', 'L', 'M', 'K']:\n",
    "        sheet_ADCNReport.column_dimensions[column_letter].width = 40\n",
    "    elif column_letter in ['N', 'C']:\n",
    "        sheet_ADCNReport.column_dimensions[column_letter].width = 25\n",
    "    elif column_letter in ['Q', 'R']:\n",
    "        sheet_ADCNReport.column_dimensions[column_letter].width = 60\n",
    "    else:\n",
    "        sheet_ADCNReport.column_dimensions[column_letter].width = 10\n",
    "\n",
    " # Set the width of column S to 15\n",
    "sheet_ADCNReport.column_dimensions['S'].width = 15  # Set width of column Q to 15\n",
    "\n",
    "# Set column J (10) and Q (17) to left alignment\n",
    "j_column_index = 10  # Column J (1-indexed)\n",
    "q_column_index = 17  # Column Q (1-indexed)\n",
    "\n",
    "# Align column J to the left\n",
    "for cell in sheet_ADCNReport.iter_rows(min_row=2, min_col=j_column_index, max_col=j_column_index):\n",
    "    for c in cell:\n",
    "        c.alignment = Alignment(horizontal='left', vertical='center')\n",
    "\n",
    "# Align column Q to the left\n",
    "for cell in sheet_ADCNReport.iter_rows(min_row=2, min_col=q_column_index, max_col=q_column_index):\n",
    "    for c in cell:\n",
    "        c.alignment = Alignment(horizontal='left', vertical='center')\n",
    "\n",
    "# Set column K (11) and R (18) to right alignment\n",
    "k_column_index = 11  # Column K (1-indexed)\n",
    "r_column_index = 18  # Column R (1-indexed)\n",
    "\n",
    "# Align column K to the right\n",
    "for cell in sheet_ADCNReport.iter_rows(min_row=2, min_col=k_column_index, max_col=k_column_index):\n",
    "    for c in cell:\n",
    "        c.alignment = Alignment(horizontal='right', vertical='center')\n",
    "\n",
    "# Align column R to the right\n",
    "for cell in sheet_ADCNReport.iter_rows(min_row=2, min_col=r_column_index, max_col=r_column_index):\n",
    "    for c in cell:\n",
    "        c.alignment = Alignment(horizontal='right', vertical='center')\n",
    "\n",
    "################################################################################\n",
    "# Color formating \n",
    "#################################################################################\n",
    "# Define the fill colors\n",
    "orange_fill = PatternFill(start_color=\"FFE6CD\", end_color=\"FFE6CD\", fill_type=\"solid\")  # Orange color fill\n",
    "blue_fill = PatternFill(start_color=\"DCE6F1\", end_color=\"DCE6F1\", fill_type=\"solid\")  # Blue color fill\n",
    "red_font = Font(color=\"FF0000\")  # Red font color for 'Not released'\n",
    "green_bold_font = Font(color=\"008000\", bold=True)  # Green and bold font color for values that are not 'Not released'\n",
    "yellow_fill = PatternFill(start_color=\"FFF2BD\", end_color=\"FFF2BD\", fill_type=\"solid\") # For inserted row that does not have a ADCN#\n",
    "red_fill =  PatternFill(start_color=\"F2DCDB\", end_color=\"F2DCDB\", fill_type=\"solid\")  # Red color fill\n",
    "\n",
    "# Iterate over rows to color columns B to G based on 'Release Date' and 'ADCN#'\n",
    "for row in range(2, sheet_ADCNReport.max_row + 1):  # Start from row 2 to skip header\n",
    "    release_date_cell = sheet_ADCNReport.cell(row=row, column=5)  # Column E for 'Release Date'\n",
    "    adcn_cell = sheet_ADCNReport.cell(row=row, column=2)  # Column B for 'ADCN#'\n",
    "    esr_cell = sheet_ADCNReport.cell(row=row, column=3)  # Column C for 'ESR#'\n",
    "     \n",
    "# Check if 'ESR#' is 'ESR to be submitted'\n",
    "    if esr_cell.value == 'ESR to be submitted':\n",
    "        # Apply red fill to columns B to G\n",
    "        for col in range(2, 8):  # Columns B to G (2 to 7)\n",
    "            sheet_ADCNReport.cell(row=row, column=col).fill = red_fill\n",
    "        \n",
    "        # Set font color to red for 'ESR#' in Column C\n",
    "        esr_cell.font = red_font  # Apply red font to 'ESR#'\n",
    "        \n",
    "        continue  # Skip to the next row after processing\n",
    "\n",
    "    # Check if 'ADCN#' is 'ADCN not created'\n",
    "    if adcn_cell.value == 'ADCN not created':\n",
    "        # Apply yellow fill and red font to columns B to G\n",
    "        for col in range(2, 8):  # Columns B to G (2 to 7)\n",
    "            sheet_ADCNReport.cell(row=row, column=col).fill = yellow_fill  # Apply yellow fill\n",
    "        # Apply red font to Column B\n",
    "        #adcn_cell.font = red_font\n",
    "        continue  # Skip to the next row after processing\n",
    "    \n",
    "    # Now check the 'Release Date'\n",
    "    if release_date_cell.value == 'Not released':  # If 'Not released'\n",
    "        fill_color = orange_fill  # Orange color\n",
    "        release_date_cell.font = red_font  # Set font to red\n",
    "    elif release_date_cell.value is not None and release_date_cell.value != \"\":  # If it contains other values\n",
    "        fill_color = blue_fill  # Blue color\n",
    "        release_date_cell.font = green_bold_font  # Set font to green\n",
    "    else:\n",
    "        continue  # Skip if it is empty\n",
    "\n",
    "    # Apply fill color to columns B to G\n",
    "    for col in range(2, 8):  # Columns B to G (2 to 7)\n",
    "        sheet_ADCNReport.cell(row=row, column=col).fill = fill_color\n",
    "\n",
    "# Gray font #A6A6A6 for [H] to [N]\n",
    "gray_font = Font(color=\"A6A6A6\")  # Gray font color for columns H to L\n",
    "dark_gray_font = Font(color=\"808080\")\n",
    "\n",
    "# Gray font for columns H to L\n",
    "for row in range(2, sheet_ADCNReport.max_row + 1):  # Start from row 2 to skip header\n",
    "    for col in range(8, 15):  # Columns H to N (8 to 12)\n",
    "        sheet_ADCNReport.cell(row=row, column=col).font = gray_font\n",
    "\n",
    "# Apply dark gray font to Column A\n",
    "for row in range(2, sheet_ADCNReport.max_row + 1):  # Start from row 2 to skip header\n",
    "    sheet_ADCNReport.cell(row=row, column=1).font = dark_gray_font  # Column A is 1\n",
    "\n",
    "# Apply bold font to Column B \n",
    "bold_font = Font(bold=True)  # Define bold font\n",
    "for row in range(2, sheet_ADCNReport.max_row + 1):  # Start from row 2 to skip header\n",
    "    cell_b = sheet_ADCNReport.cell(row=row, column=2)  # Column B\n",
    "    cell_b.font = bold_font  # Apply bold font\n",
    "    # If the ADCN is 'ADCN not created', set the font color to red again\n",
    "    if cell_b.value == 'ADCN not created':\n",
    "        cell_b.font = red_font  # Reapply red font to ensure it is kept\n",
    "\n",
    "#########################################################\n",
    "# Color formating on 'Hot' [O] and 'Holding Prod' [P]\n",
    "#########################################################\n",
    "# If column M not empty --> Hot fill: #FFC7CE fill and #9C0006 font\n",
    "# If column N not empty --> Holding fill: #FFCC99 fill and #3F3F76 font\n",
    "hot_fill = PatternFill(start_color=\"FFC7CE\", end_color=\"FFC7CE\", fill_type=\"solid\")  # Hot fill color\n",
    "hot_font = Font(color=\"9C0006\")  # Font color for 'Hot'\n",
    "\n",
    "holding_fill = PatternFill(start_color=\"FFCC99\", end_color=\"FFCC99\", fill_type=\"solid\")  # Holding fill color\n",
    "holding_font = Font(color=\"3F3F76\")  # Font color for 'Holding Prod'\n",
    "\n",
    "# Iterate over rows for 'Hot' and 'Holding Prod' color formatting\n",
    "for row in range(2, sheet_ADCNReport.max_row + 1):  # Start from row 2 to skip header\n",
    "    hot_cell = sheet_ADCNReport.cell(row=row, column=15)  # Column O for 'Hot'\n",
    "    holding_cell = sheet_ADCNReport.cell(row=row, column=16)  # Column P for 'Holding Prod'\n",
    "    \n",
    "    # Check 'Hot' column\n",
    "    if hot_cell.value not in [None, \"\"]:  # If not empty\n",
    "        hot_cell.fill = hot_fill  # Apply fill\n",
    "        hot_cell.font = hot_font  # Apply font color\n",
    "    \n",
    "    # Check 'Holding Prod' column\n",
    "    if holding_cell.value not in [None, \"\"]:  # If not empty\n",
    "        holding_cell.fill = holding_fill  # Apply fill\n",
    "        holding_cell.font = holding_font  # Apply font color\n",
    "\n",
    "#######################################################################################################\n",
    "# Hide column J and K as they are useless until finding a way to get the drawings number of all subs \n",
    "#######################################################################################################\n",
    "columns_to_hide = ['L', 'M']\n",
    "for col in columns_to_hide:\n",
    "    sheet_ADCNReport.column_dimensions[col].hidden = True\n",
    "\n",
    "###################################################################\n",
    "### Save the changes to the Excel file \n",
    "###################################################################\n",
    "workbook.save(original_input)\n",
    "\n",
    "# Close the workbook\n",
    "workbook.close()\n",
    "\n",
    "# New 10/29\n",
    "#***************************************************************************************************************************\n",
    "############################################################################################################################\n",
    "##  ##########  #############  ##########    ############           ##########\n",
    "##  ##          ##             ##       ##   ##        ##           ##\n",
    "##  ##          ##             ##       ##   ##        ##           ## \n",
    "##  ##########  #########      ##       ##   ############    ####   ##########\n",
    "##          ##  ##             ##       ##   ##        ##                   ##\n",
    "##          ##  ##             ##       ##   ##        ##                   ##\n",
    "##  ##########  ############   ##########    ##        ##           ########## ORTAGES\n",
    "############################################################################################################################\n",
    "#***************************************************************************************************************************\n",
    "#### Load the workbook\n",
    "workbook = load_workbook(original_input)\n",
    "df_summary = pd.read_excel(original_input, sheet_name='Summary')\n",
    "\n",
    "#### Copy existing tab |Summary| with all the rows 'Supplier' = 'SEDA' & 'Blank' \n",
    "# Filter rows for 'SEDA' and blank Suppliers\n",
    "df_seda_shortages = df_summary[(df_summary['Supplier'] == 'SAFRAN ELEC & DEFENSE(S9412)') | (df_summary['Supplier'].isnull())].copy()\n",
    "\n",
    "#### Insert column 'SEDA Component' based on tab |Magic-Decoder| from input file CM-Priority \n",
    "# Load 'Magic-Decoder' sheet from 'CM-Priority' workbook\n",
    "try:\n",
    "    df_magic_decoder = pd.read_excel(os.path.join(Path, 'CM_Priority_Database.xlsx'), sheet_name='Magic-Decoder')\n",
    "    \n",
    "    # Fill NaN values in 'SEDA Component' with '--' and assign back to the column\n",
    "    df_magic_decoder['SEDA Component'] = df_magic_decoder['SEDA Component'].fillna('--')\n",
    "\n",
    "    # Merge to add 'SEDA Component' based on 'IDD Component'\n",
    "    df_seda_shortages = df_seda_shortages.merge(df_magic_decoder[['IDD Component', 'SEDA Component']],\n",
    "                                                on='IDD Component', how='left')\n",
    "\n",
    "    # Check if 'SEDA Component' was successfully merged\n",
    "    if 'SEDA Component' in df_seda_shortages.columns:\n",
    "        # Get the index of 'IDD Component'\n",
    "        idd_index = df_seda_shortages.columns.get_loc('IDD Component') + 1\n",
    "        \n",
    "        # Use insert to place 'SEDA Component' right after 'IDD Component'\n",
    "        df_seda_shortages.insert(idd_index, 'SEDA Component', df_seda_shortages.pop('SEDA Component'))\n",
    "\n",
    "except FileNotFoundError:\n",
    "    print(\"Error: 'CM_Priority_Database.xlsx' file or 'Magic-Decoder' tab not found.\")\n",
    "    exit()\n",
    "\n",
    "# Delete row where 'Remain. crit. Qty' = '0' \n",
    "df_seda_shortages = df_seda_shortages[df_seda_shortages['Remain. crit. Qty'] != 0]\n",
    "\n",
    "# Remove duplicate rows based on specific columns (e.g., 'IDD Component' and 'SEDA Component')\n",
    "df_seda_shortages = df_seda_shortages.drop_duplicates(subset=['Pty Indice', 'IDD Component', 'SEDA Component', 'Level'])\n",
    "\n",
    "# New code to delete useless rows:\n",
    "# Identify rows with 'Level' = 0 followed by another row with 'Level' = 0\n",
    "rows_to_delete = df_seda_shortages[(df_seda_shortages['Level'] == 0) & (df_seda_shortages['Level'].shift(-1) == 0)].index\n",
    "\n",
    "# Drop identified rows if any exist\n",
    "if not rows_to_delete.empty:\n",
    "    df_seda_shortages = df_seda_shortages.drop(rows_to_delete).reset_index(drop=True)\n",
    "\n",
    "\n",
    "###########################################\n",
    "# Create |SEDA-Shortages|\n",
    "###########################################\n",
    "# Remove the sheet if it already exists, and then create it again at index 2 (third position)\n",
    "if 'SEDA-Shortages' in workbook.sheetnames:\n",
    "    workbook.remove(workbook['SEDA-Shortages'])\n",
    "seda_sheet = workbook.create_sheet(title='SEDA-Shortages', index=2)\n",
    "\n",
    "# Write headers\n",
    "for col_num, column_title in enumerate(df_seda_shortages.columns, start=1):\n",
    "    seda_sheet.cell(row=1, column=col_num, value=column_title)\n",
    "\n",
    "# Write data rows\n",
    "for row_num, row_data in enumerate(df_seda_shortages.values, start=2):\n",
    "    for col_num, cell_value in enumerate(row_data, start=1):\n",
    "        seda_sheet.cell(row=row_num, column=col_num, value=cell_value)\n",
    "\n",
    "# Write the date 'file_date_inventory' in cell Q2\n",
    "seda_sheet.cell(row=2, column=17, value=file_date_inventory)  # Q is the 17th column\n",
    "\n",
    "'''\n",
    "# Define column indexes based on positions of 'SEDA Component' and 'Level'\n",
    "seda_component_col = df_seda_shortages.columns.get_loc('SEDA Component') + 1  # +1 for 1-based indexing in Excel\n",
    "level_col = df_seda_shortages.columns.get_loc('Level') + 1\n",
    "\n",
    "# Iterate through rows to check for empty 'SEDA Component' values where 'Level' is not 0\n",
    "for row in range(2, seda_sheet.max_row + 1):  # Start from row 2 to skip headers\n",
    "    level_value = seda_sheet.cell(row=row, column=level_col).value\n",
    "    seda_component_value = seda_sheet.cell(row=row, column=seda_component_col).value\n",
    "    \n",
    "    # Check if 'Level' is not 0 and 'SEDA Component' is empty\n",
    "    if level_value != 0 and (seda_component_value is None or seda_component_value == \"\"):\n",
    "        seda_sheet.cell(row=row, column=seda_component_col, value=\"--\")\n",
    "'''      \n",
    "###########################################\n",
    "# Formating - Same as exixting |Summary|\n",
    "###########################################\n",
    "# Apply autofilter on headers\n",
    "seda_sheet.auto_filter.ref = seda_sheet.dimensions\n",
    "\n",
    "# Apply the light green fill to row 2 of column Q (cell Q2)\n",
    "seda_sheet.cell(row=2, column=17).fill = light_green_fill\n",
    "\n",
    "# Constants for column widths\n",
    "column_P_width = 15  # Width for Column P\n",
    "column_R_width = 40  # Width for 'Comment' column (R)\n",
    "column_S_width = 20   # Width for 'BOM Index' column (S)\n",
    "\n",
    "# Define column index numbers for clarity\n",
    "comment_column_index = 18  # R\n",
    "bom_index_column_index = 19  # S\n",
    "\n",
    "# Define styles\n",
    "font_color_black = '000000'\n",
    "#thin_side = Side(style='thin')  # Define thin side\n",
    "alignment = Alignment(horizontal=\"center\", vertical=\"center\")\n",
    "header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')\n",
    "header_font = Font(color='FFFFFF', bold=True)\n",
    "thin_border = Border(left=Side(style=\"thin\"), \n",
    "                     right=Side(style=\"thin\"), \n",
    "                     top=Side(style=\"thin\"), \n",
    "                     bottom=Side(style=\"thin\"))\n",
    "\n",
    "# Apply level-based conditional formatting to the 'Level' column (G)\n",
    "min_row, max_row_CTB = 2, seda_sheet.max_row  # Adjust min_row if headers start lower\n",
    "col_G = 7  # Column G is the 7th column\n",
    "for row in range(min_row, max_row_CTB + 1):\n",
    "    cell_value = seda_sheet.cell(row=row, column=col_G).value\n",
    "    if cell_value is not None:\n",
    "        # Set fill colors based on level\n",
    "        if cell_value == 0:\n",
    "            fill_color = '63BE7B'  # Green\n",
    "        elif cell_value == 1:\n",
    "            fill_color = 'A2C075'  # Lighter Green\n",
    "        elif cell_value == 2:\n",
    "            fill_color = 'FFEB84'  # Yellow\n",
    "        elif cell_value == 3:\n",
    "            fill_color = 'FFD166'  # Orange\n",
    "        elif cell_value == 4:\n",
    "            fill_color = 'F88E5B'  # Darker Orange\n",
    "        elif cell_value == 5:\n",
    "            fill_color = 'F8696B'  # Red\n",
    "        elif cell_value == 6:\n",
    "            fill_color = '8B0000'  # Darker Red\n",
    "        else:\n",
    "            fill_color = None  # No color if the level is outside the range\n",
    "\n",
    "        # Apply the fill and font to the cell if fill_color is not None\n",
    "        if fill_color:\n",
    "            fill = PatternFill(start_color=fill_color, end_color=fill_color, fill_type=\"solid\")\n",
    "            seda_sheet.cell(row=row, column=col_G).fill = fill\n",
    "            seda_sheet.cell(row=row, column=col_G).font = Font(color=font_color_black, bold=False)\n",
    "\n",
    "# Set column widths and text alignment for columns A to P\n",
    "for column in seda_sheet.iter_cols(min_col=1, max_col=16):\n",
    "    column_letter = column[0].column_letter  # Get the column letter for width adjustment\n",
    "\n",
    "    # Set widths based on column letter\n",
    "    if column_letter in ['A', 'C', 'D', 'E', 'F', 'J', 'K', 'L', 'M', 'N', 'O']:\n",
    "        seda_sheet.column_dimensions[column_letter].width = 20\n",
    "    elif column_letter in ['B', 'I', 'P']:\n",
    "        seda_sheet.column_dimensions[column_letter].width = 30\n",
    "    else:\n",
    "        seda_sheet.column_dimensions[column_letter].width = 10\n",
    "\n",
    "    # Apply alignment and border to cells in each column\n",
    "    for cell in column:\n",
    "        # Set alignment based on row number\n",
    "        cell.alignment = Alignment(horizontal='left' if cell.row == 1 else 'center', vertical='center')\n",
    "        cell.border = thin_border  # Apply border\n",
    "\n",
    "# Set alignment specifically for columns P, R, and S\n",
    "max_row_seda = seda_sheet.max_row  # Get max row dynamically\n",
    "for row in seda_sheet.iter_rows(min_row=1, max_row=max_row_seda):\n",
    "    for cell in row:\n",
    "        # Center alignment for all cells\n",
    "        cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "\n",
    "        # Right alignment specifically for Column P\n",
    "        if cell.column == 16:  # Column P\n",
    "            cell.alignment = Alignment(horizontal='right', vertical='center')\n",
    "            seda_sheet.column_dimensions[cell.column_letter].width = column_P_width  # Set width for Column P\n",
    "\n",
    "# Set width and alignment for 'Comment' and 'BOM Index' columns\n",
    "seda_sheet.column_dimensions[get_column_letter(comment_column_index)].width = column_R_width\n",
    "seda_sheet.column_dimensions[get_column_letter(bom_index_column_index)].width = column_S_width\n",
    "\n",
    "# Apply right alignment to column S specifically\n",
    "for row in seda_sheet.iter_rows(min_row=1, max_row=max_row_seda):\n",
    "    for cell in row:\n",
    "        if cell.column == bom_index_column_index:  # Column S\n",
    "            cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "\n",
    "# Apply thin border to all cells in columns R and S\n",
    "for row in seda_sheet.iter_rows(min_row=1, max_row=max_row_seda):\n",
    "    # Apply to Column R\n",
    "    cell_r = row[comment_column_index - 1]  # Adjusting index for 0-based\n",
    "    cell_r.border = thin_border\n",
    "\n",
    "    # Apply to Column S\n",
    "    cell_s = row[bom_index_column_index - 1]  # Adjusting index for 0-based\n",
    "    cell_s.border = thin_border\n",
    "    \n",
    "# Apply borders to header rows (1 and 2) in column Q\n",
    "for row in range(1, 3):\n",
    "    seda_sheet.cell(row=row, column=17).border = thin_border\n",
    "\n",
    "# Set width for Column P\n",
    "seda_sheet.column_dimensions['P'].width = 30\n",
    "\n",
    "# Apply header style\n",
    "for cell in seda_sheet[1]:\n",
    "    cell.fill = header_fill\n",
    "    cell.font = header_font\n",
    "    cell.alignment = alignment\n",
    "    cell.border = thin_border\n",
    "\n",
    "''' SAVED 10/29\n",
    "# Define styles\n",
    "header_fill = PatternFill(start_color=\"4472C4\", end_color=\"4472C4\", fill_type=\"solid\")\n",
    "header_font = Font(color='FFFFFF', bold=True)\n",
    "highlight_fill = PatternFill(start_color=\"FFC7CE\", end_color=\"FFC7CE\", fill_type=\"solid\")\n",
    "alignment = Alignment(horizontal=\"center\", vertical=\"center\")\n",
    "font_color_black = \"000000\"  # Black font color for Level column formatting\n",
    "# Define thin border style\n",
    "thin_border = Border(left=Side(style=\"thin\"), \n",
    "                     right=Side(style=\"thin\"), \n",
    "                     top=Side(style=\"thin\"), \n",
    "                     bottom=Side(style=\"thin\"))\n",
    "\n",
    "# Apply level-based conditional formatting to the 'Level' column (G)\n",
    "min_row, max_row_CTB = 2, seda_sheet.max_row  # Adjust min_row if headers start lower\n",
    "col_G = 7  # Column G is the 7th column\n",
    "for row in range(min_row, max_row_CTB + 1):\n",
    "    cell_value = seda_sheet.cell(row=row, column=col_G).value\n",
    "    if cell_value is not None:\n",
    "        # Set fill colors based on level\n",
    "        if cell_value == 0:\n",
    "            fill_color = '63BE7B'  # Green\n",
    "        elif cell_value == 1:\n",
    "            fill_color = 'A2C075'  # Lighter Green\n",
    "        elif cell_value == 2:\n",
    "            fill_color = 'FFEB84'  # Yellow\n",
    "        elif cell_value == 3:\n",
    "            fill_color = 'FFD166'  # Orange\n",
    "        elif cell_value == 4:\n",
    "            fill_color = 'F88E5B'  # Darker Orange\n",
    "        elif cell_value == 5:\n",
    "            fill_color = 'F8696B'  # Red\n",
    "        elif cell_value == 6:\n",
    "            fill_color = '8B0000'  # Darker Red\n",
    "        else:\n",
    "            fill_color = None  # No color if the level is outside the range\n",
    "\n",
    "        # Apply the fill and font to the cell if fill_color is not None\n",
    "        if fill_color:\n",
    "            fill = PatternFill(start_color=fill_color, end_color=fill_color, fill_type=\"solid\")\n",
    "            seda_sheet.cell(row=row, column=col_G).fill = fill\n",
    "            seda_sheet.cell(row=row, column=col_G).font = Font(color=font_color_black, bold=False)\n",
    "\n",
    "# Set column widths and text alignment for columns A to P\n",
    "for column in seda_sheet.iter_cols(min_col=1, max_col=16):\n",
    "    column_letter = column[0].column_letter  # Get the column letter for width adjustment\n",
    "\n",
    "    # Set widths based on column letter\n",
    "    if column_letter in ['A', 'C', 'D', 'E', 'F', 'J', 'K', 'L', 'M', 'N', 'O']:\n",
    "        seda_sheet.column_dimensions[column_letter].width = 20\n",
    "    elif column_letter in ['B', 'I', 'P']:\n",
    "        seda_sheet.column_dimensions[column_letter].width = 30\n",
    "    else:\n",
    "        seda_sheet.column_dimensions[column_letter].width = 10\n",
    "\n",
    "    # Apply alignment and border to cells in each column\n",
    "    for cell in column:\n",
    "        # Set alignment based on row number\n",
    "        cell.alignment = Alignment(horizontal='left' if cell.row == 1 else 'center', vertical='center')\n",
    "        cell.border = thin_border  # Apply border\n",
    "\n",
    "max_row_seda = seda_sheet.max_row  # Get max row dynamically\n",
    "\n",
    "# Set alignment and widths for the specified columns\n",
    "for row in seda_sheet.iter_rows(min_row=1, max_row=max_row_seda):\n",
    "    for cell in row:\n",
    "        # Center alignment for all cells\n",
    "        cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "\n",
    "        # Right alignment specifically for Column P\n",
    "        if cell.column == 16:  # Column P\n",
    "            cell.alignment = Alignment(horizontal='right', vertical='center')\n",
    "            seda_sheet.column_dimensions[cell.column_letter].width = column_P_width  # Set width for Column P\n",
    "\n",
    "        # Set width for 'Comment' and 'BOM Index' columns using index numbers\n",
    "        if cell.column == comment_column_index:  # Column R\n",
    "            seda_sheet.column_dimensions[cell.column_letter].width = column_R_width\n",
    "        elif cell.column == bom_index_column_index:  # Column S\n",
    "\n",
    "#############################################################################\n",
    "#Set column widths and text alignment for 'Comment' and 'BOM Index' columns\n",
    "##############################################################################\n",
    "# Define widths for the columns\n",
    "column_R_width = 40  # Width for 'Comment' column (R)\n",
    "column_S_width = 20   # Width for 'BOM Index' column (S)\n",
    "\n",
    "# Define column index numbers for clarity\n",
    "comment_column_index = 18  # R\n",
    "bom_index_column_index = 19  # S\n",
    "\n",
    "# Set alignment and widths for the specified columns\n",
    "for row in seda_sheet.iter_rows(min_row=1, max_row=max_row_CTB):\n",
    "    for cell in row:\n",
    "        cell.alignment = Alignment(horizontal='center', vertical='center')  # Center alignment\n",
    "\n",
    "        # Set width for 'Comment' and 'BOM Index' columns using index numbers\n",
    "        if cell.column == comment_column_index:  # Column R\n",
    "            seda_sheet.column_dimensions[cell.column_letter].width = column_R_width\n",
    "        elif cell.column == bom_index_column_index:  # Column S\n",
    "            seda_sheet.column_dimensions[cell.column_letter].width = column_S_width\n",
    "\n",
    "seda_sheet.column_dimensions[cell.column_letter].width = column_S_width\n",
    "\n",
    "# Apply borders to header rows (1 and 2) in column Q\n",
    "for row in range(1, 3):\n",
    "    seda_sheet.cell(row=row, column=17).border = thin_border\n",
    "\n",
    "# Apply header style\n",
    "for cell in seda_sheet[1]:\n",
    "    cell.fill = header_fill\n",
    "    cell.font = header_font\n",
    "    cell.alignment = alignment\n",
    "    cell.border = thin_border\n",
    "'''\n",
    "\n",
    "####################################################\n",
    "# Apply conditional formatting on \"Max Qty (GS)\"\n",
    "###################################################\n",
    "# Red fill for cells with 0\n",
    "fill_red = PatternFill(start_color='FFC7CE', end_color='FFC7CE', fill_type='solid')   # Red fill\n",
    "\n",
    "# Define the column index for \"Max Qty (GS)\"\n",
    "max_qty_col = df_seda_shortages.columns.get_loc('Max Qty (GS)') + 1\n",
    "\n",
    "# Define the range for the Max Qty (GS) column\n",
    "start_cell = seda_sheet.cell(row=2, column=max_qty_col).coordinate\n",
    "end_cell = seda_sheet.cell(row=len(df_seda_shortages) + 1, column=max_qty_col).coordinate\n",
    "range_coord = f\"{start_cell}:{end_cell}\"\n",
    "\n",
    "# Apply conditional formatting only to cells with a numerical value of 0\n",
    "seda_sheet.conditional_formatting.add(\n",
    "    range_coord,\n",
    "    CellIsRule(operator=\"equal\", formula=['0'], stopIfTrue=True, fill=fill_red)\n",
    ")\n",
    "\n",
    "\n",
    "##########################################################################\n",
    "# Apply conditional formatting for row dedicated to Top-Level (Level = 0)\n",
    "##########################################################################\n",
    "# Define fill color for Top-Level\n",
    "fill_TopLevel = PatternFill(start_color='5B9BD5', end_color='5B9BD5', fill_type='solid')  # Blue fill\n",
    "\n",
    "# Define font colors\n",
    "font_color_clear = \"FFFFFF\"  # White\n",
    "font_color_shortage = \"C00000\"  # Dark Red\n",
    "font_color_fullyClear = \"24CA77\"  # Green\n",
    "\n",
    "# Define thick border\n",
    "thick_border = Border(\n",
    "    top=Side(style='thick'),\n",
    "    bottom=Side(style='thick')\n",
    ")\n",
    "\n",
    "# Iterate through each row in the sheet\n",
    "for row in range(2, max_row_CTB + 1):\n",
    "    cell_level = seda_sheet.cell(row=row, column=7)  # Assuming 'Level' is in column 7 (G)\n",
    "    cell_max_qty = seda_sheet.cell(row=row, column=15)  # Assuming 'Max Qty Top-Level' is in column 15 (N)\n",
    "    cell_remain_crit_qty = seda_sheet.cell(row=row, column=14)  # Assuming 'Remain. crit. Qty' is in column 14 (M)\n",
    "\n",
    "    if cell_level.value == 0:\n",
    "        # Check if 'Max Qty Top-Level' and 'Remain. crit. Qty' cells are not empty\n",
    "        if cell_max_qty.value is not None and cell_remain_crit_qty.value is not None:\n",
    "            # Determine the font color based on the values of 'Max Qty Top-Level' and 'Remain. crit. Qty'\n",
    "            font_color = font_color_clear  # Default font color\n",
    "            if cell_max_qty.value >= cell_remain_crit_qty.value:\n",
    "                font_color = font_color_fullyClear\n",
    "            elif cell_max_qty.value > 0:\n",
    "                font_color = font_color_clear\n",
    "            elif cell_max_qty.value == 0:\n",
    "                font_color = font_color_shortage\n",
    "\n",
    "            # Apply fill color, font color, bold, and border to each cell in the row\n",
    "            for col in range(1, 16):\n",
    "                cell = seda_sheet.cell(row=row, column=col)\n",
    "                cell.fill = fill_TopLevel\n",
    "                cell.font = Font(color=font_color, bold=True)\n",
    "                cell.border = thick_border\n",
    "\n",
    "###################################################################\n",
    "### Apply conditional formatting for 'Top-Level Status' column\n",
    "###################################################################\n",
    "fill_green = PatternFill(start_color='C6EFCE', end_color='C6EFCE', fill_type='solid')  # Green fill\n",
    "fill_dark_green = PatternFill(start_color='6FAC46', end_color='6FAC46', fill_type='solid')   # Dark green fill\n",
    "fill_orange = PatternFill(start_color='ED7D31', end_color='ED7D31', fill_type='solid')   # orange fill\n",
    "\n",
    "for row in range(2, max_row_CTB + 1):\n",
    "    cell = seda_sheet.cell(row=row, column=1)  # Assuming 'Top-Level Status' is in column 1 (A)\n",
    "    if cell.value == 'Clear-to-Build':\n",
    "        cell.fill = fill_green\n",
    "    if cell.value == 'Completed - No Backlog':\n",
    "        cell.fill = fill_dark_green\n",
    "    if cell.value == 'Not completed - No Backlog':\n",
    "        cell.fill = fill_orange\n",
    "    elif cell.value == 'Shortage':\n",
    "        cell.fill = fill_red\n",
    "        \n",
    "################################################\n",
    "# Save the updated workbook\n",
    "################################################\n",
    "workbook.save(original_input)\n",
    "# Close the workbook\n",
    "workbook.close()\n",
    "\n",
    "print(f\"SEDA Shortages added successfully as|SEDA-Shortages| in {original_input}\")\n",
    "\n",
    "\n",
    "#///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n",
    "#*********************************************************************************************************************************************\n",
    "# FORMATTING |CM-Priority| based of |SNAPSHOT|\n",
    "#*********************************************************************************************************************************************\n",
    "#####################################################################\n",
    "### Formating |Clear to build| from CM-Priority column based on the value after filling it based on the SUMMARY \n",
    "#####################################################################\n",
    "# if |Clear to build| = 0 --> Red, if |Clear to build| > |Remaining crit. Qty.| --> Green, if |Clear to build| < |Remaining crit. Qty.| --> Black\n",
    "\n",
    "\n",
    "##### //////////////////////////////////  #####\n",
    "# Insert section |Dashboard| if needed       ##\n",
    "##### ////////////////////////////////// #####\n",
    "\n",
    "#***************************************************************************************************************************\n",
    "#############################################################################################################################\n",
    "## ########  ########  #########  #########  ##     ## \n",
    "## ##        ##    ##  ##     ##  ##     ##  ##     ##  \n",
    "## ##  ####  ########  #########  #########  #########  \n",
    "## ##    ##  ##  ###   ##     ##  ##         ##     ## \n",
    "## ########  ##    ##  ##     ##  ##         ##     ## \n",
    "##############################################################################################################################\n",
    "# --> Copy code if needed <--\n",
    "\n",
    "\n",
    "###################################\n",
    "# Function to color a sheet tab\n",
    "###################################\n",
    "def color_sheet_tab(sheet_name, color):\n",
    "    if sheet_name in workbook.sheetnames:\n",
    "        sheet = workbook[sheet_name]\n",
    "        sheet.sheet_properties.tabColor = color\n",
    "\n",
    "# Color each tab individually\n",
    "#color_sheet_tab('Dashboard', 'D8E4BC')  # Green \n",
    "color_sheet_tab('Snapshot', 'D8E4BC')  # Green\n",
    "color_sheet_tab('Summary', 'D8E4BC')  # Green\n",
    "color_sheet_tab('SEDA-Shortages', 'D8E4BC')  # Green\n",
    "color_sheet_tab('Gantt', 'B7DEE8')  # Bleu turquoise\n",
    "color_sheet_tab('Clear-to-Build', 'D8E4BC')  # Green\n",
    "color_sheet_tab('CM-Inventory', 'C5D9F1')  # Bleu\n",
    "color_sheet_tab('CM-BOM', 'C5D9F1')  # Bleu\n",
    "color_sheet_tab('CM-Priority', 'B7DEE8')  # Bleu turquoise\n",
    "color_sheet_tab('CM-Backlog', 'C5D9F1')  # Bleu\n",
    "color_sheet_tab('CM-TurnoverReport', 'C5D9F1')  # Bleu\n",
    "color_sheet_tab('CM-WIP', 'C5D9F1')  # Bleu\n",
    "color_sheet_tab('PendingReport', 'C5D9F1')  # Bleu\n",
    "color_sheet_tab('CM-Historic', 'C5D9F1')  # Bleu\n",
    "color_sheet_tab('CM-LaborReport', 'C5D9F1')  # Bleu\n",
    "color_sheet_tab('CM-MakeArchitecture', 'E4DFEC')  # Purple\n",
    "color_sheet_tab('CM-ADCNReport', 'E4DFEC')  # Purple\n",
    "\n",
    "'''\n",
    "try:\n",
    "    # Set 'Snapshot' as the active sheet\n",
    "    if 'Snapshot' in workbook.sheetnames:\n",
    "    # Save the workbook with the current filename\n",
    "    workbook.save(original_input)\n",
    "    print(\"Workbook saved successfully.\")\n",
    "\n",
    "except Exception as e:\n",
    "    print(f\"An unexpected error occurred: {e}\")\n",
    "\n",
    "finally:\n",
    "    # Close the workbook with the original_input filename\n",
    "    workbook.close()\n",
    "'''\n",
    "\n",
    "try:\n",
    "    # Check if 'Snapshot' is in the sheet names\n",
    "    if 'Snapshot' in workbook.sheetnames:\n",
    "        # Save the workbook with the current filename\n",
    "        workbook.save(original_input)\n",
    "        print(\"Workbook saved successfully.\")\n",
    "    else:\n",
    "        print(\"Sheet 'Snapshot' not found.\")\n",
    "\n",
    "except Exception as e:\n",
    "    print(f\"An unexpected error occurred: {e}\")\n",
    "    \n",
    "###################################################################################################################\n",
    "# Print the sheet names\n",
    "print(\"Sheet names in {}: {}\".format(original_input, workbook.sheetnames))\n",
    "print('Transfer Project Overview spreadsheet generated sucessfully!')\n",
    "\n",
    "# New 08/27\n",
    "#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n",
    "###################################################################################################################\n",
    "#### Update input file CM_Priority_Database.xlsx column ['Shipped'] and ['Remain. crit. Qty']\n",
    "###################################################################################################################\n",
    "#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n",
    "# |Clear-to-Build| and |CM-Inventory| are created before the update of |CM-Priority|, \n",
    "# as a consequance, the column ['Shipped'] and ['Remain. crit. Qty'] remain the values from the input df_Priority (CM_Priority_Database.xlsx)\n",
    "###################################################################################################################\n",
    "# Copy the original file with the updated name\n",
    "priority_file_name_updated = os.path.join(Path, 'CM_Priority_Database_updated.xlsx')\n",
    "shutil.copy(priority_file_name, priority_file_name_updated)\n",
    "\n",
    "# Load the original and updated workbooks\n",
    "wb_original = openpyxl.load_workbook(priority_file_name)\n",
    "wb_updated = openpyxl.load_workbook(priority_file_name_updated)\n",
    "\n",
    "# Select the active sheet (or specify by name if needed)\n",
    "ws_original = wb_original['CM-Priority'] \n",
    "ws_updated = wb_updated['CM-Priority']  \n",
    "\n",
    "# Find the column indexes for 'Pty Indice', 'Shipped', 'Critical Qty', and 'Remain. crit. Qty'\n",
    "columns = {}\n",
    "for cell in ws_original[1]:  # Assuming the first row contains headers\n",
    "    if cell.value in ['Pty Indice', 'Shipped', 'Critical Qty', 'Remain. crit. Qty']:\n",
    "        columns[cell.value] = cell.column\n",
    "\n",
    "# Ensure all necessary columns were found before proceeding\n",
    "if not all(col in columns for col in ['Pty Indice', 'Shipped', 'Critical Qty', 'Remain. crit. Qty']):\n",
    "    raise ValueError(\"Could not find one or more required columns in the header row.\")\n",
    "\n",
    "# Update 08/29\n",
    "# Update the 'Shipped' and calculate 'Remain. crit. Qty' in the updated sheet \n",
    "for row in range(2, ws_original.max_row + 1):  # Assuming the first row is headers\n",
    "    # Check if the row exists in df_Priority_updated\n",
    "    if row - 2 < len(df_Priority_updated):\n",
    "        pty_indice = df_Priority_updated.loc[row - 2, 'Pty Indice']\n",
    "        new_shipped = df_Priority_updated.loc[row - 2, 'Shipped']\n",
    "\n",
    "        # Find the corresponding row in the Excel sheet\n",
    "        for excel_row in ws_updated.iter_rows(min_row=2, max_row=ws_updated.max_row, values_only=False):\n",
    "            if excel_row[columns['Pty Indice'] - 1].value == pty_indice:\n",
    "                crit_qty = excel_row[columns['Critical Qty'] - 1].value\n",
    "                \n",
    "                # Update the 'Shipped' value regardless of whether it is greater or not\n",
    "                excel_row[columns['Shipped'] - 1].value = new_shipped\n",
    "\n",
    "                # Calculate 'Remain. crit. Qty'\n",
    "                remain_crit_qty = max(int(crit_qty) - int(new_shipped), 0)\n",
    "\n",
    "                # Update 'Remain. crit. Qty' in the Excel sheet\n",
    "                remain_crit_qty_cell = excel_row[columns['Remain. crit. Qty'] - 1]\n",
    "                remain_crit_qty_cell.value = remain_crit_qty\n",
    "                remain_crit_qty_cell.number_format = '0'  # Format the cell to show integers only\n",
    "\n",
    "                break\n",
    "            \n",
    "# Save the updated workbook\n",
    "wb_updated.save(priority_file_name_updated)\n",
    "print(f\"File {priority_file_name_updated} created successfully.\")\n",
    "\n",
    "#New 08/28\n",
    "#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n",
    "################################################################################################################################################################\n",
    "#### Update input file CM_Priority_Database.xlsx column ['Shipped'] and ['Remain. crit. Qty'] with the newlly created file CM_Priority_Database_updated.xlsx \n",
    "###############################################################################################################################################################\n",
    "#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n",
    "# open priority_file_name (CM_Priority_Database.xlsx) and update 'Shipped' and 'Remain. crit. Qty' with the values from priority_file_name_updated (CM_Priority_Database_updated.xlsx)\n",
    "\n",
    "# Select the active sheets\n",
    "#ws_original = wb_original.active  # or wb_original['SheetName']\n",
    "#ws_updated = wb_updated.active  # or wb_updated['SheetName']\n",
    "ws_original = wb_original['CM-Priority'] \n",
    "ws_updated = wb_updated['CM-Priority']  \n",
    "\n",
    "# Find the column indexes for 'Pty Indice', 'Shipped', and 'Remain. crit. Qty'\n",
    "columns = {}\n",
    "for cell in ws_original[1]:  # Assuming the first row contains headers\n",
    "    if cell.value in ['Pty Indice', 'Shipped', 'Critical Qty', 'Remain. crit. Qty']:\n",
    "        columns[cell.value] = cell.column\n",
    "\n",
    "# Ensure all necessary columns were found before proceeding\n",
    "if not all(col in columns for col in ['Pty Indice', 'Shipped', 'Remain. crit. Qty']):\n",
    "    raise ValueError(\"Could not find one or more required columns in the header row.\")\n",
    "\n",
    "# Update the 'Shipped' and 'Remain. crit. Qty' in the original sheet\n",
    "for row in range(2, ws_original.max_row + 1):  # Assuming the first row is headers\n",
    "    # Find the corresponding row in the updated Excel sheet\n",
    "    for excel_row_updated in ws_updated.iter_rows(min_row=2, max_row=ws_updated.max_row, values_only=False):\n",
    "        if excel_row_updated[columns['Pty Indice'] - 1].value == ws_original.cell(row, columns['Pty Indice']).value:\n",
    "            new_shipped = excel_row_updated[columns['Shipped'] - 1].value\n",
    "            new_remain_crit_qty = excel_row_updated[columns['Remain. crit. Qty'] - 1].value\n",
    "\n",
    "            # Update the original workbook\n",
    "            ws_original.cell(row, columns['Shipped']).value = new_shipped\n",
    "            ws_original.cell(row, columns['Remain. crit. Qty']).value = new_remain_crit_qty\n",
    "            ws_original.cell(row, columns['Remain. crit. Qty']).number_format = '0'  # Format the cell to show integers only\n",
    "\n",
    "            break\n",
    "\n",
    "# Save the updated original workbook\n",
    "wb_original.save(priority_file_name)\n",
    "print(f\"File {priority_file_name} updated successfully.\")\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ff25b83c-d0c0-4b81-a88f-1125af39b53c",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "<h2 style=\"text-align:left;\">Graph creation - WIP </h2> "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "493c6fe2-9d7f-4cb3-9fa7-c6788ab09d0b",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "File Date: 06-27-2024\n",
      "Input files loaded successfully.\n",
      "Successfully loaded 'Clear-to-Build-06-27-2024_Formatted.xlsx'\n",
      "|Graph| tab created successfully.\n",
      "Unique IDD Top Level for Clear to Build: 53\n",
      "Unique IDD Top Level for Short: 25\n",
      "Sum of 'Backlog row Qty' for 'Standard': 1545\n",
      "Sum of 'Backlog row Qty' for 'DX/DO': 1240\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Priority</th>\n",
       "      <th>Pty Indice</th>\n",
       "      <th>IDD Top Level</th>\n",
       "      <th>SEDA Top Level</th>\n",
       "      <th>Backlog row Qty</th>\n",
       "      <th>Critical Qty</th>\n",
       "      <th>Remain. crit. Qty</th>\n",
       "      <th>Backlog Description</th>\n",
       "      <th>General Description</th>\n",
       "      <th>Marge standard</th>\n",
       "      <th>...</th>\n",
       "      <th>Currency net amount</th>\n",
       "      <th>Actual amount -standard</th>\n",
       "      <th>SO Modified</th>\n",
       "      <th>Production Status</th>\n",
       "      <th>Program</th>\n",
       "      <th>Last Update</th>\n",
       "      <th>Top-Level Status</th>\n",
       "      <th>Order Type</th>\n",
       "      <th>Top-Level Status_y</th>\n",
       "      <th>Production Status_y</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>P1</td>\n",
       "      <td>840-000435-1</td>\n",
       "      <td>351-39193-001</td>\n",
       "      <td>1</td>\n",
       "      <td>Completed</td>\n",
       "      <td>Completed</td>\n",
       "      <td>CPA ASSY 351-39193-001</td>\n",
       "      <td>MCP</td>\n",
       "      <td>-3060.5</td>\n",
       "      <td>...</td>\n",
       "      <td>0.0</td>\n",
       "      <td>3060.5</td>\n",
       "      <td>NaN</td>\n",
       "      <td>Completed</td>\n",
       "      <td>Phase 4</td>\n",
       "      <td>06-27-2024</td>\n",
       "      <td>NaN</td>\n",
       "      <td>None</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1</td>\n",
       "      <td>P1</td>\n",
       "      <td>840-000435-1</td>\n",
       "      <td>351-39193-001</td>\n",
       "      <td>1</td>\n",
       "      <td>Completed</td>\n",
       "      <td>Completed</td>\n",
       "      <td>CPA ASSY 351-39193-001</td>\n",
       "      <td>MCP</td>\n",
       "      <td>-3060.5</td>\n",
       "      <td>...</td>\n",
       "      <td>0.0</td>\n",
       "      <td>3060.5</td>\n",
       "      <td>NaN</td>\n",
       "      <td>Completed</td>\n",
       "      <td>Phase 4</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>None</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>1</td>\n",
       "      <td>P1</td>\n",
       "      <td>840-000435-1</td>\n",
       "      <td>351-39193-001</td>\n",
       "      <td>1</td>\n",
       "      <td>Completed</td>\n",
       "      <td>Completed</td>\n",
       "      <td>CPA ASSY 351-39193-001</td>\n",
       "      <td>MCP</td>\n",
       "      <td>-3060.5</td>\n",
       "      <td>...</td>\n",
       "      <td>0.0</td>\n",
       "      <td>3060.5</td>\n",
       "      <td>NaN</td>\n",
       "      <td>Completed</td>\n",
       "      <td>Phase 4</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>None</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>1</td>\n",
       "      <td>P1</td>\n",
       "      <td>840-000435-1</td>\n",
       "      <td>351-39193-001</td>\n",
       "      <td>11</td>\n",
       "      <td>Completed</td>\n",
       "      <td>Completed</td>\n",
       "      <td>CPA ASSY 351-39193-001</td>\n",
       "      <td>MCP</td>\n",
       "      <td>-1334.3</td>\n",
       "      <td>...</td>\n",
       "      <td>32331.1</td>\n",
       "      <td>33665.3</td>\n",
       "      <td>NaN</td>\n",
       "      <td>Completed</td>\n",
       "      <td>Phase 4</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>Standard</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>1</td>\n",
       "      <td>P1</td>\n",
       "      <td>840-000435-1</td>\n",
       "      <td>351-39193-001</td>\n",
       "      <td>10</td>\n",
       "      <td>Completed</td>\n",
       "      <td>Completed</td>\n",
       "      <td>CPA ASSY 351-39193-001</td>\n",
       "      <td>MCP</td>\n",
       "      <td>-1213.0</td>\n",
       "      <td>...</td>\n",
       "      <td>29391.9</td>\n",
       "      <td>30604.9</td>\n",
       "      <td>NaN</td>\n",
       "      <td>Completed</td>\n",
       "      <td>Phase 4</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>Standard</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>328</th>\n",
       "      <td>SIK-New</td>\n",
       "      <td>SIK-New1</td>\n",
       "      <td>840-000400-102</td>\n",
       "      <td>441-42907-301</td>\n",
       "      <td>1</td>\n",
       "      <td>TBD</td>\n",
       "      <td>TBD</td>\n",
       "      <td>CPA ASSY 441-42907-302</td>\n",
       "      <td>CPA</td>\n",
       "      <td>1333.4</td>\n",
       "      <td>...</td>\n",
       "      <td>13468.8</td>\n",
       "      <td>12135.4</td>\n",
       "      <td>NaN</td>\n",
       "      <td>Proto &amp; FTB</td>\n",
       "      <td>SIK-New</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>Standard</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>329</th>\n",
       "      <td>SIK-New</td>\n",
       "      <td>SIK-New1</td>\n",
       "      <td>840-000400-102</td>\n",
       "      <td>441-42907-301</td>\n",
       "      <td>1</td>\n",
       "      <td>TBD</td>\n",
       "      <td>TBD</td>\n",
       "      <td>CPA ASSY 441-42907-302</td>\n",
       "      <td>CPA</td>\n",
       "      <td>1333.4</td>\n",
       "      <td>...</td>\n",
       "      <td>13468.8</td>\n",
       "      <td>12135.4</td>\n",
       "      <td>NaN</td>\n",
       "      <td>Proto &amp; FTB</td>\n",
       "      <td>SIK-New</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>Standard</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>330</th>\n",
       "      <td>SIK-New</td>\n",
       "      <td>SIK-New1</td>\n",
       "      <td>840-000400-102</td>\n",
       "      <td>441-42907-301</td>\n",
       "      <td>1</td>\n",
       "      <td>TBD</td>\n",
       "      <td>TBD</td>\n",
       "      <td>CPA ASSY 441-42907-302</td>\n",
       "      <td>CPA</td>\n",
       "      <td>1333.4</td>\n",
       "      <td>...</td>\n",
       "      <td>13468.8</td>\n",
       "      <td>12135.4</td>\n",
       "      <td>NaN</td>\n",
       "      <td>Proto &amp; FTB</td>\n",
       "      <td>SIK-New</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>Standard</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>331</th>\n",
       "      <td>SIK-New</td>\n",
       "      <td>SIK-New1</td>\n",
       "      <td>840-000400-102</td>\n",
       "      <td>441-42907-301</td>\n",
       "      <td>1</td>\n",
       "      <td>TBD</td>\n",
       "      <td>TBD</td>\n",
       "      <td>CPA ASSY 441-42907-302</td>\n",
       "      <td>CPA</td>\n",
       "      <td>1333.4</td>\n",
       "      <td>...</td>\n",
       "      <td>13468.8</td>\n",
       "      <td>12135.4</td>\n",
       "      <td>NaN</td>\n",
       "      <td>Proto &amp; FTB</td>\n",
       "      <td>SIK-New</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>Standard</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>332</th>\n",
       "      <td>SIK-New</td>\n",
       "      <td>SIK-New1</td>\n",
       "      <td>840-000400-102</td>\n",
       "      <td>441-42907-301</td>\n",
       "      <td>1</td>\n",
       "      <td>TBD</td>\n",
       "      <td>TBD</td>\n",
       "      <td>CPA ASSY 441-42907-302</td>\n",
       "      <td>CPA</td>\n",
       "      <td>1333.4</td>\n",
       "      <td>...</td>\n",
       "      <td>13468.8</td>\n",
       "      <td>12135.4</td>\n",
       "      <td>NaN</td>\n",
       "      <td>Proto &amp; FTB</td>\n",
       "      <td>SIK-New</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>Standard</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>333 rows × 26 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "    Priority Pty Indice   IDD Top Level SEDA Top Level  Backlog row Qty  \\\n",
       "0          1         P1    840-000435-1  351-39193-001                1   \n",
       "1          1         P1    840-000435-1  351-39193-001                1   \n",
       "2          1         P1    840-000435-1  351-39193-001                1   \n",
       "3          1         P1    840-000435-1  351-39193-001               11   \n",
       "4          1         P1    840-000435-1  351-39193-001               10   \n",
       "..       ...        ...             ...            ...              ...   \n",
       "328  SIK-New   SIK-New1  840-000400-102  441-42907-301                1   \n",
       "329  SIK-New   SIK-New1  840-000400-102  441-42907-301                1   \n",
       "330  SIK-New   SIK-New1  840-000400-102  441-42907-301                1   \n",
       "331  SIK-New   SIK-New1  840-000400-102  441-42907-301                1   \n",
       "332  SIK-New   SIK-New1  840-000400-102  441-42907-301                1   \n",
       "\n",
       "    Critical Qty Remain. crit. Qty     Backlog Description  \\\n",
       "0      Completed         Completed  CPA ASSY 351-39193-001   \n",
       "1      Completed         Completed  CPA ASSY 351-39193-001   \n",
       "2      Completed         Completed  CPA ASSY 351-39193-001   \n",
       "3      Completed         Completed  CPA ASSY 351-39193-001   \n",
       "4      Completed         Completed  CPA ASSY 351-39193-001   \n",
       "..           ...               ...                     ...   \n",
       "328          TBD               TBD  CPA ASSY 441-42907-302   \n",
       "329          TBD               TBD  CPA ASSY 441-42907-302   \n",
       "330          TBD               TBD  CPA ASSY 441-42907-302   \n",
       "331          TBD               TBD  CPA ASSY 441-42907-302   \n",
       "332          TBD               TBD  CPA ASSY 441-42907-302   \n",
       "\n",
       "    General Description  Marge standard  ... Currency net amount  \\\n",
       "0                   MCP         -3060.5  ...                 0.0   \n",
       "1                   MCP         -3060.5  ...                 0.0   \n",
       "2                   MCP         -3060.5  ...                 0.0   \n",
       "3                   MCP         -1334.3  ...             32331.1   \n",
       "4                   MCP         -1213.0  ...             29391.9   \n",
       "..                  ...             ...  ...                 ...   \n",
       "328                 CPA          1333.4  ...             13468.8   \n",
       "329                 CPA          1333.4  ...             13468.8   \n",
       "330                 CPA          1333.4  ...             13468.8   \n",
       "331                 CPA          1333.4  ...             13468.8   \n",
       "332                 CPA          1333.4  ...             13468.8   \n",
       "\n",
       "    Actual amount -standard SO Modified Production Status  Program  \\\n",
       "0                    3060.5         NaN         Completed  Phase 4   \n",
       "1                    3060.5         NaN         Completed  Phase 4   \n",
       "2                    3060.5         NaN         Completed  Phase 4   \n",
       "3                   33665.3         NaN         Completed  Phase 4   \n",
       "4                   30604.9         NaN         Completed  Phase 4   \n",
       "..                      ...         ...               ...      ...   \n",
       "328                 12135.4         NaN       Proto & FTB  SIK-New   \n",
       "329                 12135.4         NaN       Proto & FTB  SIK-New   \n",
       "330                 12135.4         NaN       Proto & FTB  SIK-New   \n",
       "331                 12135.4         NaN       Proto & FTB  SIK-New   \n",
       "332                 12135.4         NaN       Proto & FTB  SIK-New   \n",
       "\n",
       "    Last Update  Top-Level Status  Order Type Top-Level Status_y  \\\n",
       "0    06-27-2024               NaN        None                NaN   \n",
       "1           NaN               NaN        None                NaN   \n",
       "2           NaN               NaN        None                NaN   \n",
       "3           NaN               NaN    Standard                NaN   \n",
       "4           NaN               NaN    Standard                NaN   \n",
       "..          ...               ...         ...                ...   \n",
       "328         NaN               NaN    Standard                NaN   \n",
       "329         NaN               NaN    Standard                NaN   \n",
       "330         NaN               NaN    Standard                NaN   \n",
       "331         NaN               NaN    Standard                NaN   \n",
       "332         NaN               NaN    Standard                NaN   \n",
       "\n",
       "    Production Status_y  \n",
       "0                   NaN  \n",
       "1                   NaN  \n",
       "2                   NaN  \n",
       "3                   NaN  \n",
       "4                   NaN  \n",
       "..                  ...  \n",
       "328                 NaN  \n",
       "329                 NaN  \n",
       "330                 NaN  \n",
       "331                 NaN  \n",
       "332                 NaN  \n",
       "\n",
       "[333 rows x 26 columns]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Charts successfully added to 'Graph_06-27-2024.xlsx'\n"
     ]
    }
   ],
   "source": [
    "import xlsxwriter\n",
    "import openpyxl\n",
    "import pandas as pd\n",
    "from openpyxl import load_workbook\n",
    "from openpyxl.chart import BarChart, PieChart, Reference\n",
    "import re\n",
    "from openpyxl.styles import Border, Side, Alignment, Font\n",
    "from openpyxl.chart.label import DataLabelList\n",
    "from openpyxl.utils.dataframe import dataframe_to_rows\n",
    "from openpyxl.worksheet.datavalidation import DataValidation\n",
    "from openpyxl.styles import PatternFill, Font, Alignment\n",
    "import os\n",
    "from openpyxl.chart.text import Text, RichText\n",
    "from openpyxl.drawing.text import Paragraph, RegularTextRun\n",
    "\n",
    "##############################################################################################################################\n",
    "# Define date and path\n",
    "##############################################################################################################################\n",
    "# Define paths and file names\n",
    "input_file_formatted = 'Clear-to-Build-06-27-2024_Formatted.xlsx'\n",
    "\n",
    "# Extract date from the file name using regular expressions\n",
    "match = re.search(r'\\d{2}-\\d{2}-\\d{4}', input_file_formatted)\n",
    "if match:\n",
    "    file_date = match.group()\n",
    "    print(\"File Date:\", file_date)\n",
    "else:\n",
    "    print(\"File Date could not be determined.\")\n",
    "\n",
    "output_file_name_Graph = f'Graph_{file_date}.xlsx'\n",
    "\n",
    "#Define Path to Template\n",
    "Path = 'Inputs\\Templates'\n",
    "    \n",
    "##############################################################################################################################\n",
    "# Load workbook\n",
    "##############################################################################################################################\n",
    "# Load the Excel files into pandas DataFrames\n",
    "try:\n",
    "    df_Summary = pd.read_excel(input_file_formatted, sheet_name='Summary')\n",
    "    df_Priority = pd.read_excel(input_file_formatted, sheet_name='CM-Priority')\n",
    "    df_snapshot = pd.read_excel(input_file_formatted, sheet_name='Snapshot')\n",
    "    df_TurnoverReport = pd.read_excel(input_file_formatted, sheet_name='CM-TurnoverReport')\n",
    "    df_backlog = pd.read_excel(input_file_formatted, sheet_name='CM-Backlog')\n",
    "    print(\"Input files loaded successfully.\")\n",
    "except FileNotFoundError as e:\n",
    "    print(f\"File not found: {e}\")\n",
    "    exit()\n",
    "\n",
    "# Load the workbook\n",
    "try:\n",
    "    workbook = load_workbook(input_file_formatted)\n",
    "    print(f\"Successfully loaded '{input_file_formatted}'\")\n",
    "except FileNotFoundError as e:\n",
    "    print(f\"File not found: {e}\")\n",
    "    exit()\n",
    "\n",
    "#######################################################\n",
    "# Define function to get chart titles and indices\n",
    "######################################################\n",
    "def extract_text_from_chart_text(chart_text):\n",
    "    \"\"\"\n",
    "    Extracts text from chart title objects which may be rich text or simple strings.\n",
    "    \"\"\"\n",
    "    if isinstance(chart_text, Text):\n",
    "        return chart_text.text if chart_text.text else None\n",
    "    elif isinstance(chart_text, RichText):\n",
    "        paragraphs = chart_text.p\n",
    "        if paragraphs:\n",
    "            text_parts = []\n",
    "            for paragraph in paragraphs:\n",
    "                for run in paragraph.r:\n",
    "                    if isinstance(run, RegularTextRun):\n",
    "                        text_parts.append(run.t)\n",
    "                    elif isinstance(run, str):\n",
    "                        text_parts.append(run)\n",
    "            return \" \".join(text_parts)\n",
    "    elif isinstance(chart_text, str):  # Handle cases where title is a simple string\n",
    "        return chart_text.strip()\n",
    "\n",
    "    return None\n",
    "\n",
    "def get_chart_properties(file_path, sheet_name):\n",
    "    try:\n",
    "        wb = load_workbook(file_path, data_only=True)\n",
    "        sheet = wb[sheet_name]\n",
    "\n",
    "        chart_properties = []\n",
    "\n",
    "        if hasattr(sheet, '_charts'):  # Check if the sheet has charts\n",
    "            for idx, chart in enumerate(sheet._charts, start=1):\n",
    "                chart_type = type(chart).__name__\n",
    "                chart_title = extract_text_from_chart_text(chart.title)\n",
    "                chart_properties.append({\n",
    "                    'Chart Index': idx,\n",
    "                    'Chart Type': chart_type,\n",
    "                    'Chart Title': chart_title if chart_title else 'No title'\n",
    "                })\n",
    "        else:\n",
    "            print(f\"No charts found in sheet '{sheet_name}'.\")\n",
    "\n",
    "        return chart_properties\n",
    "\n",
    "    except FileNotFoundError:\n",
    "        print(f\"File '{file_path}' not found.\")\n",
    "        return []\n",
    "\n",
    "    except Exception as e:\n",
    "        print(f\"Error occurred while processing '{file_path}': {e}\")\n",
    "        return []\n",
    "\n",
    "'''\n",
    "# Example usage:\n",
    "file_name_Template = 'Graph_Template.xlsx'  # Replace with your actual file name\n",
    "sheet_name = 'Graph'  # Replace with your actual sheet name\n",
    "file_path = os.path.join('Inputs', 'Templates', file_name_Template)  # Adjust the path as necessary\n",
    "\n",
    "chart_properties = get_chart_properties(file_path, sheet_name)\n",
    "\n",
    "if chart_properties:\n",
    "    print(f\"Charts found in sheet '{sheet_name}':\")\n",
    "    for chart in chart_properties:\n",
    "        print(f\"Chart {chart['Chart Index']} - Type: {chart['Chart Type']}\")\n",
    "        print(f\"Chart {chart['Chart Index']} - Title: {chart['Chart Title']}\")\n",
    "else:\n",
    "    print(f\"No charts found in sheet '{sheet_name}'.\")\n",
    "'''\n",
    "#******************************************************************************************************************************\n",
    "##############################################################################################################################\n",
    "#Create |Graph|\n",
    "##############################################################################################################################\n",
    "#******************************************************************************************************************************\n",
    "# Check if 'Graph' sheet already exists and replace it\n",
    "if 'Graph' in workbook.sheetnames:\n",
    "    # Delete existing 'Graph' sheet\n",
    "    workbook.remove(workbook['Graph'])\n",
    "\n",
    "# Create 'Graph' sheet\n",
    "graph_sheet = workbook.create_sheet(title='Graph', index = 0)\n",
    "print(\"|Graph| tab created successfully.\") \n",
    "\n",
    "#********************************************************************************************************************************\n",
    "# Divide |Graph| in 2 section --> |Project History|  |General Overview|  |Clear to Build Overview| |Progression Overview| \n",
    "                                # |                                       Project Status                               |\n",
    "#******************************************************************************************************************************\n",
    "# Write title \"Project History\" in cell A1\n",
    "graph_sheet['A1'] = 'Project History'\n",
    "graph_sheet['A1'].font = Font(bold=True)\n",
    "graph_sheet['A1'].alignment = Alignment(horizontal='center')\n",
    "\n",
    "# Merge cells A1 to N1\n",
    "graph_sheet.merge_cells('A1:M1')\n",
    "\n",
    "# Write title \"General Overview\" in cell N1\n",
    "graph_sheet['N1'] = 'General Overview'\n",
    "graph_sheet['N1'].font = Font(bold=True)\n",
    "graph_sheet['N1'].alignment = Alignment(horizontal='center')\n",
    "\n",
    "# Merge cells N1 to Z1\n",
    "graph_sheet.merge_cells('N1:Z1')\n",
    "\n",
    "# Write title \"General Overview\" in cell AA1\n",
    "graph_sheet['AA1'] = 'Clear to Build Overview'\n",
    "graph_sheet['AA1'].font = Font(bold=True)\n",
    "graph_sheet['AA1'].alignment = Alignment(horizontal='center')\n",
    "\n",
    "# Merge cells AA1 to AM1\n",
    "graph_sheet.merge_cells('AA1:AM1')\n",
    "\n",
    "# Write title \"Progression Overview\" in cell AN1\n",
    "graph_sheet['AN1'] = 'Progression Overview'\n",
    "graph_sheet['AN1'].font = Font(bold=True)\n",
    "graph_sheet['AN1'].alignment = Alignment(horizontal='center')\n",
    "\n",
    "# Merge cells AN1 to A1:AZ1\n",
    "graph_sheet.merge_cells('AN1:AZ1')\n",
    "\n",
    "# Write title \"Project Status\" in cell A79\n",
    "graph_sheet['A79'] = 'Project Status'\n",
    "graph_sheet['A79'].font = Font(bold=True)\n",
    "graph_sheet['A79'].alignment = Alignment(horizontal='center')\n",
    "\n",
    "# Merge cells A79 to AZ79\n",
    "graph_sheet.merge_cells('A79:AZ79')\n",
    "\n",
    "####################\n",
    "#Formatting row 1\n",
    "##################\n",
    "# Define fill color (blue)\n",
    "fill = PatternFill(start_color='8DB4E2', end_color='8DB4E2', fill_type='solid')\n",
    "\n",
    "# Font properties (white color, size 16)\n",
    "font = Font(color='FFFFFF', size=16)\n",
    "\n",
    "# Apply styles to row 1\n",
    "for col in range(1, graph_sheet.max_column + 1):\n",
    "    cell = graph_sheet.cell(row=1, column=col)\n",
    "    cell.fill = fill\n",
    "    cell.font = font\n",
    "    cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "\n",
    "####################\n",
    "#Formatting row 79\n",
    "##################\n",
    "# Apply styles to row 79\n",
    "for col in range(1, graph_sheet.max_column + 1):\n",
    "    cell = graph_sheet.cell(row=79, column=col)\n",
    "    cell.fill = fill\n",
    "    cell.font = font\n",
    "    cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "    \n",
    "###############################\n",
    "# Graph Label number\n",
    "###############################\n",
    "'''\n",
    "graph_sheet['A2'] = 1\n",
    "graph_sheet['A27'] = 2\n",
    "graph_sheet['A52'] = 3\n",
    "graph_sheet['N2'] = 4\n",
    "graph_sheet['N27'] = 5\n",
    "graph_sheet['N52'] = 6\n",
    "graph_sheet['AA2'] = 7\n",
    "graph_sheet['AA27'] = 8\n",
    "graph_sheet['AA52'] = 9\n",
    "graph_sheet['AN2'] = 10\n",
    "graph_sheet['AN27'] = 11\n",
    "graph_sheet['AN52'] = 12\n",
    "graph_sheet['A80'] = 13\n",
    "graph_sheet['A115'] = 14\n",
    "'''\n",
    "\n",
    "# Write numbers in specified positions using indices\n",
    "positions = [(2, 1, 1), (2, 14, 4), (2, 27, 7), (27, 1, 2), (27, 14, 5), (27, 27, 8), (2, 40, 10), (27, 40, 11), (52, 1, 3), (52, 14, 6), (52, 27, 9), (52, 40, 12), (80, 1, 13), (115, 1, 14)] # (row, column, 'Number')\n",
    "for row_idx, col_idx, number in positions:\n",
    "    cell = graph_sheet.cell(row=row_idx, column=col_idx)\n",
    "    cell.value = number\n",
    "    cell.fill = fill\n",
    "    cell.font = Font(color='FFFFFF', size=14, bold=True)\n",
    "    cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "    \n",
    "#########################################################################\n",
    "# Set the width of column A to 2.5 (or any desired width)\n",
    "graph_sheet.column_dimensions['A'].width = 4\n",
    "\n",
    "# Set the width of column N to 2 (or any desired width)\n",
    "graph_sheet.column_dimensions['N'].width = 4\n",
    "\n",
    "# Set the width of column AA to 2 (or any desired width)\n",
    "graph_sheet.column_dimensions['AA'].width = 4\n",
    "\n",
    "# Set the width of column AN to 2 (or any desired width)\n",
    "graph_sheet.column_dimensions['AN'].width = 4\n",
    "\n",
    "##########################################################################################\n",
    "## Horizontal tick border column N, AB, AM, AZ/ Vertical dashDot border A30:AZ30, A52:AZ52\n",
    "##########################################################################################\n",
    "# Define a thick border style for the upper border\n",
    "thick_border_upper = Border(top=Side(style='thick',color='000000'))\n",
    "\n",
    "# Apply the thick border to row 2 from column A to AZ\n",
    "for col in range(1, 53):  # Columns A to AZ (1 to 53)\n",
    "    cell = graph_sheet.cell(row=2, column=col)\n",
    "    cell.border = thick_border_upper\n",
    "\n",
    "# Define a dashdot border style for the upper border\n",
    "dash_border_upper = Border(top=Side(style='dashDot',color='808080'))\n",
    "\n",
    "# Apply the Dash border to row 27 from column A to AZ\n",
    "for col in range(1, 53):  # Columns A to AZ (1 to 53)\n",
    "    cell = graph_sheet.cell(row=27, column=col)\n",
    "    cell.border = dash_border_upper\n",
    "\n",
    "# Apply the Dash border to row 52 from column A to AZ\n",
    "for col in range(1, 53):  # Columns A to AZ (1 to 53)\n",
    "    cell = graph_sheet.cell(row=52, column=col)\n",
    "    cell.border = dash_border_upper\n",
    "\n",
    "#####################################\n",
    "### Define vertical thick border style\n",
    "##########################################\n",
    "thick_border_left = Border(left=Side(style='thick'))\n",
    "\n",
    "# Apply the thick border to column N from row 1 to 79\n",
    "for row in range(1, 80):\n",
    "    cell_N = graph_sheet.cell(row=row, column=14)  # Column N is the 14th column\n",
    "    cell_N.border = thick_border_left\n",
    "\n",
    "# Apply the thick border to column AA from row 1 to 79\n",
    "for row in range(1, 80):\n",
    "    cell_AA = graph_sheet.cell(row=row, column=27)  # Column AA is the 27th column\n",
    "    cell_AA.border = thick_border_left\n",
    "\n",
    "# Apply the thick border to column AM from row 1 to 79\n",
    "for row in range(1, 80):\n",
    "    cell_AM = graph_sheet.cell(row=row, column=40)  # Column AM is the 40th column\n",
    "    cell_AM.border = thick_border_left\n",
    "\n",
    "# Apply the thick border to column AZ from row 1 to 150\n",
    "for row in range(1, 149):\n",
    "    cell_AM = graph_sheet.cell(row=row, column=53)  # Column AZ is the 53th column\n",
    "    cell_AM.border = thick_border_left\n",
    "\n",
    "############################\n",
    "#Combined Left/Upper border \n",
    "############################\n",
    "# Apply both the thick left and upper borders to cell N27\n",
    "cell_N2 = graph_sheet.cell(row=2, column=14)  # Column N is the 14th column\n",
    "cell_N2.border = Border(left=thick_border_left.left, top=thick_border_upper.top)\n",
    "\n",
    "# Apply both the thick left and DashDot upper borders to cell AA27\n",
    "cell_AA27= graph_sheet.cell(row=27, column=27)  # Column AA is the 27th column\n",
    "cell_AA27.border = Border(left=thick_border_left.left, top=dash_border_upper.top)\n",
    "\n",
    "# Apply both the thick left and upper borders to cell N27\n",
    "cell_N27 = graph_sheet.cell(row=27, column=14)  # Column N is the 14th column\n",
    "cell_N27.border = Border(left=thick_border_left.left, top=dash_border_upper.top)\n",
    "\n",
    "# Apply both the thick left and upper borders to cell AA2\n",
    "cell_AA2 = graph_sheet.cell(row=2, column=27)  # Column AA is the 28th column\n",
    "cell_AA2.border = Border(left=thick_border_left.left, top=thick_border_upper.top)\n",
    "\n",
    "# Apply both the thick left and upper borders to cell AN27\n",
    "cell_AN27 = graph_sheet.cell(row=27, column=40)  # Column N is the 14th column\n",
    "cell_AN27.border = Border(left=thick_border_left.left, top=dash_border_upper.top)\n",
    "\n",
    "# Apply both the thick left and upper borders to cell AN2\n",
    "cell_AN2 = graph_sheet.cell(row=2, column=40)  # Column AN is the 28th column\n",
    "cell_AN2.border = Border(left=thick_border_left.left, top=thick_border_upper.top)\n",
    "\n",
    "################################################\n",
    "# Horizantal Border for section |Project Status|\n",
    "###############################################\n",
    "# Apply the thick border to row 79 from column A to AZ\n",
    "for col in range(1, 53):  # Columns A to AZ (1 to 53)\n",
    "    cell = graph_sheet.cell(row=79, column=col)\n",
    "    cell.border = thick_border_upper\n",
    "\n",
    "# Apply the thick border to row 80 from column A to AZ\n",
    "for col in range(1, 53):  # Columns A to AZ (1 to 53)\n",
    "    cell = graph_sheet.cell(row=80, column=col)\n",
    "    cell.border = thick_border_upper\n",
    "    \n",
    "###################################\n",
    "#****************************************************************************************************************************\n",
    "# CHARTS \n",
    "#****************************************************************************************************************************\n",
    "#####################################################\n",
    "#Create a new dataframe including the completed PN\n",
    "#######################################################\n",
    "#Include the Pty Indice not in |Snapshot| (df_Snapshot) but present in |CM-Priority| (df_Priority) with 'Production Status' = 'Completed' \n",
    "#Include in a new df_Snapshot_Priority the column 'Description','Production Status', 'IDD Sale Price', 'SEDA Sale Price' from CM-Priority\n",
    "df_Priority_filtered = df_Priority[df_Priority['Production Status'] == 'Completed'][['Pty Indice', 'Priority', 'IDD Top Level', 'SEDA Top Level', 'Shipped', 'Remain. crit. Qty','Description', 'Production Status', 'SEDA Sale Price']]\n",
    "\n",
    "#Merge df_snapshot with df_Priority_filtered based on 'Pty Indice'\n",
    "df_snapshot_priority = pd.concat([df_snapshot, df_Priority_filtered], ignore_index=True)\n",
    "\n",
    "# Fill NaN values in 'Top-Level Status' with 'Completed' for the newly merged rows\n",
    "df_snapshot_priority['Top-Level Status'].fillna('Completed', inplace=True)\n",
    "\n",
    "#Aplly function to fill the 'Product Category' \n",
    "def determine_category(description):\n",
    "    if not isinstance(description, str):\n",
    "        return 'Others'\n",
    "    if description == 'Rototellite':\n",
    "        return 'Rototellite'\n",
    "    elif 'Indicator' in description or 'CPA' in description:\n",
    "        return 'CPA'\n",
    "    elif 'Lightplate' in description:\n",
    "        return 'Lightplate'\n",
    "    elif 'ISP' in description or 'Keyboard' in description:\n",
    "        return 'ISP'\n",
    "    elif 'Module' in description:\n",
    "        return 'CPA'\n",
    "    elif 'optics' in description:\n",
    "        return 'Fiber Optics'\n",
    "    else:\n",
    "        return 'Others'\n",
    "\n",
    "# Apply the determine_category function to 'Description' column\n",
    "df_snapshot_priority['Product Category'] = df_snapshot_priority['Description'].apply(determine_category)\n",
    "\n",
    "#display(df_snapshot_priority)\n",
    "\n",
    "####################################################################################\n",
    "#***************************************************************************************************************************\n",
    "#|Project History|\n",
    "#***************************************************************************************************************************\n",
    "##############################################################################################################################\n",
    "# Creating Graph#1 []\n",
    "##############################################################################################################################\n",
    "# Calculate percentage distribution and round to one decimal place\n",
    "category_counts = df_snapshot_priority['Product Category'].value_counts(normalize=True) * 100\n",
    "category_percentages = category_counts.round(1)\n",
    "\n",
    "# Write data to the worksheet starting from row 3, column 2 (B3)\n",
    "graph_sheet.cell(row=3, column=2, value=\"Product Category\")\n",
    "graph_sheet.cell(row=3, column=3, value=\"Percentage\")\n",
    "\n",
    "# Write category and percentage data to the worksheet\n",
    "for idx, (category, percentage) in enumerate(category_percentages.items(), start=4):\n",
    "    graph_sheet.cell(row=idx, column=2, value=category)\n",
    "    graph_sheet.cell(row=idx, column=3, value=percentage)\n",
    "\n",
    "###############################################\n",
    "# Create the chart title including the subtitle\n",
    "################################################\n",
    "chart_title = f\"Percentage Distribution of Product Categories\\nInputs date: {file_date} - Source: |CM-Priority|\"\n",
    "\n",
    "# Create a pie chart\n",
    "chart1 = PieChart()\n",
    "chart1.title = chart_title\n",
    "\n",
    "################################################\n",
    "# Prepare data for the pie chart using Reference\n",
    "####################################################\n",
    "min_row = 3  # Start from row 3 where your data starts\n",
    "max_row = min_row + len(category_percentages)  # Calculate the last row based on the number of categories\n",
    "min_row_label = 4  # Start from row 4 for labels\n",
    "max_row_label = min_row_label + len(category_percentages) - 1\n",
    "\n",
    "data_points = Reference(graph_sheet, min_col=3, min_row=min_row, max_row=max_row)  # Adjusted min_col to 3\n",
    "labels = Reference(graph_sheet, min_col=2, min_row=min_row_label, max_row=max_row_label)  # Adjusted min_col to 2\n",
    "\n",
    "chart1.add_data(data_points, titles_from_data=True)\n",
    "chart1.set_categories(labels)\n",
    "    \n",
    "#############################\n",
    "# Set size/position\n",
    "##############################\n",
    "chart1.width = 20  # Adjust the width as needed\n",
    "chart1.height = 11  # Adjust the height as needed\n",
    "\n",
    "# Positioning  \n",
    "graph_sheet.add_chart(chart1, \"B3\")\n",
    "\n",
    "\n",
    "\n",
    "##############################################################################################################################\n",
    "# Creating Graph#2 []\n",
    "##############################################################################################################################\n",
    "# Calculate percentage distribution and round to one decimal place\n",
    "status_counts = df_snapshot_priority['Production Status'].value_counts(normalize=True) * 100\n",
    "status_percentages = status_counts.round(1)\n",
    "\n",
    "# Write data to the worksheet starting from row 28, column 2 (B28)\n",
    "graph_sheet.cell(row=28, column=2, value=\"Production Status\")\n",
    "graph_sheet.cell(row=28, column=3, value=\"Percentage\")\n",
    "\n",
    "# Write category and percentage data to the worksheet\n",
    "for idx, (status, percentage) in enumerate(status_percentages.items(), start=28):  # Start index corrected to 28\n",
    "    graph_sheet.cell(row=idx + 1, column=2, value=status)  # Adjusted row index and added +1 to start from 29\n",
    "    graph_sheet.cell(row=idx + 1, column=3, value=percentage)  # Adjusted row index and added +1 to start from 29\n",
    "\n",
    "###############################################\n",
    "# Create the chart title including the subtitle\n",
    "################################################\n",
    "chart_title = f\"Percentage Distribution of Production Status\\nInputs date: {file_date} - Source: |CM-Priority|\"\n",
    "\n",
    "# Create a pie chart\n",
    "chart2 = PieChart()\n",
    "chart2.title = chart_title\n",
    "################################################\n",
    "\n",
    "# Prepare data for the pie chart using Reference\n",
    "min_row = 28  # Start from row 28 to include the data\n",
    "max_row = min_row + len(status_percentages)  # Calculate the last row based on the number of statuses\n",
    "min_row_label = 29  # Start from row 29 for labels\n",
    "max_row_label = min_row_label + len(status_percentages) - 1\n",
    "\n",
    "data_points = Reference(graph_sheet, min_col=3, min_row=min_row, max_row=max_row)  # Adjusted min_col to 3\n",
    "labels = Reference(graph_sheet, min_col=2, min_row=min_row_label, max_row=max_row_label)  # Adjusted min_col to 2\n",
    "\n",
    "chart2.add_data(data_points, titles_from_data=True)\n",
    "chart2.set_categories(labels)\n",
    "\n",
    "# Set the size of the chart\n",
    "chart2.width = 20  # Adjust the width as needed\n",
    "chart2.height = 11  # Adjust the height as needed\n",
    "\n",
    "# Positioning the chart\n",
    "graph_sheet.add_chart(chart2, \"B28\")\n",
    "\n",
    "\n",
    "##############################################################################################################################\n",
    "# Creating Graph#3 []\n",
    "##############################################################################################################################\n",
    "\n",
    "\n",
    "\n",
    "#***************************************************************************************************************************\n",
    "#|General Overview|\n",
    "#***************************************************************************************************************************\n",
    "##############################################################################################################################\n",
    "# Creating Graph#4 []\n",
    "##############################################################################################################################\n",
    "# Calculate percentage distribution and round to one decimal place\n",
    "category_counts = df_snapshot['Product Category'].value_counts(normalize=True) * 100\n",
    "category_percentages = category_counts.round(1)\n",
    "\n",
    "# Write data to the worksheet starting from row 3, column 15 (O3)\n",
    "graph_sheet.cell(row=3, column=15, value=\"Product Category\")\n",
    "graph_sheet.cell(row=3, column=16, value=\"Percentage\")\n",
    "\n",
    "# Write category and percentage data to the worksheet\n",
    "for idx, (category, percentage) in enumerate(category_percentages.items(), start=4):\n",
    "    graph_sheet.cell(row=idx, column=15, value=category)\n",
    "    graph_sheet.cell(row=idx, column=16, value=percentage)\n",
    "\n",
    "###############################################\n",
    "# Create the chart title including the subtitle\n",
    "################################################\n",
    "chart_title = f\"Percentage Distribution of Product Categories\\nInputs date: {file_date} - Source: |CM-Snapshot|\"\n",
    "\n",
    "# Create a pie chart\n",
    "chart4 = PieChart()\n",
    "chart4.title = chart_title\n",
    "\n",
    "##########################################################\n",
    "# Prepare data for the pie chart using Reference\n",
    "min_row = 3  # Start from row 3 where your data starts\n",
    "max_row = min_row + len(category_percentages) # Calculate the last row based on the number of categories\n",
    "min_row_label = 4  # Start from row 4 for labels\n",
    "max_row_label = min_row_label + len(category_percentages) - 1\n",
    "\n",
    "data_points = Reference(graph_sheet, min_col=16, min_row=min_row, max_row=max_row)  # Adjusted min_col to 16\n",
    "labels = Reference(graph_sheet, min_col=15, min_row=min_row_label, max_row=max_row_label)  # Adjusted min_col to 15\n",
    "\n",
    "chart4.add_data(data_points, titles_from_data=True)\n",
    "chart4.set_categories(labels)\n",
    "    \n",
    "#############################\n",
    "# Set the size of the chart4\n",
    "##############################\n",
    "chart4.width = 20  # Adjust the width as needed\n",
    "chart4.height = 11  # Adjust the height as needed\n",
    "\n",
    "# Positioning the chart4 \n",
    "graph_sheet.add_chart(chart4, \"O3\")\n",
    "##############################################################################################################################\n",
    "\n",
    "##############################################################################################################################\n",
    "# Creating Graph#5 []\n",
    "##############################################################################################################################\n",
    "# Calculate percentage distribution and round to one decimal place\n",
    "status_counts = df_snapshot['Production Status'].value_counts(normalize=True) * 100\n",
    "status_percentages = status_counts.round(1)\n",
    "\n",
    "# Write data to the worksheet starting from row 28, column 15 (O28)\n",
    "graph_sheet.cell(row=28, column=15, value=\"Production Status\")\n",
    "graph_sheet.cell(row=28, column=16, value=\"Percentage\")\n",
    "\n",
    "# Write status and percentage data to the worksheet starting from row 29\n",
    "for idx, (status, percentage) in enumerate(status_percentages.items(), start=29):\n",
    "    graph_sheet.cell(row=idx, column=15, value=status)\n",
    "    graph_sheet.cell(row=idx, column=16, value=percentage)\n",
    "\n",
    "###############################################\n",
    "# Create the chart title including the subtitle\n",
    "################################################\n",
    "chart_title = f\"Percentage Distribution of Production Status\\nInputs date: {file_date} - Source: |CM-Snapshot|\"\n",
    "\n",
    "chart5 = PieChart()\n",
    "chart5.title = chart_title\n",
    "\n",
    "############################################################\n",
    "# Prepare data for the pie chart using Reference\n",
    "min_row = 28  # Start from row 29 to include the data\n",
    "max_row = min_row + len(status_percentages)  # Calculate the last row based on the number of statuses\n",
    "min_row_label = 29  # Start from row 29 for labels\n",
    "max_row_label = min_row_label + len(status_percentages) - 1\n",
    "\n",
    "data_points = Reference(graph_sheet, min_col=16, min_row=min_row, max_row=max_row)  # Adjusted min_col to 16\n",
    "labels = Reference(graph_sheet, min_col=15, min_row=min_row_label, max_row=max_row_label)  # Adjusted min_col to 15\n",
    "\n",
    "chart5.add_data(data_points, titles_from_data=True)\n",
    "chart5.set_categories(labels)\n",
    "    \n",
    "#############################\n",
    "# Set size/position\n",
    "##############################\n",
    "chart5.width = 20  # Adjust the width as needed\n",
    "chart5.height = 11  # Adjust the height as needed\n",
    "\n",
    "# Positioning  \n",
    "graph_sheet.add_chart(chart5, \"O28\")\n",
    "\n",
    "##############################################################################################################################\n",
    "\n",
    "##############################################################################################################################\n",
    "# Creating Graph#6 []\n",
    "##############################################################################################################################\n",
    "\n",
    "\n",
    "#***************************************************************************************************************************\n",
    "#|Clear to Build Overview|\n",
    "#***************************************************************************************************************************\n",
    "##############################################################################################################################\n",
    "# Creating Graph#7 []\n",
    "##############################################################################################################################\n",
    "# Calculate unique IDD Top Level for each Product Category and each classification\n",
    "pivot_table_df = pd.pivot_table(df_snapshot,\n",
    "                                index='Product Category',\n",
    "                                columns='Top-Level Status',\n",
    "                                values='IDD Top Level',\n",
    "                                aggfunc=pd.Series.nunique,\n",
    "                                fill_value=0)\n",
    "\n",
    "# Calculate total unique IDD Top Level across all categories\n",
    "total_unique_idd_top_level = df_snapshot['IDD Top Level'].nunique()\n",
    "\n",
    "# Write headers for each column first\n",
    "start_cell_row = 3\n",
    "start_cell_col = 28  # Column 'AB3'\n",
    "\n",
    "# Write headers\n",
    "graph_sheet.cell(row=start_cell_row, column=start_cell_col, value=\"Product Category\")\n",
    "graph_sheet.cell(row=start_cell_row, column=start_cell_col + 1, value=\"Unique IDD Top Level (Clear-to-Build)\")\n",
    "graph_sheet.cell(row=start_cell_row, column=start_cell_col + 2, value=\"Unique IDD Top Level (Short)\")\n",
    "\n",
    "# Write data rows\n",
    "for r_idx, (index, row) in enumerate(pivot_table_df.iterrows(), start=start_cell_row + 1):\n",
    "    graph_sheet.cell(row=r_idx, column=start_cell_col, value=index)  # Write Product Category\n",
    "    graph_sheet.cell(row=r_idx, column=start_cell_col + 1, value=row['Clear-to-Build'])  # Write unique count for Clear-to-Build\n",
    "    graph_sheet.cell(row=r_idx, column=start_cell_col + 2, value=row['Short'])  # Write unique count for Short\n",
    "\n",
    "# Add the total unique IDD Top Level label and value in the last row\n",
    "total_row = start_cell_row + len(pivot_table_df) + 1\n",
    "graph_sheet.cell(row=total_row, column=start_cell_col, value=\"Total Unique IDD Top Level\")\n",
    "graph_sheet.cell(row=total_row, column=start_cell_col + 1, value=pivot_table_df['Clear-to-Build'].sum())\n",
    "graph_sheet.cell(row=total_row, column=start_cell_col + 2, value=pivot_table_df['Short'].sum())\n",
    "\n",
    "###############################################\n",
    "# Create the chart title including the subtitle\n",
    "################################################\n",
    "chart_title = f\"Count of Unique IDD Top Level by Product Category\\nInputs date: {file_date} - Source: |Snapshot|\"\n",
    "\n",
    "# Create a bar chart (chart6)\n",
    "chart7 = BarChart()\n",
    "chart7.title = chart_title\n",
    "chart7.x_axis.title = 'Product Category'\n",
    "chart7.y_axis.title = 'Count of Unique IDD Top Level'\n",
    "\n",
    "##################################################\n",
    "# Define data for the chart (exclude totals row)\n",
    "data = Reference(graph_sheet,\n",
    "                 min_col=start_cell_col + 1,\n",
    "                 min_row=start_cell_row,\n",
    "                 max_col=start_cell_col + 2,\n",
    "                 max_row=start_cell_row + len(pivot_table_df) + 1)\n",
    "chart7.add_data(data, titles_from_data=True)\n",
    "\n",
    "# Set categories (x-axis)\n",
    "categories = Reference(graph_sheet,\n",
    "                       min_col=start_cell_col,\n",
    "                       min_row=start_cell_row + 1,\n",
    "                       max_row=start_cell_row + len(pivot_table_df) + 1)\n",
    "chart7.set_categories(categories)\n",
    "\n",
    "###############################\n",
    "# Set the size of the chart\n",
    "###############################\n",
    "chart7.width = 20  # Adjust the width as needed\n",
    "chart7.height = 11  # Adjust the height as needed\n",
    "\n",
    "# Positioning the chart \n",
    "graph_sheet.add_chart(chart7, \"AB3\")\n",
    "\n",
    "##############################################################################################################################\n",
    "# Creating Graph#8 []\n",
    "##############################################################################################################################\n",
    "# Create a pivot table with 'Product Category' as index\n",
    "pivot_table_df = pd.pivot_table(df_snapshot,\n",
    "                                index='Product Category',\n",
    "                                columns='Top-Level Status',\n",
    "                                values='IDD Backlog Qty',\n",
    "                                aggfunc='sum',\n",
    "                                fill_value=0)\n",
    "\n",
    "# Calculate unique IDD Top Level for Clear to Build and Short\n",
    "unique_idd_top_level_ctb = df_snapshot[df_snapshot['Top-Level Status'] == 'Clear-to-Build']['IDD Top Level'].nunique()\n",
    "unique_idd_top_level_short = df_snapshot[df_snapshot['Top-Level Status'] == 'Short']['IDD Top Level'].nunique()\n",
    "\n",
    "print('Unique IDD Top Level for Clear to Build:', unique_idd_top_level_ctb)\n",
    "print('Unique IDD Top Level for Short:', unique_idd_top_level_short)\n",
    "\n",
    "# Write the pivot table to the graph_sheet starting from AB28\n",
    "start_cell_row = 28\n",
    "start_cell_col = 28  # Column 'AB28'\n",
    "\n",
    "# Write headers for each column first\n",
    "for c_idx, col in enumerate(pivot_table_df.columns, start=start_cell_col + 1):\n",
    "    graph_sheet.cell(row=start_cell_row, column=c_idx, value=col)\n",
    "\n",
    "# Write data rows\n",
    "for r_idx, (index, row) in enumerate(pivot_table_df.iterrows(), start=start_cell_row + 1):\n",
    "    graph_sheet.cell(row=r_idx, column=start_cell_col, value=index)  # Write Product Category\n",
    "    for c_idx, value in enumerate(row, start=start_cell_col + 1):\n",
    "        graph_sheet.cell(row=r_idx, column=c_idx, value=value)\n",
    "\n",
    "# Add the total unique IDD Top Level labels and values in the second row\n",
    "total_row = start_cell_row + 1\n",
    "graph_sheet.cell(row=total_row, column=start_cell_col, value=\"Total unique IDD Top Level\")\n",
    "graph_sheet.cell(row=total_row, column=start_cell_col + 1, value=unique_idd_top_level_ctb)\n",
    "graph_sheet.cell(row=total_row, column=start_cell_col + 2, value=unique_idd_top_level_short)\n",
    "\n",
    "###############################################\n",
    "# Create the chart title including the subtitle\n",
    "################################################\n",
    "chart_title = f\"IDD Backlog Qty by Product Category and Top-Level Status\\nInputs date: {file_date} - Source: |Snapshot|\"\n",
    "\n",
    "chart8 = BarChart()\n",
    "chart8.title = chart_title\n",
    "chart8.x_axis.title = 'Product Category'\n",
    "chart8.y_axis.title = 'IDD Backlog Qty'\n",
    "\n",
    "##################################################\n",
    "# Define data for the chart including total unique IDD Top Level and all rows\n",
    "data = Reference(graph_sheet,\n",
    "                 min_col=start_cell_col + 1,\n",
    "                 min_row=start_cell_row, \n",
    "                 max_col=start_cell_col + len(pivot_table_df.columns),\n",
    "                 max_row=start_cell_row + len(pivot_table_df))\n",
    "chart8.add_data(data, titles_from_data=True)\n",
    "\n",
    "# Set categories (x-axis) including the total unique IDD Top Level label and all rows\n",
    "categories = Reference(graph_sheet,\n",
    "                       min_col=start_cell_col,\n",
    "                       min_row=start_cell_row + 1, \n",
    "                       max_row=start_cell_row + len(pivot_table_df)) \n",
    "chart8.set_categories(categories)\n",
    "\n",
    "###############################\n",
    "# Set the size of the chart\n",
    "###############################\n",
    "chart8.width = 20  # Adjust the width as needed\n",
    "chart8.height = 11  # Adjust the height as needed\n",
    "\n",
    "# Positioning the chart \n",
    "graph_sheet.add_chart(chart8, \"AB28\")\n",
    "\n",
    "##############################################################################################################################\n",
    "# Creating Graph#9 []\n",
    "##############################################################################################################################\n",
    "# Merge df_backlog with df_snapshot to bring 'Top-Level Status' into df_backlog\n",
    "df_backlog = pd.merge(df_backlog, df_snapshot[['Pty Indice', 'Top-Level Status']], on='Pty Indice', how='left')\n",
    "\n",
    "# Define 'Order Type' column based on 'Order' column, excluding rows containing 'NC'\n",
    "df_backlog['Order Type'] = df_backlog['Order'].apply(lambda x: 'DX/DO' if str(x).startswith('D') else ('Standard' if 'NC' not in str(x) else None))\n",
    "\n",
    "# Calculate sum of 'Backlog row Qty' by 'Pty Indice' and 'Order Type'\n",
    "#df_backlog['Sum Backlog Qty'] = df_backlog.groupby(['Pty Indice', 'Order Type'])['Backlog row Qty'].transform('sum')\n",
    "\n",
    "#display(df_backlog) \n",
    "\n",
    "\n",
    "# Calculate sum of 'Backlog row Qty' separately for 'Standard' and 'DX/DO'\n",
    "sum_standard = df_backlog.loc[df_backlog['Order Type'] == 'Standard', 'Backlog row Qty'].sum()\n",
    "sum_dx_do = df_backlog.loc[df_backlog['Order Type'] == 'DX/DO', 'Backlog row Qty'].sum()\n",
    "\n",
    "print(f\"Sum of 'Backlog row Qty' for 'Standard': {sum_standard}\")\n",
    "print(f\"Sum of 'Backlog row Qty' for 'DX/DO': {sum_dx_do}\")\n",
    "\n",
    "#Create pivot table\n",
    "pivot_table_df = pd.pivot_table(df_backlog,\n",
    "                                index='Order Type',\n",
    "                                columns='Top-Level Status',\n",
    "                                values='Backlog row Qty',\n",
    "                                aggfunc='sum',\n",
    "                                fill_value=0)\n",
    "\n",
    "# Write the pivot table to the graph_sheet starting from AB53\n",
    "start_cell_row = 53\n",
    "start_cell_col = 28  # Column AB\n",
    "\n",
    "# Write headers for each column first\n",
    "for c_idx, col in enumerate(pivot_table_df.columns, start=start_cell_col + 1):\n",
    "    graph_sheet.cell(row=start_cell_row, column=c_idx, value=col)\n",
    "\n",
    "# Write data rows\n",
    "for r_idx, (index, row) in enumerate(pivot_table_df.iterrows(), start=start_cell_row + 1):\n",
    "    graph_sheet.cell(row=r_idx, column=start_cell_col, value=index)  # Write Order Type\n",
    "    for c_idx, value in enumerate(row, start=start_cell_col + 1):\n",
    "        graph_sheet.cell(row=r_idx, column=c_idx, value=value)\n",
    "\n",
    "##################################\n",
    "#Create and configure the chart\n",
    "######################################\n",
    "chart_title = f\"IDD Backlog Qty by type of order\\nInputs date: {file_date} - Source: |CM-Backlog|\"\n",
    "\n",
    "chart9 = BarChart()\n",
    "chart9.title = chart_title\n",
    "chart9.x_axis.title = 'Order Type'\n",
    "chart9.y_axis.title = 'IDD Backlog Qty'\n",
    "########################################\n",
    "\n",
    "# Define data for the chart\n",
    "data = Reference(graph_sheet,\n",
    "                 min_col=start_cell_col + 1,\n",
    "                 min_row=start_cell_row, \n",
    "                 max_col=start_cell_col + len(pivot_table_df.columns),\n",
    "                 max_row=start_cell_row + len(pivot_table_df))\n",
    "chart9.add_data(data, titles_from_data=True)\n",
    "\n",
    "# Set categories (x-axis)\n",
    "categories = Reference(graph_sheet,\n",
    "                       min_col=start_cell_col,\n",
    "                       min_row=start_cell_row + 1, \n",
    "                       max_row=start_cell_row + len(pivot_table_df))\n",
    "chart9.set_categories(categories)\n",
    "\n",
    "\n",
    "###############################\n",
    "# Set the size of the chart\n",
    "###############################\n",
    "chart9.width = 20  # Adjust the width as needed\n",
    "chart9.height = 11  # Adjust the height as needed\n",
    "\n",
    "# Positioning the chart \n",
    "graph_sheet.add_chart(chart9, \"AB53\")\n",
    "\n",
    "#***************************************************************************************************************************\n",
    "#|Progression Overview|\n",
    "#***************************************************************************************************************************\n",
    "##############################################################################################################################\n",
    "# Creating Graph#10 []\n",
    "##############################################################################################################################\n",
    "# Filter to exclude rows where 'Order' contains 'NC'\n",
    "filtered_df = df_TurnoverReport[~df_TurnoverReport['Order'].str.contains('NC')]\n",
    "\n",
    "# Define the span period of the report\n",
    "start_date = filtered_df['Invoice date'].min()\n",
    "end_date = filtered_df['Invoice date'].max()\n",
    "span_period = f\"{start_date} to {end_date}\"\n",
    "\n",
    "# Group by 'Pty Indice' and sum 'TurnoverReport row Qty'\n",
    "sum_qty_by_indice = filtered_df.groupby('Pty Indice')['TurnoverReport row Qty'].sum()\n",
    "\n",
    "# Print or display the result\n",
    "#print(sum_qty_by_indice)\n",
    "\n",
    "# Write sum_qty_by_indice to Excel starting from cell AO3\n",
    "start_cell_row = 3\n",
    "start_cell_col = 41  # Column 'AO'\n",
    "\n",
    "# Write headers\n",
    "graph_sheet.cell(row=start_cell_row, column=start_cell_col, value='Pty Indice')\n",
    "graph_sheet.cell(row=start_cell_row, column=start_cell_col + 1, value='Qty shipped')\n",
    "\n",
    "# Write data rows\n",
    "for r_idx, (indice, sum_qty) in enumerate(sum_qty_by_indice.items(), start=start_cell_row + 1):\n",
    "    graph_sheet.cell(row=r_idx, column=start_cell_col, value=indice)\n",
    "    graph_sheet.cell(row=r_idx, column=start_cell_col + 1, value=sum_qty)\n",
    "\n",
    "###############################################\n",
    "# Create the chart title including the subtitle\n",
    "################################################\n",
    "chart_title = f\"Qty shipped by Pty Indice - {span_period}\\nInputs date: {file_date} - Source: |CM-TurnoverReport|\"\n",
    "\n",
    "chart10 = BarChart()\n",
    "chart10.title = chart_title #f'Qty shipped by Pty Indice - {span_period}'\n",
    "chart10.x_axis.title = 'Pty Indice'\n",
    "chart10.y_axis.title = 'Qty shipped'\n",
    "\n",
    "###################################################\n",
    "# Define data for the chart\n",
    "data = Reference(graph_sheet,\n",
    "                 min_col=start_cell_col + 1,\n",
    "                 min_row=start_cell_row,\n",
    "                 max_col=start_cell_col + 1,\n",
    "                 max_row=start_cell_row + len(sum_qty_by_indice))\n",
    "chart10.add_data(data, titles_from_data=True)\n",
    "\n",
    "# Set categories (x-axis)\n",
    "categories = Reference(graph_sheet,\n",
    "                       min_col=start_cell_col,\n",
    "                       min_row=start_cell_row + 1,\n",
    "                       max_row=start_cell_row + len(sum_qty_by_indice))\n",
    "chart10.set_categories(categories)\n",
    "\n",
    "\n",
    "###############################\n",
    "# Set the size of the chart\n",
    "###############################\n",
    "chart10.width = 20  # Adjust the width as needed\n",
    "chart10.height = 11  # Adjust the height as needed\n",
    "\n",
    "# Positioning the chart \n",
    "graph_sheet.add_chart(chart10, \"AO3\")\n",
    "\n",
    "\n",
    "\n",
    "##############################################################################################################################\n",
    "# Creating Graph#11 []\n",
    "##############################################################################################################################\n",
    "# Filter to include only rows where 'Order' contains 'NC'\n",
    "filtered_df = df_TurnoverReport[df_TurnoverReport['Order'].str.contains('NC')].copy()\n",
    "\n",
    "# Categorize 'TurnoverReport row Qty' as 'Shipped' or 'Received'\n",
    "filtered_df['Category'] = filtered_df['TurnoverReport row Qty'].apply(lambda x: 'Shipped' if x > 0 else 'Received')\n",
    "\n",
    "# Group by 'Pty Indice' and sum 'TurnoverReport row Qty'\n",
    "sum_qty_by_indice = filtered_df.groupby('Pty Indice')['TurnoverReport row Qty'].sum()\n",
    "\n",
    "# Create a pivot table with 'Pty Indice' as index and 'Category' as columns\n",
    "pivot_table_df = pd.pivot_table(filtered_df,\n",
    "                                index='Pty Indice',\n",
    "                                columns='Category',\n",
    "                                values='TurnoverReport row Qty',\n",
    "                                aggfunc='sum',\n",
    "                                fill_value=0)\n",
    "\n",
    "# Write sum_qty_by_indice to Excel starting from cell AO28\n",
    "start_cell_row = 28\n",
    "start_cell_col = 41  # Column 'AO'\n",
    "\n",
    "# Write headers\n",
    "graph_sheet.cell(row=start_cell_row, column=start_cell_col, value='Pty Indice')\n",
    "graph_sheet.cell(row=start_cell_row, column=start_cell_col + 1, value='Qty shipped')\n",
    "graph_sheet.cell(row=start_cell_row, column=start_cell_col + 2, value='Category')\n",
    "\n",
    "# Write data rows\n",
    "for r_idx, (indice, sum_qty) in enumerate(sum_qty_by_indice.items(), start=start_cell_row + 1):\n",
    "    graph_sheet.cell(row=r_idx, column=start_cell_col, value=indice)\n",
    "    graph_sheet.cell(row=r_idx, column=start_cell_col + 1, value=sum_qty)\n",
    "    # Assigning the category based on sum_qty\n",
    "    category = 'Shipped' if sum_qty > 0 else 'Received'\n",
    "    graph_sheet.cell(row=r_idx, column=start_cell_col + 2, value=category)\n",
    "\n",
    "###############################################\n",
    "# Create the chart title including the subtitle\n",
    "################################################\n",
    "chart_title = f\"Qty shipped by Pty Indice - {span_period}\\nInputs date: {file_date} - Source: |CM-TurnoverReport|\"\n",
    "\n",
    "chart11 = BarChart()\n",
    "chart11.title = chart_title #f'Qty shipped by Pty Indice - {span_period}'\n",
    "chart11.x_axis.title = 'Pty Indice'\n",
    "chart11.y_axis.title = 'Qty shipped'\n",
    "\n",
    "#################################################\n",
    "# Define data for the chart\n",
    "data = Reference(graph_sheet,\n",
    "                 min_col=start_cell_col + 1,\n",
    "                 min_row=start_cell_row,\n",
    "                 max_col=start_cell_col + 1,\n",
    "                 max_row=start_cell_row + len(sum_qty_by_indice))\n",
    "chart11.add_data(data, titles_from_data=True)\n",
    "\n",
    "# Set categories (x-axis)\n",
    "categories = Reference(graph_sheet,\n",
    "                       min_col=start_cell_col,\n",
    "                       min_row=start_cell_row + 1,\n",
    "                       max_row=start_cell_row + len(sum_qty_by_indice))\n",
    "chart11.set_categories(categories)\n",
    "\n",
    "###############################\n",
    "# Set the size of the chart\n",
    "###############################\n",
    "chart11.width = 20  # Adjust the width as needed\n",
    "chart11.height = 11  # Adjust the height as needed\n",
    "\n",
    "# Positioning the chart \n",
    "graph_sheet.add_chart(chart11, \"AO28\")\n",
    "\n",
    "\n",
    "##############################################################################################################################\n",
    "# Creating Graph#12 []\n",
    "##############################################################################################################################\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "#***************************************************************************************************************************\n",
    "#|Project Status|\n",
    "#***************************************************************************************************************************\n",
    "##############################################################################################################################\n",
    "# Creating Graph#13 []\n",
    "##############################################################################################################################\n",
    "# Create a new column 'Product status' based on the condition\n",
    "df_snapshot['Industrialization'] = df_snapshot['Production Status'].apply(lambda x: 'Industrialized' if x.strip() == 'Industrialized' else 'Not Industrialized')\n",
    "\n",
    "# Create a pivot table with 'Product Category', 'Pty Indice', and 'Top-Level Status' as index\n",
    "pivot_table_df = pd.pivot_table(df_snapshot,\n",
    "                                index=['Top-Level Status', 'Industrialization', 'Product Category', 'Pty Indice'],\n",
    "                                values=['IDD Backlog Qty', 'Remain. crit. Qty', 'Qty clear to build'],\n",
    "                                aggfunc='sum',\n",
    "                                fill_value=0).reset_index()\n",
    "\n",
    "# Sort pivot_table_df by 'Top-Level Status', 'Industrialization', then 'Product Category'\n",
    "sort_order = ['Clear-to-Build', 'Short']\n",
    "pivot_table_df['Top-Level Status'] = pd.Categorical(pivot_table_df['Top-Level Status'], categories=sort_order, ordered=True)\n",
    "pivot_table_df['Industrialization'] = pd.Categorical(pivot_table_df['Industrialization'], categories=['Industrialized', 'Not Industrialized'], ordered=True)\n",
    "pivot_table_df.sort_values(by=['Top-Level Status', 'Industrialization', 'Product Category'], inplace=True)\n",
    "\n",
    "\n",
    "# Write headers for each column first\n",
    "start_cell_row = 81\n",
    "start_cell_col = 2  # Column 'B81'\n",
    "\n",
    "# Write headers for each column\n",
    "headers = ['Top-Level Status', 'Industrialization', 'Product Category', 'Pty Indice', 'IDD Backlog Qty', 'Remain. crit. Qty', 'Qty clear to build']\n",
    "for c_idx, col in enumerate(headers, start=start_cell_col):\n",
    "    graph_sheet.cell(row=start_cell_row, column=c_idx, value=col)\n",
    "\n",
    "# Initialize a set to track written statuses and categories\n",
    "written_statuses_categories = set()\n",
    "\n",
    "# Write data rows\n",
    "for r_idx, row in pivot_table_df.iterrows():\n",
    "    current_status = row['Top-Level Status']\n",
    "    current_industrialization = row['Industrialization']\n",
    "    current_category = row['Product Category']\n",
    "    \n",
    "    # Write Top-Level Status and Industrialization only if it's the first occurrence\n",
    "    if (current_status, current_industrialization) not in written_statuses_categories:\n",
    "        cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col, value=current_status)\n",
    "        cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "        cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 1, value=current_industrialization)\n",
    "        cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "        written_statuses_categories.add((current_status, current_industrialization))  # Add current_status and current_industrialization to written_statuses\n",
    "    \n",
    "    # Write Product Category only if Status, Industrialization, and Category are first occurrence\n",
    "    if (current_status, current_industrialization, current_category) not in written_statuses_categories:\n",
    "        cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 2, value=current_category)\n",
    "        cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "        written_statuses_categories.add((current_status, current_industrialization, current_category))  # Add (current_status, current_industrialization, current_category) to written_statuses\n",
    "    \n",
    "    # Write Pty Indice\n",
    "    cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 3, value=row['Pty Indice'])\n",
    "    cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "    \n",
    "    # Write IDD Backlog Qty\n",
    "    cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 4, value=row['IDD Backlog Qty'])\n",
    "    cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "    \n",
    "    # Write Remain. crit. Qty \n",
    "    cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 5, value=row['Remain. crit. Qty'])\n",
    "    cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "    \n",
    "    # Write Qty clear to build\n",
    "    cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 6, value=row['Qty clear to build'])\n",
    "    cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "\n",
    "###############################################\n",
    "# Create the chart title including the subtitle\n",
    "################################################\n",
    "chart_title = f\"IDD Backlog Qty, Remain. crit. Qty & Qty clear-to-build per Pty Indice by Top-Level Status, Production Status & Product Category\\nInputs date: {file_date} - Source: |CM-Snapshot|\"\n",
    "\n",
    "chart13 = BarChart()\n",
    "chart13.title = \"IDD Backlog Qty, Remain. crit. Qty & Qty clear-to-build per Pty Indice by Top-Level Status, Production Status & Product Category\"\n",
    "chart13.x_axis.title = None\n",
    "chart13.y_axis.title = 'IDD Backlog Qty, Remain. crit. Qty & Qty clear-to-build '\n",
    "\n",
    "########################################################\n",
    "# Define data for the chartDark \n",
    "data = Reference(graph_sheet,\n",
    "                 min_col=start_cell_col + 4,\n",
    "                 min_row=start_cell_row,\n",
    "                 max_col=start_cell_col + 6,\n",
    "                 max_row=start_cell_row + len(pivot_table_df))\n",
    "\n",
    "chart13.add_data(data, titles_from_data=True)\n",
    "\n",
    "# Set categories (x-axis)\n",
    "categories = Reference(graph_sheet,\n",
    "                       min_col=start_cell_col,\n",
    "                       min_row=start_cell_row + 1,\n",
    "                       max_col=start_cell_col + 3,\n",
    "                       max_row=start_cell_row + len(pivot_table_df))\n",
    "\n",
    "chart13.set_categories(categories)\n",
    "\n",
    "############################\n",
    "# Set the size of the chart\n",
    "############################\n",
    "chart13.width = 80  # Adjust the width as needed\n",
    "chart13.height = 16  # Adjust the height as needed\n",
    "\n",
    "# Positioning the chart \n",
    "graph_sheet.add_chart(chart13, \"B81\")\n",
    "\n",
    "##############################################################################################################################\n",
    "# Creating Graph#14 []\n",
    "##############################################################################################################################\n",
    "# Calculate IDD Total Sales\n",
    "df_snapshot['IDD Total Sales'] = df_snapshot['IDD Backlog Qty'] * df_snapshot['IDD Sale Price']\n",
    "\n",
    "# Calculate IDD Total Marge\n",
    "df_snapshot['IDD Total Marge'] = df_snapshot['IDD Backlog Qty'] * df_snapshot['IDD Marge Standard (unit)']\n",
    "\n",
    "# Create a new column 'Product status' based on the condition\n",
    "df_snapshot['Industrialization'] = df_snapshot['Production Status'].apply(lambda x: 'Industrialized' if x.strip() == 'Industrialized' else 'Not Industrialized')\n",
    "\n",
    "# Create a pivot table with 'Product Category', 'Pty Indice', and 'Top-Level Status' as index\n",
    "pivot_table_df = pd.pivot_table(df_snapshot,\n",
    "                                index=['Top-Level Status', 'Industrialization', 'Product Category', 'Pty Indice'],\n",
    "                                values=['IDD Total Sales', 'IDD Total Marge'],\n",
    "                                aggfunc='sum',\n",
    "                                fill_value=0).reset_index()\n",
    "\n",
    "# Sort pivot_table_df by 'Top-Level Status', 'Industrialization', then 'Product Category'\n",
    "sort_order = ['Clear-to-Build', 'Short']\n",
    "pivot_table_df['Top-Level Status'] = pd.Categorical(pivot_table_df['Top-Level Status'], categories=sort_order, ordered=True)\n",
    "pivot_table_df['Industrialization'] = pd.Categorical(pivot_table_df['Industrialization'], categories=['Industrialized', 'Not Industrialized'], ordered=True)\n",
    "pivot_table_df.sort_values(by=['Top-Level Status', 'Industrialization', 'Product Category'], inplace=True)\n",
    "\n",
    "\n",
    "# Write headers for each column first\n",
    "start_cell_row = 81\n",
    "start_cell_col = 14  # Column 'N81'\n",
    "\n",
    "# Write headers for each column\n",
    "headers = ['Top-Level Status', 'Industrialization', 'Product Category', 'Pty Indice', 'IDD Total Sales', 'IDD Total Marge']\n",
    "for c_idx, col in enumerate(headers, start=start_cell_col):\n",
    "    graph_sheet.cell(row=start_cell_row, column=c_idx, value=col)\n",
    "\n",
    "# Initialize a set to track written statuses and categories\n",
    "written_statuses_categories = set()\n",
    "\n",
    "# Write data rows\n",
    "for r_idx, row in pivot_table_df.iterrows():\n",
    "    current_status = row['Top-Level Status']\n",
    "    current_industrialization = row['Industrialization']\n",
    "    current_category = row['Product Category']\n",
    "    \n",
    "    # Write Top-Level Status and Industrialization only if it's the first occurrence\n",
    "    if (current_status, current_industrialization) not in written_statuses_categories:\n",
    "        cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col, value=current_status)\n",
    "        cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "        cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 1, value=current_industrialization)\n",
    "        cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "        written_statuses_categories.add((current_status, current_industrialization))  # Add current_status and current_industrialization to written_statuses\n",
    "    \n",
    "    # Write Product Category only if Status, Industrialization, and Category are first occurrence\n",
    "    if (current_status, current_industrialization, current_category) not in written_statuses_categories:\n",
    "        cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 2, value=current_category)\n",
    "        cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "        written_statuses_categories.add((current_status, current_industrialization, current_category))  # Add (current_status, current_industrialization, current_category) to written_statuses\n",
    "    \n",
    "    # Write Pty Indice\n",
    "    cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 3, value=row['Pty Indice'])\n",
    "    cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "    \n",
    "    # Write IDD Total Sales as currency\n",
    "    cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 4, value=row['IDD Total Sales'])\n",
    "    cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "    graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 4).number_format = '$#,##0.00'\n",
    "    \n",
    "    # Write IDD Total Marge as currency\n",
    "    cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 5, value=row['IDD Total Marge'])\n",
    "    cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "    graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 5).number_format = '$#,##0.00'\n",
    "\n",
    "###############################################\n",
    "# Create the chart title including the subtitle\n",
    "################################################\n",
    "chart_title = f\"IDD Total Sales & IDD Marge per Pty Indice by Top-Level Status, Production Status & Product Category\\nInputs date: {file_date} - Source: |CM-Snapshot|\"\n",
    "\n",
    "# Create a bar chart\n",
    "chart14 = BarChart()\n",
    "chart14.title = chart_title\n",
    "chart14.x_axis.title = None\n",
    "chart14.y_axis.title = 'IDD Total Sales & Marge'\n",
    "\n",
    "###################################################\n",
    "# Define data for the chart\n",
    "data = Reference(graph_sheet,\n",
    "                 min_col=start_cell_col + 4,\n",
    "                 min_row=start_cell_row,\n",
    "                 max_col=start_cell_col + 5,\n",
    "                 max_row=start_cell_row + len(pivot_table_df))\n",
    "\n",
    "chart14.add_data(data, titles_from_data=True)\n",
    "\n",
    "# Set categories (x-axis)\n",
    "categories = Reference(graph_sheet,\n",
    "                       min_col=start_cell_col,\n",
    "                       min_row=start_cell_row + 1,\n",
    "                       max_col=start_cell_col + 3,\n",
    "                       max_row=start_cell_row + len(pivot_table_df))\n",
    "\n",
    "chart14.set_categories(categories)\n",
    "\n",
    "############################\n",
    "# Set the size of the chart\n",
    "############################\n",
    "chart14.width = 80  # Adjust the width as needed\n",
    "chart14.height = 16  # Adjust the height as needed\n",
    "\n",
    "# Positioning the chart \n",
    "graph_sheet.add_chart(chart14, \"B116\")\n",
    "\n",
    "\n",
    "##############################################################################################################################\n",
    "# Creating Graph#15 []\n",
    "##############################################################################################################################\n",
    "# Merge df_backlog with df_snapshot to bring 'Top-Level Status' and 'Production Status' into df_backlog\n",
    "df_backlog = pd.merge(df_backlog, df_snapshot[['Pty Indice', 'Top-Level Status', 'Production Status']], on='Pty Indice', how='left')\n",
    "\n",
    "# Define 'Order Type' column based on 'Order' column, excluding rows containing 'NC'\n",
    "df_backlog['Order Type'] = df_backlog['Order'].apply(lambda x: 'DX/DO' if str(x).startswith('D') else ('Standard' if 'NC' not in str(x) else None))\n",
    "\n",
    "# Rename 'Production Status_x' to 'Production Status' if needed\n",
    "if 'Production Status_x' in df_backlog.columns:\n",
    "    df_backlog.rename(columns={'Production Status_x': 'Production Status'}, inplace=True)\n",
    "\n",
    "# Rename 'Top-Level Status_x' to 'Top-Level Status' if needed\n",
    "if 'Top-Level Status_x' in df_backlog.columns:\n",
    "    df_backlog.rename(columns={'Top-Level Status_x': 'Top-Level Status'}, inplace=True)\n",
    "    \n",
    "display(df_backlog)\n",
    "\n",
    "# Create a new column 'Industrialization' based on the condition\n",
    "df_backlog['Industrialization'] = df_backlog['Production Status'].apply(lambda x: 'Industrialized' if x.strip() == 'Industrialized' else 'Not Industrialized')\n",
    "\n",
    "# Create a pivot table with 'Top-Level Status', 'Industrialization', 'Order Type', and 'Pty Indice' as index\n",
    "pivot_table_df = pd.pivot_table(df_backlog,\n",
    "                                index=['Top-Level Status', 'Industrialization', 'Order Type', 'Pty Indice'],\n",
    "                                values=['Backlog row Qty'],\n",
    "                                aggfunc='sum',\n",
    "                                fill_value=0).reset_index()\n",
    "\n",
    "# Sort pivot_table_df by 'Top-Level Status', 'Industrialization', then 'Order Type'\n",
    "sort_order = ['Active', 'Inactive']\n",
    "pivot_table_df['Top-Level Status'] = pd.Categorical(pivot_table_df['Top-Level Status'], categories=sort_order, ordered=True)\n",
    "pivot_table_df['Industrialization'] = pd.Categorical(pivot_table_df['Industrialization'], categories=['Industrialized', 'Not Industrialized'], ordered=True)\n",
    "pivot_table_df.sort_values(by=['Top-Level Status', 'Industrialization', 'Order Type'], inplace=True)\n",
    "\n",
    "# Write headers for each column first\n",
    "start_cell_row = 81\n",
    "start_cell_col = 27  # Column 'AA81'\n",
    "\n",
    "# Write headers for each column\n",
    "headers = ['Top-Level Status', 'Industrialization', 'Order Type', 'Pty Indice', 'Backlog row Qty']\n",
    "for c_idx, col in enumerate(headers, start=start_cell_col):\n",
    "    cell = graph_sheet.cell(row=start_cell_row, column=c_idx, value=col)\n",
    "    cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "\n",
    "# Initialize a set to track written statuses, industrializations, categories\n",
    "written_statuses_categories = set()\n",
    "\n",
    "# Write data rows\n",
    "for r_idx, row in pivot_table_df.iterrows():\n",
    "    current_status = row['Top-Level Status']\n",
    "    current_industrialization = row['Industrialization']\n",
    "    current_order_type = row['Order Type']\n",
    "\n",
    "    # Write Top-Level Status, Industrialization, and Order Type only if it's the first occurrence\n",
    "    if (current_status, current_industrialization, current_order_type) not in written_statuses_categories:\n",
    "        cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col, value=current_status)\n",
    "        cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "        cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 1, value=current_industrialization)\n",
    "        cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "        cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 2, value=current_order_type)\n",
    "        cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "        written_statuses_categories.add((current_status, current_industrialization, current_order_type))  # Add to written_statuses\n",
    "\n",
    "    # Write Pty Indice\n",
    "    cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 3, value=row['Pty Indice'])\n",
    "    cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "    \n",
    "    # Write Backlog row Qty\n",
    "    cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 4, value=row['Backlog row Qty'])\n",
    "    cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "\n",
    "###############################################\n",
    "# Create the chart title including the subtitle\n",
    "################################################\n",
    "chart_title = f\"IDD Backlog Qty, Remain. crit. Qty & Qty clear-to-build per Pty Indice by Top-Level Status, Industrialization & Product Category\\nInputs date: {file_date} - Source: |CM-Snapshot|\"\n",
    "\n",
    "chart15 = BarChart()\n",
    "chart15.title = chart_title\n",
    "chart15.x_axis.title = None\n",
    "chart15.y_axis.title = 'IDD Backlog Qty, Remain. crit. Qty & Qty clear-to-build'\n",
    "\n",
    "########################################################\n",
    "# Define data for the chart\n",
    "data = Reference(graph_sheet,\n",
    "                 min_col=start_cell_col + 4,\n",
    "                 min_row=start_cell_row,\n",
    "                 max_col=start_cell_col + 4,\n",
    "                 max_row=start_cell_row + len(pivot_table_df))\n",
    "\n",
    "chart15.add_data(data, titles_from_data=True)\n",
    "\n",
    "# Set categories (x-axis)\n",
    "categories = Reference(graph_sheet,\n",
    "                       min_col=start_cell_col,\n",
    "                       min_row=start_cell_row + 1,\n",
    "                       max_col=start_cell_col + 3,\n",
    "                       max_row=start_cell_row + len(pivot_table_df))\n",
    "\n",
    "chart15.set_categories(categories)\n",
    "\n",
    "############################\n",
    "# Set the size of the chart\n",
    "############################\n",
    "chart15.width = 80  # Adjust the width as needed\n",
    "chart15.height = 16  # Adjust the height as needed\n",
    "\n",
    "# Positioning the chart\n",
    "graph_sheet.add_chart(chart15, \"B151\")\n",
    "\n",
    "#*******************************************************************************************************************************************\n",
    "############################################################\n",
    "# Get the sheet view (there should be only one sheet view)\n",
    "############################################################\n",
    "sheet_view = graph_sheet.sheet_view\n",
    "\n",
    "# Set the zoom scale to 60% \n",
    "sheet_view.zoomScale = 60\n",
    "\n",
    "# Save the workbook\n",
    "workbook.save(output_file_name_Graph)\n",
    "print(f\"Charts successfully added to '{output_file_name_Graph}'\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d0abe86a-0fbe-46de-bcff-1000a4cf9130",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "<h2 style=\"text-align:left;\">Section |Dashboard| to insert on the code</h2> "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "43f085d8-2f56-4e4a-b266-c2d2ff2694d3",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "KeyboardInterrupt\n",
      "\n"
     ]
    }
   ],
   "source": [
    "#***************************************************************************************************************************\n",
    "#############################################################################################################################\n",
    "## ########  ########  #########  #########  ##     ## \n",
    "## ##        ##    ##  ##     ##  ##     ##  ##     ##  \n",
    "## ##  ####  ########  #########  #########  #########  \n",
    "## ##    ##  ##  ###   ##     ##  ##         ##     ## \n",
    "## ########  ##    ##  ##     ##  ##         ##     ## \n",
    "##############################################################################################################################\n",
    "#***************************************************************************************************************************\n",
    "# Creating tab |Dashboard| in first position \n",
    "#***************************************************************************************************************************\n",
    "#########################################################################################################\n",
    "# load the formatted workbook\n",
    "######################################################################################################\n",
    "# Load the workbook\n",
    "try:\n",
    "    workbook = load_workbook(original_input)\n",
    "    #print(f\"Successfully loaded '{original_input}'\")\n",
    "except FileNotFoundError as e:\n",
    "    print(f\"File not found: {e}\")\n",
    "    exit()\n",
    "    \n",
    "# Print the sheet names\n",
    "print(\"Tabs in the workbook:\")\n",
    "print(workbook.sheetnames)\n",
    "print('Processing |Dashboard|...')\n",
    "\n",
    "# Create a new \"Dashboard\" sheet as the first sheet\n",
    "graph_sheet = workbook.create_sheet(title='Dashboard', index=0)\n",
    "\n",
    "# Check if 'Dashboard' sheet already exists and replace it\n",
    "if 'Dashboard' in workbook.sheetnames:\n",
    "    # Delete existing 'Dashboard' sheet\n",
    "    workbook.remove(workbook['Dashboard'])\n",
    "\n",
    "# Create 'Dashboard' sheet\n",
    "graph_sheet = workbook.create_sheet(title='Dashboard', index = 0)\n",
    "print(\"|Dashboard| tab created successfully.\") \n",
    "\n",
    "######################################################################################################\n",
    "# Define the relevant columns for \"Project snapshot\"\n",
    "#####################################################################################################\n",
    "#********************************************************************************************************************************\n",
    "# Divide |Graph| in 2 section --> |Project History|  |General Overview|  |Clear to Build Overview| |Progression Overview| \n",
    "                                # |                                       Project Status                               |\n",
    "#******************************************************************************************************************************\n",
    "# Write title \"Project History\" in cell A1\n",
    "graph_sheet['A1'] = 'Project History'\n",
    "graph_sheet['A1'].font = Font(bold=True)\n",
    "graph_sheet['A1'].alignment = Alignment(horizontal='center')\n",
    "\n",
    "# Merge cells A1 to N1\n",
    "graph_sheet.merge_cells('A1:M1')\n",
    "\n",
    "# Write title \"General Overview\" in cell N1\n",
    "graph_sheet['N1'] = 'General Overview'\n",
    "graph_sheet['N1'].font = Font(bold=True)\n",
    "graph_sheet['N1'].alignment = Alignment(horizontal='center')\n",
    "\n",
    "# Merge cells N1 to Z1\n",
    "graph_sheet.merge_cells('N1:Z1')\n",
    "\n",
    "# Write title \"General Overview\" in cell AA1\n",
    "graph_sheet['AA1'] = 'Clear to Build Overview'\n",
    "graph_sheet['AA1'].font = Font(bold=True)\n",
    "graph_sheet['AA1'].alignment = Alignment(horizontal='center')\n",
    "\n",
    "# Merge cells AA1 to AM1\n",
    "graph_sheet.merge_cells('AA1:AM1')\n",
    "\n",
    "# Write title \"Progression Overview\" in cell AN1\n",
    "graph_sheet['AN1'] = 'Progression Overview'\n",
    "graph_sheet['AN1'].font = Font(bold=True)\n",
    "graph_sheet['AN1'].alignment = Alignment(horizontal='center')\n",
    "\n",
    "# Merge cells AN1 to A1:AZ1\n",
    "graph_sheet.merge_cells('AN1:AZ1')\n",
    "\n",
    "# Write title \"Project Status\" in cell A79\n",
    "graph_sheet['A79'] = 'Project Status'\n",
    "graph_sheet['A79'].font = Font(bold=True)\n",
    "graph_sheet['A79'].alignment = Alignment(horizontal='center')\n",
    "\n",
    "# Merge cells A79 to AZ79\n",
    "graph_sheet.merge_cells('A79:AZ79')\n",
    "\n",
    "####################\n",
    "#Formatting row 1\n",
    "##################\n",
    "# Define fill color (blue)\n",
    "fill = PatternFill(start_color='8DB4E2', end_color='8DB4E2', fill_type='solid')\n",
    "\n",
    "# Font properties (white color, size 16)\n",
    "font = Font(color='FFFFFF', size=16)\n",
    "\n",
    "# Apply styles to row 1\n",
    "for col in range(1, graph_sheet.max_column + 1):\n",
    "    cell = graph_sheet.cell(row=1, column=col)\n",
    "    cell.fill = fill\n",
    "    cell.font = font\n",
    "    cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "\n",
    "####################\n",
    "#Formatting row 79\n",
    "##################\n",
    "# Apply styles to row 79\n",
    "for col in range(1, graph_sheet.max_column + 1):\n",
    "    cell = graph_sheet.cell(row=79, column=col)\n",
    "    cell.fill = fill\n",
    "    cell.font = font\n",
    "    cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "    \n",
    "###############################\n",
    "# Graph Label number\n",
    "###############################\n",
    "'''\n",
    "graph_sheet['A2'] = 1\n",
    "graph_sheet['A27'] = 2\n",
    "graph_sheet['A52'] = 3\n",
    "graph_sheet['N2'] = 4\n",
    "graph_sheet['N27'] = 5\n",
    "graph_sheet['N52'] = 6\n",
    "graph_sheet['AA2'] = 7\n",
    "graph_sheet['AA27'] = 8\n",
    "graph_sheet['AA52'] = 9\n",
    "graph_sheet['AN2'] = 10\n",
    "graph_sheet['AN27'] = 11\n",
    "graph_sheet['AN52'] = 12\n",
    "graph_sheet['A80'] = 13\n",
    "graph_sheet['A115'] = 14\n",
    "graph_sheet['A151'] = 15\n",
    "'''\n",
    "\n",
    "# Write numbers in specified positions using indices\n",
    "positions = [(2, 1, 1), (2, 14, 4), (2, 27, 7), (27, 1, 2), (27, 14, 5), (27, 27, 8), (2, 40, 10), (27, 40, 11), (52, 1, 3), (52, 14, 6), (52, 27, 9), (52, 40, 12), (80, 1, 13), (115, 1, 14), (151, 1, 15)] # (row, column, 'Number')\n",
    "for row_idx, col_idx, number in positions:\n",
    "    cell = graph_sheet.cell(row=row_idx, column=col_idx)\n",
    "    cell.value = number\n",
    "    cell.fill = fill\n",
    "    cell.font = Font(color='FFFFFF', size=14, bold=True)\n",
    "    cell.alignment = Alignment(horizontal='center', vertical='center')\n",
    "    \n",
    "#########################################################################\n",
    "# Set the width of column A to 2.5 (or any desired width)\n",
    "graph_sheet.column_dimensions['A'].width = 4\n",
    "\n",
    "# Set the width of column N to 2 (or any desired width)\n",
    "graph_sheet.column_dimensions['N'].width = 4\n",
    "\n",
    "# Set the width of column AA to 2 (or any desired width)\n",
    "graph_sheet.column_dimensions['AA'].width = 4\n",
    "\n",
    "# Set the width of column AN to 2 (or any desired width)\n",
    "graph_sheet.column_dimensions['AN'].width = 4\n",
    "\n",
    "##########################################################################################\n",
    "## Horizontal tick border column N, AB, AM, AZ/ Vertical dashDot border A30:AZ30, A52:AZ52\n",
    "##########################################################################################\n",
    "# Define a thick border style for the upper border\n",
    "thick_border_upper = Border(top=Side(style='thick',color='000000'))\n",
    "\n",
    "# Apply the thick border to row 2 from column A to AZ\n",
    "for col in range(1, 53):  # Columns A to AZ (1 to 53)\n",
    "    cell = graph_sheet.cell(row=2, column=col)\n",
    "    cell.border = thick_border_upper\n",
    "\n",
    "# Define a dashdot border style for the upper border\n",
    "dash_border_upper = Border(top=Side(style='dashDot',color='808080'))\n",
    "\n",
    "# Apply the Dash border to row 27 from column A to AZ\n",
    "for col in range(1, 53):  # Columns A to AZ (1 to 53)\n",
    "    cell = graph_sheet.cell(row=27, column=col)\n",
    "    cell.border = dash_border_upper\n",
    "\n",
    "# Apply the Dash border to row 52 from column A to AZ\n",
    "for col in range(1, 53):  # Columns A to AZ (1 to 53)\n",
    "    cell = graph_sheet.cell(row=52, column=col)\n",
    "    cell.border = dash_border_upper\n",
    "\n",
    "#####################################\n",
    "### Define vertical thick border style\n",
    "##########################################\n",
    "thick_border_left = Border(left=Side(style='thick'))\n",
    "\n",
    "# Apply the thick border to column N from row 1 to 79\n",
    "for row in range(1, 80):\n",
    "    cell_N = graph_sheet.cell(row=row, column=14)  # Column N is the 14th column\n",
    "    cell_N.border = thick_border_left\n",
    "\n",
    "# Apply the thick border to column AA from row 1 to 79\n",
    "for row in range(1, 80):\n",
    "    cell_AA = graph_sheet.cell(row=row, column=27)  # Column AA is the 27th column\n",
    "    cell_AA.border = thick_border_left\n",
    "\n",
    "# Apply the thick border to column AM from row 1 to 79\n",
    "for row in range(1, 80):\n",
    "    cell_AM = graph_sheet.cell(row=row, column=40)  # Column AM is the 40th column\n",
    "    cell_AM.border = thick_border_left\n",
    "\n",
    "# Apply the thick border to column AZ from row 1 to 150\n",
    "for row in range(1, 149):\n",
    "    cell_AM = graph_sheet.cell(row=row, column=53)  # Column AZ is the 53th column\n",
    "    cell_AM.border = thick_border_left\n",
    "\n",
    "############################\n",
    "#Combined Left/Upper border \n",
    "############################\n",
    "# Apply both the thick left and upper borders to cell N27\n",
    "cell_N2 = graph_sheet.cell(row=2, column=14)  # Column N is the 14th column\n",
    "cell_N2.border = Border(left=thick_border_left.left, top=thick_border_upper.top)\n",
    "\n",
    "# Apply both the thick left and DashDot upper borders to cell AA27\n",
    "cell_AA27= graph_sheet.cell(row=27, column=27)  # Column AA is the 27th column\n",
    "cell_AA27.border = Border(left=thick_border_left.left, top=dash_border_upper.top)\n",
    "\n",
    "# Apply both the thick left and upper borders to cell N27\n",
    "cell_N27 = graph_sheet.cell(row=27, column=14)  # Column N is the 14th column\n",
    "cell_N27.border = Border(left=thick_border_left.left, top=dash_border_upper.top)\n",
    "\n",
    "# Apply both the thick left and upper borders to cell AA2\n",
    "cell_AA2 = graph_sheet.cell(row=2, column=27)  # Column AA is the 28th column\n",
    "cell_AA2.border = Border(left=thick_border_left.left, top=thick_border_upper.top)\n",
    "\n",
    "# Apply both the thick left and upper borders to cell AN27\n",
    "cell_AN27 = graph_sheet.cell(row=27, column=40)  # Column N is the 14th column\n",
    "cell_AN27.border = Border(left=thick_border_left.left, top=dash_border_upper.top)\n",
    "\n",
    "# Apply both the thick left and upper borders to cell AN2\n",
    "cell_AN2 = graph_sheet.cell(row=2, column=40)  # Column AN is the 28th column\n",
    "cell_AN2.border = Border(left=thick_border_left.left, top=thick_border_upper.top)\n",
    "\n",
    "################################################\n",
    "# Horizantal Border for section |Project Status|\n",
    "###############################################\n",
    "# Apply the thick border to row 79 from column A to AZ\n",
    "for col in range(1, 53):  # Columns A to AZ (1 to 53)\n",
    "    cell = graph_sheet.cell(row=79, column=col)\n",
    "    cell.border = thick_border_upper\n",
    "\n",
    "# Apply the thick border to row 80 from column A to AZ\n",
    "for col in range(1, 53):  # Columns A to AZ (1 to 53)\n",
    "    cell = graph_sheet.cell(row=80, column=col)\n",
    "    cell.border = thick_border_upper\n",
    "    \n",
    "###################################\n",
    "#****************************************************************************************************************************\n",
    "# CHARTS \n",
    "#****************************************************************************************************************************\n",
    "#####################################################\n",
    "#Create a new dataframe including the completed PN\n",
    "#######################################################\n",
    "#Include the Pty Indice not in |Snapshot| (df_Snapshot) but present in |CM-Priority| (df_Priority) with 'Production Status' = 'Completed' \n",
    "#Include in a new df_Snapshot_Priority the column 'Description','Production Status', 'IDD Sale Price', 'SEDA Sale Price' from CM-Priority\n",
    "df_Priority_filtered = df_Priority[df_Priority['Production Status'] == 'Completed'][['Pty Indice', 'Priority', 'IDD Top Level', 'SEDA Top Level', 'Shipped', 'Remain. crit. Qty','Description', 'Production Status', 'SEDA Sale Price']]\n",
    "\n",
    "#Merge df_snapshot with df_Priority_filtered based on 'Pty Indice'\n",
    "df_snapshot_priority = pd.concat([df_snapshot, df_Priority_filtered], ignore_index=True)\n",
    "\n",
    "# Fill NaN values in 'Top-Level Status' with 'Completed' for the newly merged rows\n",
    "df_snapshot_priority['Top-Level Status'].fillna('Completed', inplace=True)\n",
    "\n",
    "#Aplly function to fill the 'Product Category' \n",
    "def determine_category(description):\n",
    "    if not isinstance(description, str):\n",
    "        return 'Others'\n",
    "    if description == 'Rototellite':\n",
    "        return 'Rototellite'\n",
    "    elif 'Indicator' in description or 'CPA' in description:\n",
    "        return 'CPA'\n",
    "    elif 'Lightplate' in description:\n",
    "        return 'Lightplate'\n",
    "    elif 'ISP' in description or 'Keyboard' in description:\n",
    "        return 'ISP'\n",
    "    elif 'Module' in description:\n",
    "        return 'CPA'\n",
    "    elif 'optics' in description:\n",
    "        return 'Fiber Optics'\n",
    "    else:\n",
    "        return 'Others'\n",
    "\n",
    "# Apply the determine_category function to 'Description' column\n",
    "df_snapshot_priority['Product Category'] = df_snapshot_priority['Description'].apply(determine_category)\n",
    "\n",
    "#display(df_snapshot_priority)\n",
    "\n",
    "####################################################################################\n",
    "#***************************************************************************************************************************\n",
    "#|Project History|\n",
    "#***************************************************************************************************************************\n",
    "##############################################################################################################################\n",
    "# Creating Graph#1 []\n",
    "##############################################################################################################################\n",
    "# Calculate percentage distribution and round to one decimal place\n",
    "category_counts = df_snapshot_priority['Product Category'].value_counts(normalize=True) * 100\n",
    "category_percentages = category_counts.round(1)\n",
    "\n",
    "# Write data to the worksheet starting from row 3, column 2 (B3)\n",
    "graph_sheet.cell(row=3, column=2, value=\"Product Category\")\n",
    "graph_sheet.cell(row=3, column=3, value=\"Percentage\")\n",
    "\n",
    "# Write category and percentage data to the worksheet\n",
    "for idx, (category, percentage) in enumerate(category_percentages.items(), start=4):\n",
    "    graph_sheet.cell(row=idx, column=2, value=category)\n",
    "    graph_sheet.cell(row=idx, column=3, value=percentage)\n",
    "\n",
    "###############################################\n",
    "# Create the chart title including the subtitle\n",
    "################################################\n",
    "chart_title = f\"Percentage Distribution of Product Categories\\nInputs date: {file_date_inventory} - Source: |CM-Priority|\"\n",
    "\n",
    "# Create a pie chart\n",
    "chart1 = PieChart()\n",
    "chart1.title = chart_title\n",
    "\n",
    "################################################\n",
    "# Prepare data for the pie chart using Reference\n",
    "####################################################\n",
    "min_row = 3  # Start from row 3 where your data starts\n",
    "max_row = min_row + len(category_percentages)  # Calculate the last row based on the number of categories\n",
    "min_row_label = 4  # Start from row 4 for labels\n",
    "max_row_label = min_row_label + len(category_percentages) - 1\n",
    "\n",
    "data_points = Reference(graph_sheet, min_col=3, min_row=min_row, max_row=max_row)  # Adjusted min_col to 3\n",
    "labels = Reference(graph_sheet, min_col=2, min_row=min_row_label, max_row=max_row_label)  # Adjusted min_col to 2\n",
    "\n",
    "chart1.add_data(data_points, titles_from_data=True)\n",
    "chart1.set_categories(labels)\n",
    "    \n",
    "#############################\n",
    "# Set size/position\n",
    "##############################\n",
    "chart1.width = 20  # Adjust the width as needed\n",
    "chart1.height = 11  # Adjust the height as needed\n",
    "\n",
    "# Positioning  \n",
    "graph_sheet.add_chart(chart1, \"B3\")\n",
    "\n",
    "\n",
    "\n",
    "##############################################################################################################################\n",
    "# Creating Graph#2 []\n",
    "##############################################################################################################################\n",
    "# Calculate percentage distribution and round to one decimal place\n",
    "status_counts = df_snapshot_priority['Production Status'].value_counts(normalize=True) * 100\n",
    "status_percentages = status_counts.round(1)\n",
    "\n",
    "# Write data to the worksheet starting from row 28, column 2 (B28)\n",
    "graph_sheet.cell(row=28, column=2, value=\"Production Status\")\n",
    "graph_sheet.cell(row=28, column=3, value=\"Percentage\")\n",
    "\n",
    "# Write category and percentage data to the worksheet\n",
    "for idx, (status, percentage) in enumerate(status_percentages.items(), start=28):  # Start index corrected to 28\n",
    "    graph_sheet.cell(row=idx + 1, column=2, value=status)  # Adjusted row index and added +1 to start from 29\n",
    "    graph_sheet.cell(row=idx + 1, column=3, value=percentage)  # Adjusted row index and added +1 to start from 29\n",
    "\n",
    "###############################################\n",
    "# Create the chart title including the subtitle\n",
    "################################################\n",
    "chart_title = f\"Percentage Distribution of Production Status\\nInputs date: {file_date_inventory} - Source: |CM-Priority|\"\n",
    "\n",
    "# Create a pie chart\n",
    "chart2 = PieChart()\n",
    "chart2.title = chart_title\n",
    "################################################\n",
    "\n",
    "# Prepare data for the pie chart using Reference\n",
    "min_row = 28  # Start from row 28 to include the data\n",
    "max_row = min_row + len(status_percentages)  # Calculate the last row based on the number of statuses\n",
    "min_row_label = 29  # Start from row 29 for labels\n",
    "max_row_label = min_row_label + len(status_percentages) - 1\n",
    "\n",
    "data_points = Reference(graph_sheet, min_col=3, min_row=min_row, max_row=max_row)  # Adjusted min_col to 3\n",
    "labels = Reference(graph_sheet, min_col=2, min_row=min_row_label, max_row=max_row_label)  # Adjusted min_col to 2\n",
    "\n",
    "chart2.add_data(data_points, titles_from_data=True)\n",
    "chart2.set_categories(labels)\n",
    "\n",
    "# Set the size of the chart\n",
    "chart2.width = 20  # Adjust the width as needed\n",
    "chart2.height = 11  # Adjust the height as needed\n",
    "\n",
    "# Positioning the chart\n",
    "graph_sheet.add_chart(chart2, \"B28\")\n",
    "\n",
    "\n",
    "##############################################################################################################################\n",
    "# Creating Graph#3 []\n",
    "##############################################################################################################################\n",
    "\n",
    "\n",
    "\n",
    "#***************************************************************************************************************************\n",
    "#|General Overview|\n",
    "#***************************************************************************************************************************\n",
    "##############################################################################################################################\n",
    "# Creating Graph#4 []\n",
    "##############################################################################################################################\n",
    "# Calculate percentage distribution and round to one decimal place\n",
    "category_counts = df_snapshot['Product Category'].value_counts(normalize=True) * 100\n",
    "category_percentages = category_counts.round(1)\n",
    "\n",
    "# Write data to the worksheet starting from row 3, column 15 (O3)\n",
    "graph_sheet.cell(row=3, column=15, value=\"Product Category\")\n",
    "graph_sheet.cell(row=3, column=16, value=\"Percentage\")\n",
    "\n",
    "# Write category and percentage data to the worksheet\n",
    "for idx, (category, percentage) in enumerate(category_percentages.items(), start=4):\n",
    "    graph_sheet.cell(row=idx, column=15, value=category)\n",
    "    graph_sheet.cell(row=idx, column=16, value=percentage)\n",
    "\n",
    "###############################################\n",
    "# Create the chart title including the subtitle\n",
    "################################################\n",
    "chart_title = f\"Percentage Distribution of Product Categories\\nInputs date: {file_date_inventory} - Source: |CM-Snapshot|\"\n",
    "\n",
    "# Create a pie chart\n",
    "chart4 = PieChart()\n",
    "chart4.title = chart_title\n",
    "\n",
    "##########################################################\n",
    "# Prepare data for the pie chart using Reference\n",
    "min_row = 3  # Start from row 3 where your data starts\n",
    "max_row = min_row + len(category_percentages) # Calculate the last row based on the number of categories\n",
    "min_row_label = 4  # Start from row 4 for labels\n",
    "max_row_label = min_row_label + len(category_percentages) - 1\n",
    "\n",
    "data_points = Reference(graph_sheet, min_col=16, min_row=min_row, max_row=max_row)  # Adjusted min_col to 16\n",
    "labels = Reference(graph_sheet, min_col=15, min_row=min_row_label, max_row=max_row_label)  # Adjusted min_col to 15\n",
    "\n",
    "chart4.add_data(data_points, titles_from_data=True)\n",
    "chart4.set_categories(labels)\n",
    "    \n",
    "#############################\n",
    "# Set the size of the chart4\n",
    "##############################\n",
    "chart4.width = 20  # Adjust the width as needed\n",
    "chart4.height = 11  # Adjust the height as needed\n",
    "\n",
    "# Positioning the chart4 \n",
    "graph_sheet.add_chart(chart4, \"O3\")\n",
    "##############################################################################################################################\n",
    "\n",
    "##############################################################################################################################\n",
    "# Creating Graph#5 []\n",
    "##############################################################################################################################\n",
    "# Calculate percentage distribution and round to one decimal place\n",
    "status_counts = df_snapshot['Production Status'].value_counts(normalize=True) * 100\n",
    "status_percentages = status_counts.round(1)\n",
    "\n",
    "# Write data to the worksheet starting from row 28, column 15 (O28)\n",
    "graph_sheet.cell(row=28, column=15, value=\"Production Status\")\n",
    "graph_sheet.cell(row=28, column=16, value=\"Percentage\")\n",
    "\n",
    "# Write status and percentage data to the worksheet starting from row 29\n",
    "for idx, (status, percentage) in enumerate(status_percentages.items(), start=29):\n",
    "    graph_sheet.cell(row=idx, column=15, value=status)\n",
    "    graph_sheet.cell(row=idx, column=16, value=percentage)\n",
    "\n",
    "###############################################\n",
    "# Create the chart title including the subtitle\n",
    "################################################\n",
    "chart_title = f\"Percentage Distribution of Production Status\\nInputs date: {file_date_inventory} - Source: |CM-Snapshot|\"\n",
    "\n",
    "chart5 = PieChart()\n",
    "chart5.title = chart_title\n",
    "\n",
    "############################################################\n",
    "# Prepare data for the pie chart using Reference\n",
    "min_row = 28  # Start from row 29 to include the data\n",
    "max_row = min_row + len(status_percentages)  # Calculate the last row based on the number of statuses\n",
    "min_row_label = 29  # Start from row 29 for labels\n",
    "max_row_label = min_row_label + len(status_percentages) - 1\n",
    "\n",
    "data_points = Reference(graph_sheet, min_col=16, min_row=min_row, max_row=max_row)  # Adjusted min_col to 16\n",
    "labels = Reference(graph_sheet, min_col=15, min_row=min_row_label, max_row=max_row_label)  # Adjusted min_col to 15\n",
    "\n",
    "chart5.add_data(data_points, titles_from_data=True)\n",
    "chart5.set_categories(labels)\n",
    "    \n",
    "#############################\n",
    "# Set size/position\n",
    "##############################\n",
    "chart5.width = 20  # Adjust the width as needed\n",
    "chart5.height = 11  # Adjust the height as needed\n",
    "\n",
    "# Positioning  \n",
    "graph_sheet.add_chart(chart5, \"O28\")\n",
    "\n",
    "##############################################################################################################################\n",
    "\n",
    "##############################################################################################################################\n",
    "# Creating Graph#6 []\n",
    "##############################################################################################################################\n",
    "\n",
    "\n",
    "#***************************************************************************************************************************\n",
    "#|Clear to Build Overview|\n",
    "#***************************************************************************************************************************\n",
    "##############################################################################################################################\n",
    "# Creating Graph#7 []\n",
    "##############################################################################################################################\n",
    "# Calculate unique IDD Top Level for each Product Category and each classification\n",
    "pivot_table_df = pd.pivot_table(df_snapshot,\n",
    "                                index='Product Category',\n",
    "                                columns='Top-Level Status',\n",
    "                                values='IDD Top Level',\n",
    "                                aggfunc=pd.Series.nunique,\n",
    "                                fill_value=0)\n",
    "\n",
    "# Calculate total unique IDD Top Level across all categories\n",
    "total_unique_idd_top_level = df_snapshot['IDD Top Level'].nunique()\n",
    "\n",
    "# Write headers for each column first\n",
    "start_cell_row = 3\n",
    "start_cell_col = 28  # Column 'AB3'\n",
    "\n",
    "# Write headers\n",
    "graph_sheet.cell(row=start_cell_row, column=start_cell_col, value=\"Product Category\")\n",
    "graph_sheet.cell(row=start_cell_row, column=start_cell_col + 1, value=\"Unique IDD Top Level (Clear-to-Build)\")\n",
    "graph_sheet.cell(row=start_cell_row, column=start_cell_col + 2, value=\"Unique IDD Top Level (Short)\")\n",
    "\n",
    "# Write data rows\n",
    "for r_idx, (index, row) in enumerate(pivot_table_df.iterrows(), start=start_cell_row + 1):\n",
    "    graph_sheet.cell(row=r_idx, column=start_cell_col, value=index)  # Write Product Category\n",
    "    graph_sheet.cell(row=r_idx, column=start_cell_col + 1, value=row['Clear-to-Build'])  # Write unique count for Clear-to-Build\n",
    "    graph_sheet.cell(row=r_idx, column=start_cell_col + 2, value=row['Short'])  # Write unique count for Short\n",
    "\n",
    "# Add the total unique IDD Top Level label and value in the last row\n",
    "total_row = start_cell_row + len(pivot_table_df) + 1\n",
    "graph_sheet.cell(row=total_row, column=start_cell_col, value=\"Total Unique IDD Top Level\")\n",
    "graph_sheet.cell(row=total_row, column=start_cell_col + 1, value=pivot_table_df['Clear-to-Build'].sum())\n",
    "graph_sheet.cell(row=total_row, column=start_cell_col + 2, value=pivot_table_df['Short'].sum())\n",
    "\n",
    "###############################################\n",
    "# Create the chart title including the subtitle\n",
    "################################################\n",
    "chart_title = f\"Count of Unique IDD Top Level by Product Category\\nInputs date: {file_date_inventory} - Source: |Snapshot|\"\n",
    "\n",
    "# Create a bar chart (chart6)\n",
    "chart7 = BarChart()\n",
    "chart7.title = chart_title\n",
    "chart7.x_axis.title = 'Product Category'\n",
    "chart7.y_axis.title = 'Count of Unique IDD Top Level'\n",
    "\n",
    "##################################################\n",
    "# Define data for the chart (exclude totals row)\n",
    "data = Reference(graph_sheet,\n",
    "                 min_col=start_cell_col + 1,\n",
    "                 min_row=start_cell_row,\n",
    "                 max_col=start_cell_col + 2,\n",
    "                 max_row=start_cell_row + len(pivot_table_df) + 1)\n",
    "chart7.add_data(data, titles_from_data=True)\n",
    "\n",
    "# Set categories (x-axis)\n",
    "categories = Reference(graph_sheet,\n",
    "                       min_col=start_cell_col,\n",
    "                       min_row=start_cell_row + 1,\n",
    "                       max_row=start_cell_row + len(pivot_table_df) + 1)\n",
    "chart7.set_categories(categories)\n",
    "\n",
    "###############################\n",
    "# Set the size of the chart\n",
    "###############################\n",
    "chart7.width = 20  # Adjust the width as needed\n",
    "chart7.height = 11  # Adjust the height as needed\n",
    "\n",
    "# Positioning the chart \n",
    "graph_sheet.add_chart(chart7, \"AB3\")\n",
    "\n",
    "##############################################################################################################################\n",
    "# Creating Graph#8 []\n",
    "##############################################################################################################################\n",
    "# Create a pivot table with 'Product Category' as index\n",
    "pivot_table_df = pd.pivot_table(df_snapshot,\n",
    "                                index='Product Category',\n",
    "                                columns='Top-Level Status',\n",
    "                                values='IDD Backlog Qty',\n",
    "                                aggfunc='sum',\n",
    "                                fill_value=0)\n",
    "\n",
    "# Calculate unique IDD Top Level for Clear to Build and Short\n",
    "unique_idd_top_level_ctb = df_snapshot[df_snapshot['Top-Level Status'] == 'Clear-to-Build']['IDD Top Level'].nunique()\n",
    "unique_idd_top_level_short = df_snapshot[df_snapshot['Top-Level Status'] == 'Short']['IDD Top Level'].nunique()\n",
    "\n",
    "#print('Unique IDD Top Level for Clear to Build:', unique_idd_top_level_ctb)\n",
    "#print('Unique IDD Top Level for Short:', unique_idd_top_level_short)\n",
    "\n",
    "# Write the pivot table to the graph_sheet starting from AB28\n",
    "start_cell_row = 28\n",
    "start_cell_col = 28  # Column 'AB28'\n",
    "\n",
    "# Write headers for each column first\n",
    "for c_idx, col in enumerate(pivot_table_df.columns, start=start_cell_col + 1):\n",
    "    graph_sheet.cell(row=start_cell_row, column=c_idx, value=col)\n",
    "\n",
    "# Write data rows\n",
    "for r_idx, (index, row) in enumerate(pivot_table_df.iterrows(), start=start_cell_row + 1):\n",
    "    graph_sheet.cell(row=r_idx, column=start_cell_col, value=index)  # Write Product Category\n",
    "    for c_idx, value in enumerate(row, start=start_cell_col + 1):\n",
    "        graph_sheet.cell(row=r_idx, column=c_idx, value=value)\n",
    "\n",
    "# Add the total unique IDD Top Level labels and values in the second row\n",
    "total_row = start_cell_row + 1\n",
    "graph_sheet.cell(row=total_row, column=start_cell_col, value=\"Total unique IDD Top Level\")\n",
    "graph_sheet.cell(row=total_row, column=start_cell_col + 1, value=unique_idd_top_level_ctb)\n",
    "graph_sheet.cell(row=total_row, column=start_cell_col + 2, value=unique_idd_top_level_short)\n",
    "\n",
    "###############################################\n",
    "# Create the chart title including the subtitle\n",
    "################################################\n",
    "chart_title = f\"IDD Backlog Qty by Product Category and Top-Level Status\\nInputs date: {file_date_inventory} - Source: |Snapshot|\"\n",
    "\n",
    "chart8 = BarChart()\n",
    "chart8.title = chart_title\n",
    "chart8.x_axis.title = 'Product Category'\n",
    "chart8.y_axis.title = 'IDD Backlog Qty'\n",
    "\n",
    "##################################################\n",
    "# Define data for the chart including total unique IDD Top Level and all rows\n",
    "data = Reference(graph_sheet,\n",
    "                 min_col=start_cell_col + 1,\n",
    "                 min_row=start_cell_row, \n",
    "                 max_col=start_cell_col + len(pivot_table_df.columns),\n",
    "                 max_row=start_cell_row + len(pivot_table_df))\n",
    "chart8.add_data(data, titles_from_data=True)\n",
    "\n",
    "# Set categories (x-axis) including the total unique IDD Top Level label and all rows\n",
    "categories = Reference(graph_sheet,\n",
    "                       min_col=start_cell_col,\n",
    "                       min_row=start_cell_row + 1, \n",
    "                       max_row=start_cell_row + len(pivot_table_df)) \n",
    "chart8.set_categories(categories)\n",
    "\n",
    "###############################\n",
    "# Set the size of the chart\n",
    "###############################\n",
    "chart8.width = 20  # Adjust the width as needed\n",
    "chart8.height = 11  # Adjust the height as needed\n",
    "\n",
    "# Positioning the chart \n",
    "graph_sheet.add_chart(chart8, \"AB28\")\n",
    "\n",
    "##############################################################################################################################\n",
    "# Creating Graph#9 []\n",
    "##############################################################################################################################\n",
    "# Merge df_backlog with df_snapshot to bring 'Top-Level Status' into df_backlog\n",
    "df_backlog = pd.merge(df_backlog, df_snapshot[['Pty Indice', 'Top-Level Status']], on='Pty Indice', how='left')\n",
    "\n",
    "# Define 'Order Type' column based on 'Order' column, excluding rows containing 'NC'\n",
    "df_backlog['Order Type'] = df_backlog['Order'].apply(lambda x: 'DX/DO' if str(x).startswith('D') else ('Standard' if 'NC' not in str(x) else None))\n",
    "\n",
    "# Calculate sum of 'Backlog row Qty' by 'Pty Indice' and 'Order Type'\n",
    "#df_backlog['Sum Backlog Qty'] = df_backlog.groupby(['Pty Indice', 'Order Type'])['Backlog row Qty'].transform('sum')\n",
    "\n",
    "#display(df_backlog) \n",
    "\n",
    "\n",
    "# Calculate sum of 'Backlog row Qty' separately for 'Standard' and 'DX/DO'\n",
    "sum_standard = df_backlog.loc[df_backlog['Order Type'] == 'Standard', 'Backlog row Qty'].sum()\n",
    "sum_dx_do = df_backlog.loc[df_backlog['Order Type'] == 'DX/DO', 'Backlog row Qty'].sum()\n",
    "\n",
    "#print(f\"Sum of 'Backlog row Qty' for 'Standard': {sum_standard}\")\n",
    "#print(f\"Sum of 'Backlog row Qty' for 'DX/DO': {sum_dx_do}\")\n",
    "\n",
    "#Create pivot table\n",
    "pivot_table_df = pd.pivot_table(df_backlog,\n",
    "                                index='Order Type',\n",
    "                                columns='Top-Level Status',\n",
    "                                values='Backlog row Qty',\n",
    "                                aggfunc='sum',\n",
    "                                fill_value=0)\n",
    "\n",
    "# Write the pivot table to the graph_sheet starting from AB53\n",
    "start_cell_row = 53\n",
    "start_cell_col = 28  # Column AB\n",
    "\n",
    "# Write headers for each column first\n",
    "for c_idx, col in enumerate(pivot_table_df.columns, start=start_cell_col + 1):\n",
    "    graph_sheet.cell(row=start_cell_row, column=c_idx, value=col)\n",
    "\n",
    "# Write data rows\n",
    "for r_idx, (index, row) in enumerate(pivot_table_df.iterrows(), start=start_cell_row + 1):\n",
    "    graph_sheet.cell(row=r_idx, column=start_cell_col, value=index)  # Write Order Type\n",
    "    for c_idx, value in enumerate(row, start=start_cell_col + 1):\n",
    "        graph_sheet.cell(row=r_idx, column=c_idx, value=value)\n",
    "\n",
    "##################################\n",
    "#Create and configure the chart\n",
    "######################################\n",
    "chart_title = f\"IDD Backlog Qty by type of order\\nInputs date: {file_date_inventory} - Source: |CM-Backlog|\"\n",
    "\n",
    "chart9 = BarChart()\n",
    "chart9.title = chart_title\n",
    "chart9.x_axis.title = 'Order Type'\n",
    "chart9.y_axis.title = 'IDD Backlog Qty'\n",
    "########################################\n",
    "\n",
    "# Define data for the chart\n",
    "data = Reference(graph_sheet,\n",
    "                 min_col=start_cell_col + 1,\n",
    "                 min_row=start_cell_row, \n",
    "                 max_col=start_cell_col + len(pivot_table_df.columns),\n",
    "                 max_row=start_cell_row + len(pivot_table_df))\n",
    "chart9.add_data(data, titles_from_data=True)\n",
    "\n",
    "# Set categories (x-axis)\n",
    "categories = Reference(graph_sheet,\n",
    "                       min_col=start_cell_col,\n",
    "                       min_row=start_cell_row + 1, \n",
    "                       max_row=start_cell_row + len(pivot_table_df))\n",
    "chart9.set_categories(categories)\n",
    "\n",
    "\n",
    "###############################\n",
    "# Set the size of the chart\n",
    "###############################\n",
    "chart9.width = 20  # Adjust the width as needed\n",
    "chart9.height = 11  # Adjust the height as needed\n",
    "\n",
    "# Positioning the chart \n",
    "graph_sheet.add_chart(chart9, \"AB53\")\n",
    "\n",
    "#***************************************************************************************************************************\n",
    "#|Progression Overview|\n",
    "#***************************************************************************************************************************\n",
    "##############################################################################################################################\n",
    "# Creating Graph#10 []\n",
    "##############################################################################################################################\n",
    "# Filter to exclude rows where 'Order' contains 'NC'\n",
    "filtered_df = df_TurnoverReport[~df_TurnoverReport['Order'].str.contains('NC')]\n",
    "\n",
    "# Define the span period of the report\n",
    "start_date = filtered_df['Invoice date'].min()\n",
    "end_date = filtered_df['Invoice date'].max()\n",
    "span_period = f\"{start_date} to {end_date}\"\n",
    "\n",
    "# Group by 'Pty Indice' and sum 'TurnoverReport row Qty'\n",
    "sum_qty_by_indice = filtered_df.groupby('Pty Indice')['TurnoverReport row Qty'].sum()\n",
    "\n",
    "# Print or display the result\n",
    "#print(sum_qty_by_indice)\n",
    "\n",
    "# Write sum_qty_by_indice to Excel starting from cell AO3\n",
    "start_cell_row = 3\n",
    "start_cell_col = 41  # Column 'AO'\n",
    "\n",
    "# Write headers\n",
    "graph_sheet.cell(row=start_cell_row, column=start_cell_col, value='Pty Indice')\n",
    "graph_sheet.cell(row=start_cell_row, column=start_cell_col + 1, value='Qty shipped')\n",
    "\n",
    "# Write data rows\n",
    "for r_idx, (indice, sum_qty) in enumerate(sum_qty_by_indice.items(), start=start_cell_row + 1):\n",
    "    graph_sheet.cell(row=r_idx, column=start_cell_col, value=indice)\n",
    "    graph_sheet.cell(row=r_idx, column=start_cell_col + 1, value=sum_qty)\n",
    "\n",
    "###############################################\n",
    "# Create the chart title including the subtitle\n",
    "################################################\n",
    "chart_title = f\"Qty shipped by Pty Indice - {span_period}\\nInputs date: {file_date_inventory} - Source: |CM-TurnoverReport|\"\n",
    "\n",
    "chart10 = BarChart()\n",
    "chart10.title = chart_title #f'Qty shipped by Pty Indice - {span_period}'\n",
    "chart10.x_axis.title = 'Pty Indice'\n",
    "chart10.y_axis.title = 'Qty shipped'\n",
    "\n",
    "###################################################\n",
    "# Define data for the chart\n",
    "data = Reference(graph_sheet,\n",
    "                 min_col=start_cell_col + 1,\n",
    "                 min_row=start_cell_row,\n",
    "                 max_col=start_cell_col + 1,\n",
    "                 max_row=start_cell_row + len(sum_qty_by_indice))\n",
    "chart10.add_data(data, titles_from_data=True)\n",
    "\n",
    "# Set categories (x-axis)\n",
    "categories = Reference(graph_sheet,\n",
    "                       min_col=start_cell_col,\n",
    "                       min_row=start_cell_row + 1,\n",
    "                       max_row=start_cell_row + len(sum_qty_by_indice))\n",
    "chart10.set_categories(categories)\n",
    "\n",
    "\n",
    "###############################\n",
    "# Set the size of the chart\n",
    "###############################\n",
    "chart10.width = 20  # Adjust the width as needed\n",
    "chart10.height = 11  # Adjust the height as needed\n",
    "\n",
    "# Positioning the chart \n",
    "graph_sheet.add_chart(chart10, \"AO3\")\n",
    "\n",
    "\n",
    "\n",
    "##############################################################################################################################\n",
    "# Creating Graph#11 []\n",
    "##############################################################################################################################\n",
    "# Filter to include only rows where 'Order' contains 'NC'\n",
    "filtered_df = df_TurnoverReport[df_TurnoverReport['Order'].str.contains('NC')].copy()\n",
    "\n",
    "# Categorize 'TurnoverReport row Qty' as 'Shipped' or 'Received'\n",
    "filtered_df['Category'] = filtered_df['TurnoverReport row Qty'].apply(lambda x: 'Shipped' if x > 0 else 'Received')\n",
    "\n",
    "\n",
    "# Adjust negative values of 'TurnoverReport row Qty' to positive\n",
    "filtered_df['TurnoverReport row Qty'] = filtered_df['TurnoverReport row Qty'].abs()\n",
    "\n",
    "# Group by 'Pty Indice' and sum 'TurnoverReport row Qty'\n",
    "sum_qty_by_indice = filtered_df.groupby('Pty Indice')['TurnoverReport row Qty'].sum()\n",
    "\n",
    "#display(sum_qty_by_indice)\n",
    "\n",
    "# Create a pivot table with 'Pty Indice' as index and 'Category' as columns\n",
    "pivot_table_df = pd.pivot_table(filtered_df,\n",
    "                                index='Pty Indice',\n",
    "                                columns='Category',\n",
    "                                values='TurnoverReport row Qty',\n",
    "                                aggfunc='sum',\n",
    "                                fill_value=0)\n",
    "\n",
    "# Write sum_qty_by_indice to Excel starting from cell AO28\n",
    "start_cell_row = 28\n",
    "start_cell_col = 41  # Column 'AO'\n",
    "\n",
    "# Write headers\n",
    "graph_sheet.cell(row=start_cell_row, column=start_cell_col, value='Pty Indice')\n",
    "graph_sheet.cell(row=start_cell_row, column=start_cell_col + 1, value='Qty shipped')\n",
    "graph_sheet.cell(row=start_cell_row, column=start_cell_col + 2, value='Category')\n",
    "\n",
    "# Write data rows\n",
    "for r_idx, (indice, sum_qty) in enumerate(sum_qty_by_indice.items(), start=start_cell_row + 1):\n",
    "    graph_sheet.cell(row=r_idx, column=start_cell_col, value=indice)\n",
    "    graph_sheet.cell(row=r_idx, column=start_cell_col + 1, value=sum_qty)\n",
    "    # Assigning the category based on sum_qty\n",
    "    category = 'Shipped' if sum_qty > 0 else 'Received'\n",
    "    graph_sheet.cell(row=r_idx, column=start_cell_col + 2, value=category)\n",
    "\n",
    "###############################################\n",
    "# Create the chart title including the subtitle\n",
    "################################################\n",
    "chart_title = f\"Qty shipped by Pty Indice - {span_period}\\nInputs date: {file_date_inventory} - Source: |CM-TurnoverReport|\"\n",
    "\n",
    "chart11 = BarChart()\n",
    "chart11.title = chart_title #f'Qty shipped by Pty Indice - {span_period}'\n",
    "chart11.x_axis.title = 'Pty Indice'\n",
    "chart11.y_axis.title = 'Qty shipped'\n",
    "\n",
    "#################################################\n",
    "# Define data for the chart\n",
    "data = Reference(graph_sheet,\n",
    "                 min_col=start_cell_col + 1,\n",
    "                 min_row=start_cell_row,\n",
    "                 max_col=start_cell_col + 1,\n",
    "                 max_row=start_cell_row + len(sum_qty_by_indice))\n",
    "chart11.add_data(data, titles_from_data=True)\n",
    "\n",
    "# Set categories (x-axis)\n",
    "categories = Reference(graph_sheet,\n",
    "                       min_col=start_cell_col,\n",
    "                       min_row=start_cell_row + 1,\n",
    "                       max_row=start_cell_row + len(sum_qty_by_indice))\n",
    "chart11.set_categories(categories)\n",
    "\n",
    "###############################\n",
    "# Set the size of the chart\n",
    "###############################\n",
    "chart11.width = 20  # Adjust the width as needed\n",
    "chart11.height = 11  # Adjust the height as needed\n",
    "\n",
    "# Positioning the chart \n",
    "graph_sheet.add_chart(chart11, \"AO28\")\n",
    "\n",
    "\n",
    "##############################################################################################################################\n",
    "# Creating Graph#12 []\n",
    "##############################################################################################################################\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "#***************************************************************************************************************************\n",
    "#|Project Status|\n",
    "#***************************************************************************************************************************\n",
    "##############################################################################################################################\n",
    "# Creating Graph#13 [] - IDD Backlog Qty, Remain. crit. Qty & Qty clear-to-build per Pty Indice by Top-Level Status, Production Status & Product Category\n",
    "##############################################################################################################################\n",
    "# Create a new column 'Product status' based on the condition\n",
    "df_snapshot['Industrialization'] = df_snapshot['Production Status'].apply(lambda x: 'Industrialized' if x.strip() == 'Industrialized' else 'Not Industrialized')\n",
    "\n",
    "# Create a pivot table with 'Product Category', 'Pty Indice', and 'Top-Level Status' as index\n",
    "pivot_table_df = pd.pivot_table(df_snapshot,\n",
    "                                index=['Top-Level Status', 'Industrialization', 'Product Category', 'Pty Indice'],\n",
    "                                values=['IDD Backlog Qty', 'Remain. crit. Qty', 'Qty clear to build'],\n",
    "                                aggfunc='sum',\n",
    "                                fill_value=0).reset_index()\n",
    "\n",
    "# Sort pivot_table_df by 'Top-Level Status', 'Industrialization', then 'Product Category'\n",
    "sort_order = ['Clear-to-Build', 'Short']\n",
    "pivot_table_df['Top-Level Status'] = pd.Categorical(pivot_table_df['Top-Level Status'], categories=sort_order, ordered=True)\n",
    "pivot_table_df['Industrialization'] = pd.Categorical(pivot_table_df['Industrialization'], categories=['Industrialized', 'Not Industrialized'], ordered=True)\n",
    "pivot_table_df.sort_values(by=['Top-Level Status', 'Industrialization', 'Product Category'], inplace=True)\n",
    "\n",
    "\n",
    "# Write headers for each column first\n",
    "start_cell_row = 81\n",
    "start_cell_col = 2  # Column 'B81'\n",
    "\n",
    "# Write headers for each column\n",
    "headers = ['Top-Level Status', 'Industrialization', 'Product Category', 'Pty Indice', 'IDD Backlog Qty', 'Remain. crit. Qty', 'Qty clear to build']\n",
    "for c_idx, col in enumerate(headers, start=start_cell_col):\n",
    "    graph_sheet.cell(row=start_cell_row, column=c_idx, value=col)\n",
    "\n",
    "# Initialize a set to track written statuses and categories\n",
    "written_statuses_categories = set()\n",
    "\n",
    "# Write data rows\n",
    "for r_idx, row in pivot_table_df.iterrows():\n",
    "    current_status = row['Top-Level Status']\n",
    "    current_industrialization = row['Industrialization']\n",
    "    current_category = row['Product Category']\n",
    "    \n",
    "    # Write Top-Level Status and Industrialization only if it's the first occurrence\n",
    "    if (current_status, current_industrialization) not in written_statuses_categories:\n",
    "        cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col, value=current_status)\n",
    "        cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "        cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 1, value=current_industrialization)\n",
    "        cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "        written_statuses_categories.add((current_status, current_industrialization))  # Add current_status and current_industrialization to written_statuses\n",
    "    \n",
    "    # Write Product Category only if Status, Industrialization, and Category are first occurrence\n",
    "    if (current_status, current_industrialization, current_category) not in written_statuses_categories:\n",
    "        cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 2, value=current_category)\n",
    "        cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "        written_statuses_categories.add((current_status, current_industrialization, current_category))  # Add (current_status, current_industrialization, current_category) to written_statuses\n",
    "    \n",
    "    # Write Pty Indice\n",
    "    cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 3, value=row['Pty Indice'])\n",
    "    cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "    \n",
    "    # Write IDD Backlog Qty\n",
    "    cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 4, value=row['IDD Backlog Qty'])\n",
    "    cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "    \n",
    "    # Write Remain. crit. Qty \n",
    "    cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 5, value=row['Remain. crit. Qty'])\n",
    "    cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "    \n",
    "    # Write Qty clear to build\n",
    "    cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 6, value=row['Qty clear to build'])\n",
    "    cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "\n",
    "###############################################\n",
    "# Create the chart title including the subtitle\n",
    "################################################\n",
    "chart_title = f\"IDD Backlog Qty, Remain. crit. Qty & Qty clear-to-build per Pty Indice by Top-Level Status, Production Status & Product Category\\nInputs date: {file_date_inventory} - Source: |CM-Snapshot|\"\n",
    "\n",
    "chart13 = BarChart()\n",
    "chart13.title = \"IDD Backlog Qty, Remain. crit. Qty & Qty clear-to-build per Pty Indice by Top-Level Status, Production Status & Product Category\"\n",
    "chart13.x_axis.title = None\n",
    "chart13.y_axis.title = 'IDD Backlog Qty, Remain. crit. Qty & Qty clear-to-build '\n",
    "\n",
    "########################################################\n",
    "# Define data for the chart\n",
    "data = Reference(graph_sheet,\n",
    "                 min_col=start_cell_col + 4,\n",
    "                 min_row=start_cell_row,\n",
    "                 max_col=start_cell_col + 6,\n",
    "                 max_row=start_cell_row + len(pivot_table_df))\n",
    "\n",
    "chart13.add_data(data, titles_from_data=True)\n",
    "\n",
    "# Set categories (x-axis)\n",
    "categories = Reference(graph_sheet,\n",
    "                       min_col=start_cell_col,\n",
    "                       min_row=start_cell_row + 1,\n",
    "                       max_col=start_cell_col + 3,\n",
    "                       max_row=start_cell_row + len(pivot_table_df))\n",
    "\n",
    "chart13.set_categories(categories)\n",
    "\n",
    "############################\n",
    "# Set the size of the chart\n",
    "############################\n",
    "chart13.width = 80  # Adjust the width as needed\n",
    "chart13.height = 16  # Adjust the height as needed\n",
    "\n",
    "# Positioning the chart \n",
    "graph_sheet.add_chart(chart13, \"B81\")\n",
    "\n",
    "##############################################################################################################################\n",
    "# Creating Graph#14 - IDD Total Sales & IDD Marge per Pty Indice by Top-Level Status, Production Status & Product Categor\n",
    "##############################################################################################################################\n",
    "# Calculate IDD Total Sales\n",
    "df_snapshot['IDD Total Sales'] = df_snapshot['IDD Backlog Qty'] * df_snapshot['IDD Sale Price']\n",
    "\n",
    "# Calculate IDD Total Marge\n",
    "df_snapshot['IDD Total Marge'] = df_snapshot['IDD Backlog Qty'] * df_snapshot['IDD Marge Standard (unit)']\n",
    "\n",
    "# Create a new column 'Product status' based on the condition\n",
    "df_snapshot['Industrialization'] = df_snapshot['Production Status'].apply(lambda x: 'Industrialized' if x.strip() == 'Industrialized' else 'Not Industrialized')\n",
    "\n",
    "# Create a pivot table with 'Product Category', 'Pty Indice', and 'Top-Level Status' as index\n",
    "pivot_table_df = pd.pivot_table(df_snapshot,\n",
    "                                index=['Top-Level Status', 'Industrialization', 'Product Category', 'Pty Indice'],\n",
    "                                values=['IDD Total Sales', 'IDD Total Marge'],\n",
    "                                aggfunc='sum',\n",
    "                                fill_value=0).reset_index()\n",
    "\n",
    "# Sort pivot_table_df by 'Top-Level Status', 'Industrialization', then 'Product Category'\n",
    "sort_order = ['Clear-to-Build', 'Short']\n",
    "pivot_table_df['Top-Level Status'] = pd.Categorical(pivot_table_df['Top-Level Status'], categories=sort_order, ordered=True)\n",
    "pivot_table_df['Industrialization'] = pd.Categorical(pivot_table_df['Industrialization'], categories=['Industrialized', 'Not Industrialized'], ordered=True)\n",
    "pivot_table_df.sort_values(by=['Top-Level Status', 'Industrialization', 'Product Category'], inplace=True)\n",
    "\n",
    "\n",
    "# Write headers for each column first\n",
    "start_cell_row = 81\n",
    "start_cell_col = 14  # Column 'N81'\n",
    "\n",
    "# Write headers for each column\n",
    "headers = ['Top-Level Status', 'Industrialization', 'Product Category', 'Pty Indice', 'IDD Total Sales', 'IDD Total Marge']\n",
    "for c_idx, col in enumerate(headers, start=start_cell_col):\n",
    "    graph_sheet.cell(row=start_cell_row, column=c_idx, value=col)\n",
    "\n",
    "# Initialize a set to track written statuses and categories\n",
    "written_statuses_categories = set()\n",
    "\n",
    "# Write data rows\n",
    "for r_idx, row in pivot_table_df.iterrows():\n",
    "    current_status = row['Top-Level Status']\n",
    "    current_industrialization = row['Industrialization']\n",
    "    current_category = row['Product Category']\n",
    "    \n",
    "    # Write Top-Level Status and Industrialization only if it's the first occurrence\n",
    "    if (current_status, current_industrialization) not in written_statuses_categories:\n",
    "        cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col, value=current_status)\n",
    "        cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "        cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 1, value=current_industrialization)\n",
    "        cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "        written_statuses_categories.add((current_status, current_industrialization))  # Add current_status and current_industrialization to written_statuses\n",
    "    \n",
    "    # Write Product Category only if Status, Industrialization, and Category are first occurrence\n",
    "    if (current_status, current_industrialization, current_category) not in written_statuses_categories:\n",
    "        cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 2, value=current_category)\n",
    "        cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "        written_statuses_categories.add((current_status, current_industrialization, current_category))  # Add (current_status, current_industrialization, current_category) to written_statuses\n",
    "    \n",
    "    # Write Pty Indice\n",
    "    cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 3, value=row['Pty Indice'])\n",
    "    cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "    \n",
    "    # Write IDD Total Sales as currency\n",
    "    cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 4, value=row['IDD Total Sales'])\n",
    "    cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "    graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 4).number_format = '$#,##0.00'\n",
    "    \n",
    "    # Write IDD Total Marge as currency\n",
    "    cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 5, value=row['IDD Total Marge'])\n",
    "    cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "    graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 5).number_format = '$#,##0.00'\n",
    "\n",
    "###############################################\n",
    "# Create the chart title including the subtitle\n",
    "################################################\n",
    "chart_title = f\"IDD Total Sales & IDD Marge per Pty Indice by Top-Level Status, Production Status & Product Category\\nInputs date: {file_date_inventory} - Source: |CM-Snapshot|\"\n",
    "\n",
    "# Create a bar chart\n",
    "chart14 = BarChart()\n",
    "chart14.title = chart_title\n",
    "chart14.x_axis.title = None\n",
    "chart14.y_axis.title = 'IDD Total Sales & Marge'\n",
    "\n",
    "###################################################\n",
    "# Define data for the chart\n",
    "data = Reference(graph_sheet,\n",
    "                 min_col=start_cell_col + 4,\n",
    "                 min_row=start_cell_row,\n",
    "                 max_col=start_cell_col + 5,\n",
    "                 max_row=start_cell_row + len(pivot_table_df))\n",
    "\n",
    "chart14.add_data(data, titles_from_data=True)\n",
    "\n",
    "# Set categories (x-axis)\n",
    "categories = Reference(graph_sheet,\n",
    "                       min_col=start_cell_col,\n",
    "                       min_row=start_cell_row + 1,\n",
    "                       max_col=start_cell_col + 3,\n",
    "                       max_row=start_cell_row + len(pivot_table_df))\n",
    "\n",
    "chart14.set_categories(categories)\n",
    "\n",
    "############################\n",
    "# Set the size of the chart\n",
    "############################\n",
    "chart14.width = 80  # Adjust the width as needed\n",
    "chart14.height = 16  # Adjust the height as needed\n",
    "\n",
    "# Positioning the chart \n",
    "graph_sheet.add_chart(chart14, \"B116\")\n",
    "\n",
    "\n",
    "##############################################################################################################################\n",
    "# Creating Graph#15 - IDD Backlog Qty, Remain. crit. Qty & Qty clear-to-build per Pty Indice by Industrialization & Type of order\n",
    "##############################################################################################################################\n",
    "# Merge df_backlog with df_snapshot to bring 'Top-Level Status' and 'Production Status' into df_backlog\n",
    "df_backlog = pd.merge(df_backlog, df_snapshot[['Pty Indice', 'Top-Level Status', 'Production Status']], on='Pty Indice', how='left')\n",
    "\n",
    "# Define 'Order Type' column based on 'Order' column, excluding rows containing 'NC'\n",
    "df_backlog['Order Type'] = df_backlog['Order'].apply(lambda x: 'DX/DO' if str(x).startswith('D') else ('Standard' if 'NC' not in str(x) else None))\n",
    "\n",
    "# Rename 'Production Status_x' to 'Production Status' if needed\n",
    "if 'Production Status_x' in df_backlog.columns:\n",
    "    df_backlog.rename(columns={'Production Status_x': 'Production Status'}, inplace=True)\n",
    "\n",
    "# Rename 'Top-Level Status_x' to 'Top-Level Status' if needed\n",
    "if 'Top-Level Status_x' in df_backlog.columns:\n",
    "    df_backlog.rename(columns={'Top-Level Status_x': 'Top-Level Status'}, inplace=True)\n",
    "    \n",
    "#display(df_backlog)\n",
    "\n",
    "# Create a new column 'Industrialization' based on the condition\n",
    "df_backlog['Industrialization'] = df_backlog['Production Status'].apply(lambda x: 'Industrialized' if x.strip() == 'Industrialized' else 'Not Industrialized')\n",
    "\n",
    "# Create a pivot table with 'Top-Level Status', 'Industrialization', 'Order Type', and 'Pty Indice' as index\n",
    "pivot_table_df = pd.pivot_table(df_backlog,\n",
    "                                index=['Top-Level Status', 'Industrialization', 'Order Type', 'Pty Indice'],\n",
    "                                values=['Backlog row Qty'],\n",
    "                                aggfunc='sum',\n",
    "                                fill_value=0).reset_index()\n",
    "\n",
    "# Sort pivot_table_df by 'Top-Level Status', 'Industrialization', then 'Order Type'\n",
    "sort_order = ['Active', 'Inactive']\n",
    "pivot_table_df['Top-Level Status'] = pd.Categorical(pivot_table_df['Top-Level Status'], categories=sort_order, ordered=True)\n",
    "pivot_table_df['Industrialization'] = pd.Categorical(pivot_table_df['Industrialization'], categories=['Industrialized', 'Not Industrialized'], ordered=True)\n",
    "pivot_table_df.sort_values(by=['Top-Level Status', 'Industrialization', 'Order Type'], inplace=True)\n",
    "\n",
    "# Write headers for each column first\n",
    "start_cell_row = 81\n",
    "start_cell_col = 27  # Column 'AA81'\n",
    "\n",
    "# Write headers for each column\n",
    "headers = ['Top-Level Status', 'Industrialization', 'Order Type', 'Pty Indice', 'Backlog row Qty']\n",
    "for c_idx, col in enumerate(headers, start=start_cell_col):\n",
    "    cell = graph_sheet.cell(row=start_cell_row, column=c_idx, value=col)\n",
    "    cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "\n",
    "# Initialize a set to track written statuses, industrializations, categories\n",
    "written_statuses_categories = set()\n",
    "\n",
    "# Write data rows\n",
    "for r_idx, row in pivot_table_df.iterrows():\n",
    "    current_status = row['Top-Level Status']\n",
    "    current_industrialization = row['Industrialization']\n",
    "    current_order_type = row['Order Type']\n",
    "\n",
    "    # Write Top-Level Status, Industrialization, and Order Type only if it's the first occurrence\n",
    "    if (current_status, current_industrialization, current_order_type) not in written_statuses_categories:\n",
    "        cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col, value=current_status)\n",
    "        cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "        cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 1, value=current_industrialization)\n",
    "        cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "        cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 2, value=current_order_type)\n",
    "        cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "        written_statuses_categories.add((current_status, current_industrialization, current_order_type))  # Add to written_statuses\n",
    "\n",
    "    # Write Pty Indice\n",
    "    cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 3, value=row['Pty Indice'])\n",
    "    cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "    \n",
    "    # Write Backlog row Qty\n",
    "    cell = graph_sheet.cell(row=r_idx + start_cell_row + 1, column=start_cell_col + 4, value=row['Backlog row Qty'])\n",
    "    cell.font = Font(color=\"FFFFFF\")  # Set font color to white\n",
    "\n",
    "###############################################\n",
    "# Create the chart title including the subtitle\n",
    "################################################\n",
    "chart_title = f\"IDD Backlog Qty, Remain. crit. Qty & Qty clear-to-build per Pty Indice by Industrialization & Type of order\\nInputs date: {file_date_inventory} - Source: |CM-Snapshot|\"\n",
    "\n",
    "chart15 = BarChart()\n",
    "chart15.title = chart_title\n",
    "chart15.x_axis.title = None\n",
    "chart15.y_axis.title = 'IDD Backlog Qty, Remain. crit. Qty & Qty clear-to-build'\n",
    "\n",
    "########################################################\n",
    "# Define data for the chart\n",
    "data = Reference(graph_sheet,\n",
    "                 min_col=start_cell_col + 4,\n",
    "                 min_row=start_cell_row,\n",
    "                 max_col=start_cell_col + 4,\n",
    "                 max_row=start_cell_row + len(pivot_table_df))\n",
    "\n",
    "chart15.add_data(data, titles_from_data=True)\n",
    "\n",
    "# Set categories (x-axis)\n",
    "categories = Reference(graph_sheet,\n",
    "                       min_col=start_cell_col,\n",
    "                       min_row=start_cell_row + 1,\n",
    "                       max_col=start_cell_col + 3,\n",
    "                       max_row=start_cell_row + len(pivot_table_df))\n",
    "\n",
    "chart15.set_categories(categories)\n",
    "\n",
    "############################\n",
    "# Set the size of the chart\n",
    "############################\n",
    "chart15.width = 80  # Adjust the width as needed\n",
    "chart15.height = 16  # Adjust the height as needed\n",
    "\n",
    "# Positioning the chart\n",
    "graph_sheet.add_chart(chart15, \"B152\")\n",
    "\n",
    "#***************************************************************************************************************************\n",
    "# Formating |Dashboard|  \n",
    "#***************************************************************************************************************************\n",
    "############################################################\n",
    "# Get the sheet view (there should be only one sheet view)\n",
    "############################################################\n",
    "sheet_view = graph_sheet.sheet_view\n",
    "\n",
    "# Set the zoom scale to 60% \n",
    "sheet_view.zoomScale = 60\n",
    "    \n",
    "###################################################################################################################\n",
    "# Final save and selection of |Dashboard| as active tab\n",
    "###################################################################################################################\n",
    "\n",
    "# Save the updated workbook\n",
    "workbook.save(original_input)\n",
    "workbook.close()\n",
    "print(f\"Dashboard added successfully as |Dashboard| in {original_input}\")\n",
    "\n",
    "###################################################################################################################\n",
    "#Coloring tab |Dashboard|Snapshot|Summary|Clear-to-Build|CM-Inventory|CM-BOM|CM-Priority|CM-Backlog|\n",
    "###################################################################################################################\n",
    "##### load the formatted workbook\n",
    "workbook = load_workbook(original_input) \n",
    "\n",
    "################################\n",
    "# Move |Gantt| in position 7 \n",
    "################################\n",
    "# Function to move a sheet to a specific position\n",
    "def move_sheet_to_position(workbook, sheet_name, position):\n",
    "    sheet_names = workbook.sheetnames\n",
    "    sheet_names.remove(sheet_name)\n",
    "    sheet_names.insert(position, sheet_name)\n",
    "    workbook._sheets = [workbook[n] for n in sheet_names]\n",
    "\n",
    "# Move 'Gantt' to position 7 (index 6, since indexing starts at 0)\n",
    "move_sheet_to_position(workbook, 'Gantt', 6)\n",
    "\n",
    "workbook.save(original_input)\n",
    "\n",
    "#########################"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2bfcfcb5-df81-4bdc-9d96-249c4fc9ea14",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}