diff --git a/.gitignore b/.gitignore index ffae7df..28da35d 100644 --- a/.gitignore +++ b/.gitignore @@ -36,3 +36,5 @@ out/ ### VS Code ### .vscode/ package-lock.json +python/Bag3.spec +python/dist/Bag3.exe diff --git a/python/Bag2.py b/python/Bag2.py index 2ffab22..5c4afb9 100644 --- a/python/Bag2.py +++ b/python/Bag2.py @@ -1,10 +1,10 @@ #!/usr/bin/env python3 """ -Bag1 – GUI to show FPSMS job orders by plan date. +Bag2 – GUI to show FPSMS job orders by plan date. Uses the public API GET /py/job-orders (no login required). UI tuned for aged users: larger font, Traditional Chinese labels, prev/next date. -Run: python Bag1.py +Run: python Bag2.py """ import json @@ -157,14 +157,21 @@ def try_printer_connection(printer_name: str, sett: dict) -> bool: # Larger font for aged users (point size) FONT_SIZE = 16 FONT_SIZE_BUTTONS = 15 -FONT_SIZE_QTY = 12 # smaller for 數量 under batch no. +FONT_SIZE_QTY = 12 # smaller for 需求數量 under batch no. +FONT_SIZE_META = 11 # single-line 需求/已印 (compact list) +# Less vertical padding so ~30 rows fit more comfortably +LIST_ROW_PADY = 2 +LIST_ROW_IPADY = 5 FONT_SIZE_ITEM = 20 # item code and item name (larger for readability) FONT_FAMILY = "Microsoft JhengHei UI" # Traditional Chinese; fallback to TkDefaultFont FONT_SIZE_ITEM_CODE = 20 # item code (larger for readability) FONT_SIZE_ITEM_NAME = 26 # item name (bigger than item code) -# Column widths: item code own column; item name at least double, wraps in its column -ITEM_CODE_WRAP = 140 # item code column width (long codes wrap under code only) -ITEM_NAME_WRAP = 640 # item name column (double width), wraps under name only +# Column widths: fixed frame widths so 品號/品名 columns line up across rows +LEFT_COL_WIDTH_PX = 300 # 工單 + 需求/已印 block +ITEM_CODE_WRAP = 140 # Label wraplength (px) +# Narrower than wrap+padding so short codes sit closer to 品名 (still aligned across rows) +CODE_COL_WIDTH_PX = ITEM_CODE_WRAP + 6 +ITEM_NAME_WRAP = 640 # item name wraps in remaining space # Light blue theme (softer than pure grey) BG_TOP = "#E8F4FC" @@ -534,62 +541,6 @@ def send_image_to_label_printer(printer_name: str, pil_image: "Image.Image") -> dc.EndDoc() -def run_dataflex_continuous_print( - root: tk.Tk, - ip: str, - port: int, - zpl: str, - label_text: str, - set_status_message: Callable[[str, bool], None], -) -> None: - """ - Run DataFlex continuous print (up to 100) in a background thread. - Shows a small window with "已列印: N" and a 停止 button; user can stop anytime. - """ - stop_event = threading.Event() - win = tk.Toplevel(root) - win.title("打袋機 連續列印") - win.geometry("320x140") - win.transient(root) - win.configure(bg=BG_TOP) - tk.Label(win, text="連續列印中,按「停止」結束", font=get_font(FONT_SIZE), bg=BG_TOP).pack(pady=(12, 4)) - count_lbl = tk.Label(win, text="已列印: 0", font=get_font(FONT_SIZE), bg=BG_TOP) - count_lbl.pack(pady=4) - - def on_stop(): - stop_event.set() - - ttk.Button(win, text="停止", command=on_stop, width=12).pack(pady=8) - win.protocol("WM_DELETE_WINDOW", lambda: (stop_event.set(), win.destroy())) - - def worker(): - sent = 0 - try: - for _ in range(100): - if stop_event.is_set(): - break - send_zpl_to_dataflex(ip, port, zpl) - sent += 1 - root.after(0, lambda s=sent: count_lbl.configure(text=f"已列印: {s}")) - if stop_event.is_set(): - break - time.sleep(2) - except ConnectionRefusedError: - root.after(0, lambda: set_status_message(f"無法連線至 {ip}:{port},請確認印表機已開機且 IP 正確。", is_error=True)) - except socket.timeout: - root.after(0, lambda: set_status_message(f"連線逾時 ({ip}:{port}),請檢查網路與連接埠。", is_error=True)) - except OSError as err: - root.after(0, lambda e=err: set_status_message(f"列印失敗:{e}", is_error=True)) - else: - if stop_event.is_set(): - root.after(0, lambda: set_status_message(f"已送出列印:批次 {label_text} x {sent} 張 (已停止)", is_error=False)) - else: - root.after(0, lambda: set_status_message(f"已送出列印:批次 {label_text} x {sent} 張 (連續完成)", is_error=False)) - root.after(0, win.destroy) - - threading.Thread(target=worker, daemon=True).start() - - def send_zpl_to_dataflex(ip: str, port: int, zpl: str) -> None: """Send ZPL to DataFlex printer via TCP. Raises on connection/send error.""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) @@ -665,6 +616,9 @@ def save_laser_last_count(date_str: str, count: int) -> None: LASER_PUSH_INTERVAL = 2 # seconds between pushes (like sample script) +# Click row with 激光機 selected: send this many times, delay between sends (not after last). +LASER_ROW_SEND_COUNT = 3 +LASER_ROW_SEND_DELAY_SEC = 3 def laser_push_loop( @@ -730,130 +684,6 @@ def laser_push_loop( pass -def run_laser_continuous_print( - root: tk.Tk, - laser_conn_ref: list, - laser_thread_ref: list, - laser_stop_ref: list, - ip: str, - port: int, - item_id: Optional[int], - stock_in_line_id: Optional[int], - item_code: str, - item_name: str, - set_status_message: Callable[[str, bool], None], -) -> None: - """ - Laser continuous send (連續 C) in a background thread. - User can stop via Stop button or keyboard: `Esc` / `Q`. - """ - # Stop any previous continuous run. - if laser_stop_ref[0] is not None: - try: - laser_stop_ref[0].set() - except Exception: - pass - - stop_event = threading.Event() - laser_stop_ref[0] = stop_event - - win = tk.Toplevel(root) - win.title("激光機 連續列印") - win.geometry("360x170") - win.transient(root) - win.configure(bg=BG_TOP) - - ttk.Label( - win, - text="連續送出中,按「停止」或 Esc / Q 結束", - font=get_font(FONT_SIZE), - background=BG_TOP, - ).pack(pady=(14, 8)) - - count_lbl = tk.Label(win, text="已送出:0 次", font=get_font(FONT_SIZE), bg=BG_TOP) - count_lbl.pack(pady=6) - - # Ensure stop keys work even if focus is on the main window. - def _unbind_stop_keys() -> None: - try: - root.unbind_all("") - root.unbind_all("") - root.unbind_all("") - except Exception: - pass - - def on_stop() -> None: - if stop_event.is_set(): - return - stop_event.set() - _unbind_stop_keys() - try: - win.destroy() - except Exception: - pass - - def _key_stop(_e: tk.Event) -> str: - on_stop() - return "break" - - root.bind_all("", _key_stop) - root.bind_all("", _key_stop) - root.bind_all("", _key_stop) - - ttk.Button(win, text="停止", command=on_stop, width=12).pack(pady=10) - win.protocol("WM_DELETE_WINDOW", on_stop) - - def worker() -> None: - sent = 0 - try: - while not stop_event.is_set(): - ok, msg = send_job_to_laser_with_retry( - laser_conn_ref, - ip, - port, - item_id, - stock_in_line_id, - item_code, - item_name, - ) - if not ok: - root.after(0, lambda m=msg: set_status_message(f"連續送出失敗:{m}", is_error=True)) - break - - sent += 1 - root.after(0, lambda s=sent: count_lbl.configure(text=f"已送出:{s} 次")) - - # Small delay between sends; check stop frequently. - for _ in range(4): # 4 * 0.05 = 0.20 sec - if stop_event.is_set(): - break - time.sleep(0.05) - except Exception as e: - root.after(0, lambda err=str(e): set_status_message(f"連續送出意外錯誤:{err}", is_error=True)) - finally: - _unbind_stop_keys() - if not stop_event.is_set(): - # Failure path ended the worker; keep window close. - try: - win.destroy() - except Exception: - pass - else: - # Stopped intentionally. - root.after(0, lambda s=sent: set_status_message(f"已停止激光機連續送出:{s} 次", is_error=False)) - - laser_stop_ref[0] = None - laser_thread_ref[0] = None - try: - win.destroy() - except Exception: - pass - - t = threading.Thread(target=worker, daemon=True) - laser_thread_ref[0] = t - t.start() - - def send_job_to_laser( conn_ref: list, ip: str, @@ -932,6 +762,107 @@ def send_job_to_laser_with_retry( return ok2, msg2 +def run_laser_row_send_thread( + root: tk.Tk, + laser_conn_ref: list, + laser_busy_ref: list, + ip: str, + port: int, + item_id: Optional[int], + stock_in_line_id: Optional[int], + item_code: str, + item_name: str, + set_status_message: Callable[[str, bool], None], + base_url: Optional[str] = None, + job_order_id: Optional[int] = None, + on_recorded: Optional[Callable[[], None]] = None, +) -> None: + """ + On row click with 激光機: send LASER_ROW_SEND_COUNT times with LASER_ROW_SEND_DELAY_SEC between sends. + UI updates on main thread; work runs in background so the window does not freeze. + After success, POST LASER qty to API when job_order_id and base_url are set. + """ + if laser_busy_ref[0]: + return + laser_busy_ref[0] = True + + def worker() -> None: + try: + n = LASER_ROW_SEND_COUNT + for i in range(n): + ok, msg = send_job_to_laser_with_retry( + laser_conn_ref, + ip, + port, + item_id, + stock_in_line_id, + item_code, + item_name, + ) + if not ok: + root.after( + 0, + lambda m=msg: messagebox.showwarning("激光機", m), + ) + return + if i < n - 1: + time.sleep(LASER_ROW_SEND_DELAY_SEC) + posted = False + if base_url and job_order_id is not None: + try: + submit_job_order_print_submit(base_url, int(job_order_id), n, "LASER") + posted = True + except requests.RequestException as ex: + root.after( + 0, + lambda err=str(ex): messagebox.showwarning( + "激光機", + f"已發送,但伺服器記錄失敗:{err}", + ), + ) + root.after( + 0, + lambda: set_status_message("已發送", is_error=False), + ) + if on_recorded is not None and posted: + root.after(0, on_recorded) + except Exception as e: + root.after( + 0, + lambda err=str(e): messagebox.showwarning("激光機", f"送出失敗:{err}"), + ) + finally: + laser_busy_ref[0] = False + + threading.Thread(target=worker, daemon=True).start() + + +def _printed_qty_int(raw) -> int: + """Parse API printed qty field (may be float JSON) to int.""" + try: + return int(float(raw)) if raw is not None else 0 + except (TypeError, ValueError): + return 0 + + +def _filter_job_orders_by_search(data: list, needle: str) -> list: + """Substring match on item code, job order code, item name, lot (case-insensitive).""" + n = needle.strip().lower() + if not n: + return data + out: list = [] + for jo in data: + parts = [ + str(jo.get("itemCode") or ""), + str(jo.get("code") or ""), + str(jo.get("itemName") or ""), + str(jo.get("lotNo") or ""), + ] + if any(n in p.lower() for p in parts): + out.append(jo) + return out + + def format_qty(val) -> str: """Format quantity: integer without .0, with thousand separator.""" if val is None: @@ -966,16 +897,33 @@ def fetch_job_orders(base_url: str, plan_start: date) -> list: return resp.json() +def submit_job_order_print_submit( + base_url: str, + job_order_id: int, + qty: int, + print_channel: str = "LABEL", +) -> None: + """POST /py/job-order-print-submit — one row per submit for DB wastage/stock tracking.""" + url = f"{base_url.rstrip('/')}/py/job-order-print-submit" + resp = requests.post( + url, + json={"jobOrderId": job_order_id, "qty": qty, "printChannel": print_channel}, + timeout=30, + ) + resp.raise_for_status() + + def set_row_highlight(row_frame: tk.Frame, selected: bool) -> None: - """Set row and all its child widgets to selected or normal background.""" + """Set row and all nested Frame/Label children to selected or normal background.""" bg = BG_ROW_SELECTED if selected else BG_ROW - row_frame.configure(bg=bg) - for w in row_frame.winfo_children(): + + def _paint(w: tk.Misc) -> None: if isinstance(w, (tk.Frame, tk.Label)): w.configure(bg=bg) for c in w.winfo_children(): - if isinstance(c, tk.Label): - c.configure(bg=bg) + _paint(c) + + _paint(row_frame) def on_job_order_click(jo: dict, batch: str) -> None: @@ -988,107 +936,59 @@ def on_job_order_click(jo: dict, batch: str) -> None: ) -def ask_laser_count(parent: tk.Tk) -> Optional[int]: +def ask_label_count(parent: tk.Tk) -> Optional[int]: """ - When printer is 激光機, ask how many times to send (like DataFlex). - Returns count (>= 1), or -1 for continuous (C), or None if cancelled. + When printer is 標簽機, ask how many labels to print: + optional direct qty in text field, +50/+10/+5/+1, 重置, then 確認送出. + Returns count (>= 1), or None if cancelled. """ - result: list = [None] - count_ref = [0] - continuous_ref = [False] + result: list[Optional[int]] = [None] + qty_var = tk.StringVar(value="0") win = tk.Toplevel(parent) - win.title("激光機送出數量") - win.geometry("580x230") # wider so 連續 (C) button is fully visible + win.title("標簽印數") + win.geometry("580x280") win.transient(parent) win.grab_set() win.configure(bg=BG_TOP) - ttk.Label(win, text="送出多少次?", font=get_font(FONT_SIZE)).pack(pady=(12, 4)) - count_lbl = tk.Label(win, text="數量: 0", font=get_font(FONT_SIZE), bg=BG_TOP) - count_lbl.pack(pady=4) - - def update_display(): - if continuous_ref[0]: - count_lbl.configure(text="數量: 連續 (C)") - else: - count_lbl.configure(text=f"數量: {count_ref[0]}") - - def add(n: int): - continuous_ref[0] = False - count_ref[0] = max(0, count_ref[0] + n) - update_display() - - def set_continuous(): - continuous_ref[0] = True - update_display() - - def confirm(): - if continuous_ref[0]: - result[0] = -1 - elif count_ref[0] < 1: - messagebox.showwarning("激光機", "請先按 +50、+10、+5 或 +1 選擇數量。", parent=win) - return - else: - result[0] = count_ref[0] - win.destroy() + ttk.Label(win, text="印多少個?", font=get_font(FONT_SIZE)).pack(pady=(12, 4)) + + entry_row = tk.Frame(win, bg=BG_TOP) + entry_row.pack(pady=8) + tk.Label(entry_row, text="需求數量:", font=get_font(FONT_SIZE), bg=BG_TOP).pack(side=tk.LEFT, padx=(0, 6)) + qty_entry = tk.Entry( + entry_row, + textvariable=qty_var, + width=12, + font=get_font(FONT_SIZE), + bg="white", + justify=tk.RIGHT, + ) + qty_entry.pack(side=tk.LEFT, padx=4) - btn_row = tk.Frame(win, bg=BG_TOP) - btn_row.pack(pady=8) - for label, value in [("+50", 50), ("+10", 10), ("+5", 5), ("+1", 1)]: - def make_add(v: int): - return lambda: add(v) - ttk.Button(btn_row, text=label, command=make_add(value), width=8).pack(side=tk.LEFT, padx=4) - ttk.Button(btn_row, text="連續 (C)", command=set_continuous, width=12).pack(side=tk.LEFT, padx=4) - ttk.Button(win, text="確認送出", command=confirm, width=14).pack(pady=12) - win.protocol("WM_DELETE_WINDOW", win.destroy) - win.wait_window() - return result[0] + def current_qty() -> int: + s = (qty_var.get() or "").strip().replace(",", "") + if not s: + return 0 + try: + return max(0, int(s)) + except ValueError: + return 0 + def reset_qty() -> None: + qty_var.set("0") -def ask_label_count(parent: tk.Tk) -> Optional[int]: - """ - When printer is 標簽機, ask how many labels to print (same style as 打袋機): - +50, +10, +5, +1, C (continuous), then 確認送出. - Returns count (>= 1), or -1 for continuous (C), or None if cancelled. - """ - result: list[Optional[int]] = [None] - count_ref = [0] - continuous_ref = [False] + ttk.Button(entry_row, text="重置", command=reset_qty, width=8).pack(side=tk.LEFT, padx=8) - win = tk.Toplevel(parent) - win.title("標簽列印數量") - # Wider so all buttons (especially 連續) are fully visible - win.geometry("580x230") - win.transient(parent) - win.grab_set() - win.configure(bg=BG_TOP) - ttk.Label(win, text="列印多少張標簽?", font=get_font(FONT_SIZE)).pack(pady=(12, 4)) - count_lbl = tk.Label(win, text="列印數量: 0", font=get_font(FONT_SIZE), bg=BG_TOP) - count_lbl.pack(pady=4) + def add(n: int) -> None: + qty_var.set(str(current_qty() + n)) - def update_display(): - if continuous_ref[0]: - count_lbl.configure(text="列印數量: 連續 (C)") - else: - count_lbl.configure(text=f"列印數量: {count_ref[0]}") - - def add(n: int): - continuous_ref[0] = False - count_ref[0] = max(0, count_ref[0] + n) - update_display() - - def set_continuous(): - continuous_ref[0] = True - update_display() - - def confirm(): - if continuous_ref[0]: - result[0] = -1 - elif count_ref[0] < 1: - messagebox.showwarning("標簽機", "請先按 +50、+10、+5 或 +1 選擇數量。", parent=win) + def confirm() -> None: + q = current_qty() + if q < 1: + messagebox.showwarning("標簽機", "請輸入需求數量或按 +50、+10、+5、+1。", parent=win) return - else: - result[0] = count_ref[0] + result[0] = q win.destroy() btn_row1 = tk.Frame(win, bg=BG_TOP) @@ -1097,55 +997,66 @@ def ask_label_count(parent: tk.Tk) -> Optional[int]: def make_add(v: int): return lambda: add(v) ttk.Button(btn_row1, text=label, command=make_add(value), width=8).pack(side=tk.LEFT, padx=4) - ttk.Button(btn_row1, text="連續 (C)", command=set_continuous, width=12).pack(side=tk.LEFT, padx=4) ttk.Button(win, text="確認送出", command=confirm, width=14).pack(pady=12) + qty_entry.bind("", lambda e: confirm()) win.protocol("WM_DELETE_WINDOW", win.destroy) win.wait_window() return result[0] def ask_bag_count(parent: tk.Tk) -> Optional[int]: """ - When printer is 打袋機 DataFlex, ask how many bags: +50, +10, +5, +1, C, then 確認送出. - Returns count (>= 1), or -1 for continuous (C), or None if cancelled. + When printer is 打袋機 DataFlex, ask how many bags: + optional direct qty in text field, +50/+10/+5/+1, 重置, then 確認送出. + Returns count (>= 1), or None if cancelled. """ result: list[Optional[int]] = [None] - count_ref = [0] - continuous_ref = [False] + qty_var = tk.StringVar(value="0") win = tk.Toplevel(parent) win.title("打袋列印數量") - win.geometry("580x230") # wider so 連續 (C) button is fully visible + win.geometry("580x280") win.transient(parent) win.grab_set() win.configure(bg=BG_TOP) ttk.Label(win, text="列印多少個袋?", font=get_font(FONT_SIZE)).pack(pady=(12, 4)) - count_lbl = tk.Label(win, text="列印數量: 0", font=get_font(FONT_SIZE), bg=BG_TOP) - count_lbl.pack(pady=4) - def update_display(): - if continuous_ref[0]: - count_lbl.configure(text="列印數量: 連續 (C)") - else: - count_lbl.configure(text=f"列印數量: {count_ref[0]}") - - def add(n: int): - continuous_ref[0] = False - count_ref[0] = max(0, count_ref[0] + n) - update_display() - - def set_continuous(): - continuous_ref[0] = True - update_display() - - def confirm(): - if continuous_ref[0]: - result[0] = -1 - elif count_ref[0] < 1: - messagebox.showwarning("打袋機", "請先按 +50、+10、+5 或 +1 選擇數量。", parent=win) + entry_row = tk.Frame(win, bg=BG_TOP) + entry_row.pack(pady=8) + tk.Label(entry_row, text="需求數量:", font=get_font(FONT_SIZE), bg=BG_TOP).pack(side=tk.LEFT, padx=(0, 6)) + qty_entry = tk.Entry( + entry_row, + textvariable=qty_var, + width=12, + font=get_font(FONT_SIZE), + bg="white", + justify=tk.RIGHT, + ) + qty_entry.pack(side=tk.LEFT, padx=4) + + def current_qty() -> int: + s = (qty_var.get() or "").strip().replace(",", "") + if not s: + return 0 + try: + return max(0, int(s)) + except ValueError: + return 0 + + def reset_qty() -> None: + qty_var.set("0") + + ttk.Button(entry_row, text="重置", command=reset_qty, width=8).pack(side=tk.LEFT, padx=8) + + def add(n: int) -> None: + qty_var.set(str(current_qty() + n)) + + def confirm() -> None: + q = current_qty() + if q < 1: + messagebox.showwarning("打袋機", "請輸入需求數量或按 +50、+10、+5、+1。", parent=win) return - else: - result[0] = count_ref[0] + result[0] = q win.destroy() btn_row1 = tk.Frame(win, bg=BG_TOP) @@ -1154,9 +1065,9 @@ def ask_bag_count(parent: tk.Tk) -> Optional[int]: def make_add(v: int): return lambda: add(v) ttk.Button(btn_row1, text=label, command=make_add(value), width=8).pack(side=tk.LEFT, padx=4) - ttk.Button(btn_row1, text="連續 (C)", command=set_continuous, width=12).pack(side=tk.LEFT, padx=4) ttk.Button(win, text="確認送出", command=confirm, width=14).pack(pady=12) + qty_entry.bind("", lambda e: confirm()) win.protocol("WM_DELETE_WINDOW", win.destroy) win.wait_window() return result[0] @@ -1215,8 +1126,7 @@ def main() -> None: # Laser: keep connection open for repeated sends; close when switching away laser_conn_ref: list = [None] - laser_thread_ref: list = [None] - laser_stop_ref: list = [None] + laser_send_busy_ref: list = [False] # Top: left [前一天] [date] [後一天] | right [printer dropdown] top = tk.Frame(root, padx=12, pady=12, bg=BG_TOP) @@ -1312,8 +1222,6 @@ def main() -> None: def on_printer_selection_changed(*args) -> None: check_printer() if printer_var.get() != "激光機": - if laser_stop_ref[0] is not None: - laser_stop_ref[0].set() if laser_conn_ref[0] is not None: try: laser_conn_ref[0].close() @@ -1406,6 +1314,25 @@ def main() -> None: job_orders_frame = tk.Frame(root, bg=BG_LIST) job_orders_frame.pack(fill=tk.BOTH, expand=True, padx=12, pady=12) + search_var = tk.StringVar() + search_frame = tk.Frame(job_orders_frame, bg=BG_LIST) + search_frame.pack(fill=tk.X, pady=(0, 6)) + tk.Label( + search_frame, + text="搜尋品號/工單/批號:", + font=get_font(FONT_SIZE_QTY), + bg=BG_LIST, + fg="black", + ).pack(side=tk.LEFT, padx=(0, 6)) + search_entry = tk.Entry( + search_frame, + textvariable=search_var, + width=32, + font=get_font(FONT_SIZE_QTY), + bg="white", + ) + search_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 8)) + # Scrollable area for buttons canvas = tk.Canvas(job_orders_frame, highlightthickness=0, bg=BG_LIST) scrollbar = ttk.Scrollbar(job_orders_frame, orient=tk.VERTICAL, command=canvas.yview) @@ -1423,7 +1350,7 @@ def main() -> None: inner.bind("", _on_inner_configure) canvas.bind("", _on_canvas_configure) - # Mouse wheel: make scroll work when hovering over canvas or the list (inner/buttons) + # Mouse wheel: default Tk scroll speed (one unit per notch) def _on_mousewheel(event): if getattr(event, "delta", None) is not None: canvas.yview_scroll(int(-1 * (event.delta / 120)), "units") @@ -1446,6 +1373,7 @@ def main() -> None: selected_row_holder = [None] # [tk.Frame | None] selected_jo_id_ref = [None] # [int | None] job order id for selection preservation last_data_ref = [None] # [list | None] last successful fetch for current date + last_plan_start_ref = [date.today()] # plan date for the current list (search filter uses same) after_id_ref = [None] # [str | None] root.after id to cancel retry/refresh def _data_equal(a: Optional[list], b: Optional[list]) -> bool: @@ -1453,9 +1381,13 @@ def main() -> None: return a is b if len(a) != len(b): return False - ids_a = [x.get("id") for x in a] - ids_b = [x.get("id") for x in b] - return ids_a == ids_b + for x, y in zip(a, b): + if x.get("id") != y.get("id"): + return False + for k in ("bagPrintedQty", "labelPrintedQty", "laserPrintedQty"): + if x.get(k) != y.get(k): + return False + return True def _build_list_from_data(data: list, plan_start: date, preserve_selection: bool) -> None: selected_row_holder[0] = None @@ -1467,38 +1399,64 @@ def main() -> None: raw_batch = batch_no(year, jo_id) if jo_id is not None else "—" lot_no_val = jo.get("lotNo") batch = (lot_no_val or "—").strip() if lot_no_val else "—" + jo_no_display = (jo.get("code") or "").strip() + if not jo_no_display and jo_id is not None: + jo_no_display = raw_batch + elif not jo_no_display: + jo_no_display = "—" + # Line 1: job order no.; line 2: 需求 + 已印(袋/標/激)on one row for compact scrolling + head_line = f"工單:{jo_no_display}" item_code = jo.get("itemCode") or "—" item_name = jo.get("itemName") or "—" req_qty = jo.get("reqQty") qty_str = format_qty(req_qty) - # Three columns: lotNo/batch+數量 | item code (own column) | item name (≥2× width, wraps in column) - row = tk.Frame(inner, bg=BG_ROW, relief=tk.RAISED, bd=2, cursor="hand2", padx=12, pady=10) - row.pack(fill=tk.X, pady=4) + bag_pq = _printed_qty_int(jo.get("bagPrintedQty")) + label_pq = _printed_qty_int(jo.get("labelPrintedQty")) + laser_pq = _printed_qty_int(jo.get("laserPrintedQty")) + meta_line = ( + f"需求:{qty_str} " + f"已印 袋{bag_pq:,} 標{label_pq:,} 激{laser_pq:,}" + ) + # Columns: fixed-width left | fixed-width 品號 | 品名 (expand) + row = tk.Frame( + inner, + bg=BG_ROW, + relief=tk.RAISED, + bd=2, + cursor="hand2", + padx=10, + pady=LIST_ROW_IPADY, + ) + row.pack(fill=tk.X, pady=LIST_ROW_PADY) - left = tk.Frame(row, bg=BG_ROW) - left.pack(side=tk.LEFT, anchor=tk.NW) + left = tk.Frame(row, bg=BG_ROW, width=LEFT_COL_WIDTH_PX) + left.pack_propagate(False) + left.pack(side=tk.LEFT, anchor=tk.NW, fill=tk.Y) batch_lbl = tk.Label( left, - text=batch, + text=head_line, font=get_font(FONT_SIZE_BUTTONS), bg=BG_ROW, fg="black", ) batch_lbl.pack(anchor=tk.W) - qty_lbl = None - if qty_str != "—": - qty_lbl = tk.Label( - left, - text=f"數量:{qty_str}", - font=get_font(FONT_SIZE_QTY), - bg=BG_ROW, - fg="black", - ) - qty_lbl.pack(anchor=tk.W) + meta_lbl = tk.Label( + left, + text=meta_line, + font=get_font(FONT_SIZE_META), + bg=BG_ROW, + fg="#222222", + anchor=tk.W, + justify=tk.LEFT, + wraplength=LEFT_COL_WIDTH_PX - 8, + ) + meta_lbl.pack(anchor=tk.W) - # Column 2: item code only, bigger font, wraps in its own column + code_col = tk.Frame(row, bg=BG_ROW, width=CODE_COL_WIDTH_PX) + code_col.pack_propagate(False) + code_col.pack(side=tk.LEFT, anchor=tk.NW, fill=tk.Y, padx=(6, 2)) code_lbl = tk.Label( - row, + code_col, text=item_code, font=get_font(FONT_SIZE_ITEM_CODE), bg=BG_ROW, @@ -1507,11 +1465,12 @@ def main() -> None: justify=tk.LEFT, anchor=tk.NW, ) - code_lbl.pack(side=tk.LEFT, anchor=tk.NW, padx=(12, 8)) + code_lbl.pack(anchor=tk.NW) - # Column 3: item name only, bigger font, at least double width, wraps under its own column + name_col = tk.Frame(row, bg=BG_ROW) + name_col.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, anchor=tk.NW) name_lbl = tk.Label( - row, + name_col, text=item_name or "—", font=get_font(FONT_SIZE_ITEM_NAME), bg=BG_ROW, @@ -1520,7 +1479,7 @@ def main() -> None: justify=tk.LEFT, anchor=tk.NW, ) - name_lbl.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, anchor=tk.NW) + name_lbl.pack(anchor=tk.NW) def _on_click(e, j=jo, b=batch, r=row): if selected_row_holder[0] is not None: @@ -1554,22 +1513,31 @@ def main() -> None: lot_no=lot_no, ) label_text = (lot_no or b).strip() - if count == -1: - run_dataflex_continuous_print(root, ip, port, zpl, label_text, set_status_message) - else: - n = count - try: - for i in range(n): - send_zpl_to_dataflex(ip, port, zpl) - if i < n - 1: - time.sleep(2) - set_status_message(f"已送出列印:批次 {label_text} x {n} 張", is_error=False) - except ConnectionRefusedError: - set_status_message(f"無法連線至 {ip}:{port},請確認印表機已開機且 IP 正確。", is_error=True) - except socket.timeout: - set_status_message(f"連線逾時 ({ip}:{port}),請檢查網路與連接埠。", is_error=True) - except OSError as err: - set_status_message(f"列印失敗:{err}", is_error=True) + n = count + try: + for i in range(n): + send_zpl_to_dataflex(ip, port, zpl) + if i < n - 1: + time.sleep(2) + set_status_message(f"已送出列印:批次 {label_text} x {n} 張", is_error=False) + jo_id = j.get("id") + if jo_id is not None: + try: + submit_job_order_print_submit( + base_url_ref[0], int(jo_id), n, "DATAFLEX" + ) + load_job_orders(from_user_date_change=False) + except requests.RequestException as ex: + messagebox.showwarning( + "打袋機", + f"已送出 {n} 張,但伺服器記錄失敗:{ex}", + ) + except ConnectionRefusedError: + set_status_message(f"無法連線至 {ip}:{port},請確認印表機已開機且 IP 正確。", is_error=True) + except socket.timeout: + set_status_message(f"連線逾時 ({ip}:{port}),請檢查網路與連接埠。", is_error=True) + except OSError as err: + set_status_message(f"列印失敗:{err}", is_error=True) elif printer_var.get() == "標簽機": com = (settings.get("label_com") or "").strip() if not com: @@ -1582,7 +1550,7 @@ def main() -> None: item_id = j.get("itemId") stock_in_line_id = j.get("stockInLineId") lot_no = j.get("lotNo") - n = 100 if count == -1 else count + n = count try: # Always render to image (Chinese OK), then send as ZPL graphic (^GFA). # This is more reliable than Windows GDI and works for both Windows printer name and COM. @@ -1598,8 +1566,27 @@ def main() -> None: send_zpl_to_label_printer(com, zpl_img) if i < n - 1: time.sleep(0.5) - msg = f"已送出列印:{n} 張標簽" if count != -1 else f"已送出列印:{n} 張標簽 (連續)" - messagebox.showinfo("標簽機", msg) + jo_id = j.get("id") + if jo_id is not None: + try: + submit_job_order_print_submit( + base_url_ref[0], int(jo_id), n, "LABEL" + ) + load_job_orders(from_user_date_change=False) + messagebox.showinfo( + "標籤機", + f"已送出列印:{n} 張標籤(已記錄)", + ) + except requests.RequestException as ex: + messagebox.showwarning( + "標籤機", + f"標籤已列印 {n} 張,但伺服器記錄失敗:{ex}", + ) + else: + messagebox.showwarning( + "標籤機", + f"已送出列印:{n} 張標籤(無工單 id,無法寫入伺服器記錄)", + ) except Exception as err: messagebox.showerror("標簽機", f"列印失敗:{err}") elif printer_var.get() == "激光機": @@ -1612,61 +1599,60 @@ def main() -> None: if not ip: set_status_message("請在設定中填寫激光機的 IP。", is_error=True) else: - count = ask_laser_count(root) - if count is not None: - item_id = j.get("itemId") - stock_in_line_id = j.get("stockInLineId") - item_code_val = j.get("itemCode") or "" - item_name_val = j.get("itemName") or "" - if count == -1: - run_laser_continuous_print( - root=root, - laser_conn_ref=laser_conn_ref, - laser_thread_ref=laser_thread_ref, - laser_stop_ref=laser_stop_ref, - ip=ip, - port=port, - item_id=item_id, - stock_in_line_id=stock_in_line_id, - item_code=item_code_val, - item_name=item_name_val, - set_status_message=set_status_message, - ) - else: - n = count - sent = 0 - for i in range(n): - ok, msg = send_job_to_laser_with_retry( - laser_conn_ref, ip, port, - item_id, stock_in_line_id, - item_code_val, item_name_val, - ) - if ok: - sent += 1 - else: - set_status_message(f"已送出 {sent} 次,第 {sent + 1} 次失敗:{msg}", is_error=True) - break - if i < n - 1: - time.sleep(0.2) - if sent == n: - set_status_message(f"已送出激光機:{sent} 次", is_error=False) - - for w in (row, left, batch_lbl, code_lbl, name_lbl): + item_id = j.get("itemId") + stock_in_line_id = j.get("stockInLineId") + item_code_val = j.get("itemCode") or "" + item_name_val = j.get("itemName") or "" + run_laser_row_send_thread( + root=root, + laser_conn_ref=laser_conn_ref, + laser_busy_ref=laser_send_busy_ref, + ip=ip, + port=port, + item_id=item_id, + stock_in_line_id=stock_in_line_id, + item_code=item_code_val, + item_name=item_name_val, + set_status_message=set_status_message, + base_url=base_url_ref[0], + job_order_id=j.get("id"), + on_recorded=lambda: load_job_orders(from_user_date_change=False), + ) + + for w in ( + row, + left, + batch_lbl, + meta_lbl, + code_col, + code_lbl, + name_col, + name_lbl, + ): w.bind("", _on_click) w.bind("", _on_mousewheel) w.bind("", _on_mousewheel) w.bind("", _on_mousewheel) - if qty_lbl is not None: - qty_lbl.bind("", _on_click) - qty_lbl.bind("", _on_mousewheel) - qty_lbl.bind("", _on_mousewheel) - qty_lbl.bind("", _on_mousewheel) if preserve_selection and selected_id is not None and jo.get("id") == selected_id: found_row = row if found_row is not None: set_row_highlight(found_row, True) selected_row_holder[0] = found_row + def refresh_visible_list() -> None: + """Re-apply search filter to last fetched rows without hitting the API.""" + raw = last_data_ref[0] + if raw is None: + return + ps = last_plan_start_ref[0] + needle = search_var.get().strip() + shown = _filter_job_orders_by_search(raw, needle) if needle else raw + for w in inner.winfo_children(): + w.destroy() + _build_list_from_data(shown, ps, preserve_selection=True) + + search_entry.bind("", lambda e: refresh_visible_list()) + def load_job_orders(from_user_date_change: bool = False) -> None: if after_id_ref[0] is not None: root.after_cancel(after_id_ref[0]) @@ -1689,13 +1675,16 @@ def main() -> None: set_status_ok() old_data = last_data_ref[0] last_data_ref[0] = data + last_plan_start_ref[0] = plan_start data_changed = not _data_equal(old_data, data) if data_changed or from_user_date_change: # Rebuild list: clear and rebuild from current data (last_data_ref already updated) for w in inner.winfo_children(): w.destroy() preserve = not from_user_date_change - _build_list_from_data(data, plan_start, preserve_selection=preserve) + needle = search_var.get().strip() + shown = _filter_job_orders_by_search(data, needle) if needle else data + _build_list_from_data(shown, plan_start, preserve_selection=preserve) if from_user_date_change: canvas.yview_moveto(0) after_id_ref[0] = root.after(REFRESH_MS, lambda: load_job_orders(from_user_date_change=False)) diff --git a/python/Bag3.py b/python/Bag3.py new file mode 100644 index 0000000..364fc36 --- /dev/null +++ b/python/Bag3.py @@ -0,0 +1,1718 @@ +#!/usr/bin/env python3 +""" +Bag3 v3.1 – FPSMS job orders by plan date (this file is the maintained version). + +Uses the public API GET /py/job-orders (no login required). +UI tuned for aged users: larger font, Traditional Chinese labels, prev/next date. + +Bag2 is kept as a separate legacy v2.x line; do not assume Bag2 matches Bag3. + +Run: python Bag3.py +""" + +import json +import os +import select +import socket +import sys +import tempfile +import threading +import time +import tkinter as tk +from datetime import date, datetime, timedelta +from tkinter import messagebox, ttk +from typing import Callable, Optional + +import requests + +try: + import serial +except ImportError: + serial = None # type: ignore + +try: + import win32print # type: ignore[import] + import win32ui # type: ignore[import] + import win32con # type: ignore[import] + import win32gui # type: ignore[import] +except ImportError: + win32print = None # type: ignore[assignment] + win32ui = None # type: ignore[assignment] + win32con = None # type: ignore[assignment] + win32gui = None # type: ignore[assignment] + +try: + from PIL import Image, ImageDraw, ImageFont, ImageOps + try: + from PIL import ImageWin # type: ignore + except Exception: + ImageWin = None # type: ignore[assignment] + import qrcode + _HAS_PIL_QR = True +except ImportError: + Image = None # type: ignore[assignment] + ImageDraw = None # type: ignore[assignment] + ImageFont = None # type: ignore[assignment] + ImageOps = None # type: ignore[assignment] + ImageWin = None # type: ignore[assignment] + qrcode = None # type: ignore[assignment] + _HAS_PIL_QR = False + +APP_VERSION = "3.1" + +DEFAULT_BASE_URL = os.environ.get("FPSMS_BASE_URL", "http://localhost:8090/api") +# When run as PyInstaller exe, save settings next to the exe; otherwise next to script +if getattr(sys, "frozen", False): + _SETTINGS_DIR = os.path.dirname(sys.executable) +else: + _SETTINGS_DIR = os.path.dirname(os.path.abspath(__file__)) +# Bag3 has its own settings file so it doesn't share with Bag1/Bag2. +SETTINGS_FILE = os.path.join(_SETTINGS_DIR, "bag3_settings.json") +LASER_COUNTER_FILE = os.path.join(_SETTINGS_DIR, "bag3_last_batch_count.txt") + +DEFAULT_SETTINGS = { + "api_ip": "localhost", + "api_port": "8090", + "dabag_ip": "", + "dabag_port": "3008", + "laser_ip": "192.168.17.10", + "laser_port": "45678", + # For 標簽機 on Windows, this is the Windows printer name, e.g. "TSC TTP-246M Pro" + "label_com": "TSC TTP-246M Pro", +} + + +def load_settings() -> dict: + """Load settings from JSON file; return defaults if missing or invalid.""" + try: + if os.path.isfile(SETTINGS_FILE): + with open(SETTINGS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {**DEFAULT_SETTINGS, **data} + except Exception: + pass + return dict(DEFAULT_SETTINGS) + + +def save_settings(settings: dict) -> None: + """Save settings to JSON file.""" + with open(SETTINGS_FILE, "w", encoding="utf-8") as f: + json.dump(settings, f, indent=2, ensure_ascii=False) + + +def build_base_url(api_ip: str, api_port: str) -> str: + ip = (api_ip or "localhost").strip() + port = (api_port or "8090").strip() + return f"http://{ip}:{port}/api" + + +def try_printer_connection(printer_name: str, sett: dict) -> bool: + """Try to connect to the selected printer (TCP IP:port or COM). Returns True if OK.""" + if printer_name == "打袋機 DataFlex": + ip = (sett.get("dabag_ip") or "").strip() + port_str = (sett.get("dabag_port") or "9100").strip() + if not ip: + return False + try: + port = int(port_str) + s = socket.create_connection((ip, port), timeout=PRINTER_SOCKET_TIMEOUT) + s.close() + return True + except (socket.error, ValueError, OSError): + return False + if printer_name == "激光機": + ip = (sett.get("laser_ip") or "").strip() + port_str = (sett.get("laser_port") or "45678").strip() + if not ip: + return False + try: + port = int(port_str) + s = socket.create_connection((ip, port), timeout=PRINTER_SOCKET_TIMEOUT) + s.close() + return True + except (socket.error, ValueError, OSError): + return False + if printer_name == "標簽機": + target = (sett.get("label_com") or "").strip() + if not target: + return False + # On Windows, allow using a Windows printer name (e.g. "TSC TTP-246M Pro") + # as an alternative to a COM port. If it doesn't look like a COM port, + # try opening it via the Windows print spooler. + if os.name == "nt" and not target.upper().startswith("COM"): + if win32print is None: + return False + try: + handle = win32print.OpenPrinter(target) + win32print.ClosePrinter(handle) + return True + except Exception: + return False + # Fallback: treat as serial COM port (original behaviour) + if serial is None: + return False + try: + ser = serial.Serial(target, timeout=1) + ser.close() + return True + except (serial.SerialException, OSError): + return False + return False + +# Larger font for aged users (point size) +FONT_SIZE = 16 +FONT_SIZE_BUTTONS = 15 +# Printer selector: field + dropdown (use tk.OptionMenu so menu font is respected on Windows) +FONT_SIZE_COMBO = 18 +FONT_SIZE_QTY = 12 # smaller for 需求數量 under batch no. +FONT_SIZE_META = 11 # single-line 需求/已印 (compact list) +# Less vertical padding so ~30 rows fit more comfortably +LIST_ROW_PADY = 2 +LIST_ROW_IPADY = 5 +FONT_SIZE_ITEM = 20 # item code and item name (larger for readability) +FONT_FAMILY = "Microsoft JhengHei UI" # Traditional Chinese; fallback to TkDefaultFont +FONT_SIZE_ITEM_CODE = 20 # item code (larger for readability) +FONT_SIZE_ITEM_NAME = 26 # item name (bigger than item code) +# Column widths: fixed frame widths so 品號/品名 columns line up across rows +LEFT_COL_WIDTH_PX = 300 # 工單 + 需求/已印 block +ITEM_CODE_WRAP = 140 # Label wraplength (px) +# Narrower than wrap+padding so short codes sit closer to 品名 (still aligned across rows) +CODE_COL_WIDTH_PX = ITEM_CODE_WRAP + 6 +ITEM_NAME_WRAP = 640 # item name wraps in remaining space + +# Light blue theme (softer than pure grey) +BG_TOP = "#E8F4FC" +BG_LIST = "#D4E8F7" +BG_ROOT = "#E1F0FF" +BG_ROW = "#C5E1F5" +BG_ROW_SELECTED = "#6BB5FF" # highlighted when selected (for printing) +# Connection status bar +BG_STATUS_ERROR = "#FFCCCB" # red background when disconnected +FG_STATUS_ERROR = "#B22222" # red text +BG_STATUS_OK = "#90EE90" # light green when connected +FG_STATUS_OK = "#006400" # green text +RETRY_MS = 30 * 1000 # 30 seconds reconnect +REFRESH_MS = 60 * 1000 # 60 seconds refresh when connected +PRINTER_CHECK_MS = 60 * 1000 # 1 minute when printer OK +PRINTER_RETRY_MS = 30 * 1000 # 30 seconds when printer failed +PRINTER_SOCKET_TIMEOUT = 3 +DATAFLEX_SEND_TIMEOUT = 10 # seconds when sending ZPL to DataFlex + + +def _zpl_escape(s: str) -> str: + """Escape text for ZPL ^FD...^FS (backslash and caret).""" + return s.replace("\\", "\\\\").replace("^", "\\^") + + +def generate_zpl_dataflex( + batch_no: str, + item_code: str, + item_name: str, + item_id: Optional[int] = None, + stock_in_line_id: Optional[int] = None, + lot_no: Optional[str] = None, + font_regular: str = "E:STXihei.ttf", + font_bold: str = "E:STXihei.ttf", +) -> str: + """ + Row 1 (from zero): QR code, then item name (rotated 90°). + Row 2: Batch/lot (left), item code (right). + Label and QR use lotNo from API when present, else batch_no (Bxxxxx). + """ + desc = _zpl_escape((item_name or "—").strip()) + code = _zpl_escape((item_code or "—").strip()) + label_line = (lot_no or batch_no or "").strip() + label_esc = _zpl_escape(label_line) + # QR payload: prefer JSON {"itemId":..., "stockInLineId":...} when both present; else fall back to lot/batch text + if item_id is not None and stock_in_line_id is not None: + qr_payload = json.dumps({"itemId": item_id, "stockInLineId": stock_in_line_id}) + else: + qr_payload = label_line if label_line else batch_no.strip() + qr_value = _zpl_escape(qr_payload) + return f"""^XA +^CI28 +^PW700 +^LL500 +^PO N +^FO10,20 +^BQN,2,4^FDQA,{qr_value}^FS +^FO170,20 +^A@R,72,72,{font_regular}^FD{desc}^FS +^FO0,200 +^A@R,72,72,{font_regular}^FD{label_esc}^FS +^FO55,200 +^A@R,88,88,{font_bold}^FD{code}^FS +^XZ""" + + +def generate_zpl_label_small( + batch_no: str, + item_code: str, + item_name: str, + item_id: Optional[int] = None, + stock_in_line_id: Optional[int] = None, + lot_no: Optional[str] = None, + font: str = "MingLiUHKSCS", +) -> str: + """ + ZPL for 標簽機. Row 1: item name. Row 2: QR left | item code + lot no (or batch) right. + QR contains {"itemId": xxx, "stockInLineId": xxx} when both present; else batch_no. + Unicode (^CI28); font set for Big-5 (e.g. MingLiUHKSCS). + """ + desc = _zpl_escape((item_name or "—").strip()) + code = _zpl_escape((item_code or "—").strip()) + label_line2 = (lot_no or batch_no or "—").strip() + label_line2_esc = _zpl_escape(label_line2) + if item_id is not None and stock_in_line_id is not None: + qr_data = _zpl_escape(json.dumps({"itemId": item_id, "stockInLineId": stock_in_line_id})) + else: + qr_data = f"QA,{batch_no}" + return f"""^XA +^CI28 +^PW500 +^LL500 +^FO10,15 +^FB480,3,0,L,0 +^A@N,38,38,{font}^FD{desc}^FS +^FO10,110 +^BQN,2,6^FD{qr_data}^FS +^FO150,110 +^A@N,48,48,{font}^FD{code}^FS +^FO150,175 +^A@N,40,40,{font}^FD{label_line2_esc}^FS +^XZ""" + + +# Label image size (pixels) for 標簽機 image printing. +# Enlarged for readability (approx +90% scale). +LABEL_IMAGE_W = 720 +LABEL_IMAGE_H = 530 +LABEL_PADDING = 23 +LABEL_FONT_NAME_SIZE = 42 +LABEL_FONT_CODE_SIZE = 49 +LABEL_FONT_BATCH_SIZE = 34 +LABEL_QR_SIZE = 210 + + +def _get_chinese_font(size: int) -> Optional["ImageFont.FreeTypeFont"]: + """Return a Chinese-capable font for PIL, or None to use default.""" + if ImageFont is None: + return None + # Prefer real font files on Windows (font *names* may fail and silently fallback). + if os.name == "nt": + fonts_dir = os.path.join(os.environ.get("WINDIR", r"C:\Windows"), "Fonts") + for rel in ( + "msjh.ttc", # Microsoft JhengHei + "msjhl.ttc", # Microsoft JhengHei Light + "msjhbd.ttc", # Microsoft JhengHei Bold + "mingliu.ttc", + "mingliub.ttc", + "kaiu.ttf", + "msyh.ttc", # Microsoft YaHei + "msyhbd.ttc", + "simhei.ttf", + "simsun.ttc", + ): + p = os.path.join(fonts_dir, rel) + try: + if os.path.exists(p): + return ImageFont.truetype(p, size) + except (OSError, IOError): + continue + # Fallback: try common font names (may still work depending on Pillow build) + for name in ( + "Microsoft JhengHei UI", + "Microsoft JhengHei", + "MingLiU", + "MingLiU_HKSCS", + "Microsoft YaHei", + "SimHei", + "SimSun", + ): + try: + return ImageFont.truetype(name, size) + except (OSError, IOError): + continue + try: + return ImageFont.load_default() + except Exception: + return None + + +def render_label_to_image( + batch_no: str, + item_code: str, + item_name: str, + item_id: Optional[int] = None, + stock_in_line_id: Optional[int] = None, + lot_no: Optional[str] = None, +) -> "Image.Image": + """ + Render 標簽機 label as a PIL Image (white bg, black text + QR). + Use this image for printing so Chinese displays correctly; words are drawn bigger. + Requires Pillow and qrcode. Raises RuntimeError if not available. + """ + if not _HAS_PIL_QR or Image is None or qrcode is None: + raise RuntimeError("Pillow and qrcode are required for image labels. Run: pip install Pillow qrcode[pil]") + img = Image.new("RGB", (LABEL_IMAGE_W, LABEL_IMAGE_H), "white") + draw = ImageDraw.Draw(img) + # QR payload (same as ZPL) + if item_id is not None and stock_in_line_id is not None: + qr_data = json.dumps({"itemId": item_id, "stockInLineId": stock_in_line_id}) + else: + qr_data = f"QA,{batch_no}" + # Draw QR top-left area + qr = qrcode.QRCode(box_size=4, border=2) + qr.add_data(qr_data) + qr.make(fit=True) + qr_img = qr.make_image(fill_color="black", back_color="white") + _resample = getattr(Image, "Resampling", Image).NEAREST + qr_img = qr_img.resize((LABEL_QR_SIZE, LABEL_QR_SIZE), _resample) + img.paste(qr_img, (LABEL_PADDING, LABEL_PADDING)) + # Fonts (bigger for readability) + font_name = _get_chinese_font(LABEL_FONT_NAME_SIZE) + font_code = _get_chinese_font(LABEL_FONT_CODE_SIZE) + font_batch = _get_chinese_font(LABEL_FONT_BATCH_SIZE) + x_right = LABEL_PADDING + LABEL_QR_SIZE + LABEL_PADDING + y_line = LABEL_PADDING + # Line 1: item name (wrap within remaining width) + name_str = (item_name or "—").strip() + max_name_w = LABEL_IMAGE_W - x_right - LABEL_PADDING + if font_name: + # Wrap rule: after 7 "words" (excl. parentheses). ()() not counted; +=*/. and A–Z/a–z count as 0.5. + def _wrap_text(text: str, font, max_width: int) -> list: + ignore = set("()()") + half = set("+=*/.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") + max_count = 6.5 + lines: list[str] = [] + current: list[str] = [] + count = 0.0 + + for ch in text: + if ch == "\n": + lines.append("".join(current).strip()) + current = [] + count = 0.0 + continue + + ch_count = 0.0 if ch in ignore else (0.5 if ch in half else 1.0) + if count + ch_count > max_count and current: + lines.append("".join(current).strip()) + current = [] + count = 0.0 + + current.append(ch) + count += ch_count + + if current: + lines.append("".join(current).strip()) + + # Max 2 rows for item name. If still long, keep everything in row 2. + if len(lines) > 2: + lines = [lines[0], "".join(lines[1:]).strip()] + + # Safety: if any line still exceeds pixel width, wrap by width as well. + if hasattr(draw, "textbbox"): + out: list[str] = [] + for ln in lines: + buf: list[str] = [] + for ch in ln: + buf.append(ch) + bbox = draw.textbbox((0, 0), "".join(buf), font=font) + if bbox[2] - bbox[0] > max_width and len(buf) > 1: + out.append("".join(buf[:-1]).strip()) + buf = [buf[-1]] + if buf: + out.append("".join(buf).strip()) + out = [x for x in out if x] + if len(out) > 2: + out = [out[0], "".join(out[1:]).strip()] + return out + + lines = [x for x in lines if x] + if len(lines) > 2: + lines = [lines[0], "".join(lines[1:]).strip()] + return lines + lines = _wrap_text(name_str, font_name, max_name_w) + for i, ln in enumerate(lines): + draw.text((x_right, y_line + i * (LABEL_FONT_NAME_SIZE + 4)), ln, font=font_name, fill="black") + y_line += len(lines) * (LABEL_FONT_NAME_SIZE + 4) + 8 + else: + draw.text((x_right, y_line), name_str[:30], fill="black") + y_line += LABEL_FONT_NAME_SIZE + 12 + # Item code (bigger) + code_str = (item_code or "—").strip() + if font_code: + draw.text((x_right, y_line), code_str, font=font_code, fill="black") + else: + draw.text((x_right, y_line), code_str, fill="black") + y_line += LABEL_FONT_CODE_SIZE + 6 + # Batch/lot line + batch_str = (lot_no or batch_no or "—").strip() + if font_batch: + draw.text((x_right, y_line), batch_str, font=font_batch, fill="black") + else: + draw.text((x_right, y_line), batch_str, fill="black") + return img + + +def _image_to_zpl_gfa(pil_image: "Image.Image") -> str: + """ + Convert a PIL image into ZPL ^GFA (ASCII hex) so we can print Chinese reliably + on ZPL printers (USB/Windows printer or COM) without relying on GDI drivers. + """ + if Image is None or ImageOps is None: + raise RuntimeError("Pillow is required for image-to-ZPL conversion.") + # Convert to 1-bit monochrome bitmap. Invert so '1' bits represent black in ZPL. + img_bw = ImageOps.invert(pil_image.convert("L")).convert("1") + w, h = img_bw.size + bytes_per_row = (w + 7) // 8 + raw = img_bw.tobytes() + total = bytes_per_row * h + # Ensure length matches expected (Pillow should already pack per row). + if len(raw) != total: + raw = raw[:total].ljust(total, b"\x00") + hex_data = raw.hex().upper() + return f"""^XA +^PW{w} +^LL{h} +^FO0,0 +^GFA,{total},{total},{bytes_per_row},{hex_data} +^FS +^XZ""" + + +def send_image_to_label_printer(printer_name: str, pil_image: "Image.Image") -> None: + """ + Send a PIL Image to 標簽機 via Windows GDI (so Chinese and graphics print correctly). + Only supported when target is a Windows printer name (not COM port). Requires pywin32. + """ + dest = (printer_name or "").strip() + if not dest: + raise ValueError("Label printer destination is empty.") + if os.name != "nt" or dest.upper().startswith("COM"): + raise RuntimeError("Image printing is only supported for a Windows printer name (e.g. TSC TTP-246M Pro).") + if win32print is None or win32ui is None or win32con is None or win32gui is None: + raise RuntimeError("pywin32 is required. Run: pip install pywin32") + dc = win32ui.CreateDC() + dc.CreatePrinterDC(dest) + dc.StartDoc("FPSMS Label") + dc.StartPage() + try: + bmp_w = pil_image.width + bmp_h = pil_image.height + # Scale-to-fit printable area (important for smaller physical labels). + try: + page_w = int(dc.GetDeviceCaps(win32con.HORZRES)) + page_h = int(dc.GetDeviceCaps(win32con.VERTRES)) + except Exception: + page_w, page_h = bmp_w, bmp_h + if page_w <= 0 or page_h <= 0: + page_w, page_h = bmp_w, bmp_h + scale = min(page_w / max(1, bmp_w), page_h / max(1, bmp_h)) + out_w = max(1, int(bmp_w * scale)) + out_h = max(1, int(bmp_h * scale)) + x0 = max(0, (page_w - out_w) // 2) + y0 = max(0, (page_h - out_h) // 2) + + # Most reliable: render via Pillow ImageWin directly to printer DC. + if ImageWin is not None: + dib = ImageWin.Dib(pil_image.convert("RGB")) + dib.draw(dc.GetHandleOutput(), (x0, y0, x0 + out_w, y0 + out_h)) + else: + # Fallback: Draw image to printer DC via temp BMP (GDI uses BMP) + with tempfile.NamedTemporaryFile(suffix=".bmp", delete=False) as f: + tmp_bmp = f.name + try: + pil_image.save(tmp_bmp, "BMP") + hbm = win32gui.LoadImage( + 0, tmp_bmp, win32con.IMAGE_BITMAP, 0, 0, + win32con.LR_LOADFROMFILE | win32con.LR_CREATEDIBSECTION, + ) + if hbm == 0: + raise RuntimeError("Failed to load label image as bitmap.") + try: + mem_dc = win32ui.CreateDCFromHandle(win32gui.CreateCompatibleDC(dc.GetSafeHdc())) + bmp = getattr(win32ui, "CreateBitmapFromHandle", lambda h: win32ui.PyCBitmap.FromHandle(h))(hbm) + mem_dc.SelectObject(bmp) + dc.StretchBlt((x0, y0), (out_w, out_h), mem_dc, (0, 0), (bmp_w, bmp_h), win32con.SRCCOPY) + finally: + win32gui.DeleteObject(hbm) + finally: + try: + os.unlink(tmp_bmp) + except OSError: + pass + finally: + dc.EndPage() + dc.EndDoc() + + +def send_zpl_to_dataflex(ip: str, port: int, zpl: str) -> None: + """Send ZPL to DataFlex printer via TCP. Raises on connection/send error.""" + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.settimeout(DATAFLEX_SEND_TIMEOUT) + try: + sock.connect((ip, port)) + sock.sendall(zpl.encode("utf-8")) + finally: + sock.close() + + +def send_zpl_to_label_printer(target: str, zpl: str) -> None: + """ + Send ZPL to 標簽機. + + On Windows, if target is not a COM port (e.g. "TSC TTP-246M Pro"), + send raw ZPL to the named Windows printer via the spooler. + Otherwise, treat target as a serial COM port (original behaviour). + """ + dest = (target or "").strip() + if not dest: + raise ValueError("Label printer destination is empty.") + + # Unicode (^CI28); send UTF-8 to 標簽機 + raw_bytes = zpl.encode("utf-8") + + # Windows printer name path (USB printer installed as normal printer) + if os.name == "nt" and not dest.upper().startswith("COM"): + if win32print is None: + raise RuntimeError("pywin32 not installed. Run: pip install pywin32") + handle = win32print.OpenPrinter(dest) + try: + job = win32print.StartDocPrinter(handle, 1, ("FPSMS Label", None, "RAW")) + win32print.StartPagePrinter(handle) + win32print.WritePrinter(handle, raw_bytes) + win32print.EndPagePrinter(handle) + win32print.EndDocPrinter(handle) + finally: + win32print.ClosePrinter(handle) + return + + # Fallback: serial COM port + if serial is None: + raise RuntimeError("pyserial not installed. Run: pip install pyserial") + ser = serial.Serial(dest, timeout=5) + try: + ser.write(raw_bytes) + finally: + ser.close() + + +def load_laser_last_count() -> tuple[int, Optional[str]]: + """Load last batch count and date from laser counter file. Returns (count, date_str).""" + if not os.path.exists(LASER_COUNTER_FILE): + return 0, None + try: + with open(LASER_COUNTER_FILE, "r", encoding="utf-8") as f: + lines = f.read().strip().splitlines() + if len(lines) >= 2: + return int(lines[1].strip()), lines[0].strip() + except Exception: + pass + return 0, None + + +def save_laser_last_count(date_str: str, count: int) -> None: + """Save laser batch count and date to file.""" + try: + with open(LASER_COUNTER_FILE, "w", encoding="utf-8") as f: + f.write(f"{date_str}\n{count}") + except Exception: + pass + + +LASER_PUSH_INTERVAL = 2 # seconds between pushes (like sample script) +# Click row with 激光機 selected: send this many times, delay between sends (not after last). +LASER_ROW_SEND_COUNT = 3 +LASER_ROW_SEND_DELAY_SEC = 3 + + +def laser_push_loop( + ip: str, + port: int, + stop_event: threading.Event, + root: tk.Tk, + on_error: Callable[[str], None], +) -> None: + """ + Run in a background thread: persistent connection to EZCAD, push B{yymmdd}{count:03d};; + every LASER_PUSH_INTERVAL seconds. Resets count each new day. Uses counter file. + """ + conn = None + push_count, last_saved_date = load_laser_last_count() + while not stop_event.is_set(): + try: + if conn is None: + conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + conn.settimeout(0.4) + conn.connect((ip, port)) + now = datetime.now() + today_str = now.strftime("%y%m%d") + if last_saved_date != today_str: + push_count = 1 + last_saved_date = today_str + batch = f"B{today_str}{push_count:03d}" + reply = f"{batch};;" + conn.sendall(reply.encode("utf-8")) + save_laser_last_count(today_str, push_count) + rlist, _, _ = select.select([conn], [], [], 0.4) + if rlist: + data = conn.recv(4096) + if not data: + conn.close() + conn = None + push_count += 1 + for _ in range(int(LASER_PUSH_INTERVAL * 2)): + if stop_event.is_set(): + break + time.sleep(0.5) + except socket.timeout: + pass + except Exception as e: + if conn: + try: + conn.close() + except Exception: + pass + conn = None + try: + root.after(0, lambda msg=str(e): on_error(msg)) + except Exception: + pass + for _ in range(6): + if stop_event.is_set(): + break + time.sleep(0.5) + if conn: + try: + conn.close() + except Exception: + pass + + +def send_job_to_laser( + conn_ref: list, + ip: str, + port: int, + item_id: Optional[int], + stock_in_line_id: Optional[int], + item_code: str, + item_name: str, +) -> tuple[bool, str]: + """ + Send to laser using `;` separated 3 params: + {"itemID": itemId, "stockInLineId": stockInLineId} ; itemCode ; itemName ;; + conn_ref: [socket or None] - reused across calls; closed only when switching printer. + When both item_id and stock_in_line_id present, sends JSON first param; else fallback: 0;item_code;item_name;; + Returns (success, message). + """ + code_str = (item_code or "").strip().replace(";", ",") + name_str = (item_name or "").strip().replace(";", ",") + + if item_id is not None and stock_in_line_id is not None: + # Use compact JSON so device-side parser doesn't get spaces. + json_part = json.dumps( + {"itemID": item_id, "stockInLineId": stock_in_line_id}, + separators=(",", ":"), + ) + reply = f"{json_part};{code_str};{name_str};;" + else: + reply = f"0;{code_str};{name_str};;" + conn = conn_ref[0] + try: + if conn is None: + conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + conn.settimeout(3.0) + conn.connect((ip, port)) + conn_ref[0] = conn + conn.settimeout(3.0) + conn.sendall(reply.encode("utf-8")) + conn.settimeout(0.5) + try: + data = conn.recv(4096) + if data: + ack = data.decode("utf-8", errors="ignore").strip().lower() + if "receive" in ack and "invalid" not in ack: + return True, f"已送出激光機:{reply}(已確認)" + except socket.timeout: + pass + return True, f"已送出激光機:{reply}" + except (ConnectionRefusedError, socket.timeout, OSError) as e: + if conn_ref[0] is not None: + try: + conn_ref[0].close() + except Exception: + pass + conn_ref[0] = None + if isinstance(e, ConnectionRefusedError): + return False, f"無法連線至 {ip}:{port},請確認激光機已開機且 IP 正確。" + if isinstance(e, socket.timeout): + return False, f"連線逾時 ({ip}:{port}),請檢查網路與連接埠。" + return False, f"激光機送出失敗:{e}" + + +def send_job_to_laser_with_retry( + conn_ref: list, + ip: str, + port: int, + item_id: Optional[int], + stock_in_line_id: Optional[int], + item_code: str, + item_name: str, +) -> tuple[bool, str]: + """Send job to laser; on failure, retry once. Returns (success, message).""" + ok, msg = send_job_to_laser(conn_ref, ip, port, item_id, stock_in_line_id, item_code, item_name) + if ok: + return True, msg + ok2, msg2 = send_job_to_laser(conn_ref, ip, port, item_id, stock_in_line_id, item_code, item_name) + return ok2, msg2 + + +def run_laser_row_send_thread( + root: tk.Tk, + laser_conn_ref: list, + laser_busy_ref: list, + ip: str, + port: int, + item_id: Optional[int], + stock_in_line_id: Optional[int], + item_code: str, + item_name: str, + set_status_message: Callable[[str, bool], None], + base_url: Optional[str] = None, + job_order_id: Optional[int] = None, + on_recorded: Optional[Callable[[], None]] = None, +) -> None: + """ + On row click with 激光機: send LASER_ROW_SEND_COUNT times with LASER_ROW_SEND_DELAY_SEC between sends. + UI updates on main thread; work runs in background so the window does not freeze. + After success, POST LASER qty to API when job_order_id and base_url are set. + """ + if laser_busy_ref[0]: + return + laser_busy_ref[0] = True + + def worker() -> None: + try: + n = LASER_ROW_SEND_COUNT + for i in range(n): + ok, msg = send_job_to_laser_with_retry( + laser_conn_ref, + ip, + port, + item_id, + stock_in_line_id, + item_code, + item_name, + ) + if not ok: + root.after( + 0, + lambda m=msg: messagebox.showwarning("激光機", m), + ) + return + if i < n - 1: + time.sleep(LASER_ROW_SEND_DELAY_SEC) + posted = False + if base_url and job_order_id is not None: + try: + submit_job_order_print_submit(base_url, int(job_order_id), n, "LASER") + posted = True + except requests.RequestException as ex: + root.after( + 0, + lambda err=str(ex): messagebox.showwarning( + "激光機", + f"已發送,但伺服器記錄失敗:{err}", + ), + ) + root.after( + 0, + lambda: set_status_message("已發送", is_error=False), + ) + if on_recorded is not None and posted: + root.after(0, on_recorded) + except Exception as e: + root.after( + 0, + lambda err=str(e): messagebox.showwarning("激光機", f"送出失敗:{err}"), + ) + finally: + laser_busy_ref[0] = False + + threading.Thread(target=worker, daemon=True).start() + + +def _printed_qty_int(raw) -> int: + """Parse API printed qty field (may be float JSON) to int.""" + try: + return int(float(raw)) if raw is not None else 0 + except (TypeError, ValueError): + return 0 + + +def _filter_job_orders_by_search(data: list, needle: str) -> list: + """Substring match on item code, job order code, item name, lot (case-insensitive).""" + n = needle.strip().lower() + if not n: + return data + out: list = [] + for jo in data: + parts = [ + str(jo.get("itemCode") or ""), + str(jo.get("code") or ""), + str(jo.get("itemName") or ""), + str(jo.get("lotNo") or ""), + ] + if any(n in p.lower() for p in parts): + out.append(jo) + return out + + +def format_qty(val) -> str: + """Format quantity: integer without .0, with thousand separator.""" + if val is None: + return "—" + try: + n = float(val) + if n == int(n): + return f"{int(n):,}" + return f"{n:,.2f}".rstrip("0").rstrip(".") + except (TypeError, ValueError): + return str(val) + + +def batch_no(year: int, job_order_id: int) -> str: + """Batch no.: B + 4-digit year + jobOrderId zero-padded to 6 digits.""" + return f"B{year}{job_order_id:06d}" + + +def get_font(size: int = FONT_SIZE, bold: bool = False) -> tuple: + try: + return (FONT_FAMILY, size, "bold" if bold else "normal") + except Exception: + return ("TkDefaultFont", size, "bold" if bold else "normal") + + +def fetch_job_orders(base_url: str, plan_start: date) -> list: + """Call GET /py/job-orders and return the JSON list.""" + url = f"{base_url.rstrip('/')}/py/job-orders" + params = {"planStart": plan_start.isoformat()} + resp = requests.get(url, params=params, timeout=30) + resp.raise_for_status() + return resp.json() + + +def submit_job_order_print_submit( + base_url: str, + job_order_id: int, + qty: int, + print_channel: str = "LABEL", +) -> None: + """POST /py/job-order-print-submit — one row per submit for DB wastage/stock tracking.""" + url = f"{base_url.rstrip('/')}/py/job-order-print-submit" + resp = requests.post( + url, + json={"jobOrderId": job_order_id, "qty": qty, "printChannel": print_channel}, + timeout=30, + ) + resp.raise_for_status() + + +def set_row_highlight(row_frame: tk.Frame, selected: bool) -> None: + """Set row and all nested Frame/Label children to selected or normal background.""" + bg = BG_ROW_SELECTED if selected else BG_ROW + + def _paint(w: tk.Misc) -> None: + if isinstance(w, (tk.Frame, tk.Label)): + w.configure(bg=bg) + for c in w.winfo_children(): + _paint(c) + + _paint(row_frame) + + +def on_job_order_click(jo: dict, batch: str) -> None: + """Show message and highlight row (keeps printing to selected printer).""" + item_code = jo.get("itemCode") or "—" + item_name = jo.get("itemName") or "—" + messagebox.showinfo( + "工單", + f'已點選:批次 {batch}\n品號 {item_code} {item_name}', + ) + + +def ask_label_count(parent: tk.Tk) -> Optional[int]: + """ + When printer is 標簽機, ask how many labels to print: + optional direct qty in text field, +50/+10/+5/+1, 重置, then 確認送出. + Returns count (>= 1), or None if cancelled. + """ + result: list[Optional[int]] = [None] + qty_var = tk.StringVar(value="0") + + win = tk.Toplevel(parent) + win.title("標簽印數") + win.geometry("580x280") + win.transient(parent) + win.grab_set() + win.configure(bg=BG_TOP) + ttk.Label(win, text="印多少個?", font=get_font(FONT_SIZE)).pack(pady=(12, 4)) + + entry_row = tk.Frame(win, bg=BG_TOP) + entry_row.pack(pady=8) + tk.Label(entry_row, text="需求數量:", font=get_font(FONT_SIZE), bg=BG_TOP).pack(side=tk.LEFT, padx=(0, 6)) + qty_entry = tk.Entry( + entry_row, + textvariable=qty_var, + width=12, + font=get_font(FONT_SIZE), + bg="white", + justify=tk.RIGHT, + ) + qty_entry.pack(side=tk.LEFT, padx=4) + + def current_qty() -> int: + s = (qty_var.get() or "").strip().replace(",", "") + if not s: + return 0 + try: + return max(0, int(s)) + except ValueError: + return 0 + + def reset_qty() -> None: + qty_var.set("0") + + ttk.Button(entry_row, text="重置", command=reset_qty, width=8).pack(side=tk.LEFT, padx=8) + + def add(n: int) -> None: + qty_var.set(str(current_qty() + n)) + + def confirm() -> None: + q = current_qty() + if q < 1: + messagebox.showwarning("標簽機", "請輸入需求數量或按 +50、+10、+5、+1。", parent=win) + return + result[0] = q + win.destroy() + + btn_row1 = tk.Frame(win, bg=BG_TOP) + btn_row1.pack(pady=8) + for label, value in [("+50", 50), ("+10", 10), ("+5", 5), ("+1", 1)]: + def make_add(v: int): + return lambda: add(v) + ttk.Button(btn_row1, text=label, command=make_add(value), width=8).pack(side=tk.LEFT, padx=4) + + ttk.Button(win, text="確認送出", command=confirm, width=14).pack(pady=12) + qty_entry.bind("", lambda e: confirm()) + win.protocol("WM_DELETE_WINDOW", win.destroy) + win.wait_window() + return result[0] + +def ask_bag_count(parent: tk.Tk) -> Optional[int]: + """ + When printer is 打袋機 DataFlex, ask how many bags: + optional direct qty in text field, +50/+10/+5/+1, 重置, then 確認送出. + Returns count (>= 1), or None if cancelled. + """ + result: list[Optional[int]] = [None] + qty_var = tk.StringVar(value="0") + + win = tk.Toplevel(parent) + win.title("打袋列印數量") + win.geometry("580x280") + win.transient(parent) + win.grab_set() + win.configure(bg=BG_TOP) + ttk.Label(win, text="列印多少個袋?", font=get_font(FONT_SIZE)).pack(pady=(12, 4)) + + entry_row = tk.Frame(win, bg=BG_TOP) + entry_row.pack(pady=8) + tk.Label(entry_row, text="需求數量:", font=get_font(FONT_SIZE), bg=BG_TOP).pack(side=tk.LEFT, padx=(0, 6)) + qty_entry = tk.Entry( + entry_row, + textvariable=qty_var, + width=12, + font=get_font(FONT_SIZE), + bg="white", + justify=tk.RIGHT, + ) + qty_entry.pack(side=tk.LEFT, padx=4) + + def current_qty() -> int: + s = (qty_var.get() or "").strip().replace(",", "") + if not s: + return 0 + try: + return max(0, int(s)) + except ValueError: + return 0 + + def reset_qty() -> None: + qty_var.set("0") + + ttk.Button(entry_row, text="重置", command=reset_qty, width=8).pack(side=tk.LEFT, padx=8) + + def add(n: int) -> None: + qty_var.set(str(current_qty() + n)) + + def confirm() -> None: + q = current_qty() + if q < 1: + messagebox.showwarning("打袋機", "請輸入需求數量或按 +50、+10、+5、+1。", parent=win) + return + result[0] = q + win.destroy() + + btn_row1 = tk.Frame(win, bg=BG_TOP) + btn_row1.pack(pady=8) + for label, value in [("+50", 50), ("+10", 10), ("+5", 5), ("+1", 1)]: + def make_add(v: int): + return lambda: add(v) + ttk.Button(btn_row1, text=label, command=make_add(value), width=8).pack(side=tk.LEFT, padx=4) + + ttk.Button(win, text="確認送出", command=confirm, width=14).pack(pady=12) + qty_entry.bind("", lambda e: confirm()) + win.protocol("WM_DELETE_WINDOW", win.destroy) + win.wait_window() + return result[0] + + +def main() -> None: + settings = load_settings() + base_url_ref = [build_base_url(settings["api_ip"], settings["api_port"])] + + root = tk.Tk() + root.title(f"FP-MTMS Bag3 v{APP_VERSION} 打袋機") + root.geometry("1120x960") + root.minsize(480, 360) + root.configure(bg=BG_ROOT) + + # Style: larger font for aged users; light blue theme + style = ttk.Style() + try: + style.configure(".", font=get_font(FONT_SIZE), background=BG_TOP) + style.configure("TButton", font=get_font(FONT_SIZE_BUTTONS), background=BG_TOP) + style.configure("TLabel", font=get_font(FONT_SIZE), background=BG_TOP) + style.configure("TEntry", font=get_font(FONT_SIZE)) + style.configure("TFrame", background=BG_TOP) + # TCombobox field (if other combos use ttk later) + style.configure("TCombobox", font=get_font(FONT_SIZE_COMBO)) + except tk.TclError: + pass + + # Status bar at top: connection state (no popup on error) + status_frame = tk.Frame(root, bg=BG_STATUS_ERROR, padx=12, pady=6) + status_frame.pack(fill=tk.X) + status_lbl = tk.Label( + status_frame, + text="連接不到服務器", + font=get_font(FONT_SIZE_BUTTONS), + bg=BG_STATUS_ERROR, + fg=FG_STATUS_ERROR, + anchor=tk.CENTER, + ) + status_lbl.pack(fill=tk.X) + + def set_status_ok(): + status_frame.configure(bg=BG_STATUS_OK) + status_lbl.configure(text="連接正常", bg=BG_STATUS_OK, fg=FG_STATUS_OK) + + def set_status_error(): + status_frame.configure(bg=BG_STATUS_ERROR) + status_lbl.configure(text="連接不到服務器", bg=BG_STATUS_ERROR, fg=FG_STATUS_ERROR) + + def set_status_message(msg: str, is_error: bool = False) -> None: + """Show a message on the status bar.""" + if is_error: + status_frame.configure(bg=BG_STATUS_ERROR) + status_lbl.configure(text=msg, bg=BG_STATUS_ERROR, fg=FG_STATUS_ERROR) + else: + status_frame.configure(bg=BG_STATUS_OK) + status_lbl.configure(text=msg, bg=BG_STATUS_OK, fg=FG_STATUS_OK) + + # Laser: keep connection open for repeated sends; close when switching away + laser_conn_ref: list = [None] + laser_send_busy_ref: list = [False] + + # Top: left [前一天] [date] [後一天] | right [printer dropdown] + top = tk.Frame(root, padx=12, pady=12, bg=BG_TOP) + top.pack(fill=tk.X) + + date_var = tk.StringVar(value=date.today().isoformat()) + printer_options = ["打袋機 DataFlex", "標簽機", "激光機"] + printer_var = tk.StringVar(value=printer_options[0]) + + def go_prev_day() -> None: + try: + d = date.fromisoformat(date_var.get().strip()) + date_var.set((d - timedelta(days=1)).isoformat()) + load_job_orders(from_user_date_change=True) + except ValueError: + date_var.set(date.today().isoformat()) + load_job_orders(from_user_date_change=True) + + def go_next_day() -> None: + try: + d = date.fromisoformat(date_var.get().strip()) + date_var.set((d + timedelta(days=1)).isoformat()) + load_job_orders(from_user_date_change=True) + except ValueError: + date_var.set(date.today().isoformat()) + load_job_orders(from_user_date_change=True) + + # 前一天 (previous day) with left arrow icon + btn_prev = ttk.Button(top, text="◀ 前一天", command=go_prev_day) + btn_prev.pack(side=tk.LEFT, padx=(0, 8)) + + # Date field (no "日期:" label); shorter width + date_entry = tk.Entry( + top, + textvariable=date_var, + font=get_font(FONT_SIZE), + width=10, + bg="white", + ) + date_entry.pack(side=tk.LEFT, padx=(0, 8), ipady=4) + + # 後一天 (next day) with right arrow icon + btn_next = ttk.Button(top, text="後一天 ▶", command=go_next_day) + btn_next.pack(side=tk.LEFT, padx=(0, 8)) + + # Top right: Setup button + printer selection + right_frame = tk.Frame(top, bg=BG_TOP) + right_frame.pack(side=tk.RIGHT) + ttk.Button(right_frame, text="設定", command=lambda: open_setup_window(root, settings, base_url_ref)).pack( + side=tk.LEFT, padx=(0, 12) + ) + # 列印機 label: green when printer connected, red when not (checked periodically) + printer_status_lbl = tk.Label( + right_frame, + text="列印機:", + font=get_font(FONT_SIZE), + bg=BG_STATUS_ERROR, + fg="black", + padx=6, + pady=2, + ) + printer_status_lbl.pack(side=tk.LEFT, padx=(0, 4)) + # tk.OptionMenu (not ttk.Combobox): on Windows the ttk dropdown uses OS font and stays tiny; + # OptionMenu's menu supports font= for the open list. + printer_combo = tk.OptionMenu(right_frame, printer_var, *printer_options) + _combo_font = get_font(FONT_SIZE_COMBO) + printer_combo.configure( + font=_combo_font, + bg=BG_TOP, + fg="black", + activebackground=BG_TOP, + activeforeground="black", + width=14, + anchor="w", + highlightthickness=0, + bd=1, + relief=tk.GROOVE, + ) + printer_combo["menu"].configure(font=_combo_font, tearoff=0) + printer_combo.pack(side=tk.LEFT) + + printer_after_ref = [None] + + def set_printer_status_ok(): + printer_status_lbl.configure(bg=BG_STATUS_OK, fg=FG_STATUS_OK) + + def set_printer_status_error(): + printer_status_lbl.configure(bg=BG_STATUS_ERROR, fg=FG_STATUS_ERROR) + + def check_printer() -> None: + if printer_after_ref[0] is not None: + root.after_cancel(printer_after_ref[0]) + printer_after_ref[0] = None + ok = try_printer_connection(printer_var.get(), settings) + if ok: + set_printer_status_ok() + printer_after_ref[0] = root.after(PRINTER_CHECK_MS, check_printer) + else: + set_printer_status_error() + printer_after_ref[0] = root.after(PRINTER_RETRY_MS, check_printer) + + def on_printer_selection_changed(*args) -> None: + check_printer() + if printer_var.get() != "激光機": + if laser_conn_ref[0] is not None: + try: + laser_conn_ref[0].close() + except Exception: + pass + laser_conn_ref[0] = None + + printer_var.trace_add("write", on_printer_selection_changed) + + def open_setup_window(parent_win: tk.Tk, sett: dict, base_url_ref_list: list) -> None: + """Modal setup: API IP/port, 打袋機/激光機 IP+port, 標簽機 COM port.""" + d = tk.Toplevel(parent_win) + d.title("設定") + d.geometry("440x520") + d.transient(parent_win) + d.grab_set() + d.configure(bg=BG_TOP) + f = tk.Frame(d, padx=16, pady=16, bg=BG_TOP) + f.pack(fill=tk.BOTH, expand=True) + grid_row = [0] # use list so inner function can update + + def _ensure_dot_in_entry(entry: tk.Entry) -> None: + """Allow typing dot (.) in Entry when IME or layout blocks it (e.g. 192.168.17.27).""" + def on_key(event): + if event.keysym in ("period", "decimal"): + pos = entry.index(tk.INSERT) + entry.insert(tk.INSERT, ".") + return "break" + entry.bind("", on_key) + + def add_section(label_text: str, key_ip: str | None, key_port: str | None, key_single: str | None): + out = [] + ttk.Label(f, text=label_text, font=get_font(FONT_SIZE_BUTTONS)).grid( + row=grid_row[0], column=0, columnspan=2, sticky=tk.W, pady=(8, 2) + ) + grid_row[0] += 1 + if key_single: + ttk.Label( + f, + text="列印機名稱 (Windows):", + ).grid( + row=grid_row[0], + column=0, + sticky=tk.W, + pady=2, + ) + var = tk.StringVar(value=sett.get(key_single, "")) + e = tk.Entry(f, textvariable=var, width=22, font=get_font(FONT_SIZE), bg="white") + e.grid(row=grid_row[0], column=1, sticky=tk.W, pady=2) + _ensure_dot_in_entry(e) + grid_row[0] += 1 + return [(key_single, var)] + if key_ip: + ttk.Label(f, text="IP:").grid(row=grid_row[0], column=0, sticky=tk.W, pady=2) + var_ip = tk.StringVar(value=sett.get(key_ip, "")) + e_ip = tk.Entry(f, textvariable=var_ip, width=22, font=get_font(FONT_SIZE), bg="white") + e_ip.grid(row=grid_row[0], column=1, sticky=tk.W, pady=2) + _ensure_dot_in_entry(e_ip) + grid_row[0] += 1 + out.append((key_ip, var_ip)) + if key_port: + ttk.Label(f, text="Port:").grid(row=grid_row[0], column=0, sticky=tk.W, pady=2) + var_port = tk.StringVar(value=sett.get(key_port, "")) + e_port = tk.Entry(f, textvariable=var_port, width=12, font=get_font(FONT_SIZE), bg="white") + e_port.grid(row=grid_row[0], column=1, sticky=tk.W, pady=2) + _ensure_dot_in_entry(e_port) + grid_row[0] += 1 + out.append((key_port, var_port)) + return out + + all_vars = [] + all_vars.extend(add_section("API 伺服器", "api_ip", "api_port", None)) + all_vars.extend(add_section("打袋機 DataFlex", "dabag_ip", "dabag_port", None)) + all_vars.extend(add_section("激光機", "laser_ip", "laser_port", None)) + all_vars.extend(add_section("標簽機 (USB)", None, None, "label_com")) + + def on_save(): + for key, var in all_vars: + sett[key] = var.get().strip() + save_settings(sett) + base_url_ref_list[0] = build_base_url(sett["api_ip"], sett["api_port"]) + d.destroy() + + btn_f = tk.Frame(d, bg=BG_TOP) + btn_f.pack(pady=12) + ttk.Button(btn_f, text="儲存", command=on_save).pack(side=tk.LEFT, padx=4) + ttk.Button(btn_f, text="取消", command=d.destroy).pack(side=tk.LEFT, padx=4) + d.wait_window() + + job_orders_frame = tk.Frame(root, bg=BG_LIST) + job_orders_frame.pack(fill=tk.BOTH, expand=True, padx=12, pady=12) + + search_var = tk.StringVar() + search_frame = tk.Frame(job_orders_frame, bg=BG_LIST) + search_frame.pack(fill=tk.X, pady=(0, 6)) + tk.Label( + search_frame, + text="搜尋品號/工單/批號:", + font=get_font(FONT_SIZE_QTY), + bg=BG_LIST, + fg="black", + ).pack(side=tk.LEFT, padx=(0, 6)) + search_entry = tk.Entry( + search_frame, + textvariable=search_var, + width=32, + font=get_font(FONT_SIZE_QTY), + bg="white", + ) + search_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 8)) + + # Scrollable area for buttons + canvas = tk.Canvas(job_orders_frame, highlightthickness=0, bg=BG_LIST) + scrollbar = ttk.Scrollbar(job_orders_frame, orient=tk.VERTICAL, command=canvas.yview) + inner = tk.Frame(canvas, bg=BG_LIST) + + win_id = canvas.create_window((0, 0), window=inner, anchor=tk.NW) + canvas.configure(yscrollcommand=scrollbar.set) + + def _on_inner_configure(event): + canvas.configure(scrollregion=canvas.bbox("all")) + + def _on_canvas_configure(event): + canvas.itemconfig(win_id, width=event.width) + + inner.bind("", _on_inner_configure) + canvas.bind("", _on_canvas_configure) + + # Mouse wheel: default Tk scroll speed (one unit per notch) + def _on_mousewheel(event): + if getattr(event, "delta", None) is not None: + canvas.yview_scroll(int(-1 * (event.delta / 120)), "units") + elif event.num == 5: + canvas.yview_scroll(1, "units") + elif event.num == 4: + canvas.yview_scroll(-1, "units") + + canvas.bind("", _on_mousewheel) + inner.bind("", _on_mousewheel) + canvas.bind("", _on_mousewheel) + canvas.bind("", _on_mousewheel) + inner.bind("", _on_mousewheel) + inner.bind("", _on_mousewheel) + + scrollbar.pack(side=tk.RIGHT, fill=tk.Y) + canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) + + # Track which row is highlighted (selected for printing) and which job id + selected_row_holder = [None] # [tk.Frame | None] + selected_jo_id_ref = [None] # [int | None] job order id for selection preservation + last_data_ref = [None] # [list | None] last successful fetch for current date + last_plan_start_ref = [date.today()] # plan date for the current list (search filter uses same) + after_id_ref = [None] # [str | None] root.after id to cancel retry/refresh + + def _data_equal(a: Optional[list], b: Optional[list]) -> bool: + if a is None or b is None: + return a is b + if len(a) != len(b): + return False + for x, y in zip(a, b): + if x.get("id") != y.get("id"): + return False + for k in ("bagPrintedQty", "labelPrintedQty", "laserPrintedQty"): + if x.get(k) != y.get(k): + return False + return True + + def _build_list_from_data(data: list, plan_start: date, preserve_selection: bool) -> None: + selected_row_holder[0] = None + year = plan_start.year + selected_id = selected_jo_id_ref[0] if preserve_selection else None + found_row = None + for jo in data: + jo_id = jo.get("id") + raw_batch = batch_no(year, jo_id) if jo_id is not None else "—" + lot_no_val = jo.get("lotNo") + batch = (lot_no_val or "—").strip() if lot_no_val else "—" + jo_no_display = (jo.get("code") or "").strip() + if not jo_no_display and jo_id is not None: + jo_no_display = raw_batch + elif not jo_no_display: + jo_no_display = "—" + # Line 1: job order no.; line 2: 需求 + 已印(袋/標/激)on one row for compact scrolling + head_line = f"工單:{jo_no_display}" + item_code = jo.get("itemCode") or "—" + item_name = jo.get("itemName") or "—" + req_qty = jo.get("reqQty") + qty_str = format_qty(req_qty) + bag_pq = _printed_qty_int(jo.get("bagPrintedQty")) + label_pq = _printed_qty_int(jo.get("labelPrintedQty")) + laser_pq = _printed_qty_int(jo.get("laserPrintedQty")) + meta_line = ( + f"需求:{qty_str} " + f"已印 袋{bag_pq:,} 標{label_pq:,} 激{laser_pq:,}" + ) + # Columns: fixed-width left | fixed-width 品號 | 品名 (expand) + row = tk.Frame( + inner, + bg=BG_ROW, + relief=tk.RAISED, + bd=2, + cursor="hand2", + padx=10, + pady=LIST_ROW_IPADY, + ) + row.pack(fill=tk.X, pady=LIST_ROW_PADY) + + left = tk.Frame(row, bg=BG_ROW, width=LEFT_COL_WIDTH_PX) + left.pack_propagate(False) + left.pack(side=tk.LEFT, anchor=tk.NW, fill=tk.Y) + batch_lbl = tk.Label( + left, + text=head_line, + font=get_font(FONT_SIZE_BUTTONS), + bg=BG_ROW, + fg="black", + ) + batch_lbl.pack(anchor=tk.W) + meta_lbl = tk.Label( + left, + text=meta_line, + font=get_font(FONT_SIZE_META), + bg=BG_ROW, + fg="#222222", + anchor=tk.W, + justify=tk.LEFT, + wraplength=LEFT_COL_WIDTH_PX - 8, + ) + meta_lbl.pack(anchor=tk.W) + + code_col = tk.Frame(row, bg=BG_ROW, width=CODE_COL_WIDTH_PX) + code_col.pack_propagate(False) + code_col.pack(side=tk.LEFT, anchor=tk.NW, fill=tk.Y, padx=(6, 2)) + code_lbl = tk.Label( + code_col, + text=item_code, + font=get_font(FONT_SIZE_ITEM_CODE), + bg=BG_ROW, + fg="black", + wraplength=ITEM_CODE_WRAP, + justify=tk.LEFT, + anchor=tk.NW, + ) + code_lbl.pack(anchor=tk.NW) + + name_col = tk.Frame(row, bg=BG_ROW) + name_col.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, anchor=tk.NW) + name_lbl = tk.Label( + name_col, + text=item_name or "—", + font=get_font(FONT_SIZE_ITEM_NAME), + bg=BG_ROW, + fg="black", + wraplength=ITEM_NAME_WRAP, + justify=tk.LEFT, + anchor=tk.NW, + ) + name_lbl.pack(anchor=tk.NW) + + def _on_click(e, j=jo, b=batch, r=row): + if selected_row_holder[0] is not None: + set_row_highlight(selected_row_holder[0], False) + set_row_highlight(r, True) + selected_row_holder[0] = r + selected_jo_id_ref[0] = j.get("id") + if printer_var.get() == "打袋機 DataFlex": + ip = (settings.get("dabag_ip") or "").strip() + port_str = (settings.get("dabag_port") or "3008").strip() + try: + port = int(port_str) + except ValueError: + port = 3008 + if not ip: + messagebox.showerror("打袋機", "請在設定中填寫打袋機 DataFlex 的 IP。") + else: + count = ask_bag_count(root) + if count is not None: + item_code = j.get("itemCode") or "—" + item_name = j.get("itemName") or "—" + item_id = j.get("itemId") + stock_in_line_id = j.get("stockInLineId") + lot_no = j.get("lotNo") + zpl = generate_zpl_dataflex( + b, + item_code, + item_name, + item_id=item_id, + stock_in_line_id=stock_in_line_id, + lot_no=lot_no, + ) + label_text = (lot_no or b).strip() + n = count + try: + for i in range(n): + send_zpl_to_dataflex(ip, port, zpl) + if i < n - 1: + time.sleep(2) + set_status_message(f"已送出列印:批次 {label_text} x {n} 張", is_error=False) + jo_id = j.get("id") + if jo_id is not None: + try: + submit_job_order_print_submit( + base_url_ref[0], int(jo_id), n, "DATAFLEX" + ) + load_job_orders(from_user_date_change=False) + except requests.RequestException as ex: + messagebox.showwarning( + "打袋機", + f"已送出 {n} 張,但伺服器記錄失敗:{ex}", + ) + except ConnectionRefusedError: + set_status_message(f"無法連線至 {ip}:{port},請確認印表機已開機且 IP 正確。", is_error=True) + except socket.timeout: + set_status_message(f"連線逾時 ({ip}:{port}),請檢查網路與連接埠。", is_error=True) + except OSError as err: + set_status_message(f"列印失敗:{err}", is_error=True) + elif printer_var.get() == "標簽機": + com = (settings.get("label_com") or "").strip() + if not com: + messagebox.showerror("標簽機", "請在設定中填寫標簽機名稱 (例如:TSC TTP-246M Pro)。") + else: + count = ask_label_count(root) + if count is not None: + item_code = j.get("itemCode") or "—" + item_name = j.get("itemName") or "—" + item_id = j.get("itemId") + stock_in_line_id = j.get("stockInLineId") + lot_no = j.get("lotNo") + n = count + try: + # Always render to image (Chinese OK), then send as ZPL graphic (^GFA). + # This is more reliable than Windows GDI and works for both Windows printer name and COM. + if not _HAS_PIL_QR: + raise RuntimeError("請先安裝 Pillow + qrcode(pip install Pillow qrcode[pil])。") + label_img = render_label_to_image( + b, item_code, item_name, + item_id=item_id, stock_in_line_id=stock_in_line_id, + lot_no=lot_no, + ) + zpl_img = _image_to_zpl_gfa(label_img) + for i in range(n): + send_zpl_to_label_printer(com, zpl_img) + if i < n - 1: + time.sleep(0.5) + jo_id = j.get("id") + if jo_id is not None: + try: + submit_job_order_print_submit( + base_url_ref[0], int(jo_id), n, "LABEL" + ) + load_job_orders(from_user_date_change=False) + messagebox.showinfo( + "標籤機", + f"已送出列印:{n} 張標籤(已記錄)", + ) + except requests.RequestException as ex: + messagebox.showwarning( + "標籤機", + f"標籤已列印 {n} 張,但伺服器記錄失敗:{ex}", + ) + else: + messagebox.showwarning( + "標籤機", + f"已送出列印:{n} 張標籤(無工單 id,無法寫入伺服器記錄)", + ) + except Exception as err: + messagebox.showerror("標簽機", f"列印失敗:{err}") + elif printer_var.get() == "激光機": + ip = (settings.get("laser_ip") or "").strip() + port_str = (settings.get("laser_port") or "45678").strip() + try: + port = int(port_str) + except ValueError: + port = 45678 + if not ip: + set_status_message("請在設定中填寫激光機的 IP。", is_error=True) + else: + item_id = j.get("itemId") + stock_in_line_id = j.get("stockInLineId") + item_code_val = j.get("itemCode") or "" + item_name_val = j.get("itemName") or "" + run_laser_row_send_thread( + root=root, + laser_conn_ref=laser_conn_ref, + laser_busy_ref=laser_send_busy_ref, + ip=ip, + port=port, + item_id=item_id, + stock_in_line_id=stock_in_line_id, + item_code=item_code_val, + item_name=item_name_val, + set_status_message=set_status_message, + base_url=base_url_ref[0], + job_order_id=j.get("id"), + on_recorded=lambda: load_job_orders(from_user_date_change=False), + ) + + for w in ( + row, + left, + batch_lbl, + meta_lbl, + code_col, + code_lbl, + name_col, + name_lbl, + ): + w.bind("", _on_click) + w.bind("", _on_mousewheel) + w.bind("", _on_mousewheel) + w.bind("", _on_mousewheel) + if preserve_selection and selected_id is not None and jo.get("id") == selected_id: + found_row = row + if found_row is not None: + set_row_highlight(found_row, True) + selected_row_holder[0] = found_row + + def refresh_visible_list() -> None: + """Re-apply search filter to last fetched rows without hitting the API.""" + raw = last_data_ref[0] + if raw is None: + return + ps = last_plan_start_ref[0] + needle = search_var.get().strip() + shown = _filter_job_orders_by_search(raw, needle) if needle else raw + for w in inner.winfo_children(): + w.destroy() + _build_list_from_data(shown, ps, preserve_selection=True) + + search_entry.bind("", lambda e: refresh_visible_list()) + + def load_job_orders(from_user_date_change: bool = False) -> None: + if after_id_ref[0] is not None: + root.after_cancel(after_id_ref[0]) + after_id_ref[0] = None + date_str = date_var.get().strip() + try: + plan_start = date.fromisoformat(date_str) + except ValueError: + messagebox.showerror("日期錯誤", f"請使用 yyyy-MM-dd 格式。目前:{date_str}") + return + if from_user_date_change: + selected_row_holder[0] = None + selected_jo_id_ref[0] = None + try: + data = fetch_job_orders(base_url_ref[0], plan_start) + except requests.RequestException: + set_status_error() + after_id_ref[0] = root.after(RETRY_MS, lambda: load_job_orders(from_user_date_change=False)) + return + set_status_ok() + old_data = last_data_ref[0] + last_data_ref[0] = data + last_plan_start_ref[0] = plan_start + data_changed = not _data_equal(old_data, data) + if data_changed or from_user_date_change: + # Rebuild list: clear and rebuild from current data (last_data_ref already updated) + for w in inner.winfo_children(): + w.destroy() + preserve = not from_user_date_change + needle = search_var.get().strip() + shown = _filter_job_orders_by_search(data, needle) if needle else data + _build_list_from_data(shown, plan_start, preserve_selection=preserve) + if from_user_date_change: + canvas.yview_moveto(0) + after_id_ref[0] = root.after(REFRESH_MS, lambda: load_job_orders(from_user_date_change=False)) + + # Load default (today) on start; then start printer connection check + root.after(100, lambda: load_job_orders(from_user_date_change=True)) + root.after(300, check_printer) + + root.mainloop() + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/python/__pycache__/Bag2.cpython-313.pyc b/python/__pycache__/Bag2.cpython-313.pyc index 64e5842..01c2f88 100644 Binary files a/python/__pycache__/Bag2.cpython-313.pyc and b/python/__pycache__/Bag2.cpython-313.pyc differ diff --git a/python/bag3_settings.json b/python/bag3_settings.json new file mode 100644 index 0000000..84ad54e --- /dev/null +++ b/python/bag3_settings.json @@ -0,0 +1,9 @@ +{ + "api_ip": "127.0.0.1", + "api_port": "8090", + "dabag_ip": "192.168.17.27", + "dabag_port": "3008", + "laser_ip": "192.168.18.68", + "laser_port": "45678", + "label_com": "TSC TTP-246M Pro" +} \ No newline at end of file diff --git a/python/installAndExe.txt b/python/installAndExe.txt index 1c596cd..8a9184c 100644 --- a/python/installAndExe.txt +++ b/python/installAndExe.txt @@ -2,6 +2,7 @@ py -m pip install pyinstaller py -m pip install --upgrade pyinstaller py -m PyInstaller --onefile --windowed --name "Bag1" Bag1.py +py -m PyInstaller --onefile --windowed --name "Bag3" Bag3.py python -m pip install pyinstaller python -m pip install --upgrade pyinstaller diff --git a/src/main/java/com/ffii/fpsms/m18/M18GrnRules.kt b/src/main/java/com/ffii/fpsms/m18/M18GrnRules.kt index 45cb98c..258aedb 100644 --- a/src/main/java/com/ffii/fpsms/m18/M18GrnRules.kt +++ b/src/main/java/com/ffii/fpsms/m18/M18GrnRules.kt @@ -3,7 +3,20 @@ package com.ffii.fpsms.m18 /** * M18 PO [createUid] is stored on [com.ffii.fpsms.modules.purchaseOrder.entity.PurchaseOrder.m18CreatedUId]. * For these M18 user ids, FPSMS does not post GRN to M18 (see [com.ffii.fpsms.modules.stock.service.StockInLineService]). + * Remarks are shown on PO stock-in traceability report ([com.ffii.fpsms.modules.report.service.ReportService.searchStockInTraceabilityReport]). */ object M18GrnRules { - val SKIP_GRN_FOR_M18_CREATED_UIDS: Set = setOf(2569L, 2676L) + private val REMARKS_FOR_M18_CREATED_UID: Map = mapOf( + 2569L to "legato", + 2676L to "xtech", + ) + + val SKIP_GRN_FOR_M18_CREATED_UIDS: Set = REMARKS_FOR_M18_CREATED_UID.keys + + /** Display string for PDF/Excel: `2569 (legato)`, or plain id when unknown. */ + fun formatM18CreatedUidForReport(uid: Long?): String { + if (uid == null) return "" + val remark = REMARKS_FOR_M18_CREATED_UID[uid] + return if (remark != null) "$uid ($remark)" else uid.toString() + } } diff --git a/src/main/java/com/ffii/fpsms/m18/entity/M18GoodsReceiptNoteLogRepository.kt b/src/main/java/com/ffii/fpsms/m18/entity/M18GoodsReceiptNoteLogRepository.kt index 9bb6c6d..e459e03 100644 --- a/src/main/java/com/ffii/fpsms/m18/entity/M18GoodsReceiptNoteLogRepository.kt +++ b/src/main/java/com/ffii/fpsms/m18/entity/M18GoodsReceiptNoteLogRepository.kt @@ -7,9 +7,12 @@ import java.time.LocalDateTime interface M18GoodsReceiptNoteLogRepository : AbstractRepository { - /** Returns true if a successful GRN was already created for this PO (avoids core_201 duplicate). */ + /** Returns true if a successful GRN was already created for this PO (legacy / broad check). */ fun existsByPurchaseOrderIdAndStatusTrue(purchaseOrderId: Long): Boolean + /** True if this stock-in line was already included in a successful M18 GRN (one delivery = one GRN batch). */ + fun existsByStockInLineIdAndStatusTrue(stockInLineId: Long): Boolean + /** * GRN log rows that need M18 AN code backfill: have record id, no grn_code yet, * created in [start, end] inclusive (e.g. start = 4 days ago 00:00, end = now). diff --git a/src/main/java/com/ffii/fpsms/m18/service/M18MasterDataService.kt b/src/main/java/com/ffii/fpsms/m18/service/M18MasterDataService.kt index 28ba99c..3b01ec7 100644 --- a/src/main/java/com/ffii/fpsms/m18/service/M18MasterDataService.kt +++ b/src/main/java/com/ffii/fpsms/m18/service/M18MasterDataService.kt @@ -303,6 +303,45 @@ open class M18MasterDataService( } } + /** Sync one product/material from M18 by item code (search list, then load line — same idea as PO/DO by code). */ + open fun saveProductByCode(code: String): SyncResult { + val trimmed = code.trim() + if (trimmed.isEmpty()) { + return SyncResult(totalProcessed = 1, totalSuccess = 0, totalFail = 1, query = "empty code") + } + ensureCunitSeededForAllIfEmpty() + val fromLocal = itemsService.findByCode(trimmed)?.m18Id + val m18Id = fromLocal ?: run { + val conds = "(code=equal=$trimmed)" + val listResponse = try { + getList( + stSearch = StSearchType.PRODUCT.value, + params = null, + conds = conds, + request = M18CommonRequest(), + ) + } catch (e: Exception) { + logger.error("(saveProductByCode) M18 search failed: ${e.message}", e) + null + } + listResponse?.values?.firstOrNull()?.id + } + if (m18Id == null) { + return SyncResult( + totalProcessed = 1, + totalSuccess = 0, + totalFail = 1, + query = "code=equal=$trimmed", + ) + } + val result = saveProduct(m18Id) + return if (result != null) { + SyncResult(totalProcessed = 1, totalSuccess = 1, totalFail = 0, query = "code=equal=$trimmed") + } else { + SyncResult(totalProcessed = 1, totalSuccess = 0, totalFail = 1, query = "code=equal=$trimmed") + } + } + open fun saveProducts(request: M18CommonRequest): SyncResult { logger.info("--------------------------------------------Start - Saving M18 Products / Materials--------------------------------------------") ensureCunitSeededForAllIfEmpty() diff --git a/src/main/java/com/ffii/fpsms/m18/web/M18TestController.kt b/src/main/java/com/ffii/fpsms/m18/web/M18TestController.kt index 9999a79..44922b4 100644 --- a/src/main/java/com/ffii/fpsms/m18/web/M18TestController.kt +++ b/src/main/java/com/ffii/fpsms/m18/web/M18TestController.kt @@ -74,6 +74,11 @@ class M18TestController ( fun testSyncDoByCode(@RequestParam code: String): SyncResult { return m18DeliveryOrderService.saveDeliveryOrderByCode(code) } + + @GetMapping("/test/product-by-code") + fun testSyncProductByCode(@RequestParam code: String): SyncResult { + return m18MasterDataService.saveProductByCode(code) + } // --------------------------------------------- Scheduler --------------------------------------------- /// // @GetMapping("/schedule/po") // fun schedulePo(@RequestParam @Valid newCron: String) { diff --git a/src/main/java/com/ffii/fpsms/modules/common/SettingNames.java b/src/main/java/com/ffii/fpsms/modules/common/SettingNames.java index 23dea74..316b865 100644 --- a/src/main/java/com/ffii/fpsms/modules/common/SettingNames.java +++ b/src/main/java/com/ffii/fpsms/modules/common/SettingNames.java @@ -99,4 +99,7 @@ public abstract class SettingNames { /** Comma-separated BOM item codes shown on /laserPrint job list (e.g. PP1175); blank = no filter (all packaging JOs) */ public static final String LASER_PRINT_ITEM_CODES = "LASER_PRINT.itemCodes"; + /** JSON: last laser TCP send where printer returned receive (job order no., lot, itemId/stockInLineId, etc.) */ + public static final String LASER_PRINT_LAST_RECEIVE_SUCCESS = "LASER_PRINT.lastReceiveSuccess"; + } diff --git a/src/main/java/com/ffii/fpsms/modules/deliveryOrder/service/DeliveryOrderService.kt b/src/main/java/com/ffii/fpsms/modules/deliveryOrder/service/DeliveryOrderService.kt index fc13ca5..c4c9265 100644 --- a/src/main/java/com/ffii/fpsms/modules/deliveryOrder/service/DeliveryOrderService.kt +++ b/src/main/java/com/ffii/fpsms/modules/deliveryOrder/service/DeliveryOrderService.kt @@ -1360,7 +1360,11 @@ open class DeliveryOrderService( } params["deliveryNoteCode"] = doPickOrderRecord.deliveryNoteCode ?: "" params["shopAddress"] = cartonLabelInfo[0].shopAddress ?: "" - params["shopName"] = doPickOrderRecord.shopName ?: cartonLabelInfo[0].shopName ?: "" + val rawShopLabel = doPickOrderRecord.shopName ?: cartonLabelInfo[0].shopName ?: "" + val parsedShopLabel = parseShopLabelForCartonLabel(rawShopLabel) + params["shopCode"] = parsedShopLabel.shopCode + params["shopCodeAbbr"] = parsedShopLabel.shopCodeAbbr + params["shopName"] = parsedShopLabel.shopNameForLabel params["truckNo"] = doPickOrderRecord.truckLanceCode ?: "" for (cartonNumber in 1..request.numOfCarton) { @@ -1374,6 +1378,44 @@ open class DeliveryOrderService( ) } + private data class ParsedShopLabelForCartonLabel( + val shopCode: String, + val shopCodeAbbr: String, + val shopNameForLabel: String + ) + + private fun parseShopLabelForCartonLabel(rawInput: String): ParsedShopLabelForCartonLabel { + // Fixed input format: shopCode - shopName1-shopName2 + val raw = rawInput.trim() + + val (shopCodePartRaw, restPart) = raw.split(" - ", limit = 2).let { parts -> + (parts.getOrNull(0)?.trim().orEmpty()) to (parts.getOrNull(1)?.trim().orEmpty()) + } + + val shopCode = shopCodePartRaw.let { code -> + val trimmed = code.trim() + if (trimmed.length > 5) trimmed.substring(0, 5) else trimmed + } + + val (shopName1, shopName2) = restPart.split("-", limit = 2).let { parts -> + (parts.getOrNull(0)?.trim().orEmpty()) to (parts.getOrNull(1)?.trim().orEmpty()) + } + + val shopNameForLabel = if (shopName2.isNotBlank()) { + "$shopName1\n$shopName2" + } else { + shopName1 + } + + val shopCodeAbbr = if (shopCode.length >= 2) shopCode.substring(0, 2) else shopCode + + return ParsedShopLabelForCartonLabel( + shopCode = shopCode, + shopCodeAbbr = shopCodeAbbr, + shopNameForLabel = shopNameForLabel + ) + } + //Print Carton Labels @Transactional diff --git a/src/main/java/com/ffii/fpsms/modules/jobOrder/scheduler/LaserBag2AutoSendScheduler.kt b/src/main/java/com/ffii/fpsms/modules/jobOrder/scheduler/LaserBag2AutoSendScheduler.kt new file mode 100644 index 0000000..b129781 --- /dev/null +++ b/src/main/java/com/ffii/fpsms/modules/jobOrder/scheduler/LaserBag2AutoSendScheduler.kt @@ -0,0 +1,42 @@ +package com.ffii.fpsms.modules.jobOrder.scheduler + +import com.ffii.fpsms.modules.jobOrder.service.LaserBag2AutoSendService +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.annotation.Value +import org.springframework.scheduling.annotation.Scheduled +import org.springframework.stereotype.Component +import java.time.LocalDate + +/** + * Periodically runs the same laser TCP send as /laserPrint (DB LASER_PRINT.host / port / itemCodes). + * Disabled by default; set laser.bag2.auto-send.enabled=true. + */ +@Component +class LaserBag2AutoSendScheduler( + private val laserBag2AutoSendService: LaserBag2AutoSendService, + @Value("\${laser.bag2.auto-send.enabled:false}") private val enabled: Boolean, + @Value("\${laser.bag2.auto-send.limit-per-run:1}") private val limitPerRun: Int, +) { + private val logger = LoggerFactory.getLogger(javaClass) + + @Scheduled(fixedRateString = "\${laser.bag2.auto-send.interval-ms:60000}") + fun tick() { + if (!enabled) { + return + } + try { + val report = laserBag2AutoSendService.runAutoSend( + planStart = LocalDate.now(), + limitPerRun = limitPerRun, + ) + logger.info( + "Laser Bag2 scheduler: processed {}/{} job orders for {}", + report.jobOrdersProcessed, + report.jobOrdersFound, + report.planStart, + ) + } catch (e: Exception) { + logger.error("Laser Bag2 scheduler failed", e) + } + } +} diff --git a/src/main/java/com/ffii/fpsms/modules/jobOrder/service/LaserBag2AutoSendService.kt b/src/main/java/com/ffii/fpsms/modules/jobOrder/service/LaserBag2AutoSendService.kt new file mode 100644 index 0000000..c884e9d --- /dev/null +++ b/src/main/java/com/ffii/fpsms/modules/jobOrder/service/LaserBag2AutoSendService.kt @@ -0,0 +1,114 @@ +package com.ffii.fpsms.modules.jobOrder.service + +import com.ffii.fpsms.modules.jobOrder.web.model.LaserBag2AutoSendReport +import com.ffii.fpsms.modules.jobOrder.web.model.LaserBag2JobSendResult +import com.ffii.fpsms.modules.jobOrder.web.model.LaserBag2SendRequest +import org.slf4j.LoggerFactory +import org.springframework.stereotype.Service +import java.time.LocalDate + +/** + * Finds packaging job orders for [planStart] using the same filter as [PlasticBagPrinterService.listLaserPrintJobOrders] + * ([LASER_PRINT.itemCodes]), then sends Bag2-style laser TCP payloads via [PlasticBagPrinterService.sendLaserBag2Job], + * which uses [com.ffii.fpsms.modules.common.SettingNames.LASER_PRINT_HOST] / [LASER_PRINT_PORT] from the database. + * + * Matches /laserPrint row click: [sendsPerJob] rounds with [delayBetweenSendsMs] between rounds (default 3 × 3s like the frontend). + */ +@Service +class LaserBag2AutoSendService( + private val plasticBagPrinterService: PlasticBagPrinterService, +) { + private val logger = LoggerFactory.getLogger(javaClass) + + companion object { + /** Same as LaserPrint page (3 sends per row click). */ + const val DEFAULT_SENDS_PER_JOB = 3 + const val DEFAULT_DELAY_BETWEEN_SENDS_MS = 3000L + } + + fun runAutoSend( + planStart: LocalDate, + limitPerRun: Int = 0, + sendsPerJob: Int = DEFAULT_SENDS_PER_JOB, + delayBetweenSendsMs: Long = DEFAULT_DELAY_BETWEEN_SENDS_MS, + ): LaserBag2AutoSendReport { + val (reachable, laserIp, laserPort) = plasticBagPrinterService.probeLaserBag2Tcp() + if (!reachable) { + logger.warn("Connection failed to the laser print: {} / {}", laserIp, laserPort) + return LaserBag2AutoSendReport( + planStart = planStart, + jobOrdersFound = 0, + jobOrdersProcessed = 0, + results = emptyList(), + ) + } + + val orders = plasticBagPrinterService.listLaserPrintJobOrders(planStart) + val toProcess = if (limitPerRun > 0) orders.take(limitPerRun) else orders + val results = mutableListOf() + + logger.info( + "Laser Bag2 auto-send: planStart={}, found={}, processing={}, sendsPerJob={}", + planStart, + orders.size, + toProcess.size, + sendsPerJob, + ) + + for (jo in toProcess) { + var lastMsg = "" + var overallOk = true + var lastPrinterAck: String? = null + var lastReceiveAck = false + for (attempt in 1..sendsPerJob) { + val resp = plasticBagPrinterService.sendLaserBag2Job( + LaserBag2SendRequest( + itemId = jo.itemId, + stockInLineId = jo.stockInLineId, + itemCode = jo.itemCode, + itemName = jo.itemName, + jobOrderId = jo.id, + jobOrderNo = jo.code, + lotNo = jo.lotNo, + source = "AUTO", + ), + ) + lastMsg = resp.message + lastPrinterAck = resp.printerAck + lastReceiveAck = resp.receiveAcknowledged + if (!resp.success) { + overallOk = false + logger.warn("Laser send failed jobOrderId={} attempt={}: {}", jo.id, attempt, resp.message) + break + } + if (attempt < sendsPerJob) { + try { + Thread.sleep(delayBetweenSendsMs) + } catch (e: InterruptedException) { + Thread.currentThread().interrupt() + overallOk = false + lastMsg = "Interrupted" + break + } + } + } + results.add( + LaserBag2JobSendResult( + jobOrderId = jo.id, + itemCode = jo.itemCode, + success = overallOk, + message = lastMsg, + printerAck = lastPrinterAck, + receiveAcknowledged = lastReceiveAck, + ), + ) + } + + return LaserBag2AutoSendReport( + planStart = planStart, + jobOrdersFound = orders.size, + jobOrdersProcessed = toProcess.size, + results = results, + ) + } +} diff --git a/src/main/java/com/ffii/fpsms/modules/jobOrder/service/PlasticBagPrinterService.kt b/src/main/java/com/ffii/fpsms/modules/jobOrder/service/PlasticBagPrinterService.kt index 970889f..29d3f64 100644 --- a/src/main/java/com/ffii/fpsms/modules/jobOrder/service/PlasticBagPrinterService.kt +++ b/src/main/java/com/ffii/fpsms/modules/jobOrder/service/PlasticBagPrinterService.kt @@ -7,12 +7,17 @@ import com.ffii.fpsms.modules.jobOrder.entity.JobOrderRepository import com.ffii.fpsms.modules.jobOrder.web.model.LaserBag2SendRequest import com.ffii.fpsms.modules.jobOrder.web.model.LaserBag2SendResponse import com.ffii.fpsms.modules.jobOrder.web.model.LaserBag2SettingsResponse +import com.ffii.fpsms.modules.jobOrder.web.model.LaserLastReceiveSuccessDto import com.ffii.fpsms.modules.jobOrder.web.model.PrintRequest import com.ffii.fpsms.modules.jobOrder.web.model.LaserRequest +import com.ffii.fpsms.modules.jobOrder.web.model.NgpclPushResponse import com.ffii.fpsms.modules.jobOrder.web.model.OnPackQrJobOrderRequest import com.ffii.fpsms.modules.settings.service.SettingsService import com.ffii.fpsms.modules.stock.entity.StockInLineRepository +import com.ffii.fpsms.py.PrintedQtyByChannel import com.ffii.fpsms.py.PyJobOrderListItem +import com.ffii.fpsms.py.PyJobOrderPrintSubmitService +import org.springframework.core.env.Environment import org.springframework.stereotype.Service import java.awt.Color import java.awt.Font @@ -26,6 +31,10 @@ import javax.imageio.ImageIO import com.google.zxing.BarcodeFormat import com.google.zxing.EncodeHintType import com.google.zxing.qrcode.QRCodeWriter +import java.net.URI +import java.net.http.HttpClient +import java.net.http.HttpRequest +import java.net.http.HttpResponse import java.net.Socket import java.net.InetSocketAddress import java.io.PrintWriter @@ -39,17 +48,32 @@ import java.net.ConnectException import java.net.SocketTimeoutException import org.springframework.core.io.ClassPathResource import org.slf4j.LoggerFactory +import com.fasterxml.jackson.databind.ObjectMapper +import java.time.Duration +import java.time.Instant import java.time.LocalDate // Data class to store bitmap bytes + width (for XML) data class BitmapResult(val bytes: ByteArray, val width: Int) +/** One Bag2-style laser TCP attempt (internal to [PlasticBagPrinterService]). */ +private data class LaserBag2TcpResult( + val success: Boolean, + val message: String, + val payload: String, + val printerAck: String?, + val receiveAcknowledged: Boolean, +) + @Service class PlasticBagPrinterService( val jobOrderRepository: JobOrderRepository, private val jdbcDao: JdbcDao, private val stockInLineRepository: StockInLineRepository, private val settingsService: SettingsService, + private val pyJobOrderPrintSubmitService: PyJobOrderPrintSubmitService, + private val environment: Environment, + private val objectMapper: ObjectMapper, ) { private val logger = LoggerFactory.getLogger(javaClass) @@ -75,7 +99,43 @@ class PlasticBagPrinterService( val itemCodes = settingsService.findByName(SettingNames.LASER_PRINT_ITEM_CODES) .map { it.value?.trim() ?: "" } .orElse(DEFAULT_LASER_ITEM_CODES) - return LaserBag2SettingsResponse(host = host, port = port, itemCodes = itemCodes) + return LaserBag2SettingsResponse( + host = host, + port = port, + itemCodes = itemCodes, + lastReceiveSuccess = readLaserLastReceiveSuccessFromSettings(), + ) + } + + private fun readLaserLastReceiveSuccessFromSettings(): LaserLastReceiveSuccessDto? { + val raw = settingsService.findByName(SettingNames.LASER_PRINT_LAST_RECEIVE_SUCCESS) + .map { it.value } + .orElse(null) + ?.trim() + .orEmpty() + if (raw.isBlank() || raw == "{}") return null + return try { + val dto = objectMapper.readValue(raw, LaserLastReceiveSuccessDto::class.java) + if (dto.sentAt.isNullOrBlank()) null else dto + } catch (e: Exception) { + logger.warn("Could not parse LASER_PRINT.lastReceiveSuccess: {}", e.message) + null + } + } + + private fun persistLaserLastReceiveSuccess(request: LaserBag2SendRequest, printerAck: String?) { + val dto = LaserLastReceiveSuccessDto( + jobOrderId = request.jobOrderId, + jobOrderNo = request.jobOrderNo?.trim()?.takeIf { it.isNotEmpty() }, + lotNo = request.lotNo?.trim()?.takeIf { it.isNotEmpty() }, + itemId = request.itemId, + stockInLineId = request.stockInLineId, + printerAck = printerAck?.trim()?.takeIf { it.isNotEmpty() }, + sentAt = Instant.now().toString(), + source = request.source?.trim()?.takeIf { it.isNotEmpty() } ?: "MANUAL", + ) + val json = objectMapper.writeValueAsString(dto) + settingsService.update(SettingNames.LASER_PRINT_LAST_RECEIVE_SUCCESS, json) } /** @@ -108,7 +168,11 @@ class PlasticBagPrinterService( allowed.contains(code) } } - return filtered.map { jo -> toPyJobOrderListItem(jo) } + val ids = filtered.mapNotNull { it.id } + val printed = pyJobOrderPrintSubmitService.sumPrintedQtyByJobOrderIds(ids) + return filtered.map { jo -> + toPyJobOrderListItem(jo, printed[jo.id!!]) + } } private fun parseLaserItemCodeFilters(raw: String?): Set { @@ -119,13 +183,14 @@ class PlasticBagPrinterService( .toSet() } - private fun toPyJobOrderListItem(jo: JobOrder): PyJobOrderListItem { + private fun toPyJobOrderListItem(jo: JobOrder, printed: PrintedQtyByChannel?): PyJobOrderListItem { val itemCode = jo.bom?.item?.code ?: jo.bom?.code val itemName = jo.bom?.name ?: jo.bom?.item?.name val itemId = jo.bom?.item?.id val stockInLine = jo.id?.let { stockInLineRepository.findFirstByJobOrder_IdAndDeletedFalse(it) } val stockInLineId = stockInLine?.id val lotNo = stockInLine?.lotNo + val p = printed ?: PrintedQtyByChannel() return PyJobOrderListItem( id = jo.id!!, code = jo.code, @@ -136,6 +201,9 @@ class PlasticBagPrinterService( stockInLineId = stockInLineId, itemId = itemId, lotNo = lotNo, + bagPrintedQty = p.bagPrintedQty, + labelPrintedQty = p.labelPrintedQty, + laserPrintedQty = p.laserPrintedQty, ) } @@ -154,22 +222,39 @@ class PlasticBagPrinterService( itemCode = request.itemCode, itemName = request.itemName, ) - if (first.first) { - return LaserBag2SendResponse(success = true, message = first.second, payloadSent = first.third) + val response = if (first.success) { + LaserBag2SendResponse( + success = true, + message = first.message, + payloadSent = first.payload, + printerAck = first.printerAck, + receiveAcknowledged = first.receiveAcknowledged, + ) + } else { + val second = sendLaserBag2TcpOnce( + ip = ip, + port = port, + itemId = request.itemId, + stockInLineId = request.stockInLineId, + itemCode = request.itemCode, + itemName = request.itemName, + ) + LaserBag2SendResponse( + success = second.success, + message = second.message, + payloadSent = second.payload, + printerAck = second.printerAck, + receiveAcknowledged = second.receiveAcknowledged, + ) } - val second = sendLaserBag2TcpOnce( - ip = ip, - port = port, - itemId = request.itemId, - stockInLineId = request.stockInLineId, - itemCode = request.itemCode, - itemName = request.itemName, - ) - return LaserBag2SendResponse( - success = second.first, - message = second.second, - payloadSent = second.third, - ) + if (response.success && response.receiveAcknowledged) { + try { + persistLaserLastReceiveSuccess(request, response.printerAck) + } catch (e: Exception) { + logger.warn("Could not persist laser last receive success: {}", e.message) + } + } + return response } private fun resolveLaserBag2Host(): String { @@ -190,6 +275,17 @@ class PlasticBagPrinterService( return v.toIntOrNull() ?: DEFAULT_LASER_BAG2_PORT } + /** + * TCP connect probe to configured [LASER_PRINT.host] / [LASER_PRINT.port] (same endpoint as [sendLaserBag2Job] / auto-send). + * @return Triple(ok, host, port) + */ + fun probeLaserBag2Tcp(): Triple { + val host = resolveLaserBag2Host() + val port = resolveLaserBag2Port() + val (ok, _) = checkTcpPrinter(host, port, "Laser") + return Triple(ok, host, port) + } + private fun sendLaserBag2TcpOnce( ip: String, port: Int, @@ -197,7 +293,7 @@ class PlasticBagPrinterService( stockInLineId: Long?, itemCode: String?, itemName: String?, - ): Triple { + ): LaserBag2TcpResult { val codeStr = (itemCode ?: "").trim().replace(";", ",") val nameStr = (itemName ?: "").trim().replace(";", ",") val payload = if (itemId != null && stockInLineId != null) { @@ -214,27 +310,61 @@ class PlasticBagPrinterService( val out = socket.getOutputStream() out.write(bytes) out.flush() + // Half-close the write side so the peer sees a clean end-of-send before we read the ack. + // Abrupt full socket close right after read often makes EZCAD log "Remote TCP client disconnected". + try { + socket.shutdownOutput() + } catch (_: Exception) { + } + var ackRaw: String? = null + var receiveAck = false socket.soTimeout = 500 try { val buf = ByteArray(4096) val n = socket.getInputStream().read(buf) if (n > 0) { - val ack = String(buf, 0, n, StandardCharsets.UTF_8).trim().lowercase() - if (ack.contains("receive") && !ack.contains("invalid")) { - return Triple(true, "已送出激光機:$payload(已確認)", payload) + ackRaw = String(buf, 0, n, StandardCharsets.UTF_8).trim() + val ackLower = ackRaw.lowercase() + if (ackLower.contains("receive") && !ackLower.contains("invalid")) { + receiveAck = true + logger.info( + "Laser TCP ack (receive): {}:{} sent={} ack={}", + ip, + port, + payload, + ackRaw, + ) + } else if (ackRaw.isNotEmpty()) { + logger.info( + "Laser TCP response: {}:{} sent={} ack={}", + ip, + port, + payload, + ackRaw, + ) } } } catch (_: SocketTimeoutException) { - // Same as Python: ignore read timeout, treat as sent + // Same as Python Bag3: ignore read timeout, payload was still sent + } + val msg = if (receiveAck) { + "已送出激光機:$payload(已確認)" + } else { + "已送出激光機:$payload" } - return Triple(true, "已送出激光機:$payload", payload) + return LaserBag2TcpResult(true, msg, payload, ackRaw, receiveAck) } catch (e: ConnectException) { - return Triple(false, "無法連線至 $ip:$port,請確認激光機已開機且 IP 正確。", payload) + return LaserBag2TcpResult(false, "無法連線至 $ip:$port,請確認激光機已開機且 IP 正確。", payload, null, false) } catch (e: SocketTimeoutException) { - return Triple(false, "連線逾時 ($ip:$port),請檢查網路與連接埠。", payload) + return LaserBag2TcpResult(false, "連線逾時 ($ip:$port),請檢查網路與連接埠。", payload, null, false) } catch (e: Exception) { - return Triple(false, "激光機送出失敗:${e.message}", payload) + return LaserBag2TcpResult(false, "激光機送出失敗:${e.message}", payload, null, false) } finally { + try { + Thread.sleep(100) + } catch (_: InterruptedException) { + Thread.currentThread().interrupt() + } try { socket?.close() } catch (_: Exception) { @@ -526,6 +656,59 @@ class PlasticBagPrinterService( return baos.toByteArray() } + /** + * Builds the same ZIP as [generateOnPackQrTextZip] and POSTs it to [ngpcl.push-url] (application/zip). + * When the URL is blank, returns [NgpclPushResponse] with pushed=false so callers can fall back to manual download. + */ + fun pushOnPackQrTextZipToNgpcl(jobOrders: List): NgpclPushResponse { + val url = (environment.getProperty("ngpcl.push-url") ?: "").trim() + if (url.isEmpty()) { + return NgpclPushResponse( + pushed = false, + message = "NGPCL push URL not configured. Set ngpcl.push-url or NGPCL_PUSH_URL, or download the ZIP and transfer loose files manually.", + ) + } + val zipBytes = try { + generateOnPackQrTextZip(jobOrders) + } catch (e: Exception) { + logger.warn("OnPack text ZIP generation failed before NGPCL push", e) + return NgpclPushResponse( + pushed = false, + message = e.message ?: "ZIP generation failed", + ) + } + return try { + val client = HttpClient.newBuilder() + .connectTimeout(Duration.ofSeconds(30)) + .build() + val request = HttpRequest.newBuilder() + .uri(URI.create(url)) + .timeout(Duration.ofMinutes(2)) + .header("Content-Type", "application/zip") + .POST(HttpRequest.BodyPublishers.ofByteArray(zipBytes)) + .build() + val response = client.send(request, HttpResponse.BodyHandlers.ofString()) + val body = response.body() + if (response.statusCode() in 200..299) { + NgpclPushResponse( + pushed = true, + message = "NGPCL accepted (HTTP ${response.statusCode()})${if (body.isNotBlank()) ": ${body.take(300)}" else ""}", + ) + } else { + NgpclPushResponse( + pushed = false, + message = "NGPCL returned HTTP ${response.statusCode()}: ${body.take(500)}", + ) + } + } catch (e: Exception) { + logger.error("NGPCL push failed", e) + NgpclPushResponse( + pushed = false, + message = e.message ?: "Push failed: ${e.javaClass.simpleName}", + ) + } + } + /** * Returns uppercase item codes present in `onpack_qr` with the given [templateType] (`bmp` or `text`). * Empty or NULL `template_type` is treated as `bmp` for backward compatibility. @@ -759,7 +942,17 @@ class PlasticBagPrinterService( ): Pair { return when (printerType.lowercase()) { "dataflex" -> checkTcpPrinter(printerIp, printerPort ?: 3008, "DataFlex") - "laser" -> checkTcpPrinter(printerIp, printerPort ?: 45678, "Laser") + // - /bagPrint: sends browser localStorage laser IP (may differ from DB — second machine). + // - /laserPrint: omit printerIp → use DB LASER_PRINT.* (same as sendLaserBag2Job). + // - Explicit empty string → not configured (do not fall back to DB). + "laser" -> { + val trimmed = printerIp?.trim().orEmpty() + when { + trimmed.isNotEmpty() -> checkTcpPrinter(trimmed, printerPort ?: 45678, "Laser") + printerIp == null -> checkTcpPrinter(resolveLaserBag2Host(), resolveLaserBag2Port(), "Laser") + else -> false to "Laser IP is not configured" + } + } "label" -> { val comPort = labelCom?.trim().orEmpty() if (comPort.isBlank()) { @@ -781,14 +974,14 @@ class PlasticBagPrinterService( return try { Socket().use { socket -> socket.connect(InetSocketAddress(ip, port), 3000) - true to "$printerName connected" + true to "$printerName 已連線($ip:$port)" } } catch (e: SocketTimeoutException) { - false to "$printerName connection timed out" + false to "$printerName 連線逾時($ip:$port)" } catch (e: ConnectException) { - false to "$printerName connection refused" + false to "$printerName 無法連線($ip:$port)" } catch (e: Exception) { - false to "$printerName connection failed: ${e.message}" + false to "$printerName 連線失敗($ip:$port):${e.message}" } } diff --git a/src/main/java/com/ffii/fpsms/modules/jobOrder/web/PlasticBagPrinterController.kt b/src/main/java/com/ffii/fpsms/modules/jobOrder/web/PlasticBagPrinterController.kt index cbe6879..101f295 100644 --- a/src/main/java/com/ffii/fpsms/modules/jobOrder/web/PlasticBagPrinterController.kt +++ b/src/main/java/com/ffii/fpsms/modules/jobOrder/web/PlasticBagPrinterController.kt @@ -1,12 +1,15 @@ package com.ffii.fpsms.modules.jobOrder.web +import com.ffii.fpsms.modules.jobOrder.service.LaserBag2AutoSendService import com.ffii.fpsms.modules.jobOrder.service.PlasticBagPrinterService import com.ffii.fpsms.modules.jobOrder.web.model.PrintRequest import com.ffii.fpsms.modules.jobOrder.web.model.LaserRequest import com.ffii.fpsms.modules.jobOrder.web.model.Laser2Request +import com.ffii.fpsms.modules.jobOrder.web.model.LaserBag2AutoSendReport import com.ffii.fpsms.modules.jobOrder.web.model.LaserBag2SendRequest import com.ffii.fpsms.modules.jobOrder.web.model.LaserBag2SendResponse import com.ffii.fpsms.modules.jobOrder.web.model.LaserBag2SettingsResponse +import com.ffii.fpsms.modules.jobOrder.web.model.NgpclPushResponse import com.ffii.fpsms.modules.jobOrder.web.model.OnPackQrDownloadRequest import com.ffii.fpsms.modules.jobOrder.web.model.PrinterStatusRequest import com.ffii.fpsms.modules.jobOrder.web.model.PrinterStatusResponse @@ -24,6 +27,7 @@ import org.slf4j.LoggerFactory @RequestMapping("/plastic") class PlasticBagPrinterController( private val plasticBagPrinterService: PlasticBagPrinterService, + private val laserBag2AutoSendService: LaserBag2AutoSendService, ) { private val logger = LoggerFactory.getLogger(javaClass) @@ -58,6 +62,24 @@ class PlasticBagPrinterController( } } + /** + * Same as /laserPrint row workflow: list job orders for [planStart] filtered by LASER_PRINT.itemCodes, + * then for each (up to [limitPerRun], 0 = all) send laser TCP commands using LASER_PRINT.host/port (3× with 3s gap per job). + * For manual runs from /testing; scheduler uses [LaserBag2AutoSendScheduler]. + */ + @PostMapping("/laser-bag2-auto-send") + fun runLaserBag2AutoSend( + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) planStart: LocalDate?, + @RequestParam(required = false, defaultValue = "0") limitPerRun: Int, + ): ResponseEntity { + val date = planStart ?: LocalDate.now() + val report = laserBag2AutoSendService.runAutoSend( + planStart = date, + limitPerRun = limitPerRun, + ) + return ResponseEntity.ok(report) + } + @PostMapping("/check-printer") fun checkPrinter(@RequestBody request: PrinterStatusRequest): ResponseEntity { val (connected, message) = plasticBagPrinterService.checkPrinterConnection( @@ -152,6 +174,15 @@ class PlasticBagPrinterController( } } + /** + * Same payload as [downloadOnPackQrText], but POSTs the generated ZIP to `ngpcl.push-url` (application/zip). + * Returns JSON: `{ pushed, message }`. When push URL is unset, `pushed` is false — use download instead. + */ + @PostMapping("/ngpcl/push-onpack-qr-text") + fun pushOnPackQrTextToNgpcl(@RequestBody request: OnPackQrDownloadRequest): ResponseEntity { + return ResponseEntity.ok(plasticBagPrinterService.pushOnPackQrTextZipToNgpcl(request.jobOrders)) + } + /** * Test API to generate and download the printer job files as a ZIP. * ONPACK2030 diff --git a/src/main/java/com/ffii/fpsms/modules/jobOrder/web/model/LaserBag2AutoSendReport.kt b/src/main/java/com/ffii/fpsms/modules/jobOrder/web/model/LaserBag2AutoSendReport.kt new file mode 100644 index 0000000..a8e5fdc --- /dev/null +++ b/src/main/java/com/ffii/fpsms/modules/jobOrder/web/model/LaserBag2AutoSendReport.kt @@ -0,0 +1,20 @@ +package com.ffii.fpsms.modules.jobOrder.web.model + +import java.time.LocalDate + +/** Result of [com.ffii.fpsms.modules.jobOrder.service.LaserBag2AutoSendService.runAutoSend]. */ +data class LaserBag2AutoSendReport( + val planStart: LocalDate, + val jobOrdersFound: Int, + val jobOrdersProcessed: Int, + val results: List, +) + +data class LaserBag2JobSendResult( + val jobOrderId: Long, + val itemCode: String?, + val success: Boolean, + val message: String, + val printerAck: String? = null, + val receiveAcknowledged: Boolean = false, +) diff --git a/src/main/java/com/ffii/fpsms/modules/jobOrder/web/model/LaserBag2SendRequest.kt b/src/main/java/com/ffii/fpsms/modules/jobOrder/web/model/LaserBag2SendRequest.kt index c135a19..5c0c81c 100644 --- a/src/main/java/com/ffii/fpsms/modules/jobOrder/web/model/LaserBag2SendRequest.kt +++ b/src/main/java/com/ffii/fpsms/modules/jobOrder/web/model/LaserBag2SendRequest.kt @@ -3,6 +3,9 @@ package com.ffii.fpsms.modules.jobOrder.web.model /** * Body for Bag2.py-style laser TCP send: `json;itemCode;itemName;;` (UTF-8). * Optional [printerIp] / [printerPort] override system settings [LASER_PRINT.host] / [LASER_PRINT.port]. + * + * Optional job metadata is used to persist [com.ffii.fpsms.modules.common.SettingNames.LASER_PRINT_LAST_RECEIVE_SUCCESS] + * when the printer returns a receive ack. */ data class LaserBag2SendRequest( val itemId: Long? = null, @@ -11,4 +14,9 @@ data class LaserBag2SendRequest( val itemName: String? = null, val printerIp: String? = null, val printerPort: Int? = null, + val jobOrderId: Long? = null, + val jobOrderNo: String? = null, + val lotNo: String? = null, + /** AUTO (auto-send) or MANUAL (/laserPrint); optional. */ + val source: String? = null, ) diff --git a/src/main/java/com/ffii/fpsms/modules/jobOrder/web/model/LaserBag2SendResponse.kt b/src/main/java/com/ffii/fpsms/modules/jobOrder/web/model/LaserBag2SendResponse.kt index 07c42df..1c68bfe 100644 --- a/src/main/java/com/ffii/fpsms/modules/jobOrder/web/model/LaserBag2SendResponse.kt +++ b/src/main/java/com/ffii/fpsms/modules/jobOrder/web/model/LaserBag2SendResponse.kt @@ -4,4 +4,8 @@ data class LaserBag2SendResponse( val success: Boolean, val message: String, val payloadSent: String? = null, + /** Raw bytes from the laser TCP peer after our payload (often `receive;;`). */ + val printerAck: String? = null, + /** True when [printerAck] contained `receive` and not `invalid` (same rule as Bag3.py). */ + val receiveAcknowledged: Boolean = false, ) diff --git a/src/main/java/com/ffii/fpsms/modules/jobOrder/web/model/LaserBag2SettingsResponse.kt b/src/main/java/com/ffii/fpsms/modules/jobOrder/web/model/LaserBag2SettingsResponse.kt index 673e3a1..ec6e64b 100644 --- a/src/main/java/com/ffii/fpsms/modules/jobOrder/web/model/LaserBag2SettingsResponse.kt +++ b/src/main/java/com/ffii/fpsms/modules/jobOrder/web/model/LaserBag2SettingsResponse.kt @@ -2,9 +2,11 @@ package com.ffii.fpsms.modules.jobOrder.web.model /** * @param itemCodes Comma-separated item codes for the laser job list filter (e.g. `PP1175` or `PP1175,AB123`). Empty string means no filter (show all packaging job orders). + * @param lastReceiveSuccess Last job where the laser printer returned a receive ack (from settings JSON); null if never recorded or empty. */ data class LaserBag2SettingsResponse( val host: String, val port: Int, val itemCodes: String, + val lastReceiveSuccess: LaserLastReceiveSuccessDto? = null, ) diff --git a/src/main/java/com/ffii/fpsms/modules/jobOrder/web/model/LaserLastReceiveSuccessDto.kt b/src/main/java/com/ffii/fpsms/modules/jobOrder/web/model/LaserLastReceiveSuccessDto.kt new file mode 100644 index 0000000..b4676d8 --- /dev/null +++ b/src/main/java/com/ffii/fpsms/modules/jobOrder/web/model/LaserLastReceiveSuccessDto.kt @@ -0,0 +1,22 @@ +package com.ffii.fpsms.modules.jobOrder.web.model + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties + +/** + * Persisted in [com.ffii.fpsms.modules.common.SettingNames.LASER_PRINT_LAST_RECEIVE_SUCCESS] when the laser + * TCP peer returns a receive-style ack ([com.ffii.fpsms.modules.jobOrder.web.model.LaserBag2SendResponse.receiveAcknowledged]). + */ +@JsonIgnoreProperties(ignoreUnknown = true) +data class LaserLastReceiveSuccessDto( + val jobOrderId: Long? = null, + /** Job order code (工單號). */ + val jobOrderNo: String? = null, + val lotNo: String? = null, + val itemId: Long? = null, + val stockInLineId: Long? = null, + val printerAck: String? = null, + /** ISO-8601 instant string (server UTC). */ + val sentAt: String? = null, + /** e.g. AUTO (scheduler/auto-send) or MANUAL (/laserPrint row). */ + val source: String? = null, +) diff --git a/src/main/java/com/ffii/fpsms/modules/jobOrder/web/model/PlasticPrintRequest.kt b/src/main/java/com/ffii/fpsms/modules/jobOrder/web/model/PlasticPrintRequest.kt index c782060..eae5fd2 100644 --- a/src/main/java/com/ffii/fpsms/modules/jobOrder/web/model/PlasticPrintRequest.kt +++ b/src/main/java/com/ffii/fpsms/modules/jobOrder/web/model/PlasticPrintRequest.kt @@ -57,4 +57,10 @@ data class OnPackQrDownloadRequest( data class OnPackQrJobOrderRequest( val jobOrderId: Long, val itemCode: String, +) + +/** Result of POST /plastic/ngpcl/push-onpack-qr-text — server POSTs the lemon ZIP bytes to [ngpcl.push-url] when configured. */ +data class NgpclPushResponse( + val pushed: Boolean, + val message: String, ) \ No newline at end of file diff --git a/src/main/java/com/ffii/fpsms/modules/report/service/ReportService.kt b/src/main/java/com/ffii/fpsms/modules/report/service/ReportService.kt index 30e945b..e9cf4d1 100644 --- a/src/main/java/com/ffii/fpsms/modules/report/service/ReportService.kt +++ b/src/main/java/com/ffii/fpsms/modules/report/service/ReportService.kt @@ -647,7 +647,7 @@ return result } /** - * Queries the database for Stock In Traceability Report data. + * Queries the database for Stock In Traceability Report data (入倉追蹤 PDF). * Joins stock_in_line, stock_in, items, qc_result, inventory_lot, inventory_lot_line, warehouse, and shop tables. * Supports comma-separated values for stockCategory (items.type) and itemCode. */ @@ -737,7 +737,7 @@ return result $lastInDateEndSql ORDER BY it.code, sil.lotNo """.trimIndent() - + return jdbcDao.queryForList(sql, args) } @@ -793,7 +793,8 @@ return result MAX(ROUND(COALESCE(pol.up, 0) * COALESCE(sil.acceptedQty, 0), 2)) AS lineAmount, MAX(COALESCE(cur.code, '')) AS currencyCode, MAX(grn.grn_code) AS grnCode, - MAX(grn.m18_record_id) AS grnId + MAX(grn.m18_record_id) AS grnId, + MAX(po.m18CreatedUId) AS poM18CreatedUId FROM stock_in_line sil LEFT JOIN items it ON sil.itemId = it.id LEFT JOIN purchase_order po ON sil.purchaseOrderId = po.id @@ -855,7 +856,15 @@ return result "lineAmount" to (row["lineAmount"]?.let { n -> (n as? Number)?.toDouble() } ?: 0.0), "currencyCode" to row["currencyCode"], "grnCode" to row["grnCode"], - "grnId" to row["grnId"] + "grnId" to row["grnId"], + "poM18CreatorDisplay" to M18GrnRules.formatM18CreatedUidForReport( + when (val v = row["poM18CreatedUId"]) { + null -> null + is Number -> v.toLong() + is BigDecimal -> v.toLong() + else -> v.toString().toLongOrNull() + }, + ), ) } } diff --git a/src/main/java/com/ffii/fpsms/modules/stock/entity/StockInLineRepository.kt b/src/main/java/com/ffii/fpsms/modules/stock/entity/StockInLineRepository.kt index 69b3b81..ede7185 100644 --- a/src/main/java/com/ffii/fpsms/modules/stock/entity/StockInLineRepository.kt +++ b/src/main/java/com/ffii/fpsms/modules/stock/entity/StockInLineRepository.kt @@ -80,6 +80,26 @@ fun findFirstByJobOrder_IdAndDeletedFalse(jobOrderId: Long): StockInLine? """) fun findCompletedByPurchaseOrderIdAndDeletedFalseWithItemNames(@Param("purchaseOrderId") purchaseOrderId: Long): List + /** Completed stock-in lines for this PO whose calendar receipt day matches (one M18 GRN per delivery date / DN batch). */ + @Query( + """ + SELECT DISTINCT sil FROM StockInLine sil + LEFT JOIN FETCH sil.item + LEFT JOIN FETCH sil.purchaseOrderLine pol + LEFT JOIN FETCH pol.item + WHERE sil.purchaseOrder.id = :purchaseOrderId + AND sil.deleted = false + AND sil.status = 'completed' + AND sil.receiptDate IS NOT NULL + AND DATE(sil.receiptDate) = :receiptDate + ORDER BY sil.id + """ + ) + fun findCompletedByPurchaseOrderIdAndReceiptDateAndDeletedFalseWithItemNames( + @Param("purchaseOrderId") purchaseOrderId: Long, + @Param("receiptDate") receiptDate: LocalDate, + ): List + @Query(""" SELECT sil FROM StockInLine sil WHERE sil.receiptDate IS NOT NULL diff --git a/src/main/java/com/ffii/fpsms/modules/stock/service/SearchCompletedDnService.kt b/src/main/java/com/ffii/fpsms/modules/stock/service/SearchCompletedDnService.kt index f705b4e..0f8f07d 100644 --- a/src/main/java/com/ffii/fpsms/modules/stock/service/SearchCompletedDnService.kt +++ b/src/main/java/com/ffii/fpsms/modules/stock/service/SearchCompletedDnService.kt @@ -15,6 +15,7 @@ import java.time.LocalDateTime /** * Search completed stock-in lines (DN) by receipt date and process M18 GRN creation. * Query: receiptDate = yesterday, status = completed, purchaseOrderId not null. + * Same PO may appear on multiple dates; each receipt date batch can produce its own M18 GRN. */ @Service open class SearchCompletedDnService( @@ -82,7 +83,7 @@ open class SearchCompletedDnService( /** * Post completed DNs and process each related purchase order for M18 GRN creation. - * Triggered by scheduler. One GRN per Purchase Order, with the PO lines it received (acceptedQty as ant qty). + * Triggered by scheduler. One GRN per PO **per receipt date** for lines completed on that date (same PO may receive multiple GRNs on different days). * @param receiptDate Default: yesterday * @param skipFirst For testing/manual trigger: skip the first N POs. 1 = skip 1st, process from 2nd. 0 = process from 1st. * @param limitToFirst For testing/manual trigger: process only the next N POs after skip. 1 = one PO. null = all remaining POs. @@ -101,7 +102,7 @@ open class SearchCompletedDnService( toProcess.forEach { (poId, silList) -> silList.firstOrNull()?.let { first -> try { - stockInLineService.processPurchaseOrderForGrn(first) + stockInLineService.processPurchaseOrderForGrn(first, grnReceiptDate = receiptDate) } catch (e: Exception) { logger.error("[postCompletedDnAndProcessGrn] Failed for PO id=$poId: ${e.message}", e) } @@ -111,13 +112,9 @@ open class SearchCompletedDnService( } /** - * Retry GRN creation for completed stock-in lines where the PO does not have a SUCCESS log in - * `m18_goods_receipt_note_log`. - * - * Grouping behavior matches normal scheduler: - * - iterate by `receiptDate` day window - * - for each day, group by `PO (purchaseOrderId)` - * - process one GRN per PO using the first line from that PO group + * Retry GRN creation for completed stock-in lines where **some** line in that PO batch (same receipt date) + * has no SUCCESS row in `m18_goods_receipt_note_log` (matched by `stock_in_line_id`). + * Same PO can receive multiple GRNs on different delivery/receipt dates. */ @Transactional open fun postCompletedDnAndProcessGrnWithMissingRetry( @@ -172,9 +169,12 @@ open class SearchCompletedDnService( val byPo = lines.groupBy { it.purchaseOrder?.id ?: 0L }.filterKeys { it != 0L } val entries = byPo.entries.toList() - // Only retry POs that do NOT have any successful GRN log. - val missingEntries = entries.filter { (poId, _) -> - !m18GoodsReceiptNoteLogRepository.existsByPurchaseOrderIdAndStatusTrue(poId) + // Per delivery date: retry if any completed line for this PO on this date lacks a successful GRN log. + val missingEntries = entries.filter { (_, silList) -> + silList.any { sil -> + val id = sil.id ?: return@any true + !m18GoodsReceiptNoteLogRepository.existsByStockInLineIdAndStatusTrue(id) + } } val toProcess = missingEntries @@ -190,7 +190,7 @@ open class SearchCompletedDnService( toProcess.forEach { (poId, silList) -> silList.firstOrNull()?.let { first -> try { - stockInLineService.processPurchaseOrderForGrn(first) + stockInLineService.processPurchaseOrderForGrn(first, grnReceiptDate = receiptDate) } catch (e: Exception) { logger.error("[postCompletedDnAndProcessMissingGrnForReceiptDate] Failed for PO id=$poId: ${e.message}", e) } diff --git a/src/main/java/com/ffii/fpsms/modules/stock/service/StockInLineService.kt b/src/main/java/com/ffii/fpsms/modules/stock/service/StockInLineService.kt index 2bc46dd..784b10d 100644 --- a/src/main/java/com/ffii/fpsms/modules/stock/service/StockInLineService.kt +++ b/src/main/java/com/ffii/fpsms/modules/stock/service/StockInLineService.kt @@ -660,10 +660,10 @@ open class StockInLineService( /** * Processes a purchase order for M18 GRN creation. Updates PO/line status and creates GRN if applicable. - * Called by SearchCompletedDnService (scheduler postCompletedDnAndProcessGrn) for batch processing of yesterday's completed DNs. + * @param grnReceiptDate When set (scheduler paths), only completed lines on that calendar receipt day are included — separate deliveries get separate GRNs. */ - open fun processPurchaseOrderForGrn(stockInLine: StockInLine) { - tryUpdatePurchaseOrderAndCreateGrnIfCompleted(stockInLine) + open fun processPurchaseOrderForGrn(stockInLine: StockInLine, grnReceiptDate: LocalDate? = null) { + tryUpdatePurchaseOrderAndCreateGrnIfCompleted(stockInLine, grnReceiptDate = grnReceiptDate) } /** @@ -671,7 +671,10 @@ open class StockInLineService( * creates M18 Goods Receipt Note. Called after saving stock-in line for both * RECEIVED and PENDING/ESCALATED status flows. */ - private fun tryUpdatePurchaseOrderAndCreateGrnIfCompleted(savedStockInLine: StockInLine) { + private fun tryUpdatePurchaseOrderAndCreateGrnIfCompleted( + savedStockInLine: StockInLine, + grnReceiptDate: LocalDate? = null, + ) { if (savedStockInLine.purchaseOrderLine == null) return val pol = savedStockInLine.purchaseOrderLine ?: return updatePurchaseOrderLineStatus(pol) @@ -682,12 +685,29 @@ open class StockInLineService( // Align POL.m18Lot with M18 before GRN (sourceLot must match M18 PO line lot or AN save may fail). syncPurchaseOrderLineM18LotFromM18(savedPo) - // Defensive: load only completed stock-in lines for the PO, so GRN payload can't include pending/escalated. - val linesForGrn = stockInLineRepository.findCompletedByPurchaseOrderIdAndDeletedFalseWithItemNames(savedPo.id!!) + // Completed lines for GRN: either this receipt date only (multi-delivery POs) or all completed on PO (legacy). + val linesForGrn = if (grnReceiptDate != null) { + stockInLineRepository.findCompletedByPurchaseOrderIdAndReceiptDateAndDeletedFalseWithItemNames( + savedPo.id!!, + grnReceiptDate, + ) + } else { + stockInLineRepository.findCompletedByPurchaseOrderIdAndDeletedFalseWithItemNames(savedPo.id!!) + } if (linesForGrn.isEmpty()) { logger.info("[tryUpdatePurchaseOrderAndCreateGrnIfCompleted] DEBUG: Skipping M18 GRN - no stock-in lines for PO id=${savedPo.id} code=${savedPo.code}") return } + if (grnReceiptDate != null && linesForGrn.all { sil -> + val id = sil.id ?: return@all false + m18GoodsReceiptNoteLogRepository.existsByStockInLineIdAndStatusTrue(id) + }) { + logger.info( + "[tryUpdatePurchaseOrderAndCreateGrnIfCompleted] Skipping M18 GRN — all ${linesForGrn.size} line(s) for PO id=${savedPo.id} " + + "code=${savedPo.code} on receipt date $grnReceiptDate already have successful GRN logs" + ) + return + } if (savedPo.m18BeId == null || savedPo.supplier?.m18Id == null || savedPo.currency?.m18Id == null) { logger.info("[tryUpdatePurchaseOrderAndCreateGrnIfCompleted] DEBUG: Skipping M18 GRN - missing M18 ids for PO id=${savedPo.id} code=${savedPo.code}. m18BeId=${savedPo.m18BeId}, supplier.m18Id=${savedPo.supplier?.m18Id}, currency.m18Id=${savedPo.currency?.m18Id}") return diff --git a/src/main/java/com/ffii/fpsms/py/PrintedQtyByChannel.kt b/src/main/java/com/ffii/fpsms/py/PrintedQtyByChannel.kt new file mode 100644 index 0000000..1f53f6e --- /dev/null +++ b/src/main/java/com/ffii/fpsms/py/PrintedQtyByChannel.kt @@ -0,0 +1,8 @@ +package com.ffii.fpsms.py + +/** Per–job-order cumulative printed qty, split by printer channel (not mixed). */ +data class PrintedQtyByChannel( + val bagPrintedQty: Long = 0, + val labelPrintedQty: Long = 0, + val laserPrintedQty: Long = 0, +) diff --git a/src/main/java/com/ffii/fpsms/py/PyController.kt b/src/main/java/com/ffii/fpsms/py/PyController.kt index 2fc88d9..e80157e 100644 --- a/src/main/java/com/ffii/fpsms/py/PyController.kt +++ b/src/main/java/com/ffii/fpsms/py/PyController.kt @@ -7,9 +7,13 @@ import com.ffii.fpsms.modules.stock.entity.StockInLineRepository import org.springframework.format.annotation.DateTimeFormat import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.PostMapping +import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController +import org.springframework.web.server.ResponseStatusException +import org.springframework.http.HttpStatus import java.time.LocalDate import java.time.LocalDateTime @@ -23,6 +27,7 @@ open class PyController( private val jobOrderRepository: JobOrderRepository, private val stockInLineRepository: StockInLineRepository, private val plasticBagPrinterService: PlasticBagPrinterService, + private val pyJobOrderPrintSubmitService: PyJobOrderPrintSubmitService, ) { companion object { private const val PACKAGING_PROCESS_NAME = "包裝" @@ -46,10 +51,34 @@ open class PyController( dayEndExclusive, PACKAGING_PROCESS_NAME, ) - val list = orders.map { jo -> toListItem(jo) } + val ids = orders.mapNotNull { it.id } + val printed = pyJobOrderPrintSubmitService.sumPrintedQtyByJobOrderIds(ids) + val list = orders.map { jo -> + toListItem(jo, printed[jo.id!!]) + } return ResponseEntity.ok(list) } + /** + * Record a print submit from Bag2 (e.g. 標簽機). No login. + * POST /py/job-order-print-submit + * Body: { "jobOrderId": 1, "qty": 10, "printChannel": "LABEL" | "DATAFLEX" | "LASER" } + */ + @PostMapping("/job-order-print-submit") + open fun submitJobOrderPrint( + @RequestBody body: PyJobOrderPrintSubmitRequest, + ): ResponseEntity { + val channel = body.printChannel?.trim()?.takeIf { it.isNotEmpty() } ?: PyPrintChannel.LABEL + if ( + channel != PyPrintChannel.LABEL && + channel != PyPrintChannel.DATAFLEX && + channel != PyPrintChannel.LASER + ) { + throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Unsupported printChannel: $channel") + } + return ResponseEntity.ok(pyJobOrderPrintSubmitService.recordPrint(body.jobOrderId, body.qty, channel)) + } + /** * Same as [listJobOrders] but filtered by system setting [com.ffii.fpsms.modules.common.SettingNames.LASER_PRINT_ITEM_CODES] * (comma-separated item codes). Public — no login (same as /py/job-orders). @@ -62,13 +91,14 @@ open class PyController( return ResponseEntity.ok(plasticBagPrinterService.listLaserPrintJobOrders(date)) } - private fun toListItem(jo: JobOrder): PyJobOrderListItem { + private fun toListItem(jo: JobOrder, printed: PrintedQtyByChannel?): PyJobOrderListItem { val itemCode = jo.bom?.item?.code ?: jo.bom?.code val itemName = jo.bom?.name ?: jo.bom?.item?.name val itemId = jo.bom?.item?.id val stockInLine = jo.id?.let { stockInLineRepository.findFirstByJobOrder_IdAndDeletedFalse(it) } val stockInLineId = stockInLine?.id val lotNo = stockInLine?.lotNo + val p = printed ?: PrintedQtyByChannel() return PyJobOrderListItem( id = jo.id!!, code = jo.code, @@ -79,6 +109,9 @@ open class PyController( stockInLineId = stockInLineId, itemId = itemId, lotNo = lotNo, + bagPrintedQty = p.bagPrintedQty, + labelPrintedQty = p.labelPrintedQty, + laserPrintedQty = p.laserPrintedQty, ) } } diff --git a/src/main/java/com/ffii/fpsms/py/PyJobOrderListItem.kt b/src/main/java/com/ffii/fpsms/py/PyJobOrderListItem.kt index ac29be9..017d9d6 100644 --- a/src/main/java/com/ffii/fpsms/py/PyJobOrderListItem.kt +++ b/src/main/java/com/ffii/fpsms/py/PyJobOrderListItem.kt @@ -19,4 +19,10 @@ data class PyJobOrderListItem( val stockInLineId: Long?, val itemId: Long?, val lotNo: String?, + /** Cumulative qty from 打袋機 DataFlex submits (DATAFLEX). */ + val bagPrintedQty: Long = 0, + /** Cumulative qty from 標簽機 submits (LABEL). */ + val labelPrintedQty: Long = 0, + /** Cumulative qty from 激光機 submits (LASER). */ + val laserPrintedQty: Long = 0, ) diff --git a/src/main/java/com/ffii/fpsms/py/PyJobOrderPrintSubmitRepository.kt b/src/main/java/com/ffii/fpsms/py/PyJobOrderPrintSubmitRepository.kt new file mode 100644 index 0000000..713bdcc --- /dev/null +++ b/src/main/java/com/ffii/fpsms/py/PyJobOrderPrintSubmitRepository.kt @@ -0,0 +1,35 @@ +package com.ffii.fpsms.py + +import com.ffii.core.support.AbstractRepository +import com.ffii.fpsms.py.entity.PyJobOrderPrintSubmit +import org.springframework.data.jpa.repository.Query +import org.springframework.data.repository.query.Param + +interface PyJobOrderPrintSubmitRepository : AbstractRepository { + + @Query( + value = + "SELECT job_order_id, COALESCE(SUM(qty), 0) FROM py_job_order_print_submit " + + "WHERE deleted = 0 AND job_order_id IN (:ids) AND print_channel = :channel " + + "GROUP BY job_order_id", + nativeQuery = true, + ) + fun sumQtyGroupedByJobOrderId( + @Param("ids") ids: List, + @Param("channel") channel: String, + ): List> + + /** + * One row per (job_order_id, print_channel) with summed qty. + */ + @Query( + value = + "SELECT job_order_id, print_channel, COALESCE(SUM(qty), 0) FROM py_job_order_print_submit " + + "WHERE deleted = 0 AND job_order_id IN (:ids) " + + "GROUP BY job_order_id, print_channel", + nativeQuery = true, + ) + fun sumQtyGroupedByJobOrderIdAndChannel( + @Param("ids") ids: List, + ): List> +} diff --git a/src/main/java/com/ffii/fpsms/py/PyJobOrderPrintSubmitRequest.kt b/src/main/java/com/ffii/fpsms/py/PyJobOrderPrintSubmitRequest.kt new file mode 100644 index 0000000..503a6f1 --- /dev/null +++ b/src/main/java/com/ffii/fpsms/py/PyJobOrderPrintSubmitRequest.kt @@ -0,0 +1,11 @@ +package com.ffii.fpsms.py + +/** + * POST /py/job-order-print-submit + */ +data class PyJobOrderPrintSubmitRequest( + val jobOrderId: Long, + val qty: Int, + /** [PyPrintChannel.LABEL] | [PyPrintChannel.DATAFLEX] | [PyPrintChannel.LASER]; omit or blank → LABEL. */ + val printChannel: String? = null, +) diff --git a/src/main/java/com/ffii/fpsms/py/PyJobOrderPrintSubmitResponse.kt b/src/main/java/com/ffii/fpsms/py/PyJobOrderPrintSubmitResponse.kt new file mode 100644 index 0000000..f32f147 --- /dev/null +++ b/src/main/java/com/ffii/fpsms/py/PyJobOrderPrintSubmitResponse.kt @@ -0,0 +1,9 @@ +package com.ffii.fpsms.py + +data class PyJobOrderPrintSubmitResponse( + val jobOrderId: Long, + val submittedQty: Int, + val printChannel: String, + /** Cumulative printed qty for this job order and [printChannel] after this submit. */ + val cumulativeQtyForChannel: Long, +) diff --git a/src/main/java/com/ffii/fpsms/py/PyJobOrderPrintSubmitService.kt b/src/main/java/com/ffii/fpsms/py/PyJobOrderPrintSubmitService.kt new file mode 100644 index 0000000..5f168b3 --- /dev/null +++ b/src/main/java/com/ffii/fpsms/py/PyJobOrderPrintSubmitService.kt @@ -0,0 +1,72 @@ +package com.ffii.fpsms.py + +import com.ffii.fpsms.modules.jobOrder.entity.JobOrderRepository +import com.ffii.fpsms.py.entity.PyJobOrderPrintSubmit +import org.springframework.http.HttpStatus +import org.springframework.stereotype.Service +import org.springframework.transaction.annotation.Transactional +import org.springframework.web.server.ResponseStatusException + +@Service +open class PyJobOrderPrintSubmitService( + private val repository: PyJobOrderPrintSubmitRepository, + private val jobOrderRepository: JobOrderRepository, +) { + + /** + * Cumulative printed qty per job order, split by channel (打袋 / 標籤 / 激光). + */ + open fun sumPrintedQtyByJobOrderIds(ids: List): Map { + if (ids.isEmpty()) return emptyMap() + val rows = repository.sumQtyGroupedByJobOrderIdAndChannel(ids) + val out = mutableMapOf() + for (row in rows) { + val jobOrderId = (row[0] as Number).toLong() + val channel = (row[1] as String).trim() + val qty = (row[2] as Number).toLong() + val cur = out.getOrDefault(jobOrderId, PrintedQtyByChannel()) + out[jobOrderId] = + when (channel) { + PyPrintChannel.DATAFLEX -> cur.copy(bagPrintedQty = qty) + PyPrintChannel.LABEL -> cur.copy(labelPrintedQty = qty) + PyPrintChannel.LASER -> cur.copy(laserPrintedQty = qty) + else -> cur + } + } + return out + } + + private fun sumPrintedByJobOrderIdsAndChannel(ids: List, channel: String): Map { + if (ids.isEmpty()) return emptyMap() + val rows = repository.sumQtyGroupedByJobOrderId(ids, channel) + return rows.associate { row -> + (row[0] as Number).toLong() to (row[1] as Number).toLong() + } + } + + /** + * Persist one submit row and return cumulative print total for that job order and channel. + */ + @Transactional + open fun recordPrint(jobOrderId: Long, qty: Int, printChannel: String): PyJobOrderPrintSubmitResponse { + if (qty < 1) { + throw ResponseStatusException(HttpStatus.BAD_REQUEST, "qty must be at least 1") + } + val jo = jobOrderRepository.findById(jobOrderId).orElseThrow { + ResponseStatusException(HttpStatus.NOT_FOUND, "Job order not found: $jobOrderId") + } + val row = PyJobOrderPrintSubmit().apply { + jobOrder = jo + this.qty = qty + this.printChannel = printChannel + } + repository.save(row) + val total = sumPrintedByJobOrderIdsAndChannel(listOf(jobOrderId), printChannel)[jobOrderId] ?: qty.toLong() + return PyJobOrderPrintSubmitResponse( + jobOrderId = jobOrderId, + submittedQty = qty, + printChannel = printChannel, + cumulativeQtyForChannel = total, + ) + } +} diff --git a/src/main/java/com/ffii/fpsms/py/PyPrintChannel.kt b/src/main/java/com/ffii/fpsms/py/PyPrintChannel.kt new file mode 100644 index 0000000..f2f81ae --- /dev/null +++ b/src/main/java/com/ffii/fpsms/py/PyPrintChannel.kt @@ -0,0 +1,8 @@ +package com.ffii.fpsms.py + +/** Values for [com.ffii.fpsms.py.entity.PyJobOrderPrintSubmit.printChannel]. */ +object PyPrintChannel { + const val LABEL = "LABEL" + const val DATAFLEX = "DATAFLEX" + const val LASER = "LASER" +} diff --git a/src/main/java/com/ffii/fpsms/py/entity/PyJobOrderPrintSubmit.kt b/src/main/java/com/ffii/fpsms/py/entity/PyJobOrderPrintSubmit.kt new file mode 100644 index 0000000..92a7858 --- /dev/null +++ b/src/main/java/com/ffii/fpsms/py/entity/PyJobOrderPrintSubmit.kt @@ -0,0 +1,35 @@ +package com.ffii.fpsms.py.entity + +import com.ffii.core.entity.BaseEntity +import com.ffii.fpsms.modules.jobOrder.entity.JobOrder +import jakarta.persistence.Column +import jakarta.persistence.Entity +import jakarta.persistence.FetchType +import jakarta.persistence.JoinColumn +import jakarta.persistence.ManyToOne +import jakarta.persistence.Table +import jakarta.validation.constraints.NotNull +import jakarta.validation.constraints.Size + +/** + * One row each time a Bag/py client submits a print quantity for a job order (per printer channel). + * [printChannel] distinguishes 打袋 (DATAFLEX), 標籤 (LABEL), 激光 (LASER); cumulative [qty] per channel. + */ +@Entity +@Table(name = "py_job_order_print_submit") +open class PyJobOrderPrintSubmit : BaseEntity() { + + @NotNull + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "job_order_id", nullable = false, columnDefinition = "INT") + open var jobOrder: JobOrder? = null + + @NotNull + @Column(name = "qty", nullable = false) + open var qty: Int? = null + + @Size(max = 32) + @NotNull + @Column(name = "print_channel", nullable = false, length = 32) + open var printChannel: String? = null +} diff --git a/src/main/resources/DeliveryNote/DeliveryNoteCartonLabelsPDF.jrxml b/src/main/resources/DeliveryNote/DeliveryNoteCartonLabelsPDF.jrxml index bd6161c..953bdd4 100644 --- a/src/main/resources/DeliveryNote/DeliveryNoteCartonLabelsPDF.jrxml +++ b/src/main/resources/DeliveryNote/DeliveryNoteCartonLabelsPDF.jrxml @@ -1,166 +1,180 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index deca0cb..f6d66b6 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -50,6 +50,20 @@ jwt: logging: config: 'classpath:log4j2.yml' +# Optional NGPCL gateway: receives the same bytes as /plastic/download-onpack-qr-text (Content-Type: application/zip). +# Leave empty to disable; set NGPCL_PUSH_URL in production if you expose an HTTP receiver for the lemon OnPack ZIP. +ngpcl: + push-url: ${NGPCL_PUSH_URL:} + +# Laser Bag2 (/laserPrint) auto-send: same as listing + TCP send using DB LASER_PRINT.host / port / itemCodes. +# Scheduler is off by default. limit-per-run: max job orders per tick (1 = first matching only); 0 = all matches (heavy). +laser: + bag2: + auto-send: + enabled: false + interval-ms: 60000 + limit-per-run: 1 + bom: import: temp-dir: ${java.io.tmpdir}/fpsms-bom-import diff --git a/src/main/resources/db/changelog/changes/20260326_fai/01_create_py_job_order_print_submit.sql b/src/main/resources/db/changelog/changes/20260326_fai/01_create_py_job_order_print_submit.sql new file mode 100644 index 0000000..1825ba7 --- /dev/null +++ b/src/main/resources/db/changelog/changes/20260326_fai/01_create_py_job_order_print_submit.sql @@ -0,0 +1,22 @@ +--liquibase formatted sql +--changeset fai:20260326_py_job_order_print_submit + +CREATE TABLE IF NOT EXISTS `py_job_order_print_submit` ( + `id` BIGINT NOT NULL AUTO_INCREMENT, + `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + `createdBy` VARCHAR(30) NULL DEFAULT NULL, + `version` INT NOT NULL DEFAULT '0', + `modified` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `modifiedBy` VARCHAR(30) NULL DEFAULT NULL, + `deleted` TINYINT(1) NOT NULL DEFAULT '0', + + `job_order_id` INT NOT NULL COMMENT 'FK job_order (must match job_order.id type)', + `qty` INT NOT NULL COMMENT 'Quantity printed this submit (labels, bags, etc.)', + `print_channel` VARCHAR(32) NOT NULL DEFAULT 'LABEL' COMMENT 'LABEL=標簽機, DATAFLEX=打袋機, …', + + CONSTRAINT `pk_py_job_order_print_submit` PRIMARY KEY (`id`), + KEY `idx_py_jops_job_order` (`job_order_id`), + KEY `idx_py_jops_channel_created` (`print_channel`, `created`), + CONSTRAINT `fk_py_jops_job_order` FOREIGN KEY (`job_order_id`) REFERENCES `job_order` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + COMMENT='Per-submit print qty for Bag2/py clients; cumulative per job order for wastage/stock.'; diff --git a/src/main/resources/db/changelog/changes/20260327_laser_last_receive_success/01_laser_print_last_receive_success.sql b/src/main/resources/db/changelog/changes/20260327_laser_last_receive_success/01_laser_print_last_receive_success.sql new file mode 100644 index 0000000..a85edc6 --- /dev/null +++ b/src/main/resources/db/changelog/changes/20260327_laser_last_receive_success/01_laser_print_last_receive_success.sql @@ -0,0 +1,8 @@ +--liquibase formatted sql +--changeset fpsms:20260327_laser_print_last_receive_success + +INSERT INTO `settings` (`name`, `value`, `category`, `type`) +SELECT 'LASER_PRINT.lastReceiveSuccess', '{}', 'LASER', 'string' +WHERE NOT EXISTS ( + SELECT 1 FROM `settings` s WHERE s.name = 'LASER_PRINT.lastReceiveSuccess' +); diff --git a/src/main/resources/fonts/fonts.xml b/src/main/resources/fonts/fonts.xml index 8a909f9..79d3016 100644 --- a/src/main/resources/fonts/fonts.xml +++ b/src/main/resources/fonts/fonts.xml @@ -24,5 +24,4 @@ '華文宋體', Arial, Helvetica, sans-serif - - + \ No newline at end of file