import socket import datetime from .print_config import PrintConfigManager class NetworkPrintService: def __init__(self, ip=None, port=None): config = PrintConfigManager.get_config('network_printer') self.ip = ip if ip is not None else config['ip'] self.port = port if port is not None else config['port'] def _send_to_printer(self, content): """ 对于 A4 打印机,后端直接发送 Socket 指令通常无效或导致乱码。 因此这里只做日志记录,实际打印由前端浏览器完成。 """ print(f"--- [后端日志] 收到打印请求 (实际由前端处理) ---\n{content}\n----------------") return True, "记录成功" def print_outbound_selection(self, items): """ 仅记录出库日志,不发送物理指令 """ try: timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M") total_qty = sum([float(i.get('quantity', 0)) for i in items]) # 简单构造一个日志字符串 log_content = f"出库时间: {timestamp}, 总数: {int(total_qty)}\n" for item in items: log_content += f"- {item.get('name')} (规格:{item.get('standard')}) x {item.get('quantity')}\n" # 调用虚拟发送 return self._send_to_printer(log_content) except Exception as e: print(f"日志记录失败: {e}") return True, "记录忽略" # 即使失败也不要在前端报错 def print_stocktake_report(self, data): # 同样处理 return self._send_to_printer(f"盘点报告: 应盘{data.get('total')}, 实盘{data.get('scanned')}")