You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

1291 lines
50 KiB

  1. #!/usr/bin/env python3
  2. """
  3. Bag1 – GUI to show FPSMS job orders by plan date.
  4. Uses the public API GET /py/job-orders (no login required).
  5. UI tuned for aged users: larger font, Traditional Chinese labels, prev/next date.
  6. Run: python Bag1.py
  7. """
  8. import json
  9. import os
  10. import select
  11. import socket
  12. import sys
  13. import tempfile
  14. import threading
  15. import time
  16. import tkinter as tk
  17. from datetime import date, datetime, timedelta
  18. from tkinter import messagebox, ttk
  19. from typing import Callable, Optional
  20. import requests
  21. try:
  22. import serial
  23. except ImportError:
  24. serial = None # type: ignore
  25. try:
  26. import win32print # type: ignore[import]
  27. import win32ui # type: ignore[import]
  28. import win32con # type: ignore[import]
  29. import win32gui # type: ignore[import]
  30. except ImportError:
  31. win32print = None # type: ignore[assignment]
  32. win32ui = None # type: ignore[assignment]
  33. win32con = None # type: ignore[assignment]
  34. win32gui = None # type: ignore[assignment]
  35. try:
  36. from PIL import Image, ImageDraw, ImageFont
  37. import qrcode
  38. _HAS_PIL_QR = True
  39. except ImportError:
  40. Image = None # type: ignore[assignment]
  41. ImageDraw = None # type: ignore[assignment]
  42. ImageFont = None # type: ignore[assignment]
  43. qrcode = None # type: ignore[assignment]
  44. _HAS_PIL_QR = False
  45. DEFAULT_BASE_URL = os.environ.get("FPSMS_BASE_URL", "http://localhost:8090/api")
  46. # When run as PyInstaller exe, save settings next to the exe; otherwise next to script
  47. if getattr(sys, "frozen", False):
  48. _SETTINGS_DIR = os.path.dirname(sys.executable)
  49. else:
  50. _SETTINGS_DIR = os.path.dirname(os.path.abspath(__file__))
  51. SETTINGS_FILE = os.path.join(_SETTINGS_DIR, "bag1_settings.json")
  52. LASER_COUNTER_FILE = os.path.join(_SETTINGS_DIR, "last_batch_count.txt")
  53. DEFAULT_SETTINGS = {
  54. "api_ip": "localhost",
  55. "api_port": "8090",
  56. "dabag_ip": "",
  57. "dabag_port": "3008",
  58. "laser_ip": "192.168.17.10",
  59. "laser_port": "45678",
  60. # For 標簽機 on Windows, this is the Windows printer name, e.g. "TSC TTP-246M Pro"
  61. "label_com": "TSC TTP-246M Pro",
  62. }
  63. def load_settings() -> dict:
  64. """Load settings from JSON file; return defaults if missing or invalid."""
  65. try:
  66. if os.path.isfile(SETTINGS_FILE):
  67. with open(SETTINGS_FILE, "r", encoding="utf-8") as f:
  68. data = json.load(f)
  69. return {**DEFAULT_SETTINGS, **data}
  70. except Exception:
  71. pass
  72. return dict(DEFAULT_SETTINGS)
  73. def save_settings(settings: dict) -> None:
  74. """Save settings to JSON file."""
  75. with open(SETTINGS_FILE, "w", encoding="utf-8") as f:
  76. json.dump(settings, f, indent=2, ensure_ascii=False)
  77. def build_base_url(api_ip: str, api_port: str) -> str:
  78. ip = (api_ip or "localhost").strip()
  79. port = (api_port or "8090").strip()
  80. return f"http://{ip}:{port}/api"
  81. def try_printer_connection(printer_name: str, sett: dict) -> bool:
  82. """Try to connect to the selected printer (TCP IP:port or COM). Returns True if OK."""
  83. if printer_name == "打袋機 DataFlex":
  84. ip = (sett.get("dabag_ip") or "").strip()
  85. port_str = (sett.get("dabag_port") or "9100").strip()
  86. if not ip:
  87. return False
  88. try:
  89. port = int(port_str)
  90. s = socket.create_connection((ip, port), timeout=PRINTER_SOCKET_TIMEOUT)
  91. s.close()
  92. return True
  93. except (socket.error, ValueError, OSError):
  94. return False
  95. if printer_name == "激光機":
  96. ip = (sett.get("laser_ip") or "").strip()
  97. port_str = (sett.get("laser_port") or "45678").strip()
  98. if not ip:
  99. return False
  100. try:
  101. port = int(port_str)
  102. s = socket.create_connection((ip, port), timeout=PRINTER_SOCKET_TIMEOUT)
  103. s.close()
  104. return True
  105. except (socket.error, ValueError, OSError):
  106. return False
  107. if printer_name == "標簽機":
  108. target = (sett.get("label_com") or "").strip()
  109. if not target:
  110. return False
  111. # On Windows, allow using a Windows printer name (e.g. "TSC TTP-246M Pro")
  112. # as an alternative to a COM port. If it doesn't look like a COM port,
  113. # try opening it via the Windows print spooler.
  114. if os.name == "nt" and not target.upper().startswith("COM"):
  115. if win32print is None:
  116. return False
  117. try:
  118. handle = win32print.OpenPrinter(target)
  119. win32print.ClosePrinter(handle)
  120. return True
  121. except Exception:
  122. return False
  123. # Fallback: treat as serial COM port (original behaviour)
  124. if serial is None:
  125. return False
  126. try:
  127. ser = serial.Serial(target, timeout=1)
  128. ser.close()
  129. return True
  130. except (serial.SerialException, OSError):
  131. return False
  132. return False
  133. # Larger font for aged users (point size)
  134. FONT_SIZE = 16
  135. FONT_SIZE_BUTTONS = 15
  136. FONT_SIZE_QTY = 12 # smaller for 數量 under batch no.
  137. FONT_SIZE_ITEM = 20 # item code and item name (larger for readability)
  138. FONT_FAMILY = "Microsoft JhengHei UI" # Traditional Chinese; fallback to TkDefaultFont
  139. # Column widths: item code own column; item name at least double, wraps in its column
  140. ITEM_CODE_WRAP = 140 # item code column width (long codes wrap under code only)
  141. ITEM_NAME_WRAP = 640 # item name column (double width), wraps under name only
  142. # Light blue theme (softer than pure grey)
  143. BG_TOP = "#E8F4FC"
  144. BG_LIST = "#D4E8F7"
  145. BG_ROOT = "#E1F0FF"
  146. BG_ROW = "#C5E1F5"
  147. BG_ROW_SELECTED = "#6BB5FF" # highlighted when selected (for printing)
  148. # Connection status bar
  149. BG_STATUS_ERROR = "#FFCCCB" # red background when disconnected
  150. FG_STATUS_ERROR = "#B22222" # red text
  151. BG_STATUS_OK = "#90EE90" # light green when connected
  152. FG_STATUS_OK = "#006400" # green text
  153. RETRY_MS = 30 * 1000 # 30 seconds reconnect
  154. REFRESH_MS = 60 * 1000 # 60 seconds refresh when connected
  155. PRINTER_CHECK_MS = 60 * 1000 # 1 minute when printer OK
  156. PRINTER_RETRY_MS = 30 * 1000 # 30 seconds when printer failed
  157. PRINTER_SOCKET_TIMEOUT = 3
  158. DATAFLEX_SEND_TIMEOUT = 10 # seconds when sending ZPL to DataFlex
  159. def _zpl_escape(s: str) -> str:
  160. """Escape text for ZPL ^FD...^FS (backslash and caret)."""
  161. return s.replace("\\", "\\\\").replace("^", "\\^")
  162. def generate_zpl_dataflex(
  163. batch_no: str,
  164. item_code: str,
  165. item_name: str,
  166. item_id: Optional[int] = None,
  167. stock_in_line_id: Optional[int] = None,
  168. lot_no: Optional[str] = None,
  169. font_regular: str = "E:STXihei.ttf",
  170. font_bold: str = "E:STXihei.ttf",
  171. ) -> str:
  172. """
  173. Generate ZPL for DataFlex label (53 mm media, 90° rotated).
  174. QR contains {"itemId": xxx, "stockInLineId": xxx} when both present; else QA,{batch_no}.
  175. Label shows lotNo when present, else batch_no.
  176. """
  177. desc = _zpl_escape((item_name or "—").strip())
  178. code = _zpl_escape((item_code or "—").strip())
  179. label_line2 = (lot_no or batch_no or "—").strip()
  180. batch = _zpl_escape(label_line2)
  181. if item_id is not None and stock_in_line_id is not None:
  182. qr_data = _zpl_escape(json.dumps({"itemId": item_id, "stockInLineId": stock_in_line_id}))
  183. else:
  184. qr_data = f"QA,{batch_no}"
  185. return f"""^XA
  186. ^PW420
  187. ^LL780
  188. ^PO N
  189. ^CI28
  190. ^FO70,70
  191. ^A@R,60,60,{font_regular}^FD{desc}^FS
  192. ^FO220,70
  193. ^A@R,50,50,{font_bold}^FD{code}^FS
  194. ^FO310,70
  195. ^A@R,45,45,{font_bold}^FD批次: {batch}^FS
  196. ^FO150,420
  197. ^BQN,2,6^FD{qr_data}^FS
  198. ^XZ"""
  199. def generate_zpl_label_small(
  200. batch_no: str,
  201. item_code: str,
  202. item_name: str,
  203. item_id: Optional[int] = None,
  204. stock_in_line_id: Optional[int] = None,
  205. lot_no: Optional[str] = None,
  206. font: str = "MingLiUHKSCS",
  207. ) -> str:
  208. """
  209. ZPL for 標簽機. Row 1: item name. Row 2: QR left | item code + lot no (or batch) right.
  210. QR contains {"itemId": xxx, "stockInLineId": xxx} when both present; else batch_no.
  211. Unicode (^CI28); font set for Big-5 (e.g. MingLiUHKSCS).
  212. """
  213. desc = _zpl_escape((item_name or "—").strip())
  214. code = _zpl_escape((item_code or "—").strip())
  215. label_line2 = (lot_no or batch_no or "—").strip()
  216. label_line2_esc = _zpl_escape(label_line2)
  217. if item_id is not None and stock_in_line_id is not None:
  218. qr_data = _zpl_escape(json.dumps({"itemId": item_id, "stockInLineId": stock_in_line_id}))
  219. else:
  220. qr_data = f"QA,{batch_no}"
  221. return f"""^XA
  222. ^CI28
  223. ^PW500
  224. ^LL500
  225. ^FO10,15
  226. ^FB480,3,0,L,0
  227. ^A@N,38,38,{font}^FD{desc}^FS
  228. ^FO10,110
  229. ^BQN,2,6^FD{qr_data}^FS
  230. ^FO150,110
  231. ^A@N,48,48,{font}^FD{code}^FS
  232. ^FO150,175
  233. ^A@N,40,40,{font}^FD{label_line2_esc}^FS
  234. ^XZ"""
  235. # Label image size (pixels) for 標簽機 image printing; words drawn bigger for readability
  236. LABEL_IMAGE_W = 520
  237. LABEL_IMAGE_H = 520
  238. LABEL_PADDING = 20
  239. LABEL_FONT_NAME_SIZE = 38 # item name (bigger)
  240. LABEL_FONT_CODE_SIZE = 44 # item code (bigger)
  241. LABEL_FONT_BATCH_SIZE = 30 # batch/lot line
  242. LABEL_QR_SIZE = 140 # QR module size in pixels
  243. def _get_chinese_font(size: int) -> Optional["ImageFont.FreeTypeFont"]:
  244. """Return a Chinese-capable font for PIL, or None to use default."""
  245. if ImageFont is None:
  246. return None
  247. # Prefer Traditional Chinese fonts on Windows
  248. for name in ("Microsoft JhengHei UI", "Microsoft JhengHei", "MingLiU", "SimHei", "Microsoft YaHei", "SimSun"):
  249. try:
  250. return ImageFont.truetype(name, size)
  251. except (OSError, IOError):
  252. continue
  253. try:
  254. return ImageFont.load_default()
  255. except Exception:
  256. return None
  257. def render_label_to_image(
  258. batch_no: str,
  259. item_code: str,
  260. item_name: str,
  261. item_id: Optional[int] = None,
  262. stock_in_line_id: Optional[int] = None,
  263. lot_no: Optional[str] = None,
  264. ) -> "Image.Image":
  265. """
  266. Render 標簽機 label as a PIL Image (white bg, black text + QR).
  267. Use this image for printing so Chinese displays correctly; words are drawn bigger.
  268. Requires Pillow and qrcode. Raises RuntimeError if not available.
  269. """
  270. if not _HAS_PIL_QR or Image is None or qrcode is None:
  271. raise RuntimeError("Pillow and qrcode are required for image labels. Run: pip install Pillow qrcode[pil]")
  272. img = Image.new("RGB", (LABEL_IMAGE_W, LABEL_IMAGE_H), "white")
  273. draw = ImageDraw.Draw(img)
  274. # QR payload (same as ZPL)
  275. if item_id is not None and stock_in_line_id is not None:
  276. qr_data = json.dumps({"itemId": item_id, "stockInLineId": stock_in_line_id})
  277. else:
  278. qr_data = f"QA,{batch_no}"
  279. # Draw QR top-left area
  280. qr = qrcode.QRCode(box_size=4, border=2)
  281. qr.add_data(qr_data)
  282. qr.make(fit=True)
  283. qr_img = qr.make_image(fill_color="black", back_color="white")
  284. _resample = getattr(Image, "Resampling", Image).NEAREST
  285. qr_img = qr_img.resize((LABEL_QR_SIZE, LABEL_QR_SIZE), _resample)
  286. img.paste(qr_img, (LABEL_PADDING, LABEL_PADDING))
  287. # Fonts (bigger for readability)
  288. font_name = _get_chinese_font(LABEL_FONT_NAME_SIZE)
  289. font_code = _get_chinese_font(LABEL_FONT_CODE_SIZE)
  290. font_batch = _get_chinese_font(LABEL_FONT_BATCH_SIZE)
  291. x_right = LABEL_PADDING + LABEL_QR_SIZE + LABEL_PADDING
  292. y_line = LABEL_PADDING
  293. # Line 1: item name (wrap within remaining width)
  294. name_str = (item_name or "—").strip()
  295. max_name_w = LABEL_IMAGE_W - x_right - LABEL_PADDING
  296. if font_name:
  297. # Wrap by text width (Pillow 8+ textbbox) or by char count
  298. def _wrap_text(text: str, font, max_width: int) -> list:
  299. if hasattr(draw, "textbbox"):
  300. words = list(text)
  301. lines, line = [], []
  302. for c in words:
  303. line.append(c)
  304. bbox = draw.textbbox((0, 0), "".join(line), font=font)
  305. if bbox[2] - bbox[0] > max_width and len(line) > 1:
  306. lines.append("".join(line[:-1]))
  307. line = [line[-1]]
  308. if line:
  309. lines.append("".join(line))
  310. return lines
  311. # Fallback: ~12 chars per line for Chinese
  312. chunk = 12
  313. return [text[i : i + chunk] for i in range(0, len(text), chunk)]
  314. lines = _wrap_text(name_str, font_name, max_name_w)
  315. for i, ln in enumerate(lines):
  316. draw.text((x_right, y_line + i * (LABEL_FONT_NAME_SIZE + 4)), ln, font=font_name, fill="black")
  317. y_line += len(lines) * (LABEL_FONT_NAME_SIZE + 4) + 8
  318. else:
  319. draw.text((x_right, y_line), name_str[:30], fill="black")
  320. y_line += LABEL_FONT_NAME_SIZE + 12
  321. # Item code (bigger)
  322. code_str = (item_code or "—").strip()
  323. if font_code:
  324. draw.text((x_right, y_line), code_str, font=font_code, fill="black")
  325. else:
  326. draw.text((x_right, y_line), code_str, fill="black")
  327. y_line += LABEL_FONT_CODE_SIZE + 6
  328. # Batch/lot line
  329. batch_str = (lot_no or batch_no or "—").strip()
  330. if font_batch:
  331. draw.text((x_right, y_line), batch_str, font=font_batch, fill="black")
  332. else:
  333. draw.text((x_right, y_line), batch_str, fill="black")
  334. return img
  335. def send_image_to_label_printer(printer_name: str, pil_image: "Image.Image") -> None:
  336. """
  337. Send a PIL Image to 標簽機 via Windows GDI (so Chinese and graphics print correctly).
  338. Only supported when target is a Windows printer name (not COM port). Requires pywin32.
  339. """
  340. dest = (printer_name or "").strip()
  341. if not dest:
  342. raise ValueError("Label printer destination is empty.")
  343. if os.name != "nt" or dest.upper().startswith("COM"):
  344. raise RuntimeError("Image printing is only supported for a Windows printer name (e.g. TSC TTP-246M Pro).")
  345. if win32print is None or win32ui is None or win32con is None or win32gui is None:
  346. raise RuntimeError("pywin32 is required. Run: pip install pywin32")
  347. # Draw image to printer DC via temp BMP (GDI uses BMP)
  348. with tempfile.NamedTemporaryFile(suffix=".bmp", delete=False) as f:
  349. tmp_bmp = f.name
  350. try:
  351. pil_image.save(tmp_bmp, "BMP")
  352. hbm = win32gui.LoadImage(
  353. 0, tmp_bmp, win32con.IMAGE_BITMAP, 0, 0,
  354. win32con.LR_LOADFROMFILE | win32con.LR_CREATEDIBSECTION,
  355. )
  356. if hbm == 0:
  357. raise RuntimeError("Failed to load label image as bitmap.")
  358. dc = win32ui.CreateDC()
  359. dc.CreatePrinterDC(dest)
  360. dc.StartDoc("FPSMS Label")
  361. dc.StartPage()
  362. try:
  363. mem_dc = win32ui.CreateDCFromHandle(win32gui.CreateCompatibleDC(dc.GetSafeHdc()))
  364. # PyCBitmap.FromHandle works across pywin32 versions
  365. bmp = getattr(win32ui, "CreateBitmapFromHandle", lambda h: win32ui.PyCBitmap.FromHandle(h))(hbm)
  366. mem_dc.SelectObject(bmp)
  367. bmp_w = pil_image.width
  368. bmp_h = pil_image.height
  369. dc.StretchBlt((0, 0), (bmp_w, bmp_h), mem_dc, (0, 0), (bmp_w, bmp_h), win32con.SRCCOPY)
  370. finally:
  371. win32gui.DeleteObject(hbm)
  372. dc.EndPage()
  373. dc.EndDoc()
  374. finally:
  375. try:
  376. os.unlink(tmp_bmp)
  377. except OSError:
  378. pass
  379. def send_zpl_to_dataflex(ip: str, port: int, zpl: str) -> None:
  380. """Send ZPL to DataFlex printer via TCP. Raises on connection/send error."""
  381. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  382. sock.settimeout(DATAFLEX_SEND_TIMEOUT)
  383. try:
  384. sock.connect((ip, port))
  385. sock.sendall(zpl.encode("utf-8"))
  386. finally:
  387. sock.close()
  388. def send_zpl_to_label_printer(target: str, zpl: str) -> None:
  389. """
  390. Send ZPL to 標簽機.
  391. On Windows, if target is not a COM port (e.g. "TSC TTP-246M Pro"),
  392. send raw ZPL to the named Windows printer via the spooler.
  393. Otherwise, treat target as a serial COM port (original behaviour).
  394. """
  395. dest = (target or "").strip()
  396. if not dest:
  397. raise ValueError("Label printer destination is empty.")
  398. # Unicode (^CI28); send UTF-8 to 標簽機
  399. raw_bytes = zpl.encode("utf-8")
  400. # Windows printer name path (USB printer installed as normal printer)
  401. if os.name == "nt" and not dest.upper().startswith("COM"):
  402. if win32print is None:
  403. raise RuntimeError("pywin32 not installed. Run: pip install pywin32")
  404. handle = win32print.OpenPrinter(dest)
  405. try:
  406. job = win32print.StartDocPrinter(handle, 1, ("FPSMS Label", None, "RAW"))
  407. win32print.StartPagePrinter(handle)
  408. win32print.WritePrinter(handle, raw_bytes)
  409. win32print.EndPagePrinter(handle)
  410. win32print.EndDocPrinter(handle)
  411. finally:
  412. win32print.ClosePrinter(handle)
  413. return
  414. # Fallback: serial COM port
  415. if serial is None:
  416. raise RuntimeError("pyserial not installed. Run: pip install pyserial")
  417. ser = serial.Serial(dest, timeout=5)
  418. try:
  419. ser.write(raw_bytes)
  420. finally:
  421. ser.close()
  422. def load_laser_last_count() -> tuple[int, Optional[str]]:
  423. """Load last batch count and date from laser counter file. Returns (count, date_str)."""
  424. if not os.path.exists(LASER_COUNTER_FILE):
  425. return 0, None
  426. try:
  427. with open(LASER_COUNTER_FILE, "r", encoding="utf-8") as f:
  428. lines = f.read().strip().splitlines()
  429. if len(lines) >= 2:
  430. return int(lines[1].strip()), lines[0].strip()
  431. except Exception:
  432. pass
  433. return 0, None
  434. def save_laser_last_count(date_str: str, count: int) -> None:
  435. """Save laser batch count and date to file."""
  436. try:
  437. with open(LASER_COUNTER_FILE, "w", encoding="utf-8") as f:
  438. f.write(f"{date_str}\n{count}")
  439. except Exception:
  440. pass
  441. LASER_PUSH_INTERVAL = 2 # seconds between pushes (like sample script)
  442. def laser_push_loop(
  443. ip: str,
  444. port: int,
  445. stop_event: threading.Event,
  446. root: tk.Tk,
  447. on_error: Callable[[str], None],
  448. ) -> None:
  449. """
  450. Run in a background thread: persistent connection to EZCAD, push B{yymmdd}{count:03d};;
  451. every LASER_PUSH_INTERVAL seconds. Resets count each new day. Uses counter file.
  452. """
  453. conn = None
  454. push_count, last_saved_date = load_laser_last_count()
  455. while not stop_event.is_set():
  456. try:
  457. if conn is None:
  458. conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  459. conn.settimeout(0.4)
  460. conn.connect((ip, port))
  461. now = datetime.now()
  462. today_str = now.strftime("%y%m%d")
  463. if last_saved_date != today_str:
  464. push_count = 1
  465. last_saved_date = today_str
  466. batch = f"B{today_str}{push_count:03d}"
  467. reply = f"{batch};;"
  468. conn.sendall(reply.encode("utf-8"))
  469. save_laser_last_count(today_str, push_count)
  470. rlist, _, _ = select.select([conn], [], [], 0.4)
  471. if rlist:
  472. data = conn.recv(4096)
  473. if not data:
  474. conn.close()
  475. conn = None
  476. push_count += 1
  477. for _ in range(int(LASER_PUSH_INTERVAL * 2)):
  478. if stop_event.is_set():
  479. break
  480. time.sleep(0.5)
  481. except socket.timeout:
  482. pass
  483. except Exception as e:
  484. if conn:
  485. try:
  486. conn.close()
  487. except Exception:
  488. pass
  489. conn = None
  490. try:
  491. root.after(0, lambda msg=str(e): on_error(msg))
  492. except Exception:
  493. pass
  494. for _ in range(6):
  495. if stop_event.is_set():
  496. break
  497. time.sleep(0.5)
  498. if conn:
  499. try:
  500. conn.close()
  501. except Exception:
  502. pass
  503. def send_job_to_laser(
  504. conn_ref: list,
  505. ip: str,
  506. port: int,
  507. item_id: Optional[int],
  508. stock_in_line_id: Optional[int],
  509. item_code: str,
  510. item_name: str,
  511. ) -> tuple[bool, str]:
  512. """
  513. Send to laser. Standard format: {"itemId": xxx, "stockInLineId": xxx}.
  514. conn_ref: [socket or None] - reused across calls; closed only when switching printer.
  515. When both item_id and stock_in_line_id present, sends JSON; else fallback: 0;item_code;item_name;;
  516. Returns (success, message).
  517. """
  518. if item_id is not None and stock_in_line_id is not None:
  519. reply = json.dumps({"itemId": item_id, "stockInLineId": stock_in_line_id})
  520. else:
  521. code_str = (item_code or "").strip().replace(";", ",")
  522. name_str = (item_name or "").strip().replace(";", ",")
  523. reply = f"0;{code_str};{name_str};;"
  524. conn = conn_ref[0]
  525. try:
  526. if conn is None:
  527. conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  528. conn.settimeout(3.0)
  529. conn.connect((ip, port))
  530. conn_ref[0] = conn
  531. conn.settimeout(3.0)
  532. conn.sendall(reply.encode("utf-8"))
  533. conn.settimeout(0.5)
  534. try:
  535. data = conn.recv(4096)
  536. if data:
  537. ack = data.decode("utf-8", errors="ignore").strip().lower()
  538. if "receive" in ack and "invalid" not in ack:
  539. return True, f"已送出激光機:{reply}(已確認)"
  540. except socket.timeout:
  541. pass
  542. return True, f"已送出激光機:{reply}"
  543. except (ConnectionRefusedError, socket.timeout, OSError) as e:
  544. if conn_ref[0] is not None:
  545. try:
  546. conn_ref[0].close()
  547. except Exception:
  548. pass
  549. conn_ref[0] = None
  550. if isinstance(e, ConnectionRefusedError):
  551. return False, f"無法連線至 {ip}:{port},請確認激光機已開機且 IP 正確。"
  552. if isinstance(e, socket.timeout):
  553. return False, f"連線逾時 ({ip}:{port}),請檢查網路與連接埠。"
  554. return False, f"激光機送出失敗:{e}"
  555. def send_job_to_laser_with_retry(
  556. conn_ref: list,
  557. ip: str,
  558. port: int,
  559. item_id: Optional[int],
  560. stock_in_line_id: Optional[int],
  561. item_code: str,
  562. item_name: str,
  563. ) -> tuple[bool, str]:
  564. """Send job to laser; on failure, retry once. Returns (success, message)."""
  565. ok, msg = send_job_to_laser(conn_ref, ip, port, item_id, stock_in_line_id, item_code, item_name)
  566. if ok:
  567. return True, msg
  568. ok2, msg2 = send_job_to_laser(conn_ref, ip, port, item_id, stock_in_line_id, item_code, item_name)
  569. return ok2, msg2
  570. def format_qty(val) -> str:
  571. """Format quantity: integer without .0, with thousand separator."""
  572. if val is None:
  573. return "—"
  574. try:
  575. n = float(val)
  576. if n == int(n):
  577. return f"{int(n):,}"
  578. return f"{n:,.2f}".rstrip("0").rstrip(".")
  579. except (TypeError, ValueError):
  580. return str(val)
  581. def batch_no(year: int, job_order_id: int) -> str:
  582. """Batch no.: B + 4-digit year + jobOrderId zero-padded to 6 digits."""
  583. return f"B{year}{job_order_id:06d}"
  584. def get_font(size: int = FONT_SIZE, bold: bool = False) -> tuple:
  585. try:
  586. return (FONT_FAMILY, size, "bold" if bold else "normal")
  587. except Exception:
  588. return ("TkDefaultFont", size, "bold" if bold else "normal")
  589. def fetch_job_orders(base_url: str, plan_start: date) -> list:
  590. """Call GET /py/job-orders and return the JSON list."""
  591. url = f"{base_url.rstrip('/')}/py/job-orders"
  592. params = {"planStart": plan_start.isoformat()}
  593. resp = requests.get(url, params=params, timeout=30)
  594. resp.raise_for_status()
  595. return resp.json()
  596. def set_row_highlight(row_frame: tk.Frame, selected: bool) -> None:
  597. """Set row and all its child widgets to selected or normal background."""
  598. bg = BG_ROW_SELECTED if selected else BG_ROW
  599. row_frame.configure(bg=bg)
  600. for w in row_frame.winfo_children():
  601. if isinstance(w, (tk.Frame, tk.Label)):
  602. w.configure(bg=bg)
  603. for c in w.winfo_children():
  604. if isinstance(c, tk.Label):
  605. c.configure(bg=bg)
  606. def on_job_order_click(jo: dict, batch: str) -> None:
  607. """Show message and highlight row (keeps printing to selected printer)."""
  608. item_code = jo.get("itemCode") or "—"
  609. item_name = jo.get("itemName") or "—"
  610. messagebox.showinfo(
  611. "工單",
  612. f'已點選:批次 {batch}\n品號 {item_code} {item_name}',
  613. )
  614. def ask_laser_count(parent: tk.Tk) -> Optional[int]:
  615. """
  616. When printer is 激光機, ask how many times to send (like DataFlex).
  617. Returns count (>= 1), or -1 for continuous (C), or None if cancelled.
  618. """
  619. result: list = [None]
  620. count_ref = [0]
  621. continuous_ref = [False]
  622. win = tk.Toplevel(parent)
  623. win.title("激光機送出數量")
  624. win.geometry("420x200")
  625. win.transient(parent)
  626. win.grab_set()
  627. win.configure(bg=BG_TOP)
  628. ttk.Label(win, text="送出多少次?", font=get_font(FONT_SIZE)).pack(pady=(12, 4))
  629. count_lbl = tk.Label(win, text="數量: 0", font=get_font(FONT_SIZE), bg=BG_TOP)
  630. count_lbl.pack(pady=4)
  631. def update_display():
  632. if continuous_ref[0]:
  633. count_lbl.configure(text="數量: 連續 (C)")
  634. else:
  635. count_lbl.configure(text=f"數量: {count_ref[0]}")
  636. def add(n: int):
  637. continuous_ref[0] = False
  638. count_ref[0] = max(0, count_ref[0] + n)
  639. update_display()
  640. def set_continuous():
  641. continuous_ref[0] = True
  642. update_display()
  643. def confirm():
  644. if continuous_ref[0]:
  645. result[0] = -1
  646. elif count_ref[0] < 1:
  647. messagebox.showwarning("激光機", "請先按 +50、+10、+5 或 +1 選擇數量。", parent=win)
  648. return
  649. else:
  650. result[0] = count_ref[0]
  651. win.destroy()
  652. btn_row = tk.Frame(win, bg=BG_TOP)
  653. btn_row.pack(pady=8)
  654. for label, value in [("+50", 50), ("+10", 10), ("+5", 5), ("+1", 1)]:
  655. def make_add(v: int):
  656. return lambda: add(v)
  657. ttk.Button(btn_row, text=label, command=make_add(value), width=8).pack(side=tk.LEFT, padx=4)
  658. ttk.Button(btn_row, text="C", command=set_continuous, width=8).pack(side=tk.LEFT, padx=4)
  659. ttk.Button(win, text="確認送出", command=confirm, width=14).pack(pady=12)
  660. win.protocol("WM_DELETE_WINDOW", win.destroy)
  661. win.wait_window()
  662. return result[0]
  663. def ask_label_count(parent: tk.Tk) -> Optional[str]:
  664. """
  665. When printer is 標簽機, ask how many labels to print.
  666. Returns "1", "10", "50", "100", "C" (continuous), or None if cancelled.
  667. """
  668. result = [None] # mutable so inner callback can set it
  669. win = tk.Toplevel(parent)
  670. win.title("標簽列印數量")
  671. win.geometry("360x180")
  672. win.transient(parent)
  673. win.grab_set()
  674. win.configure(bg=BG_TOP)
  675. ttk.Label(win, text="列印多少張標簽?", font=get_font(FONT_SIZE)).pack(pady=(16, 12))
  676. btn_frame = tk.Frame(win, bg=BG_TOP)
  677. btn_frame.pack(pady=8)
  678. for label, value in [("1", "1"), ("10", "10"), ("50", "50"), ("100", "100"), ("連續 (C)", "C")]:
  679. def make_cmd(v):
  680. def cmd():
  681. result[0] = v
  682. win.destroy()
  683. return cmd
  684. ttk.Button(btn_frame, text=label, command=make_cmd(value), width=10).pack(side=tk.LEFT, padx=4)
  685. win.protocol("WM_DELETE_WINDOW", win.destroy)
  686. win.wait_window()
  687. return result[0]
  688. def main() -> None:
  689. settings = load_settings()
  690. base_url_ref = [build_base_url(settings["api_ip"], settings["api_port"])]
  691. root = tk.Tk()
  692. root.title("FP-MTMS Bag v1.1 打袋機")
  693. root.geometry("1120x960")
  694. root.minsize(480, 360)
  695. root.configure(bg=BG_ROOT)
  696. # Style: larger font for aged users; light blue theme
  697. style = ttk.Style()
  698. try:
  699. style.configure(".", font=get_font(FONT_SIZE), background=BG_TOP)
  700. style.configure("TButton", font=get_font(FONT_SIZE_BUTTONS), background=BG_TOP)
  701. style.configure("TLabel", font=get_font(FONT_SIZE), background=BG_TOP)
  702. style.configure("TEntry", font=get_font(FONT_SIZE))
  703. style.configure("TFrame", background=BG_TOP)
  704. except tk.TclError:
  705. pass
  706. # Status bar at top: connection state (no popup on error)
  707. status_frame = tk.Frame(root, bg=BG_STATUS_ERROR, padx=12, pady=6)
  708. status_frame.pack(fill=tk.X)
  709. status_lbl = tk.Label(
  710. status_frame,
  711. text="連接不到服務器",
  712. font=get_font(FONT_SIZE_BUTTONS),
  713. bg=BG_STATUS_ERROR,
  714. fg=FG_STATUS_ERROR,
  715. anchor=tk.CENTER,
  716. )
  717. status_lbl.pack(fill=tk.X)
  718. def set_status_ok():
  719. status_frame.configure(bg=BG_STATUS_OK)
  720. status_lbl.configure(text="連接正常", bg=BG_STATUS_OK, fg=FG_STATUS_OK)
  721. def set_status_error():
  722. status_frame.configure(bg=BG_STATUS_ERROR)
  723. status_lbl.configure(text="連接不到服務器", bg=BG_STATUS_ERROR, fg=FG_STATUS_ERROR)
  724. def set_status_message(msg: str, is_error: bool = False) -> None:
  725. """Show a message on the status bar."""
  726. if is_error:
  727. status_frame.configure(bg=BG_STATUS_ERROR)
  728. status_lbl.configure(text=msg, bg=BG_STATUS_ERROR, fg=FG_STATUS_ERROR)
  729. else:
  730. status_frame.configure(bg=BG_STATUS_OK)
  731. status_lbl.configure(text=msg, bg=BG_STATUS_OK, fg=FG_STATUS_OK)
  732. # Laser: keep connection open for repeated sends; close when switching away
  733. laser_conn_ref: list = [None]
  734. laser_thread_ref: list = [None]
  735. laser_stop_ref: list = [None]
  736. # Top: left [前一天] [date] [後一天] | right [printer dropdown]
  737. top = tk.Frame(root, padx=12, pady=12, bg=BG_TOP)
  738. top.pack(fill=tk.X)
  739. date_var = tk.StringVar(value=date.today().isoformat())
  740. printer_options = ["打袋機 DataFlex", "標簽機", "激光機"]
  741. printer_var = tk.StringVar(value=printer_options[0])
  742. def go_prev_day() -> None:
  743. try:
  744. d = date.fromisoformat(date_var.get().strip())
  745. date_var.set((d - timedelta(days=1)).isoformat())
  746. load_job_orders(from_user_date_change=True)
  747. except ValueError:
  748. date_var.set(date.today().isoformat())
  749. load_job_orders(from_user_date_change=True)
  750. def go_next_day() -> None:
  751. try:
  752. d = date.fromisoformat(date_var.get().strip())
  753. date_var.set((d + timedelta(days=1)).isoformat())
  754. load_job_orders(from_user_date_change=True)
  755. except ValueError:
  756. date_var.set(date.today().isoformat())
  757. load_job_orders(from_user_date_change=True)
  758. # 前一天 (previous day) with left arrow icon
  759. btn_prev = ttk.Button(top, text="◀ 前一天", command=go_prev_day)
  760. btn_prev.pack(side=tk.LEFT, padx=(0, 8))
  761. # Date field (no "日期:" label); shorter width
  762. date_entry = tk.Entry(
  763. top,
  764. textvariable=date_var,
  765. font=get_font(FONT_SIZE),
  766. width=10,
  767. bg="white",
  768. )
  769. date_entry.pack(side=tk.LEFT, padx=(0, 8), ipady=4)
  770. # 後一天 (next day) with right arrow icon
  771. btn_next = ttk.Button(top, text="後一天 ▶", command=go_next_day)
  772. btn_next.pack(side=tk.LEFT, padx=(0, 8))
  773. # Top right: Setup button + printer selection
  774. right_frame = tk.Frame(top, bg=BG_TOP)
  775. right_frame.pack(side=tk.RIGHT)
  776. ttk.Button(right_frame, text="設定", command=lambda: open_setup_window(root, settings, base_url_ref)).pack(
  777. side=tk.LEFT, padx=(0, 12)
  778. )
  779. # 列印機 label: green when printer connected, red when not (checked periodically)
  780. printer_status_lbl = tk.Label(
  781. right_frame,
  782. text="列印機:",
  783. font=get_font(FONT_SIZE),
  784. bg=BG_STATUS_ERROR,
  785. fg="black",
  786. padx=6,
  787. pady=2,
  788. )
  789. printer_status_lbl.pack(side=tk.LEFT, padx=(0, 4))
  790. printer_combo = ttk.Combobox(
  791. right_frame,
  792. textvariable=printer_var,
  793. values=printer_options,
  794. state="readonly",
  795. width=14,
  796. font=get_font(FONT_SIZE),
  797. )
  798. printer_combo.pack(side=tk.LEFT)
  799. printer_after_ref = [None]
  800. def set_printer_status_ok():
  801. printer_status_lbl.configure(bg=BG_STATUS_OK, fg=FG_STATUS_OK)
  802. def set_printer_status_error():
  803. printer_status_lbl.configure(bg=BG_STATUS_ERROR, fg=FG_STATUS_ERROR)
  804. def check_printer() -> None:
  805. if printer_after_ref[0] is not None:
  806. root.after_cancel(printer_after_ref[0])
  807. printer_after_ref[0] = None
  808. ok = try_printer_connection(printer_var.get(), settings)
  809. if ok:
  810. set_printer_status_ok()
  811. printer_after_ref[0] = root.after(PRINTER_CHECK_MS, check_printer)
  812. else:
  813. set_printer_status_error()
  814. printer_after_ref[0] = root.after(PRINTER_RETRY_MS, check_printer)
  815. def on_printer_selection_changed(*args) -> None:
  816. check_printer()
  817. if printer_var.get() != "激光機":
  818. if laser_stop_ref[0] is not None:
  819. laser_stop_ref[0].set()
  820. if laser_conn_ref[0] is not None:
  821. try:
  822. laser_conn_ref[0].close()
  823. except Exception:
  824. pass
  825. laser_conn_ref[0] = None
  826. printer_var.trace_add("write", on_printer_selection_changed)
  827. def open_setup_window(parent_win: tk.Tk, sett: dict, base_url_ref_list: list) -> None:
  828. """Modal setup: API IP/port, 打袋機/激光機 IP+port, 標簽機 COM port."""
  829. d = tk.Toplevel(parent_win)
  830. d.title("設定")
  831. d.geometry("440x520")
  832. d.transient(parent_win)
  833. d.grab_set()
  834. d.configure(bg=BG_TOP)
  835. f = tk.Frame(d, padx=16, pady=16, bg=BG_TOP)
  836. f.pack(fill=tk.BOTH, expand=True)
  837. grid_row = [0] # use list so inner function can update
  838. def _ensure_dot_in_entry(entry: tk.Entry) -> None:
  839. """Allow typing dot (.) in Entry when IME or layout blocks it (e.g. 192.168.17.27)."""
  840. def on_key(event):
  841. if event.keysym in ("period", "decimal"):
  842. pos = entry.index(tk.INSERT)
  843. entry.insert(tk.INSERT, ".")
  844. return "break"
  845. entry.bind("<KeyPress>", on_key)
  846. def add_section(label_text: str, key_ip: str | None, key_port: str | None, key_single: str | None):
  847. out = []
  848. ttk.Label(f, text=label_text, font=get_font(FONT_SIZE_BUTTONS)).grid(
  849. row=grid_row[0], column=0, columnspan=2, sticky=tk.W, pady=(8, 2)
  850. )
  851. grid_row[0] += 1
  852. if key_single:
  853. ttk.Label(
  854. f,
  855. text="列印機名稱 (Windows):",
  856. ).grid(
  857. row=grid_row[0],
  858. column=0,
  859. sticky=tk.W,
  860. pady=2,
  861. )
  862. var = tk.StringVar(value=sett.get(key_single, ""))
  863. e = tk.Entry(f, textvariable=var, width=22, font=get_font(FONT_SIZE), bg="white")
  864. e.grid(row=grid_row[0], column=1, sticky=tk.W, pady=2)
  865. _ensure_dot_in_entry(e)
  866. grid_row[0] += 1
  867. return [(key_single, var)]
  868. if key_ip:
  869. ttk.Label(f, text="IP:").grid(row=grid_row[0], column=0, sticky=tk.W, pady=2)
  870. var_ip = tk.StringVar(value=sett.get(key_ip, ""))
  871. e_ip = tk.Entry(f, textvariable=var_ip, width=22, font=get_font(FONT_SIZE), bg="white")
  872. e_ip.grid(row=grid_row[0], column=1, sticky=tk.W, pady=2)
  873. _ensure_dot_in_entry(e_ip)
  874. grid_row[0] += 1
  875. out.append((key_ip, var_ip))
  876. if key_port:
  877. ttk.Label(f, text="Port:").grid(row=grid_row[0], column=0, sticky=tk.W, pady=2)
  878. var_port = tk.StringVar(value=sett.get(key_port, ""))
  879. e_port = tk.Entry(f, textvariable=var_port, width=12, font=get_font(FONT_SIZE), bg="white")
  880. e_port.grid(row=grid_row[0], column=1, sticky=tk.W, pady=2)
  881. _ensure_dot_in_entry(e_port)
  882. grid_row[0] += 1
  883. out.append((key_port, var_port))
  884. return out
  885. all_vars = []
  886. all_vars.extend(add_section("API 伺服器", "api_ip", "api_port", None))
  887. all_vars.extend(add_section("打袋機 DataFlex", "dabag_ip", "dabag_port", None))
  888. all_vars.extend(add_section("激光機", "laser_ip", "laser_port", None))
  889. all_vars.extend(add_section("標簽機 (USB)", None, None, "label_com"))
  890. def on_save():
  891. for key, var in all_vars:
  892. sett[key] = var.get().strip()
  893. save_settings(sett)
  894. base_url_ref_list[0] = build_base_url(sett["api_ip"], sett["api_port"])
  895. d.destroy()
  896. btn_f = tk.Frame(d, bg=BG_TOP)
  897. btn_f.pack(pady=12)
  898. ttk.Button(btn_f, text="儲存", command=on_save).pack(side=tk.LEFT, padx=4)
  899. ttk.Button(btn_f, text="取消", command=d.destroy).pack(side=tk.LEFT, padx=4)
  900. d.wait_window()
  901. job_orders_frame = tk.Frame(root, bg=BG_LIST)
  902. job_orders_frame.pack(fill=tk.BOTH, expand=True, padx=12, pady=12)
  903. # Scrollable area for buttons
  904. canvas = tk.Canvas(job_orders_frame, highlightthickness=0, bg=BG_LIST)
  905. scrollbar = ttk.Scrollbar(job_orders_frame, orient=tk.VERTICAL, command=canvas.yview)
  906. inner = tk.Frame(canvas, bg=BG_LIST)
  907. win_id = canvas.create_window((0, 0), window=inner, anchor=tk.NW)
  908. canvas.configure(yscrollcommand=scrollbar.set)
  909. def _on_inner_configure(event):
  910. canvas.configure(scrollregion=canvas.bbox("all"))
  911. def _on_canvas_configure(event):
  912. canvas.itemconfig(win_id, width=event.width)
  913. inner.bind("<Configure>", _on_inner_configure)
  914. canvas.bind("<Configure>", _on_canvas_configure)
  915. # Mouse wheel: make scroll work when hovering over canvas or the list (inner/buttons)
  916. def _on_mousewheel(event):
  917. if getattr(event, "delta", None) is not None:
  918. canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
  919. elif event.num == 5:
  920. canvas.yview_scroll(1, "units")
  921. elif event.num == 4:
  922. canvas.yview_scroll(-1, "units")
  923. canvas.bind("<MouseWheel>", _on_mousewheel)
  924. inner.bind("<MouseWheel>", _on_mousewheel)
  925. canvas.bind("<Button-4>", _on_mousewheel)
  926. canvas.bind("<Button-5>", _on_mousewheel)
  927. inner.bind("<Button-4>", _on_mousewheel)
  928. inner.bind("<Button-5>", _on_mousewheel)
  929. scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
  930. canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
  931. # Track which row is highlighted (selected for printing) and which job id
  932. selected_row_holder = [None] # [tk.Frame | None]
  933. selected_jo_id_ref = [None] # [int | None] job order id for selection preservation
  934. last_data_ref = [None] # [list | None] last successful fetch for current date
  935. after_id_ref = [None] # [str | None] root.after id to cancel retry/refresh
  936. def _data_equal(a: Optional[list], b: Optional[list]) -> bool:
  937. if a is None or b is None:
  938. return a is b
  939. if len(a) != len(b):
  940. return False
  941. ids_a = [x.get("id") for x in a]
  942. ids_b = [x.get("id") for x in b]
  943. return ids_a == ids_b
  944. def _build_list_from_data(data: list, plan_start: date, preserve_selection: bool) -> None:
  945. selected_row_holder[0] = None
  946. year = plan_start.year
  947. selected_id = selected_jo_id_ref[0] if preserve_selection else None
  948. found_row = None
  949. for jo in data:
  950. jo_id = jo.get("id")
  951. lot_no_val = jo.get("lotNo")
  952. batch = (lot_no_val or "—").strip() if lot_no_val else "—"
  953. item_code = jo.get("itemCode") or "—"
  954. item_name = jo.get("itemName") or "—"
  955. req_qty = jo.get("reqQty")
  956. qty_str = format_qty(req_qty)
  957. # Three columns: batch+數量 | item code (own column) | item name (≥2× width, wraps in column)
  958. row = tk.Frame(inner, bg=BG_ROW, relief=tk.RAISED, bd=2, cursor="hand2", padx=12, pady=10)
  959. row.pack(fill=tk.X, pady=4)
  960. left = tk.Frame(row, bg=BG_ROW)
  961. left.pack(side=tk.LEFT, anchor=tk.NW)
  962. batch_lbl = tk.Label(
  963. left,
  964. text=batch,
  965. font=get_font(FONT_SIZE_BUTTONS),
  966. bg=BG_ROW,
  967. fg="black",
  968. )
  969. batch_lbl.pack(anchor=tk.W)
  970. qty_lbl = None
  971. if qty_str != "—":
  972. qty_lbl = tk.Label(
  973. left,
  974. text=f"數量:{qty_str}",
  975. font=get_font(FONT_SIZE_QTY),
  976. bg=BG_ROW,
  977. fg="black",
  978. )
  979. qty_lbl.pack(anchor=tk.W)
  980. # Column 2: item code only, bigger font, wraps in its own column
  981. code_lbl = tk.Label(
  982. row,
  983. text=item_code,
  984. font=get_font(FONT_SIZE_ITEM),
  985. bg=BG_ROW,
  986. fg="black",
  987. wraplength=ITEM_CODE_WRAP,
  988. justify=tk.LEFT,
  989. anchor=tk.NW,
  990. )
  991. code_lbl.pack(side=tk.LEFT, anchor=tk.NW, padx=(12, 8))
  992. # Column 3: item name only, same bigger font, at least double width, wraps under its own column
  993. name_lbl = tk.Label(
  994. row,
  995. text=item_name or "—",
  996. font=get_font(FONT_SIZE_ITEM),
  997. bg=BG_ROW,
  998. fg="black",
  999. wraplength=ITEM_NAME_WRAP,
  1000. justify=tk.LEFT,
  1001. anchor=tk.NW,
  1002. )
  1003. name_lbl.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, anchor=tk.NW)
  1004. def _on_click(e, j=jo, b=batch, r=row):
  1005. if selected_row_holder[0] is not None:
  1006. set_row_highlight(selected_row_holder[0], False)
  1007. set_row_highlight(r, True)
  1008. selected_row_holder[0] = r
  1009. selected_jo_id_ref[0] = j.get("id")
  1010. if printer_var.get() == "打袋機 DataFlex":
  1011. ip = (settings.get("dabag_ip") or "").strip()
  1012. port_str = (settings.get("dabag_port") or "3008").strip()
  1013. try:
  1014. port = int(port_str)
  1015. except ValueError:
  1016. port = 3008
  1017. if not ip:
  1018. messagebox.showerror("打袋機", "請在設定中填寫打袋機 DataFlex 的 IP。")
  1019. else:
  1020. item_code = j.get("itemCode") or "—"
  1021. item_name = j.get("itemName") or "—"
  1022. item_id = j.get("itemId")
  1023. stock_in_line_id = j.get("stockInLineId")
  1024. lot_no = j.get("lotNo")
  1025. zpl = generate_zpl_dataflex(
  1026. b, item_code, item_name,
  1027. item_id=item_id, stock_in_line_id=stock_in_line_id,
  1028. lot_no=lot_no,
  1029. )
  1030. try:
  1031. send_zpl_to_dataflex(ip, port, zpl)
  1032. messagebox.showinfo("打袋機", f"已送出列印:批次 {b}")
  1033. except ConnectionRefusedError:
  1034. messagebox.showerror("打袋機", f"無法連線至 {ip}:{port},請確認印表機已開機且 IP 正確。")
  1035. except socket.timeout:
  1036. messagebox.showerror("打袋機", f"連線逾時 ({ip}:{port}),請檢查網路與連接埠。")
  1037. except OSError as err:
  1038. messagebox.showerror("打袋機", f"列印失敗:{err}")
  1039. elif printer_var.get() == "標簽機":
  1040. com = (settings.get("label_com") or "").strip()
  1041. if not com:
  1042. messagebox.showerror("標簽機", "請在設定中填寫標簽機名稱 (例如:TSC TTP-246M Pro)。")
  1043. else:
  1044. count = ask_label_count(root)
  1045. if count is not None:
  1046. item_code = j.get("itemCode") or "—"
  1047. item_name = j.get("itemName") or "—"
  1048. item_id = j.get("itemId")
  1049. stock_in_line_id = j.get("stockInLineId")
  1050. lot_no = j.get("lotNo")
  1051. n = 100 if count == "C" else int(count)
  1052. try:
  1053. # Prefer image printing so Chinese displays correctly; words are bigger
  1054. if _HAS_PIL_QR and os.name == "nt" and not com.upper().startswith("COM"):
  1055. label_img = render_label_to_image(
  1056. b, item_code, item_name,
  1057. item_id=item_id, stock_in_line_id=stock_in_line_id,
  1058. lot_no=lot_no,
  1059. )
  1060. for i in range(n):
  1061. send_image_to_label_printer(com, label_img)
  1062. if i < n - 1:
  1063. time.sleep(0.5)
  1064. else:
  1065. zpl = generate_zpl_label_small(
  1066. b, item_code, item_name,
  1067. item_id=item_id, stock_in_line_id=stock_in_line_id,
  1068. lot_no=lot_no,
  1069. )
  1070. for i in range(n):
  1071. send_zpl_to_label_printer(com, zpl)
  1072. if i < n - 1:
  1073. time.sleep(0.5)
  1074. msg = f"已送出列印:{n} 張標簽" if count != "C" else f"已送出列印:{n} 張標簽 (連續)"
  1075. messagebox.showinfo("標簽機", msg)
  1076. except Exception as err:
  1077. messagebox.showerror("標簽機", f"列印失敗:{err}")
  1078. elif printer_var.get() == "激光機":
  1079. ip = (settings.get("laser_ip") or "").strip()
  1080. port_str = (settings.get("laser_port") or "45678").strip()
  1081. try:
  1082. port = int(port_str)
  1083. except ValueError:
  1084. port = 45678
  1085. if not ip:
  1086. set_status_message("請在設定中填寫激光機的 IP。", is_error=True)
  1087. else:
  1088. count = ask_laser_count(root)
  1089. if count is not None:
  1090. item_id = j.get("itemId")
  1091. stock_in_line_id = j.get("stockInLineId")
  1092. item_code_val = j.get("itemCode") or ""
  1093. item_name_val = j.get("itemName") or ""
  1094. n = 100 if count == -1 else count
  1095. sent = 0
  1096. for i in range(n):
  1097. ok, msg = send_job_to_laser_with_retry(
  1098. laser_conn_ref, ip, port,
  1099. item_id, stock_in_line_id,
  1100. item_code_val, item_name_val,
  1101. )
  1102. if ok:
  1103. sent += 1
  1104. else:
  1105. set_status_message(f"已送出 {sent} 次,第 {sent + 1} 次失敗:{msg}", is_error=True)
  1106. break
  1107. if i < n - 1:
  1108. time.sleep(0.2)
  1109. if sent == n:
  1110. set_status_message(f"已送出激光機:{sent} 次", is_error=False)
  1111. on_job_order_click(j, b)
  1112. for w in (row, left, batch_lbl, code_lbl, name_lbl):
  1113. w.bind("<Button-1>", _on_click)
  1114. w.bind("<MouseWheel>", _on_mousewheel)
  1115. w.bind("<Button-4>", _on_mousewheel)
  1116. w.bind("<Button-5>", _on_mousewheel)
  1117. if qty_lbl is not None:
  1118. qty_lbl.bind("<Button-1>", _on_click)
  1119. qty_lbl.bind("<MouseWheel>", _on_mousewheel)
  1120. qty_lbl.bind("<Button-4>", _on_mousewheel)
  1121. qty_lbl.bind("<Button-5>", _on_mousewheel)
  1122. if preserve_selection and selected_id is not None and jo.get("id") == selected_id:
  1123. found_row = row
  1124. if found_row is not None:
  1125. set_row_highlight(found_row, True)
  1126. selected_row_holder[0] = found_row
  1127. def load_job_orders(from_user_date_change: bool = False) -> None:
  1128. if after_id_ref[0] is not None:
  1129. root.after_cancel(after_id_ref[0])
  1130. after_id_ref[0] = None
  1131. date_str = date_var.get().strip()
  1132. try:
  1133. plan_start = date.fromisoformat(date_str)
  1134. except ValueError:
  1135. messagebox.showerror("日期錯誤", f"請使用 yyyy-MM-dd 格式。目前:{date_str}")
  1136. return
  1137. if from_user_date_change:
  1138. selected_row_holder[0] = None
  1139. selected_jo_id_ref[0] = None
  1140. try:
  1141. data = fetch_job_orders(base_url_ref[0], plan_start)
  1142. except requests.RequestException:
  1143. set_status_error()
  1144. after_id_ref[0] = root.after(RETRY_MS, lambda: load_job_orders(from_user_date_change=False))
  1145. return
  1146. set_status_ok()
  1147. old_data = last_data_ref[0]
  1148. last_data_ref[0] = data
  1149. data_changed = not _data_equal(old_data, data)
  1150. if data_changed or from_user_date_change:
  1151. # Rebuild list: clear and rebuild from current data (last_data_ref already updated)
  1152. for w in inner.winfo_children():
  1153. w.destroy()
  1154. preserve = not from_user_date_change
  1155. _build_list_from_data(data, plan_start, preserve_selection=preserve)
  1156. if from_user_date_change:
  1157. canvas.yview_moveto(0)
  1158. after_id_ref[0] = root.after(REFRESH_MS, lambda: load_job_orders(from_user_date_change=False))
  1159. # Load default (today) on start; then start printer connection check
  1160. root.after(100, lambda: load_job_orders(from_user_date_change=True))
  1161. root.after(300, check_printer)
  1162. root.mainloop()
  1163. if __name__ == "__main__":
  1164. main()