Repository navigation
Expand file tree
/
Copy pathAutoFill_v2.py
More file actions
471 lines (385 loc) · 18.7 KB
/
Copy pathAutoFill_v2.py
File metadata and controls
471 lines (385 loc) · 18.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
import os
import time
import pandas as pd
import pyautogui
import pyperclip
import keyboard
import threading
import unicodedata
import tkinter as tk
from tkinter import filedialog, messagebox
# ==============================================================================
# CẤU HÌNH
# ==============================================================================
TAB_SAU_MA_KH_MOI = True
# Tên các cột cần đọc trong file A
COT_MA_SO_THUE = "Mã số thuế"
COT_TEN_DON_VI = "Tên đơn vị mua"
COT_DIA_CHI = "Địa chỉ"
# Tên cột chứa mã số thuế trong file B (file danh sách khách hàng đã lưu ACPRO)
COT_VAT_KH_FILE_B = "vat_kh"
# ==============================================================================
# HÀM CHUYỂN CHỮ CÁI EXCEL (A, B, C...) THÀNH SỐ THỨ TỰ (0, 1, 2...)
# ==============================================================================
def letter_to_index(letter):
letter = letter.upper().strip()
num = 0
for c in letter:
num = num * 26 + (ord(c) - ord('A') + 1)
return num - 1
# ==============================================================================
# CÔNG TẮC KHẨN CẤP: GIỮ PHÍM F12 TRONG 1 GIÂY ĐỂ TẮT CHƯƠNG TRÌNH
# ==============================================================================
def monitor_kill_switch():
hold_time = 0
while True:
if keyboard.is_pressed('f12'):
hold_time += 0.1
if hold_time >= 1.0:
print("\n[!] ĐÃ NHẬN LỆNH DỪNG KHẨN CẤP. ĐANG TẮT BOT NGAY LẬP TỨC...")
os._exit(1)
else:
hold_time = 0
time.sleep(0.1)
kill_thread = threading.Thread(target=monitor_kill_switch, daemon=True)
kill_thread.start()
# ==============================================================================
# 1. HÀM CHUYỂN ĐỔI UNICODE -> TCVN3 (.VnTime) CHUẨN CẢ CHỮ HOA VÀ CHỮ THƯỜNG
# ==============================================================================
def unicode_to_tcvn3(text):
if pd.isna(text) or text is None:
return ""
text = str(text)
if text.strip() == "":
return ""
# Chuẩn hóa Unicode vì phần mềm dùng TCVN3
text = unicodedata.normalize('NFC', text)
char_map = {
# Chữ thường
"á": "¸", "à": "µ", "ả": "¶", "ã": "·", "ạ": "¹",
"ă": "¨", "ắ": "¾", "ằ": "»", "ẳ": "¼", "ẵ": "½", "ặ": "Æ",
"â": "©", "ấ": "Ê", "ầ": "Ç", "ẩ": "È", "ẫ": "É", "ậ": "Ë",
"đ": "®",
"é": "Ð", "è": "Ì", "ẻ": "Î", "ẽ": "Ï", "ẹ": "Ñ",
"ê": "ª", "ế": "Õ", "ề": "Ò", "ể": "Ó", "ễ": "Ô", "ệ": "Ö",
"í": "Ý", "ì": "×", "ỉ": "Ø", "ĩ": "Ü", "ị": "Þ",
"ó": "ã", "ò": "ß", "ỏ": "á", "õ": "â", "ọ": "ä",
"ô": "«", "ố": "è", "ồ": "å", "ổ": "æ", "ỗ": "ç", "ộ": "é",
"ơ": "¬", "ớ": "í", "ờ": "ê", "ở": "ë", "ỡ": "ì",
"ư": "", "ứ": "ø", "ừ": "õ", "ử": "ö", "ữ": "÷", "ự": "ù",
"ý": "ý", "ỳ": "ú", "ỷ": "û", "ỹ": "ü", "ỵ": "þ",
"đ": "®",
# Chữ hoa
"Á": "¸", "À": "µ", "Ả": "¶", "Ã": "·", "Ạ": "¹",
"Ă": "¡", "Ắ": "¾", "Ằ": "»", "Ẳ": "¼", "Ẵ": "½", "Ặ": "Æ",
"Â": "¢", "Ấ": "Ê", "Ầ": "Ç", "Ẩ": "È", "Ẫ": "É", "Ậ": "Ë",
"Đ": "§",
"É": "Ð", "È": "Ì", "Ẻ": "Î", "Ẽ": "Ï", "Ẹ": "Ñ",
"Ê": "£", "Ế": "Õ", "Ề": "Ò", "Ể": "Ó", "Ễ": "Ô", "Ệ": "Ö",
"Í": "ý", "Ì": "×", "Ỉ": "Ø", "Ĩ": "Ü", "Ị": "Þ",
"Ó": "ã", "Ò": "ß", "Ỏ": "á", "Õ": "â", "Ọ": "ä",
"Ô": "¤", "Ố": "è", "Ồ": "å", "Ổ": "æ", "Ỗ": "ç", "Ộ": "é",
"Ơ": "¥", "Ớ": "í", "Ờ": "ê", "Ở": "ë", "Ỡ": "ì", "Ợ": "î",
"Ú": "ó", "Ù": "ï", "Ủ": "ñ", "Ũ": "ò", "Ụ": "ô",
"Ư": "¦", "Ứ": "ø", "Ừ": "õ", "Ử": "ö", "Ữ": "÷", "Ự": "ù",
"Ý": "ý", "Ỳ": "ú", "Ỷ": "û", "Ỹ": "ü", "Ỵ": "þ",
}
res = []
for char in text:
res.append(char_map.get(char, char))
return "".join(res)
# ==============================================================================
# 2. HÀM THỰC HIỆN DÁN
# ==============================================================================
def paste_value(value, is_number=False):
if is_number:
val_str = str(int(value)) if pd.notna(value) else "0"
else:
val_str = str(value) if pd.notna(value) else ""
pyperclip.copy(val_str)
pyautogui.hotkey('ctrl', 'v')
time.sleep(0.15)
# ==============================================================================
# 3. HÀM TẠO MÃ KHÁCH HÀNG TỪ MÃ SỐ THUẾ
# ==============================================================================
def generate_customer_code(tax_code):
tax_code = str(tax_code).strip()
if "-" in tax_code:
before, after = tax_code.split("-", 1)
before_digits = "".join(ch for ch in before if ch.isdigit())
after_digits = "".join(ch for ch in after if ch.isdigit())
code = before_digits[-5:] + after_digits[:3]
else:
digits = "".join(ch for ch in tax_code if ch.isdigit())
code = digits[-5:] #lấy 5 chữ số cuối cùng của mã số thuế
return code
# ==============================================================================
# 4. CÁC HÀM ĐỌC / GHI FILE B
# ==============================================================================
def load_customer_db(file_b_path):
if file_b_path.endswith('.csv'):
df_b = pd.read_csv(file_b_path, dtype=str)
else:
df_b = pd.read_excel(file_b_path, dtype=str)
df_b = df_b.fillna("")
return df_b
def save_customer_db(df_b, file_b_path):
if file_b_path.endswith('.csv'):
df_b.to_csv(file_b_path, index=False)
return file_b_path
elif file_b_path.lower().endswith('.xls'):
new_path = file_b_path[:-4] + '.xlsx'
df_b.to_excel(new_path, index=False)
print(f" -> File B là .xls, đã lưu bản cập nhật sang: {new_path}")
return new_path
else:
df_b.to_excel(file_b_path, index=False)
return file_b_path
def find_customer_code(df_b, tax_code):
if COT_VAT_KH_FILE_B not in df_b.columns:
raise ValueError(f"File B không có cột '{COT_VAT_KH_FILE_B}'!")
mask = df_b[COT_VAT_KH_FILE_B].astype(str).str.strip() == str(tax_code).strip()
matches = df_b[mask]
if not matches.empty:
ma_kh_col = df_b.columns[0]
return str(matches.iloc[0][ma_kh_col]).strip()
return None
def add_customer_to_db(df_b, new_code, tax_code):
ma_kh_col = df_b.columns[0]
new_row = {col: "" for col in df_b.columns}
new_row[ma_kh_col] = new_code
new_row[COT_VAT_KH_FILE_B] = tax_code
df_b = pd.concat([df_b, pd.DataFrame([new_row])], ignore_index=True)
return df_b
# ==============================================================================
# 5. KỊCH BẢN AUTO
# ==============================================================================
def run_automation(file_path, file_b_path, start_invoice=None):
idx_so_hd = letter_to_index('D')
if file_path.endswith('.csv'):
df = pd.read_csv(file_path)
else:
df = pd.read_excel(file_path)
df = df.iloc[:-1]
if start_invoice is not None:
df_temp_so = pd.to_numeric(df.iloc[:, idx_so_hd], errors='coerce')
df = df[df_temp_so >= start_invoice]
if df.empty:
raise ValueError(f"Không tìm thấy số hóa đơn nào từ {start_invoice} trở đi tại cột D!")
for cot in (COT_MA_SO_THUE, COT_TEN_DON_VI, COT_DIA_CHI):
if cot not in df.columns:
raise ValueError(f"File A không có cột '{cot}'! Vui lòng kiểm tra lại tên cột.")
df_b = load_customer_db(file_b_path)
print(f"Sẵn sàng nhập {len(df)} dòng dữ liệu từ file.")
print(">>> ĐẶT CHUỘT VÀO VỊ TRÍ BẮT ĐẦU TRÊN ACPRO TRONG VÒNG 5 GIÂY TỚI <<<")
print(">>> ẤN GIỮ PHÍM F12 TRONG 1 GIÂY ĐỂ DỪNG KHẨN CẤP BẤT CỨ LÚC NÀO! <<<")
time.sleep(5)
for index, row in df.iterrows():
so_hd = row.iloc[idx_so_hd]
ngay_hd = row['Ngày hóa đơn']
tien_truoc_thue = row['Tổng tiền trước thuế']
tien_thue = row['Tổng tiền thuế']
ma_so_thue = row[COT_MA_SO_THUE]
ten_don_vi = row[COT_TEN_DON_VI]
dia_chi = row[COT_DIA_CHI]
mst_str = "" if pd.isna(ma_so_thue) else str(ma_so_thue).strip()
print(f"\n--> Đang nhập dòng số {index + 1} - Số hóa đơn (Cột D): {so_hd}")
# 1. tab
pyautogui.press('tab')
time.sleep(0.1)
# 2. Nhập ngày
paste_value(ngay_hd)
# 3. tab x2
pyautogui.press('tab', presses=2, interval=0.1)
time.sleep(0.1)
# 4. Nhập ngày
paste_value(ngay_hd)
# 5. tab x4
pyautogui.press('tab', presses=4, interval=0.1)
time.sleep(0.1)
# 6. Nhập số hóa đơn
paste_value(so_hd, is_number=True)
# 7. tab -> vào ô mã khách hàng
pyautogui.press('tab')
time.sleep(0.1)
# --------------------------------------------------------------------
# XỬ LÝ Ô MÃ KHÁCH HÀNG THEO MÃ SỐ THUẾ
# --------------------------------------------------------------------
if mst_str == "":
print(" -> Không có mã số thuế, nhập 'kl'.")
paste_value("kl") #change here
pyautogui.press('enter', presses=5, interval=0.1)
time.sleep(0.1)
else:
existing_code = find_customer_code(df_b, mst_str)
if existing_code:
print(f" -> Mã số thuế {mst_str} đã có trong file B, dùng mã khách hàng: {existing_code}")
paste_value(existing_code)
pyautogui.press('enter', presses=5, interval=0.1)
time.sleep(0.1)
else:
print(f" -> Mã số thuế {mst_str} CHƯA có, tạo khách hàng mới...")
# 1. bấm enter
pyautogui.press('enter')
time.sleep(0.1)
# 2. bấm F4
keyboard.send('f4')
time.sleep(0.3)
# 3. nhập mã khách hàng mới + cập nhật file B
ma_kh_moi = generate_customer_code(mst_str)
paste_value(ma_kh_moi)
df_b = add_customer_to_db(df_b, ma_kh_moi, mst_str)
file_b_path = save_customer_db(df_b, file_b_path)
print(f" -> Đã tạo mã khách hàng mới: {ma_kh_moi}")
if TAB_SAU_MA_KH_MOI:
pyautogui.press('tab')
time.sleep(0.1)
# 4. Nhập cột Tên đơn vị mua
paste_value(unicode_to_tcvn3(ten_don_vi))
# 5. enter 2 lần
pyautogui.press('enter', presses=2, interval=0.1)
time.sleep(0.1)
# 6. Nhập cột địa chỉ (Đã chuyển sang TCVN3 chuẩn)
paste_value(unicode_to_tcvn3(dia_chi))
# 7. enter 6 lần
pyautogui.press('enter', presses=6, interval=0.1)
time.sleep(0.1)
# 8. Nhập mã số thuế
paste_value(mst_str)
# 9. di chuột đến (242, 518) và bấm nút Lưu
pyautogui.click(x=242, y=518)#box
time.sleep(0.3)
# 10. bấm escape để đóng bảng tạo khách hàng
pyautogui.press('escape')
time.sleep(0.4)
# 11. Nhập lại mã khách hàng mới vừa tạo
#click lại vô ô mã khách hàng
pyautogui.click(x=866, y=366)#box
time.sleep(0.2)
paste_value(ma_kh_moi)
pyautogui.press('enter')
time.sleep(0.1)
# 12. enter 4 lần để chuyển xuống phần chi tiết tiền
pyautogui.press('enter', presses=4, interval=0.1)
time.sleep(0.1)
# --------------------------------------------------------------------
# NHẬP CHI TIẾT TIỀN HÀNG
# --------------------------------------------------------------------
# 9. Nhập Thuê Phòng
paste_value(unicode_to_tcvn3("Thuê Phòng"))
# 10. tab rồi nhập số tiền trước thuế
pyautogui.press('tab')
time.sleep(0.1)
paste_value(tien_truoc_thue, is_number=True)
# 11. enter tab
pyautogui.press('enter')
paste_value("131") #Change here
pyautogui.press('tab')
time.sleep(0.1)
# 12. Nhập "5113"
paste_value("5113")
# 13. tab rồi nhập 10 rồi tab x3
pyautogui.press('tab')
time.sleep(0.1)
paste_value("10")
pyautogui.press('tab', presses=3, interval=0.1)
time.sleep(0.1)
# 14. nhập tiền thuế
paste_value(tien_thue, is_number=True)
# 15. enter
pyautogui.press('enter')
time.sleep(0.1)
# 16. Lưu và tạo mới
x_nut = 976 #box
y_nut = 790
print(" -> Click nút Lưu/Tạo mới (Lần 1)...")
pyautogui.click(x=x_nut, y=y_nut)
time.sleep(2.0)
print(" -> Click nút Lưu/Tạo mới (Lần 2)...")
pyautogui.click(x=x_nut, y=y_nut)
time.sleep(1)
print(f"Xong hóa đơn số {so_hd}!")
print("\n==================================")
print("BOT ĐÃ HOÀN THÀNH TOÀN BỘ CÔNG VIỆC!")
print("==================================")
# ==============================================================================
# 6. CÁC HÀM XỬ LÝ GIAO DIỆN ĐỒ HỌA (GUI)
# ==============================================================================
def chon_file_a():
path_da_chon = filedialog.askopenfilename(
title="Chọn file Excel dữ liệu đầu vào (File A)",
filetypes=[("Excel Files", "*.xlsx *.xls"), ("CSV Files", "*.csv"), ("All Files", "*.*")]
)
if path_da_chon:
o_nhap_lieu.delete(0, tk.END)
o_nhap_lieu.insert(0, path_da_chon)
def chon_file_b():
path_da_chon = filedialog.askopenfilename(
title="Chọn file danh sách mã khách hàng (File B)",
filetypes=[("Excel Files", "*.xlsx *.xls"), ("CSV Files", "*.csv"), ("All Files", "*.*")]
)
if path_da_chon:
o_file_b.delete(0, tk.END)
o_file_b.insert(0, path_da_chon)
def bat_dau_chay_bot():
duong_dan_file = o_nhap_lieu.get()
duong_dan_file_b = o_file_b.get()
chuoi_so_hd_bat_dau = o_so_hd_bat_dau.get().strip()
if not duong_dan_file or not os.path.exists(duong_dan_file):
messagebox.showerror("Lỗi dữ liệu", "Vui lòng chọn đường dẫn file Excel A hợp lệ trước khi chạy!")
return
if not duong_dan_file_b or not os.path.exists(duong_dan_file_b):
messagebox.showerror("Lỗi dữ liệu", "Vui lòng chọn đường dẫn file B (danh sách khách hàng) hợp lệ trước khi chạy!")
return
start_invoice = None
if chuoi_so_hd_bat_dau:
try:
start_invoice = int(chuoi_so_hd_bat_dau)
except ValueError:
messagebox.showerror("Lỗi nhập liệu", "Số hóa đơn bắt đầu phải là một số nguyên!")
return
cua_so.withdraw()
try:
run_automation(duong_dan_file, duong_dan_file_b, start_invoice)
messagebox.showinfo("Thành công", "Bot đã hoàn thành toàn bộ công việc nhập liệu!")
except Exception as e:
messagebox.showerror("Lỗi hệ thống", f"Có lỗi xảy ra trong quá trình chạy:\n{e}")
finally:
cua_so.deiconify()
def thoat_toan_bo_chuong_trinh():
print("\n[!] Đang đóng ứng dụng và giải phóng tiến trình chạy ngầm...")
os._exit(0)
# ==============================================================================
# KHỞI TẠO CỬA SỔ GIAO DIỆN CHÍNH
# ==============================================================================
if __name__ == "__main__":
cua_so = tk.Tk()
cua_so.title("PHẦN MỀM NHẬP LIỆU TỰ ĐỘNG - ACPRO")
cua_so.geometry("560x300")
cua_so.resizable(False, False)
lbl_huong_dan = tk.Label(cua_so, text="CHỌN FILE DỮ LIỆU ĐẦU VÀO (FILE A)", font=("Arial", 10, "bold"), fg="#1e3d59")
lbl_huong_dan.pack(pady=(10, 5))
khung_file = tk.Frame(cua_so)
khung_file.pack(padx=20, fill="x")
o_nhap_lieu = tk.Entry(khung_file, font=("Arial", 10), width=42)
o_nhap_lieu.pack(side="left", padx=(0, 5), ipady=4)
btn_browse = tk.Button(khung_file, text="Chọn file...", font=("Arial", 9, "bold"), bg="#e8e1d5", command=chon_file_a)
btn_browse.pack(side="left", padx=5, ipady=1)
lbl_huong_dan_b = tk.Label(cua_so, text="CHỌN FILE DANH SÁCH MÃ KHÁCH HÀNG (FILE B)", font=("Arial", 10, "bold"), fg="#1e3d59")
lbl_huong_dan_b.pack(pady=(10, 5))
khung_file_b = tk.Frame(cua_so)
khung_file_b.pack(padx=20, fill="x")
o_file_b = tk.Entry(khung_file_b, font=("Arial", 10), width=42)
o_file_b.pack(side="left", padx=(0, 5), ipady=4)
btn_browse_b = tk.Button(khung_file_b, text="Chọn file...", font=("Arial", 9, "bold"), bg="#e8e1d5", command=chon_file_b)
btn_browse_b.pack(side="left", padx=5, ipady=1)
khung_cau_hinh = tk.Frame(cua_so)
khung_cau_hinh.pack(padx=20, pady=15, fill="x")
lbl_so_hd = tk.Label(khung_cau_hinh, text="Bắt đầu từ số hóa đơn (để trống nếu chạy từ đầu):", font=("Arial", 10))
lbl_so_hd.pack(side="left", padx=(0, 10))
o_so_hd_bat_dau = tk.Entry(khung_cau_hinh, font=("Arial", 10, "bold"), width=12, fg="blue", justify="center")
o_so_hd_bat_dau.pack(side="left", ipady=3)
btn_start = tk.Button(cua_so, text="BẮT ĐẦU CHẠY BOT", font=("Arial", 11, "bold"), bg="#17b978", fg="white", height=2, command=bat_dau_chay_bot)
btn_start.pack(fill="x", padx=20, pady=(5, 10))
cua_so.protocol("WM_DELETE_WINDOW", thoat_toan_bo_chuong_trinh)
cua_so.mainloop()