No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 

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