-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauto_single_click_auto_run_no_need__following_steps.py
More file actions
2055 lines (1751 loc) · 85.7 KB
/
Copy pathauto_single_click_auto_run_no_need__following_steps.py
File metadata and controls
2055 lines (1751 loc) · 85.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import io
import re
import sys
import time
import json
import zipfile
import shutil
import requests
import pyodbc
import pandas as pd
import subprocess
import tkinter as tk
from datetime import datetime
from unittest.mock import patch
from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
from googleDrive.credentials_loader import (
get_drive_service_account_credentials,
get_env_var,
list_depots,
)
# Reconfigure console output encoding to prevent Windows crash on non-ASCII characters
if hasattr(sys.stdout, 'reconfigure'):
try:
sys.stdout.reconfigure(encoding='utf-8', errors='backslashreplace')
except:
pass
# ══════════════════════════════════════════════════════════════════
# Google Drive & Upgrade Configuration
# All paths are resolved dynamically relative to this script's location,
# so the project can be cloned/copied anywhere (D:, E:, another laptop, etc.)
# without any hard-coded C:\Users\...\... references.
# ══════════════════════════════════════════════════════════════════
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PARENT_DIR = os.path.dirname(SCRIPT_DIR)
# Project-internal googleDrive/ folder is the single source of truth.
# If a sibling "googleDrive" folder exists next to this script, use it;
# otherwise, fall back to a parent-level googleDrive/ folder.
_LOCAL_GDRIVE_NEXT_TO_SCRIPT = os.path.join(SCRIPT_DIR, "googleDrive")
_LOCAL_GDRIVE_PARENT = os.path.join(PARENT_DIR, "googleDrive")
if os.path.isdir(_LOCAL_GDRIVE_NEXT_TO_SCRIPT):
LOCAL_GDRIVE_DIR = _LOCAL_GDRIVE_NEXT_TO_SCRIPT
elif os.path.isdir(_LOCAL_GDRIVE_PARENT):
LOCAL_GDRIVE_DIR = _LOCAL_GDRIVE_PARENT
else:
# Last-resort fallback so legacy code that references these names
# doesn't crash on import. These paths will simply not exist on disk
# if googleDrive/ is missing, and downstream code will fail gracefully.
LOCAL_GDRIVE_DIR = _LOCAL_GDRIVE_NEXT_TO_SCRIPT
CLIENT_SECRET_PATH = os.path.join(LOCAL_GDRIVE_DIR, "client_secret_1076305260584-t28u3map5uuuqvdk28mrqjk0oigbadh4.apps.googleusercontent.com.json")
TOKEN_PICKLE_PATH = os.path.join(LOCAL_GDRIVE_DIR, "token.pickle")
# NOTE: EXCEL_PATH and ENV_PATH are now LEGACY references. Real values come from
# googleDrive/credentials_master.json (loaded via credentials_loader.get_env_var()
# and list_depots()). The legacy variables are kept defined (set to a non-existent
# path) so that any external importer that still references them by name will not
# crash with NameError — downstream code in this file has been migrated.
EXCEL_PATH = os.path.join(LOCAL_GDRIVE_DIR, "gDriveDepotLinks.xlsx")
ENV_PATH = os.path.join(LOCAL_GDRIVE_DIR, "env")
BASE_DEPOT_DIR = os.path.join(LOCAL_GDRIVE_DIR, "All_Depots")
RCLONE_REMOTE_NAME = 'grive_new'
SQL_SERVER = r'localhost' # Default instance (MSSQLSERVER). For SQLEXPRESS use r'.\SQLEXPRESS'
# ══════════════════════════════════════════════════════════════════
# LOCAL-FIRST PATH OVERRIDE (legacy comment kept for reference)
# All configuration paths above are now computed relative to this
# script, so the project is fully portable. Any folder containing
# this script + a sibling "googleDrive/" will Just Work.
# ══════════════════════════════════════════════════════════════════
def find_rclone_executable():
if shutil.which("rclone"):
return "rclone"
common_paths = [r"C:\rclone\rclone.exe"]
try:
for item in os.listdir("C:\\"):
if "rclone" in item.lower():
full_path = os.path.join("C:\\", item, "rclone.exe")
if os.path.exists(full_path):
common_paths.append(full_path)
except:
pass
for path in common_paths:
if os.path.exists(path):
return path
return "rclone"
def load_env(env_path):
env = {}
if os.path.exists(env_path):
with open(env_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#'):
parts = line.split('=', 1)
if len(parts) == 2:
env[parts[0].strip()] = parts[1].strip()
return env
def get_drive_service():
# Use single-source credentials from credentials_master.json (in-memory, no JSON file needed).
from googleDrive.credentials_loader import get_drive_service_account_credentials
scopes = ['https://www.googleapis.com/auth/drive']
creds = get_drive_service_account_credentials(scopes=scopes)
return build('drive', 'v3', credentials=creds)
def list_drive_folder_items(drive_service, folder_id):
query = f"'{folder_id}' in parents and trashed = false"
for attempt in range(1, 4):
try:
results = drive_service.files().list(
q=query,
pageSize=100,
fields="files(id, name, mimeType, createdTime, modifiedTime, size)"
).execute()
return results.get('files', [])
except Exception as e:
print(f" [Warning] Google Drive API list failed (Attempt {attempt}/3): {e}")
if attempt < 3:
time.sleep(5)
else:
raise e
def load_mpo_mapping_from_google_sheet(sheet_id='1Q4utivZ5OpgDznqlqElYU-HWNnZYI71YYpcZKcSM3xY', gid='1918615875'):
"""
Load the MPO mapping directly from the public Google Sheet
(DREAM APPS MPO CODE column) when the local mpo_code.xlsx file
is not available.
The sheet is publicly shared, so this works without authentication
by exporting it as XLSX via the standard Google Sheets export URL.
IMPORTANT: Filters out rows where MPO CODE is blank (footer/notes rows)
so they don't pollute the SQL join with fake mappings.
"""
try:
url = f'https://docs.google.com/spreadsheets/d/{sheet_id}/export?format=csv&gid={gid}'
print(f" Pulling MPO mapping from Google Sheet gid={gid}...")
df = pd.read_csv(url)
# Normalize column names: 'DREAM APPS MPO CODE' -> 'MPO CODE'
rename_map = {}
for c in df.columns:
cs = str(c).strip()
if cs.upper() == 'DREAM APPS MPO CODE':
rename_map[c] = 'MPO CODE'
elif cs.upper() == 'DREAM APPS DEPOT':
rename_map[c] = 'DEPOT'
elif cs.upper() == 'DREAM APPS ZONE':
rename_map[c] = 'ZONE'
if rename_map:
df.rename(columns=rename_map, inplace=True)
# Filter out rows with blank MPO CODE (footer/separator rows in the sheet)
total_raw = len(df)
if 'MPO CODE' in df.columns:
df['MPO CODE'] = df['MPO CODE'].astype(str).str.strip()
df = df[df['MPO CODE'].notna()
& (df['MPO CODE'] != '')
& (df['MPO CODE'].str.lower() != 'nan')]
# Also drop rows with blank DEPOT (those would be pure noise too)
if 'DEPOT' in df.columns:
df['DEPOT'] = df['DEPOT'].astype(str).str.strip()
df = df[df['DEPOT'].notna()
& (df['DEPOT'] != '')
& (df['DEPOT'].str.lower() != 'nan')]
print(f" [OK] Loaded MPO mapping: {len(df)} valid rows (filtered {total_raw - len(df)} blank rows)")
else:
print(f" [WARN] MPO CODE column not found, returning {len(df)} raw rows")
# Normalize keys for join
if 'MPO CODE' in df.columns:
df['MPO CODE'] = df['MPO CODE'].astype(str).str.strip().str.upper()
if 'DEPOT' in df.columns:
df['DEPOT'] = df['DEPOT'].astype(str).str.strip().str.upper()
if 'DEPOT' in df.columns and 'MPO CODE' in df.columns:
df['DEPOT_MPO_CODE'] = df['DEPOT'] + '_' + df['MPO CODE']
df = df.drop_duplicates(subset=['DEPOT_MPO_CODE'], keep='first')
print(f" [OK] Columns: {list(df.columns)[:6]}...")
return df
except Exception as e:
print(f" [ERROR] Could not load MPO mapping from Google Sheet: {e}")
return None
def get_best_item_from_groq(depot_name, items, groq_api_key):
items_summary = []
for item in items:
size_mb = f"{float(item.get('size', 0))/(1024*1024):.2f} MB" if 'size' in item else "DIR"
items_summary.append(
f"Name: {item['name']}, ID: {item['id']}, Type: {item['mimeType']}, Size: {size_mb}, Modified: {item.get('modifiedTime', 'N/A')}"
)
items_str = "\n".join(items_summary)
prompt = f"""
You are an expert AI agent. We are automating the process of downloading the latest database backup files for a specific depot.
Target Depot Name: {depot_name}
Here is a list of available files and folders in the Google Drive parent folder for this depot:
{items_str}
Please analyze the list of items and identify which item we should download or enter to retrieve the database files.
Guidelines:
1. We want the database backup file. This can be inside a subfolder (like 'Data') or it could be a zip file (like '03.06.2026(Sylhet).zip').
2. DHAKA-1 and DHAKA-2 share the same folder URL.
- For DHAKA-1: Select the item/folder representing Dhaka 1 (e.g. name contains 'DK 1', 'DK1', 'Dhaka 1').
- For DHAKA-2: Select the item/folder representing Dhaka 2 (e.g. name contains 'DK-2', 'DK2', 'Dhaka 2').
3. For other depots (e.g. JASHORE, FARIDPUR, SYLHET, etc.), pick the folder or archive file that matches the depot and is the latest upload.
- If there is a direct 'Data' folder and no other folders, select it.
- If there is a zip file containing the depot's database, select it.
- If there is a folder with a name like 'Data-03.06.26' or 'Closing Data May-26', select it.
Return a JSON object with the following fields:
- "selected_item_name": The exact name of the selected file or folder.
- "selected_item_id": The ID of the selected file or folder.
- "selected_item_type": Either "folder" or "file".
- "reasoning": A brief explanation of why you selected this item.
"""
url = "https://api.groq.com/openai/v1/chat/completions"
headers = {
"Authorization": f"Bearer {groq_api_key}",
"Content-Type": "application/json"
}
data = {
"model": "openai/gpt-oss-120b",
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.0,
"response_format": {"type": "json_object"}
}
for attempt in range(1, 4):
try:
response = requests.post(url, headers=headers, json=data, timeout=30)
response.raise_for_status()
result = response.json()
content = result['choices'][0]['message']['content']
return json.loads(content)
except Exception as e:
print(f" [Warning] Groq API call failed (Attempt {attempt}/3): {e}")
if attempt < 3:
time.sleep(5)
else:
raise e
def grant_sql_server_permissions(folder_path):
try:
accounts = [
'NT SERVICE\\MSSQL$SQLEXPRESS',
'NT SERVICE\\MSSQLSERVER',
'NT AUTHORITY\\NETWORK SERVICE',
'NT AUTHORITY\\SYSTEM'
]
for account in accounts:
try:
cmd = f'icacls "{folder_path}" /grant "{account}:(OI)(CI)F" /T /Q'
subprocess.run(cmd, shell=True, capture_output=True, timeout=10)
except:
pass
except Exception as e:
print(f"Warning: Permissions check failed: {e}")
# Server options tried in order by connect_sql_server() below.
# On systems where SQL Server is installed as the DEFAULT instance
# (i.e. service name = MSSQLSERVER), 'localhost' / '.' works.
# On systems where it was installed as a NAMED instance (SQLEXPRESS),
# 'localhost\SQLEXPRESS' / '.\SQLEXPRESS' works.
_SQL_SERVER_CANDIDATES = [
r'localhost',
r'.',
r'(local)',
r'localhost\SQLEXPRESS',
r'.\SQLEXPRESS',
r'(local)\SQLEXPRESS',
]
def connect_sql_server(database='master', timeout=5):
"""
Try connecting to SQL Server using several common server names,
returning the first successful pyodbc connection. Raises the last
error if none succeed.
"""
last_err = None
for server in _SQL_SERVER_CANDIDATES:
try:
conn_str = (
f'DRIVER={{ODBC Driver 17 for SQL Server}};'
f'SERVER={server};'
f'DATABASE={database};'
f'Trusted_Connection=yes;'
f'Connection Timeout={timeout};'
)
conn = pyodbc.connect(conn_str, timeout=timeout)
print(f" [OK] SQL Server connected via SERVER={server}")
return conn
except Exception as e:
last_err = e
raise last_err
def upgrade_db_compatibility(mdf_path, ldf_path, depot_name):
db_name = f"{depot_name.upper().replace('-', '_')}_UPGRADE_DB"
conn = connect_sql_server(database='master')
conn.autocommit = True
cursor = conn.cursor()
# Drop/Detach if already exists
cursor.execute(f"SELECT database_id FROM sys.databases WHERE name = '{db_name}'")
if cursor.fetchone():
print(f" Database {db_name} already exists. Detaching first...")
try:
cursor.execute(f"ALTER DATABASE [{db_name}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE")
cursor.execute(f"EXEC sp_detach_db '{db_name}', 'true'")
except Exception as e:
print(f" Error detaching: {e}")
# Attach database
mdf_path = os.path.normpath(mdf_path)
grant_sql_server_permissions(os.path.dirname(mdf_path))
if ldf_path and os.path.exists(ldf_path):
ldf_path = os.path.normpath(ldf_path)
attach_query = f"""
CREATE DATABASE [{db_name}] ON
(FILENAME = N'{mdf_path}'),
(FILENAME = N'{ldf_path}')
FOR ATTACH;
"""
else:
attach_query = f"""
CREATE DATABASE [{db_name}] ON
(FILENAME = N'{mdf_path}')
FOR ATTACH_REBUILD_LOG;
"""
print(f" Attaching {db_name} to SQLEXPRESS...")
cursor.execute(attach_query)
# Set compatibility level to 100
print(f" Upgrading compatibility level of {db_name} to 100...")
cursor.execute(f"ALTER DATABASE [{db_name}] SET COMPATIBILITY_LEVEL = 100")
# Detach database
print(f" Detaching database {db_name}...")
cursor.execute(f"ALTER DATABASE [{db_name}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE")
cursor.execute(f"EXEC sp_detach_db '{db_name}', 'true'")
print(f" [SUCCESS] {depot_name} compatibility upgraded successfully!")
conn.close()
def recover_sylhet_db(mdf_path, depot_name):
"""Special recovery for SYLHET MDF file where log rebuild fails standard attach"""
db_name = f"{depot_name.upper().replace('-', '_')}_DB"
data_dir = os.path.dirname(mdf_path)
# Grant write access to SQL Server service account on the depot Data folder
# (the user folder may not have MSSQLSERVER in its ACL).
grant_sql_server_permissions(data_dir)
# Use a temp directory under TEMP (writable by SQL Server service) for dummy files
# instead of the depot's Data folder, to avoid "Access is denied" on CREATE DATABASE.
import tempfile
_sylhet_tmp = os.path.join(tempfile.gettempdir(), f"alco_sylhet_{depot_name}")
os.makedirs(_sylhet_tmp, exist_ok=True)
# Ensure SQL Server can read/write this temp dir
grant_sql_server_permissions(_sylhet_tmp)
dummy_mdf_path = os.path.join(_sylhet_tmp, f'{depot_name}_dummy.mdf')
dummy_ldf_path = os.path.join(_sylhet_tmp, f'{depot_name}_dummy_log.ldf')
conn = connect_sql_server(database='master')
conn.autocommit = True
cursor = conn.cursor()
# Clean up existing database if any
cursor.execute(f"SELECT database_id FROM sys.databases WHERE name = '{db_name}'")
if cursor.fetchone():
try:
cursor.execute(f"ALTER DATABASE [{db_name}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE")
cursor.execute(f"DROP DATABASE [{db_name}]")
except:
pass
# Delete dummy files if they exist
for f in [dummy_mdf_path, dummy_ldf_path]:
if os.path.exists(f):
os.remove(f)
# Create dummy database in our workspace directory
create_query = f"""
CREATE DATABASE [{db_name}] ON PRIMARY
(NAME = '{db_name}_data', FILENAME = '{dummy_mdf_path}')
LOG ON
(NAME = '{db_name}_log', FILENAME = '{dummy_ldf_path}')
"""
cursor.execute(create_query)
# Set offline
cursor.execute(f"ALTER DATABASE [{db_name}] SET OFFLINE WITH ROLLBACK IMMEDIATE")
# Replace dummy MDF with target MDF
if os.path.exists(dummy_mdf_path):
os.remove(dummy_mdf_path)
shutil.copy2(mdf_path, dummy_mdf_path)
# Delete dummy LDF to force rebuild
if os.path.exists(dummy_ldf_path):
os.remove(dummy_ldf_path)
# Set online (will fail/warn, which is expected)
try:
cursor.execute(f"ALTER DATABASE [{db_name}] SET ONLINE")
except:
pass
# Set to EMERGENCY mode
cursor.execute(f"ALTER DATABASE [{db_name}] SET EMERGENCY")
# Set to SINGLE_USER
cursor.execute(f"ALTER DATABASE [{db_name}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE")
# Rebuild Log and Repair
print(" Running DBCC CHECKDB with REPAIR_ALLOW_DATA_LOSS to rebuild log file...")
dbcc_errors = []
try:
cursor.execute(f"DBCC CHECKDB ('{db_name}', REPAIR_ALLOW_DATA_LOSS) WITH NO_INFOMSGS, ALL_ERRORMSGS")
while True:
if not cursor.nextset():
break
try:
row = cursor.fetchone()
if row is None:
break
except Exception:
break
except Exception as e:
dbcc_errors.append(str(e))
print(f" DBCC warning (expected): {e}")
# ── SAFETY CHECK: count rows in main transaction tables ──
# REPAIR_ALLOW_DATA_LOSS can silently delete damaged rows. We verify that
# key tables (xline, xorder) still have rows. If 0 rows -> data is lost.
print(" Verifying recovered database row counts (data-loss safety check)...")
row_counts = {}
try:
cursor.execute(f"USE [{db_name}]")
for tbl in ['xline', 'xorder', 'xsp', 'xcustomer']:
try:
cursor.execute(f"SELECT COUNT(*) FROM dbo.{tbl}")
row_counts[tbl] = cursor.fetchone()[0]
except Exception:
row_counts[tbl] = None
total = sum(v for v in row_counts.values() if v)
print(f" [SAFETY] Row counts after recovery: {row_counts} (total={total})")
if total == 0:
print(f" [CRITICAL] SYLHET database recovery returned ZERO rows in all main tables.")
print(f" This depot's data is likely LOST/corrupted in the source MDF.")
print(f" Pipeline will SKIP {depot_name} to avoid polluting aggregates with zeros.")
try:
cursor.execute(f"ALTER DATABASE [{db_name}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE")
cursor.execute(f"EXEC sp_detach_db '{db_name}', 'true'")
except Exception:
pass
return None
elif total < 100:
print(f" [WARN] Very low row count ({total}) in SYLHET. May indicate partial data loss.")
except Exception as e:
print(f" [WARN] Safety check failed: {e}")
# Set back to MULTI_USER
try:
cursor.execute(f"ALTER DATABASE [{db_name}] SET MULTI_USER")
except:
pass
# Upgrade compatibility
cursor.execute(f"ALTER DATABASE [{db_name}] SET COMPATIBILITY_LEVEL = 100")
print(f" [SUCCESS] Recovered and attached suspect database: {db_name}")
conn.close()
return db_name
def attach_database(depot_name, mdf_path, ldf_path):
db_name = f"{depot_name.upper().replace('-', '_')}_DB"
conn = connect_sql_server(database='master')
conn.autocommit = True
cursor = conn.cursor()
# Drop/Detach if already exists
cursor.execute(f"SELECT database_id FROM sys.databases WHERE name = '{db_name}'")
if cursor.fetchone():
try:
cursor.execute(f"ALTER DATABASE [{db_name}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE")
cursor.execute(f"EXEC sp_detach_db '{db_name}', 'true'")
except:
pass
mdf_path = os.path.normpath(mdf_path)
grant_sql_server_permissions(os.path.dirname(mdf_path))
if ldf_path and os.path.exists(ldf_path):
ldf_path = os.path.normpath(ldf_path)
attach_query = f"""
CREATE DATABASE [{db_name}] ON
(FILENAME = N'{mdf_path}'),
(FILENAME = N'{ldf_path}')
FOR ATTACH;
"""
else:
attach_query = f"""
CREATE DATABASE [{db_name}] ON
(FILENAME = N'{mdf_path}')
FOR ATTACH_REBUILD_LOG;
"""
print(f" Attaching database {db_name}...")
cursor.execute(attach_query)
conn.close()
return db_name
def detach_database(db_name):
try:
conn = connect_sql_server(database='master')
conn.autocommit = True
cursor = conn.cursor()
cursor.execute(f"SELECT database_id FROM sys.databases WHERE name = '{db_name}'")
if cursor.fetchone():
cursor.execute(f"ALTER DATABASE [{db_name}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE")
cursor.execute(f"EXEC sp_detach_db '{db_name}', 'true'")
print(f" ✓ Detached {db_name}")
conn.close()
except Exception as e:
print(f" Error detaching {db_name}: {e}")
def extract_sales_data(depot_name, db_name):
try:
conn = connect_sql_server(database=db_name)
query = f"""
SELECT
'{depot_name}' AS Depot,
o.xsp AS MPO_Code,
o.xordernum AS Invoice_No,
o.xdate AS Invoice_Date,
o.ztime AS Transaction_Time,
CASE
WHEN o.xordernum LIKE 'IN-%' OR o.xordernum LIKE 'IN--%' THEN 'Sale'
WHEN o.xordernum LIKE 'SR-%' OR o.xordernum LIKE 'SR--%' THEN 'Return'
ELSE 'Other'
END AS Transaction_Type,
o.xcus AS Customer_ID,
LTRIM(RTRIM(c.xorg)) AS Customer_Name,
od.xitem AS Product_Code,
i.xdesc AS Product_Name,
od.xqtyord AS Quantity,
od.xlineamt AS Line_Amount
FROM opord o
LEFT JOIN opodt od ON o.xordernum = od.xordernum
LEFT JOIN cacus c ON o.xcus = c.xcus
LEFT JOIN caitem i ON od.xitem = i.xitem
WHERE o.xsp IS NOT NULL
AND o.xsp != ''
AND (o.xordernum LIKE 'IN-%' OR o.xordernum LIKE 'IN--%'
OR o.xordernum LIKE 'SR-%' OR o.xordernum LIKE 'SR--%')
"""
df = pd.read_sql(query, conn)
conn.close()
return df
except Exception as e:
print(f" [ERROR] Error extracting from {db_name}: {e}")
return pd.DataFrame()
def get_local_data_paths(depot_name):
"""Look for existing MDF/LDF in local depot folder (case-insensitive)."""
depot_dir = os.path.join(BASE_DEPOT_DIR, depot_name)
data_dir = os.path.join(depot_dir, "Data")
if not os.path.isdir(data_dir):
return None, None
mdf_path = ldf_path = None
for entry in os.listdir(data_dir):
low = entry.lower()
full = os.path.join(data_dir, entry)
if low in ("erponthenet_data.mdf", "erponthenet.mdf"):
mdf_path = full
elif low in ("erponthenet_log.ldf", "erponthenet.ldf"):
ldf_path = full
return mdf_path, ldf_path
# ══════════════════════════════════════════════════════════════════
# 3-STAGE / 3-LAYER LOCAL FILE VERIFICATION SYSTEM
# Purpose: Decide whether we can SKIP Google Drive download because
# every depot's data is already present locally.
#
# Stage 1 = Depot folder exists under BASE_DEPOT_DIR/All_Depots/<DEPOT>
# Stage 2 = A "Data" folder exists somewhere inside that depot folder
# (depth 1..N sub-folders allowed — recursive search)
# Stage 3 = At least EXPECTED_MIN_FILES MDF/LDF files exist in that Data
# folder, each with size > 0 bytes (non-empty / fully downloaded)
#
# Each stage is verified by 3 INDEPENDENT Python layers to avoid false
# positives — all 3 layers must agree per stage before that stage counts
# as "passed".
#
# Returns: (passes: bool, details: dict) where details holds per-stage
# and per-layer booleans for diagnostic logging.
# ══════════════════════════════════════════════════════════════════
EXPECTED_MIN_FILES = 15 # MDF + LDF files combined. FARIDPUR has 17, etc.
def _layer1_os_pathlib(depot_name):
"""Layer 1: os.path / listdir based verification (classic stdlib)."""
depot_dir = os.path.join(BASE_DEPOT_DIR, depot_name)
# STAGE 1: depot folder exists
s1 = os.path.isdir(depot_dir)
# STAGE 2: a "Data" folder exists anywhere underneath depot_dir
s2 = False
if s1:
for root, dirs, _files in os.walk(depot_dir):
if "Data" in dirs:
# Confirm it's a directory (defense-in-depth)
candidate = os.path.join(root, "Data")
if os.path.isdir(candidate):
s2 = True
break
# STAGE 3: file count via os.listdir + extension check, size > 0
s3_count = 0
if s2:
# Re-walk to find the same Data folder we confirmed above
for root, dirs, _files in os.walk(depot_dir):
if "Data" in dirs:
data_dir = os.path.join(root, "Data")
try:
for entry in os.listdir(data_dir):
full = os.path.join(data_dir, entry)
if not os.path.isfile(full):
continue
low = entry.lower()
if low.endswith(".mdf") or low.endswith(".ldf"):
try:
if os.path.getsize(full) > 0:
s3_count += 1
except OSError:
pass
except OSError:
pass
break
s3 = s3_count >= EXPECTED_MIN_FILES
return {"s1": s1, "s2": s2, "s3": s3, "s3_count": s3_count}
def _layer2_pathlib_rglob(depot_name):
"""Layer 2: pathlib.Path with rglob (recursive glob)."""
from pathlib import Path
depot_path = Path(BASE_DEPOT_DIR) / depot_name
# STAGE 1
s1 = depot_path.is_dir()
# STAGE 2: rglob for any 'Data' folder case-insensitively
s2 = False
if s1:
for p in depot_path.rglob("Data"):
if p.is_dir():
s2 = True
break
# also accept case-insensitive match
if not s2:
for p in depot_path.rglob("*"):
if p.is_dir() and p.name.lower() == "data":
s2 = True
break
# STAGE 3: use iterdir() on the Data folder
s3_count = 0
if s2:
for p in depot_path.rglob("*"):
if p.is_dir() and p.name.lower() == "data":
try:
for f in p.iterdir():
if not f.is_file():
continue
if f.suffix.lower() in (".mdf", ".ldf"):
try:
if f.stat().st_size > 0:
s3_count += 1
except OSError:
pass
except OSError:
pass
break
s3 = s3_count >= EXPECTED_MIN_FILES
return {"s1": s1, "s2": s2, "s3": s3, "s3_count": s3_count}
def _layer3_scandir_size(depot_name):
"""Layer 3: os.scandir (fast, returns DirEntry objects with stat)
plus third independent walk-based file extension validation.
"""
depot_dir = os.path.join(BASE_DEPOT_DIR, depot_name)
# STAGE 1 — use scandir on parent
s1 = False
try:
base = Path(BASE_DEPOT_DIR) if False else None # noqa
parent = os.path.dirname(depot_dir)
with os.scandir(parent) as it:
for entry in it:
if entry.name == depot_name and entry.is_dir():
s1 = True
break
except (FileNotFoundError, OSError):
s1 = os.path.isdir(depot_dir) # fallback
# STAGE 2 — manual stack-based DFS using os.scandir (no os.walk)
s2 = False
data_dir_found = None
if s1:
try:
stack = [depot_dir]
while stack:
current = stack.pop()
try:
with os.scandir(current) as it:
for entry in it:
if entry.is_dir(follow_symlinks=False):
if entry.name.lower() == "data":
data_dir_found = entry.path
s2 = True
break
stack.append(entry.path)
if s2:
break
except (PermissionError, OSError):
continue
except OSError:
pass
# STAGE 3 — count via scandir on the discovered Data folder
s3_count = 0
if s2 and data_dir_found:
try:
with os.scandir(data_dir_found) as it:
for entry in it:
if not entry.is_file():
continue
low = entry.name.lower()
if low.endswith(".mdf") or low.endswith(".ldf"):
try:
st = entry.stat()
if st.st_size > 0:
s3_count += 1
except OSError:
pass
except OSError:
pass
s3 = s3_count >= EXPECTED_MIN_FILES
return {"s1": s1, "s2": s2, "s3": s3, "s3_count": s3_count}
def verify_local_depot_complete(depot_name, min_files=EXPECTED_MIN_FILES,
verbose=True):
"""Triple-Stage + Triple-Layer verification for a single depot.
Returns (passes: bool, report: dict)
- `passes` is True ONLY if every stage passes in every layer.
- `report` is a dict like:
{
'layer1': {'s1':bool,'s2':bool,'s3':bool,'s3_count':int},
'layer2': {...},
'layer3': {...},
'all_passed': bool
}
The caller can short-circuit Google Drive download when `passes` is True.
"""
l1 = _layer1_os_pathlib(depot_name)
l2 = _layer2_pathlib_rglob(depot_name)
l3 = _layer3_scandir_size(depot_name)
# Each stage must be True across all 3 layers before download can be skipped
stage1_ok = l1["s1"] and l2["s1"] and l3["s1"]
stage2_ok = l1["s2"] and l2["s2"] and l3["s2"]
# Stage 3: also cross-check the count to be reasonably close across layers
counts = [l1["s3_count"], l2["s3_count"], l3["s3_count"]]
max_count = max(counts)
min_count = min(counts)
# Allow at most 1-file discrepancy between layers due to race conditions
count_consistent = (max_count - min_count) <= 1
stage3_ok = (l1["s3"] and l2["s3"] and l3["s3"]
and max_count >= min_files and count_consistent)
all_passed = stage1_ok and stage2_ok and stage3_ok
if verbose:
l1c = l1["s3_count"]; l2c = l2["s3_count"]; l3c = l3["s3_count"]
print(f" [VERIFY] {depot_name}")
print(f" Stage1 (Depot folder): L1={l1['s1']} L2={l2['s1']} L3={l3['s1']} -> {'OK' if stage1_ok else 'FAIL'}")
print(f" Stage2 (Data folder): L1={l1['s2']} L2={l2['s2']} L3={l3['s2']} -> {'OK' if stage2_ok else 'FAIL'}")
print(f" Stage3 ({min_files}+ files): L1={l1c} L2={l2c} L3={l3c} -> {'OK' if stage3_ok else 'FAIL'}")
print(f" >>> {'LOCAL COMPLETE — will skip Google Drive' if all_passed else 'INCOMPLETE — must download'}")
report = {
"layer1": l1,
"layer2": l2,
"layer3": l3,
"stage1_ok": stage1_ok,
"stage2_ok": stage2_ok,
"stage3_ok": stage3_ok,
"all_passed": all_passed,
"counts": counts,
}
return all_passed, report
def all_depots_have_local_mdf(depots_to_process):
"""
Check if EVERY depot in the list already has a local MDF file on disk.
If yes, we can skip Google Drive connection and rclone download entirely,
and work directly with the local files via SQL Server.
This is the SINGLE-FILE (just MDF) check used as a quick precondition.
The deeper triple-stage verification is run per-depot in the main loop
via `verify_local_depot_complete`.
"""
missing = []
for depot_name, _folder_url in depots_to_process:
mdf_path, _ldf_path = get_local_data_paths(depot_name)
if not mdf_path or not os.path.exists(mdf_path):
missing.append(depot_name)
return (len(missing) == 0), missing
def download_depot_files(depot_name, folder_url, drive_service, groq_api_key):
"""Download MDF/LDF files for a single depot from Google Drive.
Per user requirement, this ALWAYS downloads fresh files on every run.
Any existing local files are overwritten by rclone. Files persist on disk
after this function returns (no deletion by this function).
"""
depot_dir = os.path.join(BASE_DEPOT_DIR, depot_name)
data_dir = os.path.join(depot_dir, "Data")
os.makedirs(data_dir, exist_ok=True)
final_mdf_path = os.path.join(data_dir, "ERPonTheNet_Data.MDF")
final_ldf_path = os.path.join(data_dir, "ERPonTheNet_log.LDF")
# Log whether we're going to overwrite an existing cached file
if os.path.exists(final_mdf_path):
print(f" Existing local MDF will be overwritten: {final_mdf_path}")
folder_id_match = re.search(r'folders/([a-zA-Z0-9-_]+)', str(folder_url))
if not folder_id_match:
print(f" Error: Invalid folder URL: {folder_url}")
return None, None
folder_id = folder_id_match.group(1)
items = list_drive_folder_items(drive_service, folder_id)
if not items:
print(f" No files or folders found in drive folder.")
return None, None
print(" Asking Groq LLM to verify and select the correct file...")
decision = get_best_item_from_groq(depot_name, items, groq_api_key)
selected_name = decision.get("selected_item_name")
selected_id = decision.get("selected_item_id")
selected_type = decision.get("selected_item_type")
print(f" Selected '{selected_name}' ({selected_type})")
temp_download_dir = os.path.join(depot_dir, "Temp_Download")
# ── CLEANUP LEFTOVER TEMP DOWNLOAD ON RERUN ──
if os.path.exists(temp_download_dir):
print(f" Cleaning leftover Temp_Download directory: {temp_download_dir}...")
shutil.rmtree(temp_download_dir, ignore_errors=True)
os.makedirs(temp_download_dir, exist_ok=True)
rclone_exe = find_rclone_executable()
mdf_local_path = None
ldf_local_path = None
try:
# Download ZIP file type
if selected_type == 'file' and selected_name.lower().endswith('.zip'):
zip_path = os.path.join(temp_download_dir, selected_name)
remote_file_path = f"{RCLONE_REMOTE_NAME},root_folder_id={folder_id}:{selected_name}"
# Added --progress flag for speed display
cmd = [rclone_exe, "copyto", "--progress", remote_file_path, zip_path]
print(f" Downloading ZIP file...")
subprocess.run(cmd, check=True)
print(f" Extracting ZIP file...")
extract_dir = os.path.join(temp_download_dir, "extracted")
os.makedirs(extract_dir, exist_ok=True)
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(extract_dir)
for root, dirs, files in os.walk(extract_dir):
for file in files:
f_name = file.lower()
if f_name == 'erponthenet_data.mdf':
mdf_local_path = os.path.join(root, file)
elif f_name == 'erponthenet_log.ldf':
ldf_local_path = os.path.join(root, file)
if not mdf_local_path:
for root, dirs, files in os.walk(extract_dir):
for file in files:
if file.lower().endswith('.mdf') and not file.lower().startswith(('master', 'tempdb', 'msdb', 'model')):
mdf_local_path = os.path.join(root, file)
elif file.lower().endswith('.ldf') and not file.lower().startswith(('mastlog', 'templog', 'msdb', 'model')):
ldf_local_path = os.path.join(root, file)
# Download folder type
elif selected_type == 'folder':
print(" Downloading MDF/LDF from folder...")
cmd = [
rclone_exe, "copy",
"--progress",
f"{RCLONE_REMOTE_NAME},root_folder_id={selected_id}:",
temp_download_dir,
"--include", "*erponthenet*",
"--ignore-case"
]
subprocess.run(cmd, check=True)
for root, dirs, files in os.walk(temp_download_dir):
for file in files:
f_name = file.lower()
if f_name == 'erponthenet_data.mdf':
mdf_local_path = os.path.join(root, file)
elif f_name == 'erponthenet_log.ldf':
ldf_local_path = os.path.join(root, file)
# Download single file type (direct MDF/LDF download)
else:
if selected_name.lower().endswith('.mdf'):
temp_mdf_path = os.path.join(temp_download_dir, selected_name)
remote_mdf_path = f"{RCLONE_REMOTE_NAME},root_folder_id={folder_id}:{selected_name}"
# Added --progress flag for speed display
cmd = [rclone_exe, "copyto", "--progress", remote_mdf_path, temp_mdf_path]
print(f" Downloading MDF file...")
subprocess.run(cmd, check=True)
mdf_local_path = temp_mdf_path
for item in items:
if item['name'].lower().endswith('.ldf') and 'erponthenet' in item['name'].lower():
temp_ldf_path = os.path.join(temp_download_dir, item['name'])
remote_ldf_path = f"{RCLONE_REMOTE_NAME},root_folder_id={folder_id}:{item['name']}"
# Added --progress flag for speed display
cmd = [rclone_exe, "copyto", "--progress", remote_ldf_path, temp_ldf_path]
print(f" Downloading LDF file...")
subprocess.run(cmd, check=True)
ldf_local_path = temp_ldf_path
break
if not mdf_local_path or not os.path.exists(mdf_local_path):
print(" Error: MDF file not downloaded successfully.")
return None, None
# Move to final destination
if os.path.exists(final_mdf_path):
os.remove(final_mdf_path)
shutil.move(mdf_local_path, final_mdf_path)
if ldf_local_path and os.path.exists(ldf_local_path):
if os.path.exists(final_ldf_path):
os.remove(final_ldf_path)
shutil.move(ldf_local_path, final_ldf_path)
else:
final_ldf_path = None
shutil.rmtree(temp_download_dir, ignore_errors=True)
return final_mdf_path, final_ldf_path
except Exception as e:
print(f" Error downloading depot {depot_name}: {e}")
shutil.rmtree(temp_download_dir, ignore_errors=True)
return None, None
def check_free_space():