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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
conn.close()
|
2 |
|
3 |
if not workers:
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import sqlite3
|
3 |
+
import json
|
4 |
+
from huggingface_hub import hf_hub_download, upload_file
|
5 |
+
import os
|
6 |
+
from pathlib import Path
|
7 |
+
from reportlab.lib.pagesizes import A4
|
8 |
+
from reportlab.lib.units import cm
|
9 |
+
from reportlab.pdfgen import canvas
|
10 |
+
from reportlab.pdfbase import pdfmetrics
|
11 |
+
from reportlab.pdfbase.ttfonts import TTFont
|
12 |
+
import qrcode
|
13 |
+
import zipfile
|
14 |
+
import io
|
15 |
+
from dotenv import load_dotenv
|
16 |
+
import time
|
17 |
+
|
18 |
+
# อ่าน .env (ถ้ามี)
|
19 |
+
load_dotenv()
|
20 |
+
REPO_ID = os.getenv("REPO_ID", "protae5544/WorkerManagement")
|
21 |
+
ORIGINAL_REPO_ID = os.getenv("ORIGINAL_REPO_ID", None)
|
22 |
+
|
23 |
+
# ตั้งค่าฟอนต์
|
24 |
+
try:
|
25 |
+
pdfmetrics.registerFont(TTFont('THSarabun', 'THSarabunNew.ttf'))
|
26 |
+
pdfmetrics.registerFont(TTFont('THSarabunBold', 'THSarabunNew-Bold.ttf'))
|
27 |
+
except Exception as e:
|
28 |
+
print(f"Warning: Could not load fonts: {e}")
|
29 |
+
|
30 |
+
# ฟังก์ชันแปลงวันที่เป็นภาษาไทย
|
31 |
+
def thai_date_time(timestamp):
|
32 |
+
months = {
|
33 |
+
1: "มกราคม", 2: "กุมภาพันธ์", 3: "มีนาคม", 4: "เมษายน",
|
34 |
+
5: "พฤษภาคม", 6: "มิถุนายน", 7: "กรกฎาคม", 8: "สิงหาคม",
|
35 |
+
9: "กันยายน", 10: "ตุลาคม", 11: "พฤศจิกายน", 12: "ธันวาคม"
|
36 |
+
}
|
37 |
+
dt = time.localtime(timestamp)
|
38 |
+
day = dt.tm_mday
|
39 |
+
month = months[dt.tm_mon]
|
40 |
+
year = dt.tm_year + 543
|
41 |
+
hour = dt.tm_hour
|
42 |
+
minute = dt.tm_min
|
43 |
+
return f"{day:02d} {month} {year} {hour:02d}:{minute:02d} น."
|
44 |
+
|
45 |
+
# เริ่มต้นฐานข้อมูล
|
46 |
+
def init_db():
|
47 |
+
conn = sqlite3.connect("workers.db")
|
48 |
+
c = conn.cursor()
|
49 |
+
c.execute('''CREATE TABLE IF NOT EXISTS workers (
|
50 |
+
request_number TEXT PRIMARY KEY,
|
51 |
+
english_name TEXT,
|
52 |
+
foreign_reference_number TEXT,
|
53 |
+
id_number TEXT,
|
54 |
+
nationality TEXT,
|
55 |
+
receipt_number TEXT,
|
56 |
+
payment_number TEXT,
|
57 |
+
created_at TEXT
|
58 |
+
)''')
|
59 |
+
c.execute('''CREATE TABLE IF NOT EXISTS attachments (
|
60 |
+
request_number TEXT,
|
61 |
+
file_url TEXT,
|
62 |
+
FOREIGN KEY(request_number) REFERENCES workers(request_number)
|
63 |
+
)''')
|
64 |
+
c.execute('''CREATE TABLE IF NOT EXISTS pdfs (
|
65 |
+
request_number TEXT,
|
66 |
+
pdf_url TEXT,
|
67 |
+
FOREIGN KEY(request_number) REFERENCES workers(request_number)
|
68 |
+
)''')
|
69 |
+
conn.commit()
|
70 |
+
conn.close()
|
71 |
+
|
72 |
+
# สำรองฐานข้อมูล
|
73 |
+
def backup_db():
|
74 |
+
try:
|
75 |
+
upload_file(
|
76 |
+
path_or_fileobj="workers.db",
|
77 |
+
path_in_repo="workers.db",
|
78 |
+
repo_id=REPO_ID,
|
79 |
+
repo_type="space"
|
80 |
+
)
|
81 |
+
except Exception as e:
|
82 |
+
print(f"Error backing up database: {e}")
|
83 |
+
|
84 |
+
# ดึงเลขคำขอถัดไป
|
85 |
+
def get_next_request_number():
|
86 |
+
conn = sqlite3.connect("workers.db")
|
87 |
+
c = conn.cursor()
|
88 |
+
c.execute("SELECT request_number FROM workers")
|
89 |
+
request_numbers = c.fetchall()
|
90 |
+
conn.close()
|
91 |
+
|
92 |
+
if not request_numbers:
|
93 |
+
return "WP-68-366-150"
|
94 |
+
|
95 |
+
try:
|
96 |
+
max_num = max([int(num[0].split('-')[-1]) for num in request_numbers if num[0].startswith('WP-68-366-')])
|
97 |
+
return f"WP-68-366-{max_num + 1:03d}"
|
98 |
+
except:
|
99 |
+
return "WP-68-366-150"
|
100 |
+
|
101 |
+
# สร้าง PDF
|
102 |
+
def create_receipt_pdf(request_number, english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number):
|
103 |
+
filename = f"pdfs/receipt_{request_number}.pdf"
|
104 |
+
local_path = f"temp_{request_number}.pdf"
|
105 |
+
|
106 |
+
# สร้างโฟลเดอร์ pdfs ถ้าไม่มี
|
107 |
+
os.makedirs("pdfs", exist_ok=True)
|
108 |
+
|
109 |
+
c = canvas.Canvas(local_path, pagesize=A4)
|
110 |
+
|
111 |
+
# ใช้ฟอนต์ไทยถ้ามี ไม่งั้นใช้ Helvetica
|
112 |
+
try:
|
113 |
+
c.setFont("THSarabunBold", 18)
|
114 |
+
font_available = True
|
115 |
+
except:
|
116 |
+
c.setFont("Helvetica-Bold", 16)
|
117 |
+
font_available = False
|
118 |
+
|
119 |
+
# Header
|
120 |
+
c.drawString(2*cm, 28*cm, "กระทรวงแรงงาน" if font_available else "Ministry of Labour")
|
121 |
+
|
122 |
+
try:
|
123 |
+
c.setFont("THSarabun", 14) if font_available else c.setFont("Helvetica", 12)
|
124 |
+
except:
|
125 |
+
c.setFont("Helvetica", 12)
|
126 |
+
|
127 |
+
c.drawString(2*cm, 27.5*cm, "ใบเสร็จรับเงิน (ต้นฉบับ)" if font_available else "Receipt (Original)")
|
128 |
+
c.drawString(2*cm, 26*cm, f"เลขที่: {receipt_number}" if font_available else f"Number: {receipt_number}")
|
129 |
+
c.drawString(2*cm, 25.5*cm, "ที่ทำการ: สำนักบริหารแรงงานต่างด้าว" if font_available else "Office: Bureau of Foreign Workers Administration")
|
130 |
+
c.drawString(2*cm, 25*cm, "วันที่: 01 เมษายน 2568" if font_available else "Date: 01 April 2025")
|
131 |
+
c.drawString(2*cm, 24.5*cm, f"เลขที่ใบชำระเงิน: {payment_number}" if font_available else f"Payment Number: {payment_number}")
|
132 |
+
c.drawString(2*cm, 24*cm, f"เลขรับคำขอที่: {request_number}" if font_available else f"Request Number: {request_number}")
|
133 |
+
c.drawString(2*cm, 23.5*cm, f"ชื่อผู้ชำระเงิน: {english_name}" if font_available else f"Payer Name: {english_name}")
|
134 |
+
c.drawString(2*cm, 23*cm, f"สัญชาติ: {nationality}" if font_available else f"Nationality: {nationality}")
|
135 |
+
c.drawString(2*cm, 22.5*cm, f"เลขอ้างอิงคนต่างด้าว: {foreign_reference_number}" if font_available else f"Foreign Reference: {foreign_reference_number}")
|
136 |
+
c.drawString(2*cm, 22*cm, f"หมายเลขประจำตัวคนต่างด้าว: {id_number}" if font_available else f"Foreign Worker ID: {id_number}")
|
137 |
+
c.drawString(2*cm, 21.5*cm, "ชื่อนายจ้าง/สถานประกอบการ: บริษัท บาน กง เอ็นจิเนียริ่ง จำกัด" if font_available else "Employer: Ban Kong Engineering Co., Ltd.")
|
138 |
+
c.drawString(2*cm, 21*cm, "เลขประจำตัวนายจ้าง: 0415567000061" if font_available else "Employer ID: 0415567000061")
|
139 |
+
|
140 |
+
# รายการ
|
141 |
+
try:
|
142 |
+
c.setFont("THSarabunBold", 14) if font_available else c.setFont("Helvetica-Bold", 12)
|
143 |
+
except:
|
144 |
+
c.setFont("Helvetica-Bold", 12)
|
145 |
+
|
146 |
+
c.drawString(2*cm, 20*cm, "รายการ" if font_available else "Items")
|
147 |
+
|
148 |
+
try:
|
149 |
+
c.setFont("THSarabun", 12) if font_available else c.setFont("Helvetica", 10)
|
150 |
+
except:
|
151 |
+
c.setFont("Helvetica", 10)
|
152 |
+
|
153 |
+
c.drawString(2*cm, 19.5*cm, "1. ค่าธรรมเนียมในการยื่นคำขอ ฉบับละ 100 บาท: 100.00" if font_available else "1. Application fee 100 Baht each: 100.00")
|
154 |
+
c.drawString(2*cm, 19*cm, "2. ค่าธรรมเนียม: 900.00" if font_available else "2. Service fee: 900.00")
|
155 |
+
c.drawString(2*cm, 18.5*cm, "รวมเป็นเงินทั้งสิ้น (บาท): (หนึ่งพันบาทถ้วน) 1,000.00" if font_available else "Total (Baht): (One thousand Baht) 1,000.00")
|
156 |
+
c.drawString(2*cm, 18*cm, "ได้รับเงินไว้เป็นการถูกต้องแล้ว" if font_available else "Payment received correctly")
|
157 |
+
c.drawString(2*cm, 17.5*cm, "(ลงชื่อ) นางสาวอารีวรรณ โพธิ์นิ่มแดง (ผู้รับเงิน)" if font_available else "(Signature) Ms. Areewan Pho Nim Daeng")
|
158 |
+
c.drawString(2*cm, 17*cm, "ตำแหน่ง: นักวิชาการแรงงานชำนาญการ" if font_available else "Position: Senior Labor Academic")
|
159 |
+
|
160 |
+
# QR Code
|
161 |
+
pdf_url = f"https://huggingface.co/spaces/{REPO_ID}/resolve/main/{filename}"
|
162 |
+
try:
|
163 |
+
qr = qrcode.QRCode(version=1, box_size=10, border=5)
|
164 |
+
qr.add_data(pdf_url)
|
165 |
+
qr.make(fit=True)
|
166 |
+
qr_img = qr.make_image(fill_color="black", back_color="white")
|
167 |
+
qr_img.save("temp_qr.png")
|
168 |
+
c.drawImage("temp_qr.png", 15*cm, 15*cm, width=3*cm, height=3*cm)
|
169 |
+
except Exception as e:
|
170 |
+
print(f"Error creating QR code: {e}")
|
171 |
+
|
172 |
+
# Timestamp
|
173 |
+
try:
|
174 |
+
c.setFont("THSarabun", 8) if font_available else c.setFont("Helvetica", 8)
|
175 |
+
except:
|
176 |
+
c.setFont("Helvetica", 8)
|
177 |
+
|
178 |
+
print_time = thai_date_time(time.time())
|
179 |
+
c.drawString(2*cm, 2*cm, f"พิมพ์เมื่อ: {print_time}" if font_available else f"Printed: {print_time}")
|
180 |
+
|
181 |
+
c.showPage()
|
182 |
+
c.save()
|
183 |
+
|
184 |
+
# อัพโหลด PDF
|
185 |
+
try:
|
186 |
+
upload_file(
|
187 |
+
path_or_fileobj=local_path,
|
188 |
+
path_in_repo=filename,
|
189 |
+
repo_id=REPO_ID,
|
190 |
+
repo_type="space"
|
191 |
+
)
|
192 |
+
print(f"PDF uploaded successfully: {filename}")
|
193 |
+
except Exception as e:
|
194 |
+
print(f"Error uploading PDF: {e}")
|
195 |
+
return None
|
196 |
+
|
197 |
+
# บันทึกข้อมูล PDF ในฐานข้อมูล
|
198 |
+
conn = sqlite3.connect("workers.db")
|
199 |
+
cursor = conn.cursor()
|
200 |
+
cursor.execute("INSERT OR REPLACE INTO pdfs (request_number, pdf_url) VALUES (?, ?)",
|
201 |
+
(request_number, pdf_url))
|
202 |
+
conn.commit()
|
203 |
+
conn.close()
|
204 |
+
|
205 |
+
return pdf_url
|
206 |
+
|
207 |
+
# ตรวจสอบข้อมูล
|
208 |
+
def validate_input(english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number):
|
209 |
+
if not english_name or not english_name.strip():
|
210 |
+
return "กรุณากรอกชื่อภาษาอังกฤษ"
|
211 |
+
if not foreign_reference_number or not foreign_reference_number.strip():
|
212 |
+
return "กรุณากรอกหมายเลขอ้างอิงคนต่างด้าว"
|
213 |
+
if not id_number or not id_number.isdigit() or len(id_number) != 13:
|
214 |
+
return "��มายเลขประจำตัวต้องเป็นตัวเลข 13 หลัก"
|
215 |
+
if not nationality or not nationality.strip():
|
216 |
+
return "กรุณากรอกสัญชาติ"
|
217 |
+
if not receipt_number or not receipt_number.strip():
|
218 |
+
return "กรุณากรอกเลขที่ใบเสร็จ"
|
219 |
+
if not payment_number or not payment_number.strip():
|
220 |
+
return "กรุณากรอกหมายเลขชำระเงิน"
|
221 |
+
return None
|
222 |
+
|
223 |
+
# เพิ่มข้อมูลพนักงาน
|
224 |
+
def add_worker(english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number, attachments):
|
225 |
+
# ตรวจสอบข้อมูล
|
226 |
+
error = validate_input(english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number)
|
227 |
+
if error:
|
228 |
+
return f"❌ {error}"
|
229 |
+
|
230 |
+
try:
|
231 |
+
request_number = get_next_request_number()
|
232 |
+
|
233 |
+
# บันทึกข้อมูลในฐานข้อมูล
|
234 |
+
conn = sqlite3.connect("workers.db")
|
235 |
+
c = conn.cursor()
|
236 |
+
c.execute('''INSERT INTO workers (
|
237 |
+
request_number, english_name, foreign_reference_number, id_number,
|
238 |
+
nationality, receipt_number, payment_number, created_at
|
239 |
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)''', (
|
240 |
+
request_number, english_name, foreign_reference_number, id_number,
|
241 |
+
nationality, receipt_number, payment_number, time.time()
|
242 |
+
))
|
243 |
+
|
244 |
+
# จัดการไฟล์แนบ
|
245 |
+
attachment_urls = []
|
246 |
+
if attachments:
|
247 |
+
for i, file_data in enumerate(attachments):
|
248 |
+
if file_data is not None:
|
249 |
+
try:
|
250 |
+
filename = f"attachments/file_{request_number}_{i}_{os.path.basename(file_data.name)}"
|
251 |
+
upload_file(
|
252 |
+
path_or_fileobj=file_data.name,
|
253 |
+
path_in_repo=filename,
|
254 |
+
repo_id=REPO_ID,
|
255 |
+
repo_type="space"
|
256 |
+
)
|
257 |
+
url = f"https://huggingface.co/spaces/{REPO_ID}/resolve/main/{filename}"
|
258 |
+
c.execute("INSERT INTO attachments (request_number, file_url) VALUES (?, ?)",
|
259 |
+
(request_number, url))
|
260 |
+
attachment_urls.append(url)
|
261 |
+
except Exception as e:
|
262 |
+
print(f"Error uploading attachment: {e}")
|
263 |
+
|
264 |
+
conn.commit()
|
265 |
+
conn.close()
|
266 |
+
|
267 |
+
# สร้าง PDF
|
268 |
+
pdf_url = create_receipt_pdf(request_number, english_name, foreign_reference_number,
|
269 |
+
id_number, nationality, receipt_number, payment_number)
|
270 |
+
|
271 |
+
if pdf_url:
|
272 |
+
# สำรองฐานข้อมูล
|
273 |
+
backup_db()
|
274 |
+
|
275 |
+
result = f"✅ เพิ่มข้อมูลพนักงานสำเร็จ!\n"
|
276 |
+
result += f"📋 เลขคำขอ: {request_number}\n"
|
277 |
+
result += f"📄 PDF: {pdf_url}\n"
|
278 |
+
if attachment_urls:
|
279 |
+
result += f"📎 ไฟล์แนบ: {len(attachment_urls)} ไฟล์"
|
280 |
+
else:
|
281 |
+
result += f"📎 ไฟล์แนบ: ไม่มี"
|
282 |
+
return result
|
283 |
+
else:
|
284 |
+
return f"❌ เกิดข้อผิดพลาดในการสร้าง PDF สำหรับเลขคำขอ: {request_number}"
|
285 |
+
|
286 |
+
except Exception as e:
|
287 |
+
return f"❌ เกิดข้อผิดพลาด: {str(e)}"
|
288 |
+
|
289 |
+
# ดาวน์โหลด PDF ทั้งหมด
|
290 |
+
def download_all_pdfs():
|
291 |
+
try:
|
292 |
+
conn = sqlite3.connect("workers.db")
|
293 |
+
c = conn.cursor()
|
294 |
+
c.execute("SELECT request_number, pdf_url FROM pdfs")
|
295 |
+
pdfs = c.fetchall()
|
296 |
+
conn.close()
|
297 |
+
|
298 |
+
if not pdfs:
|
299 |
+
return "❌ ไม่มี PDF ในระบบ"
|
300 |
+
|
301 |
+
zip_buffer = io.BytesIO()
|
302 |
+
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
|
303 |
+
for request_number, pdf_url in pdfs:
|
304 |
+
try:
|
305 |
+
# ดาวน์โหลด PDF จาก Space
|
306 |
+
local_path = hf_hub_download(
|
307 |
+
repo_id=REPO_ID,
|
308 |
+
filename=f"pdfs/receipt_{request_number}.pdf",
|
309 |
+
repo_type="space"
|
310 |
+
)
|
311 |
+
zip_file.write(local_path, f"receipt_{request_number}.pdf")
|
312 |
+
except Exception as e:
|
313 |
+
print(f"Error downloading PDF {request_number}: {e}")
|
314 |
+
continue
|
315 |
+
|
316 |
+
zip_path = "all_receipts.zip"
|
317 |
+
with open(zip_path, 'wb') as f:
|
318 |
+
f.write(zip_buffer.getvalue())
|
319 |
+
|
320 |
+
# อัพโหลด ZIP file
|
321 |
+
upload_file(
|
322 |
+
path_or_fileobj=zip_path,
|
323 |
+
path_in_repo="downloads/all_receipts.zip",
|
324 |
+
repo_id=REPO_ID,
|
325 |
+
repo_type="space"
|
326 |
+
)
|
327 |
+
|
328 |
+
download_url = f"https://huggingface.co/spaces/{REPO_ID}/resolve/main/downloads/all_receipts.zip"
|
329 |
+
return f"✅ สร้างไฟล์ ZIP สำเร็จ!\n📥 ดาวน์โหลด: {download_url}\n📊 จำนวน PDF: {len(pdfs)} ไฟล์"
|
330 |
+
|
331 |
+
except Exception as e:
|
332 |
+
return f"❌ เกิดข้อผิดพลาด: {str(e)}"
|
333 |
+
|
334 |
+
# ดูรายการพนักงาน
|
335 |
+
def get_worker_list():
|
336 |
+
try:
|
337 |
+
conn = sqlite3.connect("workers.db")
|
338 |
+
c = conn.cursor()
|
339 |
+
c.execute("""SELECT request_number, english_name, nationality, id_number,
|
340 |
+
receipt_number, payment_number FROM workers ORDER BY request_number DESC""")
|
341 |
+
workers = c.fetchall()
|
342 |
conn.close()
|
343 |
|
344 |
if not workers:
|