選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 

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