Spaces:
Sleeping

File size: 32,796 Bytes
d3485b8
 
 
 
 
 
95f83bb
 
 
2a1d7b0
fdb15d0
d3485b8
3451bac
 
0526543
cbe5e85
cb172fb
5b39bd6
 
ac5f890
 
573e5d6
 
c2b919c
 
 
3b83d23
2785131
 
 
d3485b8
 
 
 
 
555745b
 
 
 
 
d3485b8
 
 
 
 
 
 
 
 
 
 
95935bb
948f940
d3485b8
 
 
7f91cd9
d3485b8
948f940
d3485b8
95935bb
948f940
95935bb
 
 
 
 
 
 
 
 
d3485b8
 
 
948f940
 
95935bb
 
 
 
 
 
948f940
 
95935bb
 
948f940
 
95935bb
 
 
 
948f940
95935bb
 
 
 
948f940
95935bb
d3485b8
95935bb
948f940
 
95935bb
 
948f940
 
95935bb
d3485b8
95935bb
f277b7f
 
 
95935bb
f277b7f
68dfe1c
f277b7f
06575d7
68dfe1c
 
f277b7f
 
68dfe1c
 
 
 
f277b7f
 
06575d7
 
f277b7f
 
15b5097
 
 
 
 
b690c47
15b5097
f277b7f
b690c47
68dfe1c
7dddad9
 
 
 
 
 
 
 
68dfe1c
4652c1b
44312df
4652c1b
 
 
 
 
7dddad9
 
4652c1b
7dddad9
b690c47
f277b7f
7dddad9
06575d7
 
68dfe1c
d3485b8
0c051b6
b690c47
0c051b6
 
 
5145b21
0c051b6
5145b21
0c051b6
 
 
5145b21
0c051b6
 
5145b21
 
0c051b6
5145b21
0c051b6
5145b21
0c051b6
 
5145b21
0c051b6
 
5145b21
 
0c051b6
5145b21
0c051b6
 
 
 
943691c
ef36910
5145b21
58c2eac
 
 
 
 
5ff5683
58c2eac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ff5683
58c2eac
 
 
 
5ff5683
58c2eac
5ff5683
 
58c2eac
 
 
 
 
 
 
 
 
5ff5683
58c2eac
 
 
5ff5683
 
58c2eac
5ff5683
58c2eac
 
 
 
 
 
 
 
 
 
5ff5683
 
 
 
 
58c2eac
 
047f39a
 
 
58c2eac
 
 
5ff5683
58c2eac
 
 
 
3fdd0e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58c2eac
0a8e88d
d60355c
72eb2af
7dddad9
72eb2af
2e86e19
72eb2af
d60355c
 
3d8f1c2
 
 
d60355c
 
 
 
 
 
72eb2af
d60355c
d56193c
1ddd9cb
 
 
 
 
 
 
 
 
 
 
 
 
3d8f1c2
d56193c
 
d60355c
d56193c
 
 
3d8f1c2
d56193c
 
d60355c
 
2e86e19
 
 
 
d60355c
 
 
e1b163c
d60355c
3d8f1c2
704ace2
3d8f1c2
505223f
704ace2
29723e8
 
 
 
 
d60355c
 
 
2e86e19
3d8f1c2
 
d56193c
d60355c
d56193c
d60355c
d56193c
 
d60355c
72eb2af
 
d60355c
ea43bf1
 
a3b56f2
3451bac
 
a3b56f2
 
 
 
 
 
 
 
ea43bf1
a3b56f2
ea43bf1
a3b56f2
 
 
ea43bf1
a3b56f2
 
 
 
 
 
ea43bf1
3451bac
 
 
a3b56f2
3451bac
 
ea43bf1
3451bac
 
 
 
ea43bf1
a3b56f2
3451bac
 
e39ebd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c4c4bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a0a511
 
262562c
 
9b2021c
 
 
 
 
 
 
 
 
 
262562c
 
 
 
 
 
 
 
 
 
 
 
9b2021c
 
 
262562c
 
 
9b2021c
 
 
2a0a511
 
262562c
 
2a0a511
262562c
 
 
 
 
 
 
 
 
 
2a0a511
9b2021c
262562c
 
 
750bdaf
 
fe4e66b
750bdaf
 
a57536d
 
 
5d2ae37
 
 
 
fe4e66b
 
a57536d
fe4e66b
5d2ae37
 
 
fe4e66b
5d2ae37
 
fe4e66b
 
 
5d2ae37
 
 
 
a57536d
 
 
5d2ae37
fe4e66b
d9ed467
 
 
fe4e66b
d9afd49
5d2ae37
 
 
 
3c6ec61
d9ed467
750bdaf
5d2ae37
 
 
750bdaf
a57536d
 
d9ed467
1bcfc68
 
 
 
d9ed467
 
 
1bcfc68
d9ed467
be04e77
 
 
 
65c5264
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be04e77
65c5264
6c3aa4f
2785131
 
7104d67
f9d0902
2785131
7104d67
2785131
7104d67
2785131
 
7104d67
2b149de
021746d
2b149de
 
 
021746d
2b149de
 
 
7104d67
 
 
3ffc93b
fc95f92
 
 
 
 
 
 
bce19ff
fc95f92
 
bce19ff
fc95f92
bce19ff
e8e48cb
 
9a940d5
e8e48cb
ce7cbdd
 
 
 
e8e48cb
 
 
 
 
 
 
c4ee47d
ce7cbdd
e8e48cb
f0d63ee
 
 
e8e48cb
42034ce
 
2e245e8
 
42034ce
c4ee47d
f0d63ee
ce7cbdd
e8e48cb
 
ce7cbdd
 
 
 
 
 
 
 
 
d533f7e
ce7cbdd
e8e48cb
ce7cbdd
d533f7e
e8e48cb
9ffadeb
ce7cbdd
e8e48cb
 
9ffadeb
e8e48cb
9a940d5
 
ce7cbdd
3d5d52f
c4ee47d
573e5d6
907be71
 
 
573e5d6
907be71
 
 
 
5569468
907be71
 
573e5d6
 
 
 
 
907be71
 
573e5d6
 
907be71
573e5d6
907be71
 
 
 
 
 
 
 
 
 
573e5d6
 
 
 
 
907be71
 
 
 
 
573e5d6
907be71
 
573e5d6
5569468
907be71
5569468
 
ddd1270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f13bf73
 
 
 
 
 
 
 
 
 
 
f83d834
f13bf73
 
f843092
f83d834
 
f843092
f13bf73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b989dd7
c2b919c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c03d05
c2b919c
 
5532f46
1524e19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from huggingface_hub import list_repo_files
from collections import defaultdict
from openpyxl import load_workbook
from huggingface_hub import hf_hub_download
import tempfile
from datetime import datetime
from fastapi.responses import JSONResponse
import os
import io
import base64
import pandas as pd
import matplotlib.pyplot as plt 
from fastapi import APIRouter, HTTPException, Query
from urllib.parse import unquote
import traceback
import openpyxl
from openpyxl.utils.dataframe import dataframe_to_rows
from fastapi import APIRouter, Request, HTTPException
from huggingface_hub import upload_file
from fastapi import APIRouter, UploadFile, File, HTTPException
from huggingface_hub import upload_file
from io import BytesIO
from fastapi import Form



app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")

@app.get("/", response_class=HTMLResponse)
async def root(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})


REPO_ID = "doluong6/Quatest1"
HF_TOKEN = os.environ.get("HF_TOKEN")

@app.get("/dem_pyc_tat_ca")
def dem_pyc_tat_ca():
    try:
        all_files = list_repo_files(
            repo_id=REPO_ID,
            repo_type="dataset",
            token=HF_TOKEN
        )

        # Lọc file PYC chỉ trong thư mục Phieu_yeu_cau của từng khách hàng
        pyc_files = [
            f for f in all_files
            if f.startswith("Khach_hang/")
            and "/6. Phieu yeu cau/" in f
            and f.lower().endswith(".xlsx")
            and len(f.split("/")) == 4  # Đảm bảo cấu trúc: Khach_hang/<KHACH>/Phieu_yeu_cau/<file.xlsx>
        ]

        # Lọc file GCN trong thư mục Scan (đã hoàn thành)
        gcn_files = [
            f for f in all_files
            if f.startswith("Khach_hang/")
            and "/Scan/" in f
            and "GCN" in os.path.basename(f).upper()
        ]

        # Gom PYC theo khách hàng
        thong_ke_pyc = defaultdict(list)
        for f in pyc_files:
            parts = f.split("/")
            if len(parts) >= 3:
                ten_khach = parts[1]
                thong_ke_pyc[ten_khach].append(f)

        # Gom GCN theo khách hàng
        thong_ke_gcn = defaultdict(list)
        for f in gcn_files:
            parts = f.split("/")
            if len(parts) >= 3:
                ten_khach = parts[1]
                thong_ke_gcn[ten_khach].append(f)

        ket_qua = {}
        tong_pyc = 0
        tong_dang_xu_ly = 0

        for khach, ds_pyc in thong_ke_pyc.items():
            so_pyc = len(ds_pyc)
            so_gcn = len(thong_ke_gcn.get(khach, []))
            so_dxl = max(so_pyc - so_gcn, 0)

            ket_qua[khach] = {
                "tong_pyc": so_pyc,
                "so_hoan_thanh": so_gcn,
                "dang_xu_ly": so_dxl,
                "danh_sach_pyc": ds_pyc
            }

            tong_pyc += so_pyc
            tong_dang_xu_ly += so_dxl

        return {
            "tong_so_pyc": tong_pyc,
            "tong_dang_xu_ly": tong_dang_xu_ly,
            "khach_hang": ket_qua
        }

    except Exception as e:
        return {"error": str(e)}


@app.get("/tong_doanh_thu_pyc")
async def tong_doanh_thu_pyc():
    try:
        all_files = list_repo_files(repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN)

        # ✅ Chỉ lấy file PYC trong thư mục "6. Phieu yeu cau"
        pyc_files = [
            f for f in all_files
            if f.startswith("Khach_hang/")
            and "/6. Phieu yeu cau/" in f
            and f.endswith(".xlsx")
            and len(f.split("/")) == 4  # Đảm bảo đúng cấu trúc: Khach_hang/<KHACH>/6. Phieu yeu cau/<file.xlsx>
        ]

        tong_doanh_thu = 0

        for file_path in pyc_files:
            try:
                local_path = hf_hub_download(
                    repo_id=REPO_ID,
                    repo_type="dataset",
                    token=HF_TOKEN,
                    filename=file_path,
                    cache_dir="/tmp"
                )
                wb = load_workbook(local_path, data_only=True)

                # ✅ Ưu tiên tìm sheet chứa "phương tiện"
                sheet = None
                for s in wb.sheetnames:
                    if "phương tiện" in s.lower():
                        sheet = wb[s]
                        break
                if sheet is None:
                    sheet = wb.active

                # ✅ Quét cột BX (cột 76), từ dòng 24 trở đi
                for row in sheet.iter_rows(min_row=24, min_col=76, max_col=76):
                    cell = row[0]
                    val = cell.value
                    if isinstance(val, (int, float)):
                        tong_doanh_thu += val
                    elif isinstance(val, str):
                        try:
                            cleaned = float(val.replace(".", "").replace(",", "").strip())
                            tong_doanh_thu += cleaned
                        except:
                            pass

            except Exception as e:
                print(f"❌ Lỗi đọc file {file_path}: {e}")

        return {"tong_doanh_thu": round(tong_doanh_thu, 2)}

    except Exception as e:
        return {"error": str(e)}

@app.get("/dem_pyc_hoan_thanh")
def dem_pyc_hoan_thanh():
    try:
        all_files = list_repo_files(repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN)

        hoan_thanh_files = [
            f for f in all_files
            if f.startswith("Khach_hang/")
            and "/Scan/" in f
            and "GCN" in os.path.basename(f).upper()  # kiểm tra tên file chứa "GCN"
        ]

        thong_ke = defaultdict(list)
        for f in hoan_thanh_files:
            parts = f.split("/")
            if len(parts) >= 3:
                ten_khach = parts[1]
                thong_ke[ten_khach].append(f)

        return {
            "tong_so_hoan_thanh": len(hoan_thanh_files),
            "khach_hang": {
                khach: {
                    "so_hoan_thanh": len(files),
                    "danh_sach": files
                }
                for khach, files in thong_ke.items()
            }
        }

    except Exception as e:
        return {"error": str(e)}


@app.get("/pyc_chua_hoan_thanh")
def pyc_chua_hoan_thanh():
    try:
        all_files = list_repo_files(repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN)

        # Tìm các khách hàng có GCN
        gcn_files = [
            f for f in all_files
            if f.startswith("Khach_hang/")
            and "/Scan/" in f
            and "GCN" in os.path.basename(f).upper()
        ]
        khach_co_gcn = set(f.split("/")[1] for f in gcn_files if len(f.split("/")) >= 3)

        # Tìm các file phiếu yêu cầu
        pyc_files = [
            f for f in all_files
            if f.startswith("Khach_hang/")
            and "/Phieu_yeu_cau/" in f
            and f.endswith(".xlsx")
        ]

        ket_qua = []

        for file in pyc_files:
            parts = file.split("/")
            if len(parts) < 3:
                continue

            ten_khach = parts[1]
            if ten_khach in khach_co_gcn:
                continue  # bỏ qua khách đã có GCN

            try:
                local = hf_hub_download(
                    repo_id=REPO_ID,
                    repo_type="dataset",
                    filename=file,
                    token=HF_TOKEN,
                    cache_dir="/tmp"
                )

                wb = load_workbook(local, data_only=True)
                sheet = wb.active

                # Mã phiếu yêu cầu: ô D3
                pyc_code = str(sheet["D3"].value or "").strip()

                # Khách hàng: I8 đến CD8
                cols_kh = [
                    "I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X",
                    "Y","Z","AA","AB","AC","AD","AE","AF","AG","AH","AI","AJ","AK",
                    "AL","AM","AN","AO","AP","AQ","AR","AS","AT","AU","AV","AW","AX",
                    "AY","AZ","BA","BB","BC","BD","BE","BF","BG","BH","BI","BJ","BK",
                    "BL","BM","BN","BO","BP","BQ","BR","BS","BT","BU","BV","BW","BX",
                    "BY","BZ","CA","CB","CC","CD"
                ]
                khach_hang = "".join(str(sheet[f"{col}8"].value or "") for col in cols_kh).strip()

                # Ngày tạo phiếu: BM3:BN3 (ngày), BS3:BT3 (tháng), BX3:CA3 (năm)
                ngay = "".join(str(sheet[f"{col}3"].value or "") for col in ["BM", "BN"]).strip()
                thang = "".join(str(sheet[f"{col}3"].value or "") for col in ["BS", "BT"]).strip()
                nam = "".join(str(sheet[f"{col}3"].value or "") for col in ["BX", "BY", "BZ", "CA"]).strip()
                ngay_tao = f"{ngay}/{thang}/{nam}".strip("/")

                ket_qua.append({
                    "Phiếu yêu cầu": pyc_code or "Không rõ",
                    "Khách hàng": khach_hang or "Không rõ",
                    "Ngày tạo phiếu": ngay_tao or "Không rõ"
                })

            except Exception as e:
                print(f"Lỗi đọc {file}: {e}")
                continue

        return ket_qua

    except Exception as e:
        return {"error": str(e)}

@app.get("/ty_le_dich_vu")
def ty_le_dich_vu():
    try:
        # Tải file Excel từ dataset
        local_path = hf_hub_download(
            repo_id=REPO_ID,
            repo_type="dataset",
            filename="thong_ke_dich_vu.xlsx",
            token=HF_TOKEN,
            cache_dir="/tmp"
        )

        wb = load_workbook(local_path, data_only=True)
        sheet = wb.active

        result = {}
        for row in range(2, 5):  # Dòng 2–4 chứa dữ liệu
            loai = sheet[f"A{row}"].value  # Cột A: "Dịch vụ"
            ty_le = sheet[f"C{row}"].value  # Cột C: "Tỷ lệ (%)"
            if loai and ty_le is not None:
                result[loai.strip()] = float(ty_le)

        return {
            "Kiem_dinh": result.get("KĐ", 0),
            "Hieu_chuan": result.get("HC", 0),
            "Do_thu_nghiem": result.get("ĐTN", 0)
        }

    except Exception as e:
        return {"error": str(e)}

@app.get("/ds_pyc_cho_xu_ly")
def ds_pyc_cho_xu_ly():
    try:
        all_files = list_repo_files(repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN)

        pyc_files = [
            f for f in all_files
            if f.startswith("Khach_hang/")
            and "/Phieu_yeu_cau/" in f
            and f.endswith(".xlsx")
        ]

        ket_qua = []
        ten_nguoi_lap_hop_le = [
            "Nguyễn Duy Thảo", "Lê Danh Huy", "Nguyễn Mạnh Cường", "Trần Văn Dương", "Nguyễn Ngọc Vinh"
        ]

        for file in pyc_files:
            try:
                ten_khach = file.split("/")[1]
                thu_muc_pyc = file.split("/")[2]

                # === KIỂM TRA ĐÃ CÓ GCN HAY CHƯA ===
                has_gcn = any(
                    f.startswith(f"Khach_hang/{ten_khach}/{thu_muc_pyc}/Giay_chung_nhan/")
                    and "GCN" in f.upper()
                    for f in all_files
                )
                if has_gcn:
                    continue  # bỏ qua phiếu đã có GCN (đã hoàn thành)

                # === ĐỌC THÔNG TIN PYC ===
                local = hf_hub_download(
                    repo_id=REPO_ID,
                    repo_type="dataset",
                    filename=file,
                    token=HF_TOKEN,
                    cache_dir="/tmp"
                )
                wb = load_workbook(local, data_only=True)
                sheet = wb.active

                ten_file = file.split("/")[-1]
                nguoi_lap = sheet["AH51"].value
                ngay = sheet["BM3"].value
                thang = sheet["BS3"].value
                nam = sheet["BX3"].value

                if nguoi_lap not in ten_nguoi_lap_hop_le:
                    continue

                ngay_lap = f"{int(ngay):02}/{int(thang):02}/{nam}" if all([ngay, thang, nam]) else "Không rõ"

                thiet_bi_list = []
                for row in range(24, 100):
                    ten_tb = sheet[f"D{row}"].value
                    so_luong = sheet[f"BM{row}"].value
                    if ten_tb and "tên loại dịch vụ" not in str(ten_tb).lower():
                        thiet_bi_list.append({
                            "Thiết bị": str(ten_tb).strip(),
                            "Số lượng": int(so_luong) if isinstance(so_luong, (int, float)) else 1
                        })

                ket_qua.append({
                    "Khách hàng": ten_khach,
                    "File PYC": ten_file,
                    "Người lập": nguoi_lap,
                    "Ngày lập": ngay_lap,
                    "Danh sách thiết bị": thiet_bi_list
                })

            except Exception as e:
                print(f"Lỗi đọc file {file}: {e}")
                continue

        return JSONResponse(content=ket_qua)

    except Exception as e:
        return JSONResponse(content={"error": str(e)}, status_code=500)
@app.get("/doanh_thu_dich_vu")
def doanh_thu_dich_vu():
    try:
        FILE_NAME = "thong_ke_dich_vu.xlsx"

        # Tải file Excel từ Hugging Face dataset
        excel_path = hf_hub_download(
            repo_id=REPO_ID,
            repo_type="dataset",
            token=HF_TOKEN,
            filename=FILE_NAME,
            local_dir="/tmp"
        )

        df = pd.read_excel(excel_path)

        # Vẽ biểu đồ từ cột "Tổng doanh thu"
        labels = df["Dịch vụ"]
        values = df["Tổng doanh thu"]

        plt.figure(figsize=(6, 6))
        colors = ['#4caf50', '#2196f3', '#ff9800']
        plt.pie(values, labels=labels, autopct='%1.1f%%', colors=colors, startangle=140)
        plt.title("Tỷ lệ doanh thu theo dịch vụ")
        plt.axis('equal')
        plt.tight_layout()

        # Lưu vào buffer base64
        buf = io.BytesIO()
        plt.savefig(buf, format="png")
        plt.close()
        buf.seek(0)
        b64_image = base64.b64encode(buf.read()).decode("utf-8")

        return {
            "data": df.to_dict(orient="records"),
            "image_base64": b64_image
        }

    except Exception as e:
        return {"error": str(e)}
  
@app.get("/doanh_thu_tong")
def doanh_thu_tong():
    try:
        local_file = hf_hub_download(
            repo_id=REPO_ID,
            repo_type="dataset",
            token=HF_TOKEN,
            filename="Theo doi DTNB & DT 2025.xlsx",
            cache_dir="/tmp"
        )

        wb = load_workbook(local_file, data_only=True)

        # Lấy giá trị F100 và G100 từ sheet "Nội bộ"
        sheet_nb = wb["Nội bộ"]
        f100 = sheet_nb["F100"].value or 0
        g100 = sheet_nb["G100"].value or 0

        # Tính tổng cột F và I từ Tháng 1 đến Tháng 12
        tong_F = tong_I = 0
        for i in range(1, 13):
            sheet_name = f"Tháng {i}"
            if sheet_name in wb.sheetnames:
                sheet = wb[sheet_name]
                for row in sheet.iter_rows(min_row=2):
                    f_val = row[5].value  # Cột F
                    i_val = row[8].value  # Cột I
                    if isinstance(f_val, (int, float)):
                        tong_F += f_val
                    if isinstance(i_val, (int, float)):
                        tong_I += i_val

        tong_cong = f100 + g100 + tong_F + tong_I
        return {"tong_doanh_thu": round(tong_cong, 2)}

    except Exception as e:
        return {"error": str(e)}
@app.get("/doanh_thu_theo_thang")
def doanh_thu_theo_thang():
    try:
        HF_TOKEN = os.getenv("HF_TOKEN")
        REPO_ID = "doluong6/Quatest1"
        FILENAME = "Theo doi DTNB & DT 2025.xlsx"

        # Tải file Excel từ dataset
        file_path = hf_hub_download(
            repo_id=REPO_ID,
            repo_type="dataset",
            token=HF_TOKEN,
            filename=FILENAME,
            cache_dir="/tmp"
        )

        wb = load_workbook(file_path, data_only=True)
        doanh_thu = {}

        for i in range(1, 13):
            sheet_name = f"Tháng {i}"
            if sheet_name not in wb.sheetnames:
                continue

            sheet = wb[sheet_name]
            # Lấy các giá trị số trong cột F (bỏ None, chuỗi)
            col_F = [cell.value for cell in sheet["F"] if isinstance(cell.value, (int, float))]
            tong = sum(col_F)
            doanh_thu[f"Tháng {i}"] = round(tong, 2)

        return doanh_thu

    except Exception as e:
        return {"error": str(e)}
@app.get("/doanh_thu_noi_bo")
async def doanh_thu_noi_bo():
    try:
        HF_TOKEN = os.environ.get("HF_TOKEN")

        ds = hf_hub_download(
            repo_id="doluong6/Quatest1",
            filename="Theo doi DTNB & DT 2025.xlsx",
            repo_type="dataset",
            token=HF_TOKEN,
            cache_dir="/tmp"
        )

        wb = openpyxl.load_workbook(ds, data_only=True)
        ws = wb["Nội bộ"]

        data = []
        tong_cd = 0
        tong_di = 0

        for row in ws.iter_rows(min_row=4):
            phong = row[1].value  # cột B
            chuyen_den = row[5].value  # cột F
            chuyen_di = row[6].value   # cột G

            # ✅ Bỏ dòng trống và chỉ lấy các dòng có doanh thu > 0
            if not phong:
                continue
            cd = chuyen_den if isinstance(chuyen_den, (int, float)) else 0
            di = chuyen_di if isinstance(chuyen_di, (int, float)) else 0

            if cd + di <= 0:
                continue  # Bỏ nếu không có doanh thu

            data.append({
                "Phòng": phong,
                "Chuyển đến": cd,
                "Chuyển đi": di
            })

            tong_cd += cd
            tong_di += di

        return {
            "data": data,
            "tong": {
                "Tổng chuyển đến": tong_cd,
                "Tổng chuyển đi": tong_di
            }
        }

    except Exception as e:
        print("❌ Lỗi xử lý doanh_thu_noi_bo:", e)
        traceback.print_exc()
        return JSONResponse(status_code=500, content={"error": str(e)})
@app.get("/xem_pdf")
def xem_pdf(file_name: str):
    try:
        HF_TOKEN = os.environ.get("HF_TOKEN")
        if not HF_TOKEN:
            raise Exception("❌ Thiếu HF_TOKEN")

        repo_id = "doluong6/Quatest1"
        repo_type = "dataset"
        folder = "Tai_lieu"

        normalized_request_name = unidecode(file_name).lower().strip()
        print(f"📄 Đang tìm file: {normalized_request_name}")

        # Lấy danh sách file
        files = list_repo_files(repo_id=repo_id, repo_type=repo_type, token=HF_TOKEN)
        tai_lieu_files = [f for f in files if f.startswith(folder + "/") and f.lower().endswith(".pdf")]

        # Tìm file phù hợp
        matched_file = None
        for f in tai_lieu_files:
            original_name = os.path.basename(f)
            normalized_file_name = unidecode(original_name).lower().strip()
            if normalized_file_name == normalized_request_name:
                matched_file = f
                break

        if not matched_file:
            raise HTTPException(status_code=404, detail=f"❌ Không tìm thấy file: {file_name}")

        print(f"✅ Tải file: {matched_file}")

        # ✅ Đảm bảo sử dụng cache dir hợp lệ
        cache_dir = "/tmp/hf_cache"
        os.makedirs(cache_dir, exist_ok=True)
        os.environ["HF_HUB_CACHE"] = cache_dir

        # ✅ Tải file
        local_path = hf_hub_download(
            repo_id=repo_id,
            filename=matched_file,
            repo_type=repo_type,
            token=HF_TOKEN,
            cache_dir=cache_dir
        )

        return FileResponse(local_path, media_type="application/pdf")

    except Exception as e:
        print("❌ LỖI:", traceback.format_exc())
        return JSONResponse(status_code=500, content={"detail": str(e)})

@app.get("/danh_sach_pdf")
async def danh_sach_pdf():
    try:
        HF_TOKEN = os.environ.get("HF_TOKEN")
        all_files = list_repo_files("doluong6/Quatest1", repo_type="dataset", token=HF_TOKEN)
        pdfs = [f.split("/")[-1] for f in all_files if f.startswith("Tai_lieu/") and f.lower().endswith(".pdf")]
        return JSONResponse(content={"pdfs": pdfs})
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Lỗi khi lấy danh sách PDF: {str(e)}")
@app.get("/quy_trinh")
async def quy_trinh():
    try:
        HF_TOKEN = os.environ.get("HF_TOKEN")
        repo_id = "doluong6/Quatest1"

        all_files = list_repo_files(
            repo_id=repo_id,
            repo_type="dataset",
            token=HF_TOKEN
        )

        # Lọc các file thuộc thư mục Quy_trinh/ và có đuôi PDF, DOCX, XLSX
        pdfs = [
            f.split("/")[-1]
            for f in all_files
            if f.startswith("Quy_trinh/") and f.lower().endswith((".pdf", ".docx", ".xlsx"))
        ]

        return {"pdfs": pdfs}
    except Exception as e:
        return {"pdfs": [], "error": str(e)}
@app.get("/danh_muc_thiet_bi")
async def danh_muc_thiet_bi():
    try:
        HF_TOKEN = os.environ.get("HF_TOKEN")
        file_path = hf_hub_download(
            repo_id="doluong6/Quatest1",
            filename="Quan_ly_thiet_bi.xlsx",
            repo_type="dataset",
            token=HF_TOKEN,
            cache_dir="/tmp"
        )

        # Đọc sheet
        df = pd.read_excel(file_path, sheet_name="DUNG CU SU DUNG")
        df = df.dropna(how='all')              # Bỏ dòng trống
        df = df.dropna(axis=1, how='all')      # Bỏ cột trống
        df = df.fillna("")                     # Thay NaN bằng chuỗi rỗng

        # Trả về dạng list of dict
        data = df.to_dict(orient="records")
        return data

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Lỗi đọc danh mục thiết bị: {str(e)}")

def chuan_hoa_ngay(value):
    if pd.isna(value):
        return None
    if isinstance(value, datetime):
        return value
    if isinstance(value, str):
        for fmt in ("%d/%m/%Y", "%d-%m-%Y", "%Y-%m-%d", "%Y/%m/%d"):
            try:
                return datetime.strptime(value.strip(), fmt)
            except:
                continue
    return None

@app.get("/quan_ly_hoa_chat")
async def quan_ly_hoa_chat():
    try:
        HF_TOKEN = os.environ.get("HF_TOKEN")
        if not HF_TOKEN:
            raise ValueError("Biến môi trường HF_TOKEN chưa được thiết lập.")

        # Tải file từ Hugging Face dataset
        file_path = hf_hub_download(
            repo_id="doluong6/Quatest1",
            filename="Quan_ly_hoa_chat.xlsx",
            repo_type="dataset",
            token=HF_TOKEN,
            cache_dir="/tmp"
        )

        # Đọc dữ liệu từ sheet
        df = pd.read_excel(file_path, sheet_name="HOA CHAT SU DUNG")
        for col in df.columns:
            if pd.api.types.is_datetime64_any_dtype(df[col]):
                df[col] = df[col].dt.strftime('%Y-%m-%d')
        df = df.fillna("")
        # Chuyển STT về số nguyên (loại bỏ .0)
        if "STT" in df.columns:
            df["STT"] = df["STT"].apply(lambda x: str(int(float(x))) if str(x).replace('.', '', 1).isdigit() else str(x))




        # Chuẩn hóa ngày hết hạn + tính tình trạng
        def xu_ly_tinh_trang(row):
            try:
                het_han = pd.to_datetime(row['NGÀY HẾT HẠN'], errors='coerce')
                today = pd.Timestamp.today()
                if pd.isna(het_han):
                    return "KHÔNG RÕ"
                diff = (het_han - today).days
                if diff < 0:
                    return "HẾT HẠN"
                elif diff <= 30:
                    return f"CÒN: {diff} NGÀY ⚠"
                else:
                    return f"CÒN: {diff} NGÀY"
            except:
                return "KHÔNG RÕ"

        df["TÌNH TRẠNG"] = df.apply(xu_ly_tinh_trang, axis=1)

        # Trả về kết quả
        columns = df.columns.tolist()
        rows = df.astype(str).values.tolist()

        return {"columns": columns, "rows": rows}

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Lỗi đọc danh sách hóa chất: {str(e)}\n{traceback.format_exc()}")



@app.post("/cap_nhat_hoa_chat")
async def cap_nhat_hoa_chat(request: Request):
    try:
        # Nhận dữ liệu từ frontend
        body = await request.json()
        columns = body["columns"]
        data = body["data"]

        # Tạo DataFrame mới
        df = pd.DataFrame(data, columns=columns)

        # Chuẩn hóa STT
        if "STT" in df.columns:
            df["STT"] = df["STT"].apply(lambda x: str(int(float(x))) if str(x).replace('.', '', 1).isdigit() else x)

        # Xử lý cột ngày: chuyển về 'YYYY-MM-DD' hoặc ""
        for col in df.columns:
            if "ngày" in col.lower():
                df[col] = df[col].apply(lambda x: pd.to_datetime(x, errors="coerce").strftime('%Y-%m-%d') 
                                        if pd.notna(pd.to_datetime(x, errors="coerce")) else "")

        # Ghi vào file Excel tạm
        file_path = "/tmp/Quan_ly_hoa_chat.xlsx"
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.title = "HOA CHAT SU DUNG"

        for r in dataframe_to_rows(df, index=False, header=True):
            ws.append(r)

        wb.save(file_path)

        # Upload lên Hugging Face Dataset
        token = os.environ.get("HF_TOKEN")
        if not token:
            raise ValueError("Biến môi trường HF_TOKEN chưa được thiết lập.")

        upload_file(
            path_or_fileobj=file_path,
            path_in_repo="Quan_ly_hoa_chat.xlsx",
            repo_id="doluong6/Quatest1",
            repo_type="dataset",
            token=token
        )

        return {"message": "✅ Đã lưu dữ liệu mới thành công!"}

    except Exception as e:
        print("❌ Lỗi khi cập nhật hóa chất:\n", traceback.format_exc())
        raise HTTPException(status_code=500, detail=f"Lỗi khi lưu: {str(e)}")
# Sau khi upload_file(...)
# Gửi cảnh báo nếu có hóa chất sắp hết hạn
try:
    df_cb = df[df["TÌNH TRẠNG"].str.contains("HẾT HẠN|⚠", na=False)]

    if not df_cb.empty:
        from sendgrid import SendGridAPIClient
        from sendgrid.helpers.mail import Mail

        api_key = os.environ["SENDGRID_API_KEY"]
        email_nguoinhan = "doluong6@quatest1.com.vn"  # ✅ bạn có thể thay đổi địa chỉ nhận

        html_noi_dung = "<p>📢 <b>Cảnh báo hóa chất hết hạn hoặc sắp hết hạn:</b></p><ul>"
        for _, row in df_cb.iterrows():
            ten = row.get("TÊN HÓA CHẤT", "Không rõ")
            han = row.get("NGÀY HẾT HẠN", "")
            tt = row.get("TÌNH TRẠNG", "")
            html_noi_dung += f"<li><b>{ten}</b> – Hạn: {han} – <span style='color:red'>{tt}</span></li>"
        html_noi_dung += "</ul><br><p>Vui lòng kiểm tra và xử lý kịp thời.</p>"

        message = Mail(
            from_email="doluong6.quatest1@gmail.com",
            to_emails=email_nguoinhan,
            subject="⏰ Cảnh báo hóa chất hết/sắp hết hạn",
            html_content=html_noi_dung
        )
        sg = SendGridAPIClient(api_key)
        sg.send(message)
except Exception as e:
    print("⚠ Gửi mail cảnh báo lỗi:", e)
@app.get("/hien_thi_hskh")
async def hien_thi_hskh():
    try:
        HF_TOKEN = os.environ["HF_TOKEN"]
        file_path = hf_hub_download(
            repo_id="doluong6/Quatest1",
            filename="QLHS_LUU_2025.xlsx",
            repo_type="dataset",
            token=HF_TOKEN,
            cache_dir="/tmp"
        )

        df = pd.read_excel(file_path, sheet_name="HSKH")
        df = df.fillna("")

        # ✅ Làm sạch tiêu đề cột: bỏ xuống dòng và khoảng trắng dư
        df.columns = [str(col).replace("\n", " ").strip() for col in df.columns]

        return {
            "columns": df.columns.tolist(),
            "rows": df.astype(str).values.tolist()
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
@app.post("/cap_nhat_hskh")
async def cap_nhat_hskh(request: Request):
    try:
        body = await request.json()
        columns = body["columns"]
        rows = body["rows"]

        df = pd.DataFrame(rows, columns=columns)

        file_path = hf_hub_download(
            repo_id="doluong6/Quatest1",
            filename="QLHS_LUU_2025.xlsx",
            repo_type="dataset",
            token=os.environ["HF_TOKEN"],
            cache_dir="/tmp"
        )

        wb = openpyxl.load_workbook(file_path)
        if "HSKH" in wb.sheetnames:
            std = wb["HSKH"]
            wb.remove(std)
        ws = wb.create_sheet("HSKH")

        for i, row in enumerate([columns] + rows):
            for j, val in enumerate(row):
                ws.cell(row=i+1, column=j+1, value=val)

        temp_path = os.path.join(tempfile.gettempdir(), "QLHS_LUU_2025.xlsx")
        wb.save(temp_path)

        upload_file(
            path_or_fileobj=temp_path,
            path_in_repo="QLHS_LUU_2025.xlsx",
            repo_id="doluong6/Quatest1",
            repo_type="dataset",
            token=os.environ["HF_TOKEN"]
        )

        return {"message": "✅ Cập nhật sheet HSKH thành công!"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Lỗi cập nhật HSKH: {str(e)}")

@app.post("/upload_pyc")
async def upload_pyc(file: UploadFile = File(...)):
    try:
        filename = file.filename
        content = await file.read()

        # === Đọc file Excel ===
        wb = load_workbook(filename=BytesIO(content), data_only=True)
        ws = wb.active

        ten_khach = str(ws["I8"].value or "Khach_hang_khong_ten").strip()
        ma_phieu = str(ws["D3"].value or "KHONG_CO_MA").strip().replace("/", "-")
        thang = str(ws["BS3"].value or "00").zfill(2)
        nam = str(ws["BX3"].value or "2025")

        ten_khach_sach = ten_khach.replace("/", "-").replace("\\", "-").replace(" ", "_")
        thu_muc_khach = f"{ten_khach_sach}_{nam}-{thang}_{ma_phieu}"
        path_pyc_repo = f"Khach_hang/{thu_muc_khach}/Phieu_yeu_cau/{filename}"

        # === Ghi file PYC lên repo ===
        tmp_pyc = f"/tmp/{filename}"
        with open(tmp_pyc, "wb") as f:
            f.write(content)

        upload_file(
            path_or_fileobj=tmp_pyc,
            path_in_repo=path_pyc_repo,
            repo_id=REPO_ID,
            repo_type="dataset",
            token=HF_TOKEN,
            commit_message=f"Upload PYC {filename}"
        )

        return {"message": f"✅ Đã upload `{filename}` thành công và lưu vào thư mục `{thu_muc_khach}`."}

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Lỗi xử lý: {e}")
@app.post("/upload_kemtheo")
async def upload_kemtheo(
    khach_hang: str = Form(...),
    loai_tai_lieu: str = Form(...),  # Ví dụ: Scan, Hop_dong_thanh_ly, Ho_so_cong_tac, Giay_chung_nhan
    file: UploadFile = File(...)
):
    try:
        # Lưu file tạm vào thư mục hệ thống
        with tempfile.TemporaryDirectory() as temp_dir:
            temp_file_path = os.path.join(temp_dir, file.filename)
            with open(temp_file_path, "wb") as f:
                content = await file.read()
                f.write(content)

            # Định dạng đường dẫn trên Hugging Face dataset
            remote_path = f"Khach_hang/{khach_hang}/{loai_tai_lieu}/{file.filename}"

            # Upload lên Hugging Face dataset
            upload_file(
                path_or_fileobj=temp_file_path,
                path_in_repo=remote_path,
                repo_id="doluong6/Quatest1",
                repo_type="dataset",
                token=os.environ.get("HF_TOKEN"),
                commit_message=f"📎 Upload {loai_tai_lieu} cho {khach_hang}: {file.filename}"
            )

        return {"status": "success", "message": f"Đã upload {file.filename} vào {remote_path}"}

    except Exception as e:
        return {"status": "error", "message": str(e)}