""" 数据库操作模块 使用 MySQL 存储地磅单、公司名称、货物名称、用户等所有业务数据 (已移除 SQLite,当前工程仅支持 MySQL) """ import os import sys import time from datetime import datetime from typing import List, Dict, Optional, Tuple import logging # 尝试导入MySQL相关模块 try: import pymysql PYMySQL_AVAILABLE = True except ImportError: PYMySQL_AVAILABLE = False # 尝试导入配置模块 try: import config MYSQL_ENABLED = getattr(config, 'ENABLE_MYSQL', False) and PYMySQL_AVAILABLE MYSQL_CONFIG = getattr(config, 'MYSQL_CONFIG', {}) CONTINUE_ON_MYSQL_ERROR = getattr(config, 'CONTINUE_ON_MYSQL_ERROR', True) except ImportError: MYSQL_ENABLED = False MYSQL_CONFIG = {} CONTINUE_ON_MYSQL_ERROR = True # 配置日志 - 设置为INFO级别以便看到MySQL操作信息 logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) def get_base_path(): """ 获取程序运行的基础路径 在开发环境中返回脚本所在目录,在打包后返回exe所在目录 """ if getattr(sys, 'frozen', False): # 打包后的exe环境 return os.path.dirname(sys.executable) else: # 开发环境 return os.path.dirname(os.path.abspath(__file__)) class Database: WAITING_STATUS_MAP = { '入库': '待入库', '出库': '待出库' } IN_PROGRESS_STATUS_MAP = { '入库': '入库中', '出库': '出库中' } DONE_STATUS_MAP = { '入库': '已完成', '出库': '已完成' } EXCEEDED_STATUS_MAP = { '入库': '已超额', '出库': '已超额' } """数据库操作类,仅支持 MySQL 存储""" def __init__(self, db_path: str = None): """ 初始化数据库连接 :param db_path: 兼容旧版本参数(已废弃,不再使用 SQLite 文件) """ import time init_start = time.time() logger.info("📦 开始初始化数据库...") # 兼容旧版本属性,占位,不再实际使用 SQLite 文件 self.db_path = db_path if db_path: logger.info(f" (兼容信息) 传入的本地数据库路径已忽略: {db_path}") self.mysql_enabled = MYSQL_ENABLED logger.info(f" MySQL支持: {'启用' if self.mysql_enabled else '禁用'}") self.mysql_connection = None if not self.mysql_enabled: logger.error("当前工程已移除 SQLite,必须启用 MySQL 才能正常运行,请在 config.py 中将 ENABLE_MYSQL 设置为 True") raise RuntimeError("必须启用 MySQL(ENABLE_MYSQL = True)") db_init_start = time.time() logger.info(" 开始初始化 MySQL 数据库表结构(如有需要)...") self.init_database() logger.info(f" ✅ MySQL 数据库初始化流程执行完成 (耗时: {time.time() - db_init_start:.3f}秒)") logger.info(f"✅ 数据库对象创建完成 (总耗时: {time.time() - init_start:.3f}秒)") def _get_waiting_status(self, business_type: str) -> str: return self.WAITING_STATUS_MAP.get(business_type, '待入库') def _get_in_progress_status(self, business_type: str) -> str: return self.IN_PROGRESS_STATUS_MAP.get(business_type, '入库中') def _get_done_status(self, business_type: str) -> str: return self.DONE_STATUS_MAP.get(business_type, '已完成') def _get_exceeded_status(self, business_type: str) -> str: return self.EXCEEDED_STATUS_MAP.get(business_type, '已超额') def _update_plan_status(self, plan_id: int, status: str, executed_at: Optional[str], slip_id: Optional[int], executed_quantity: Optional[float]): """更新采购计划状态(仅 MySQL)""" if not plan_id: return try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" UPDATE purchase_plans SET execution_status = %s, executed_at = %s, last_weighing_slip_id = %s, executed_quantity = %s WHERE id = %s """, (status, executed_at, slip_id, executed_quantity, plan_id)) mysql_conn.commit() except Exception as e: logger.warning(f"MySQL更新计划状态失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise def _get_latest_active_slip_for_plan(self, plan_id: int) -> Optional[Dict]: """获取计划最新且未作废的地磅单(仅 MySQL)""" try: mysql_conn = self.get_mysql_connection() if not mysql_conn: return None with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" SELECT * FROM weighing_slips WHERE purchase_plan_id = %s AND is_voided = 0 ORDER BY id DESC LIMIT 1 """, (plan_id,)) row = mysql_cursor.fetchone() return dict(row) if row else None except Exception as e: logger.warning(f"MySQL获取最新地磅单失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return None def refresh_plan_execution_status(self, plan_id: int): """根据地磅单净重累加刷新计划状态""" if not plan_id: return plan = self.get_purchase_plan_by_id(plan_id) if not plan: return # 计算已执行量(通过地磅单的净重数据累加,单位:kg) executed_quantity = self._calculate_execution_quantity(plan_id) # 计划量(单位:t,需要转换为kg) planned_quantity_kg = plan.get('planned_quantity', 0) * 1000 # 根据已执行量和计划量比较得出状态 if executed_quantity == 0: # 已执行量=0 -> 待入库/待出库 status = self._get_waiting_status(plan['business_type']) elif executed_quantity > 0 and executed_quantity < planned_quantity_kg: # 已执行量>0且<计划量 -> 入库中/出库中 status = self._get_in_progress_status(plan['business_type']) elif executed_quantity == planned_quantity_kg: # 已执行量=计划量 -> 已完成 status = self._get_done_status(plan['business_type']) else: # executed_quantity > planned_quantity_kg # 已执行量>计划量 -> 已超额 status = self._get_exceeded_status(plan['business_type']) # 获取最新地磅单的时间 latest_slip = self._get_latest_active_slip_for_plan(plan_id) executed_at = latest_slip.get('created_at') if latest_slip else None slip_id = latest_slip.get('id') if latest_slip else None self._update_plan_status(plan_id, status, executed_at, slip_id, executed_quantity) def refresh_all_plans_execution_status(self, plan_ids: List[int]) -> Dict[int, Dict]: """ 批量刷新多个计划的执行状态(一次连接内完成),减少登录/刷新时的数据库往返。 返回 {plan_id: {execution_status, executed_quantity, executed_at, last_weighing_slip_id}} """ if not plan_ids: return {} plan_ids = list({int(pid) for pid in plan_ids if pid}) if not plan_ids or not self.mysql_enabled: return {} try: mysql_conn = self.get_mysql_connection() if not mysql_conn: return {} with mysql_conn.cursor() as cur: placeholders = ", ".join(["%s"] * len(plan_ids)) cur.execute( f"SELECT id, business_type, planned_quantity FROM purchase_plans WHERE id IN ({placeholders})", tuple(plan_ids), ) plans_rows = {row["id"]: dict(row) for row in cur.fetchall()} if not plans_rows: return {} cur.execute( f""" SELECT purchase_plan_id, COALESCE(SUM(net_weight), 0) as total_weight FROM weighing_slips WHERE purchase_plan_id IN ({placeholders}) AND is_voided = 0 GROUP BY purchase_plan_id """, tuple(plan_ids), ) executed_map = { row["purchase_plan_id"]: float(row["total_weight"] or 0) for row in cur.fetchall() } cur.execute( f""" SELECT purchase_plan_id, id, created_at FROM weighing_slips WHERE is_voided = 0 AND purchase_plan_id IN ({placeholders}) ORDER BY purchase_plan_id, id DESC """, tuple(plan_ids), ) latest_slips = {} for row in cur.fetchall(): pid = row["purchase_plan_id"] if pid not in latest_slips: latest_slips[pid] = {"id": row["id"], "created_at": row.get("created_at")} updates = [] result = {} for pid in plan_ids: plan_row = plans_rows.get(pid) if not plan_row: continue planned_quantity_kg = (plan_row.get("planned_quantity") or 0) * 1000 executed_quantity = executed_map.get(pid, 0.0) business_type = plan_row.get("business_type") or "" if executed_quantity == 0: status = self._get_waiting_status(business_type) elif executed_quantity > 0 and executed_quantity < planned_quantity_kg: status = self._get_in_progress_status(business_type) elif executed_quantity == planned_quantity_kg: status = self._get_done_status(business_type) else: status = self._get_exceeded_status(business_type) slip_info = latest_slips.get(pid) executed_at = slip_info["created_at"] if slip_info else None slip_id = slip_info["id"] if slip_info else None updates.append((status, executed_at, slip_id, executed_quantity, pid)) result[pid] = { "execution_status": status, "executed_quantity": executed_quantity, "executed_at": executed_at, "last_weighing_slip_id": slip_id, } cur.executemany( """ UPDATE purchase_plans SET execution_status = %s, executed_at = %s, last_weighing_slip_id = %s, executed_quantity = %s WHERE id = %s """, updates, ) mysql_conn.commit() return result except Exception as e: logger.warning(f"MySQL批量刷新计划状态失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return {} def link_plan_with_slip(self, plan_id: int, slip_id: int): """在保存地磅单后关联计划状态""" if not plan_id: return self.refresh_plan_execution_status(plan_id) def _calculate_execution_quantity(self, plan_id: int) -> float: """统计计划已执行量(kg)- 通过地磅单的净重数据累加(仅 MySQL)""" try: mysql_conn = self.get_mysql_connection() if not mysql_conn: return 0.0 with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" SELECT COALESCE(SUM(net_weight), 0) as total_weight FROM weighing_slips WHERE purchase_plan_id = %s AND is_voided = 0 """, (plan_id,)) row = mysql_cursor.fetchone() if row: return float(row['total_weight'] if row['total_weight'] is not None else 0.0) except Exception as e: logger.warning(f"MySQL计算已执行量失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return 0.0 def _recalculate_slip_executed_quantities(self, plan_id: Optional[int] = None, plan_no: Optional[str] = None): """ 根据创建时间对同一计划下的地磅单逐条累加净重,回写已执行量 :param plan_id: 采购计划ID :param plan_no: 计划号 """ plan_no = plan_no.strip() if isinstance(plan_no, str) else None if not plan_id and not plan_no: return conditions = [] params: List = [] if plan_id: conditions.append("purchase_plan_id = ?") params.append(plan_id) if plan_no: conditions.append("(plan_no = ? AND plan_no <> '')") params.append(plan_no) if not conditions: return # 使用MySQL查询 if not self.mysql_enabled: logger.warning("MySQL未启用,无法重算已执行量") return try: mysql_conn = self.get_mysql_connection() if not mysql_conn: logger.warning("无法获取MySQL连接,无法重算已执行量") return with mysql_conn.cursor() as cursor: # 构建WHERE条件 where_parts = [] query_params = [] if plan_id: where_parts.append("purchase_plan_id = %s") query_params.append(plan_id) if plan_no: where_parts.append("(plan_no = %s AND plan_no <> '')") query_params.append(plan_no) if not where_parts: return where_clause = " OR ".join(where_parts) # 查询地磅单 cursor.execute(f""" SELECT id, net_weight, created_at FROM weighing_slips WHERE is_voided = 0 AND ({where_clause}) ORDER BY CASE WHEN created_at IS NULL OR created_at = '' THEN 1 ELSE 0 END, created_at ASC, id ASC """, query_params) rows = cursor.fetchall() cumulative = 0.0 updates = [] for row in rows: net_weight = row.get('net_weight') if row.get('net_weight') is not None else 0.0 if net_weight < 0: net_weight = 0.0 cumulative += float(net_weight) updates.append((cumulative, row['id'])) if updates: cursor.executemany(""" UPDATE weighing_slips SET executed_quantity = %s WHERE id = %s """, updates) mysql_conn.commit() except Exception as e: logger.warning(f"重算已执行量失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise def get_mysql_connection(self, force_reconnect: bool = False): """ 获取MySQL数据库连接 :param force_reconnect: 是否强制重新连接(用于确保读取最新数据) :return: MySQL连接对象 """ if not self.mysql_enabled: return None try: # 如果强制重新连接,先关闭旧连接 if force_reconnect and self.mysql_connection is not None: try: self.mysql_connection.close() logger.info("强制重新建立MySQL连接以获取最新数据") except: pass self.mysql_connection = None # 检查连接是否存在且有效 if self.mysql_connection is None: self.mysql_connection = pymysql.connect( host=MYSQL_CONFIG.get('host', 'localhost'), port=MYSQL_CONFIG.get('port', 3306), user=MYSQL_CONFIG.get('user', 'root'), password=MYSQL_CONFIG.get('password', ''), database=MYSQL_CONFIG.get('database', 'dibang'), charset=MYSQL_CONFIG.get('charset', 'utf8mb4'), cursorclass=pymysql.cursors.DictCursor, autocommit=False, connect_timeout=5, # 连接超时5秒 read_timeout=10, # 读取超时10秒 write_timeout=10 # 写入超时10秒 ) else: # 检查连接是否有效 try: self.mysql_connection.ping(reconnect=True) except Exception as ping_error: # 连接失效,重新连接 logger.info(f"MySQL连接失效,重新连接: {str(ping_error)}") try: self.mysql_connection.close() except: pass self.mysql_connection = pymysql.connect( host=MYSQL_CONFIG.get('host', 'localhost'), port=MYSQL_CONFIG.get('port', 3306), user=MYSQL_CONFIG.get('user', 'root'), password=MYSQL_CONFIG.get('password', ''), database=MYSQL_CONFIG.get('database', 'dibang'), charset=MYSQL_CONFIG.get('charset', 'utf8mb4'), cursorclass=pymysql.cursors.DictCursor, autocommit=False, connect_timeout=5, # 连接超时5秒 read_timeout=10, # 读取超时10秒 write_timeout=10 # 写入超时10秒 ) return self.mysql_connection except Exception as e: logger.warning(f"MySQL连接失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return None def _execute_mysql(self, sql: str, params: tuple = None): """执行MySQL语句(内部方法)""" if not self.mysql_enabled: return conn = self.get_mysql_connection() if conn is None: return try: with conn.cursor() as cursor: cursor.execute(sql, params) conn.commit() except Exception as e: logger.warning(f"MySQL执行失败: {str(e)}, SQL: {sql}") if not CONTINUE_ON_MYSQL_ERROR: raise try: conn.rollback() except: pass def init_database(self): """ 初始化数据库表结构(仅 MySQL) - 创建/升级 MySQL 表结构 - 确保默认管理员存在 """ # 使用原有的 MySQL 初始化逻辑 self._init_mysql_database() # 确保默认管理员存在(仅 MySQL) self.ensure_default_admin() def _init_mysql_database(self): """初始化MySQL数据库表结构""" conn = self.get_mysql_connection() if conn is None: return try: with conn.cursor() as cursor: # 创建地磅单表 cursor.execute(""" CREATE TABLE IF NOT EXISTS weighing_slips ( id INT PRIMARY KEY AUTO_INCREMENT, vehicle_no VARCHAR(255) NOT NULL, plan_no VARCHAR(255), cargo_name VARCHAR(255) NOT NULL, business_type VARCHAR(255) NOT NULL, batch_no VARCHAR(255), supplier VARCHAR(255) NOT NULL, consignee VARCHAR(255) NOT NULL, gross_weight DOUBLE NOT NULL, gross_weight_time VARCHAR(255) NOT NULL, tare_weight DOUBLE NOT NULL, tare_weight_time VARCHAR(255) NOT NULL, deduction DOUBLE DEFAULT 0, net_weight DOUBLE NOT NULL, planned_quantity DOUBLE, executed_quantity DOUBLE, weighing_point VARCHAR(255) DEFAULT '山峡地磅', remarks TEXT, is_voided INT DEFAULT 0, created_at VARCHAR(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 """) # 创建公司名称表 cursor.execute(""" CREATE TABLE IF NOT EXISTS companies ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255) NOT NULL UNIQUE, is_deleted INT DEFAULT 0, created_at VARCHAR(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 """) # 创建货物名称表 cursor.execute(""" CREATE TABLE IF NOT EXISTS cargos ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255) NOT NULL UNIQUE, is_deleted INT DEFAULT 0, created_at VARCHAR(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 """) # 创建采购计划表 cursor.execute(""" CREATE TABLE IF NOT EXISTS purchase_plans ( id INT PRIMARY KEY AUTO_INCREMENT, plan_date VARCHAR(255) NOT NULL, business_type VARCHAR(255) NOT NULL, product VARCHAR(255) NOT NULL, specification VARCHAR(255), planned_quantity DOUBLE NOT NULL, vehicle_no VARCHAR(255) DEFAULT '' COMMENT '车牌号(保留字段,不再使用)', customer_name VARCHAR(255), remarks TEXT, is_deleted INT DEFAULT 0, execution_status VARCHAR(50), executed_at VARCHAR(255), last_weighing_slip_id INT, executed_quantity DOUBLE DEFAULT 0, created_at VARCHAR(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 """) # 创建用户表 cursor.execute(""" CREATE TABLE IF NOT EXISTS users ( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(255) NOT NULL UNIQUE, password VARCHAR(255) NOT NULL, role VARCHAR(50) NOT NULL DEFAULT 'user', created_at VARCHAR(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 """) # 检查并添加customer_name字段(如果不存在) try: cursor.execute("ALTER TABLE purchase_plans ADD COLUMN customer_name VARCHAR(255)") except: pass # 字段已存在,忽略错误 # 检查并添加remarks字段(如果不存在) try: cursor.execute("ALTER TABLE purchase_plans ADD COLUMN remarks TEXT") except: pass # 检查并添加is_deleted字段 try: cursor.execute("ALTER TABLE purchase_plans ADD COLUMN is_deleted INT DEFAULT 0") cursor.execute("UPDATE purchase_plans SET is_deleted = 0 WHERE is_deleted IS NULL") except: pass # companies 表补充 is_deleted try: cursor.execute("ALTER TABLE companies ADD COLUMN is_deleted INT DEFAULT 0") cursor.execute("UPDATE companies SET is_deleted = 0 WHERE is_deleted IS NULL") except: pass # cargos 表补充 is_deleted try: cursor.execute("ALTER TABLE cargos ADD COLUMN is_deleted INT DEFAULT 0") cursor.execute("UPDATE cargos SET is_deleted = 0 WHERE is_deleted IS NULL") except: pass # purchase_plans execution_status try: cursor.execute("ALTER TABLE purchase_plans ADD COLUMN execution_status VARCHAR(50)") except: pass # purchase_plans vehicle_no 设置默认值(如果已存在表) try: cursor.execute("ALTER TABLE purchase_plans MODIFY vehicle_no VARCHAR(255) DEFAULT ''") except: pass # 如果失败(比如字段已存在且有不同约束),忽略错误 # purchase_plans executed_at try: cursor.execute("ALTER TABLE purchase_plans ADD COLUMN executed_at VARCHAR(255)") except: pass # purchase_plans last_weighing_slip_id try: cursor.execute("ALTER TABLE purchase_plans ADD COLUMN last_weighing_slip_id INT") except: pass # purchase_plans executed_quantity try: cursor.execute("ALTER TABLE purchase_plans ADD COLUMN executed_quantity DOUBLE DEFAULT 0") except: pass # weighing_slips purchase_plan_id try: cursor.execute("ALTER TABLE weighing_slips ADD COLUMN purchase_plan_id INT") except: pass # 创建出入库表 cursor.execute(""" CREATE TABLE IF NOT EXISTS inbound_outbound ( id INT PRIMARY KEY AUTO_INCREMENT, date VARCHAR(255) NOT NULL, partner_company VARCHAR(255) NOT NULL, business_type VARCHAR(255) NOT NULL, product VARCHAR(255) NOT NULL, quantity DOUBLE NOT NULL, plan_no VARCHAR(255), batch_no VARCHAR(255), vehicle_no VARCHAR(255) NOT NULL, status VARCHAR(50), remarks TEXT, purchase_plan_id INT, is_deleted INT DEFAULT 0, created_at VARCHAR(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 """) # purchase_plans 表添加 plan_no 字段 try: cursor.execute("ALTER TABLE purchase_plans ADD COLUMN plan_no VARCHAR(255)") except: pass # purchase_plans 表添加 start_date 和 end_date 字段 try: cursor.execute("ALTER TABLE purchase_plans ADD COLUMN start_date VARCHAR(255)") except: pass try: cursor.execute("ALTER TABLE purchase_plans ADD COLUMN end_date VARCHAR(255)") except: pass # weighing_slips 表添加 inbound_outbound_id 字段 try: cursor.execute("ALTER TABLE weighing_slips ADD COLUMN inbound_outbound_id INT") except: pass # weighing_slips 表添加 current_quantity 字段(本次量,单位:kg) try: cursor.execute("ALTER TABLE weighing_slips ADD COLUMN current_quantity DOUBLE") except: pass # 初始化MySQL execution_status cursor.execute(""" UPDATE purchase_plans SET execution_status = CASE business_type WHEN '入库' THEN '待入库' WHEN '出库' THEN '待出库' ELSE '待入库' END WHERE execution_status IS NULL OR execution_status = '' """) cursor.execute(""" UPDATE purchase_plans SET executed_quantity = 0 WHERE executed_quantity IS NULL """) # 将现有plan_date复制到start_date和end_date cursor.execute(""" UPDATE purchase_plans SET start_date = plan_date, end_date = plan_date WHERE (start_date IS NULL OR end_date IS NULL) AND plan_date IS NOT NULL """) conn.commit() except Exception as e: logger.warning(f"MySQL表初始化失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise try: conn.rollback() except: pass def _sync_mysql_to_sqlite(self): """ 兼容保留的方法(已废弃) 目前工程已不再使用 SQLite,仅保留空实现以避免旧代码引用报错。 """ logger.info("当前版本已不再从 MySQL 同步数据到 SQLite,_sync_mysql_to_sqlite 将被忽略。") # ========== 地磅单相关操作 ========== def insert_weighing_slip(self, data: Dict) -> int: """ 插入地磅单记录 :param data: 地磅单数据字典 :return: 插入记录的ID """ # 计算净重 net_weight = data['gross_weight'] - data['tare_weight'] - data.get('deduction', 0) created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S') inbound_id = data.get('inbound_outbound_id') if inbound_id: existing_slip = self.get_weighing_slip_by_inbound_id(inbound_id, include_voided=False) if existing_slip: raise ValueError("该出入库单已关联有效的地磅单,请先作废或解除关联后再新增。") record_id = None # 先操作MySQL,获取MySQL生成的ID if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" INSERT INTO weighing_slips ( vehicle_no, plan_no, cargo_name, business_type, batch_no, supplier, consignee, gross_weight, gross_weight_time, tare_weight, tare_weight_time, deduction, net_weight, planned_quantity, executed_quantity, purchase_plan_id, inbound_outbound_id, weighing_point, remarks, current_quantity, is_voided, created_at ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """, ( data['vehicle_no'], data.get('plan_no', ''), data['cargo_name'], data['business_type'], data.get('batch_no', ''), data['supplier'], data['consignee'], data['gross_weight'], data['gross_weight_time'], data['tare_weight'], data['tare_weight_time'], data.get('deduction', 0), net_weight, data.get('planned_quantity'), data.get('executed_quantity'), data.get('purchase_plan_id'), data.get('inbound_outbound_id'), data.get('weighing_point', '山峡地磅'), data.get('remarks', ''), data.get('current_quantity'), 0, # is_voided created_at )) record_id = mysql_cursor.lastrowid mysql_conn.commit() except Exception as e: logger.warning(f"MySQL插入地磅单失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise if record_id is None: raise RuntimeError("无法插入地磅单:MySQL未启用或插入失败") # 按创建时间重新计算同一计划下所有地磅单的已执行量 plan_no_value = data.get('plan_no') self._recalculate_slip_executed_quantities( plan_id=data.get('purchase_plan_id'), plan_no=plan_no_value if plan_no_value else None ) # 如果关联了出入库单,刷新出入库单状态 if data.get('inbound_outbound_id'): try: self.refresh_inbound_status(data['inbound_outbound_id']) except Exception as e: logger.warning(f"刷新出入库单状态失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise # 如果关联了计划,刷新计划状态(通过出入库单) if data.get('purchase_plan_id'): try: self.refresh_plan_execution_status(data['purchase_plan_id']) except Exception as e: logger.warning(f"刷新计划状态失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return record_id def update_weighing_slip(self, slip_id: int, data: Dict) -> bool: """ 更新地磅单记录 :param slip_id: 地磅单ID :param data: 更新后的地磅单数据 """ existing = self.get_weighing_slip_by_id(slip_id) if not existing: return False old_plan_id = existing.get('purchase_plan_id') old_plan_no = (existing.get('plan_no') or '').strip() new_plan_id = data.get('purchase_plan_id') new_plan_no = (data.get('plan_no') or '').strip() net_weight = data['gross_weight'] - data['tare_weight'] - data.get('deduction', 0) weighing_point = data.get('weighing_point', existing.get('weighing_point', '山峡地磅')) new_inbound_id = data.get('inbound_outbound_id') if new_inbound_id: conflict_slip = self.get_weighing_slip_by_inbound_id(new_inbound_id, include_voided=False) if conflict_slip and conflict_slip['id'] != slip_id: raise ValueError("该出入库单已关联其他地磅单,无法重复关联。") params = ( data['vehicle_no'], data.get('plan_no', ''), data['cargo_name'], data['business_type'], data.get('batch_no', ''), data['supplier'], data['consignee'], data['gross_weight'], data.get('gross_weight_time', ''), data['tare_weight'], data.get('tare_weight_time', ''), data.get('deduction', 0), net_weight, data.get('planned_quantity'), data.get('executed_quantity'), data.get('purchase_plan_id'), data.get('inbound_outbound_id'), weighing_point, data.get('remarks', ''), data.get('current_quantity'), slip_id ) mysql_success = False if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" UPDATE weighing_slips SET vehicle_no = %s, plan_no = %s, cargo_name = %s, business_type = %s, batch_no = %s, supplier = %s, consignee = %s, gross_weight = %s, gross_weight_time = %s, tare_weight = %s, tare_weight_time = %s, deduction = %s, net_weight = %s, planned_quantity = %s, executed_quantity = %s, purchase_plan_id = %s, inbound_outbound_id = %s, weighing_point = %s, remarks = %s, current_quantity = %s WHERE id = %s """, params) mysql_success = mysql_cursor.rowcount > 0 mysql_conn.commit() except Exception as e: logger.warning(f"MySQL更新地磅单失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return False if not self.mysql_enabled: logger.warning("MySQL未启用,无法更新地磅单") return False normalized_new_plan_no = new_plan_no if new_plan_no else None normalized_old_plan_no = old_plan_no if old_plan_no else None self._recalculate_slip_executed_quantities(plan_id=new_plan_id, plan_no=normalized_new_plan_no) if (old_plan_id or normalized_old_plan_no) and (old_plan_id, normalized_old_plan_no) != (new_plan_id, normalized_new_plan_no): self._recalculate_slip_executed_quantities(plan_id=old_plan_id, plan_no=normalized_old_plan_no) # 如果关联了出入库单,刷新出入库单状态 old_inbound_id = existing.get('inbound_outbound_id') new_inbound_id = data.get('inbound_outbound_id') try: if old_inbound_id and old_inbound_id != new_inbound_id: self.refresh_inbound_status(old_inbound_id) if new_inbound_id: self.refresh_inbound_status(new_inbound_id) except Exception as e: logger.warning(f"刷新出入库单状态失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise # 如果关联了计划,刷新计划状态(通过出入库单) try: if old_plan_id and old_plan_id != new_plan_id: self.refresh_plan_execution_status(old_plan_id) if new_plan_id: self.refresh_plan_execution_status(new_plan_id) except Exception as e: logger.warning(f"刷新计划状态失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return mysql_success def get_all_weighing_slips(self, include_voided: bool = False, keyword: Optional[str] = None) -> List[Dict]: """ 获取所有地磅单记录 :param include_voided: 是否包含作废的记录 :return: 地磅单记录列表(从出入库单关联获取 date 字段,别名为 inbound_date) """ search_text = (keyword or "").strip() like_value = f"%{search_text}%" if search_text else None # 仅使用MySQL查询 if not self.mysql_enabled: logger.warning("MySQL未启用,无法查询地磅单列表") return [] if self.mysql_enabled: try: # 复用已有 MySQL 连接,必要时由 get_mysql_connection 内部自动重连 mysql_conn = self.get_mysql_connection() if mysql_conn: try: # 确保事务已提交 mysql_conn.commit() # 设置隔离级别为READ COMMITTED with mysql_conn.cursor() as cursor: cursor.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED") with mysql_conn.cursor() as mysql_cursor: # 通过出入库单表关联获取日期字段(inbound_outbound.date → inbound_date) if include_voided: base_query = """ SELECT ws.*, io.date AS inbound_date FROM weighing_slips ws LEFT JOIN inbound_outbound io ON ws.inbound_outbound_id = io.id """ where_clause = "" else: base_query = """ SELECT ws.*, io.date AS inbound_date FROM weighing_slips ws LEFT JOIN inbound_outbound io ON ws.inbound_outbound_id = io.id """ where_clause = "WHERE ws.is_voided = 0" params: Tuple = () if like_value: search_clause = ( "ws.supplier LIKE %s OR ws.consignee LIKE %s " "OR ws.vehicle_no LIKE %s OR ws.cargo_name LIKE %s" ) if where_clause: where_clause = f"{where_clause} AND ({search_clause})" else: where_clause = f"WHERE ({search_clause})" params = (like_value, like_value, like_value, like_value) # 按关联的出入库单日期、创建时间、毛重时间、皮重时间倒序排列 order_clause = ( "ORDER BY io.date DESC, ws.created_at DESC, " "ws.gross_weight_time DESC, ws.tare_weight_time DESC, ws.id DESC" ) mysql_cursor.execute(f"{base_query} {where_clause} {order_clause}", params) rows = mysql_cursor.fetchall() result = [dict(row) for row in rows] logger.info(f"✅ 从MySQL获取地磅单列表,共{len(result)}条记录") return result except Exception as query_error: logger.error(f"MySQL查询地磅单执行失败: {str(query_error)}", exc_info=True) raise else: logger.warning("⚠️ MySQL连接不可用") return [] except Exception as e: logger.warning(f"⚠️ MySQL查询地磅单失败: {str(e)}", exc_info=True) return [] return [] def get_weighing_slip_by_id(self, slip_id: int) -> Optional[Dict]: """ 根据ID获取地磅单记录 :param slip_id: 地磅单ID :return: 地磅单记录字典,如果不存在返回None """ # 仅使用MySQL查询 if not self.mysql_enabled: logger.warning("MySQL未启用,无法查询地磅单") return None try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute("SELECT * FROM weighing_slips WHERE id = %s", (slip_id,)) row = mysql_cursor.fetchone() if row: return dict(row) except Exception as e: logger.warning(f"MySQL查询地磅单失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return None def get_weighing_slip_by_inbound_id(self, inbound_id: int, include_voided: bool = False) -> Optional[Dict]: """ 根据出入库单ID获取关联的地磅单 :param inbound_id: 出入库单ID :param include_voided: 是否包含已作废的地磅单 """ if not inbound_id: return None if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: query = """ SELECT * FROM weighing_slips WHERE inbound_outbound_id = %s """ if not include_voided: query += " AND is_voided = 0" query += " ORDER BY id DESC LIMIT 1" mysql_cursor.execute(query, (inbound_id,)) row = mysql_cursor.fetchone() if row: return dict(row) except Exception as e: # 如果是超时错误,只记录简要警告 if "timed out" in str(e) or "Lost connection" in str(e): logger.debug(f"MySQL查询出入库关联地磅单超时: {str(e)}") else: logger.warning(f"MySQL查询出入库关联地磅单失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise # MySQL失败或未启用,返回None(已移除SQLite支持) logger.warning("⚠️ MySQL查询失败且已移除SQLite支持,返回None") return None def get_weighing_slip_summary_by_inbound_ids( self, inbound_ids: List[int], include_voided: bool = False ) -> Dict[int, Dict]: """ 批量获取出入库单关联的最新地磅单概要(净重、毛重、皮重) :param inbound_ids: 出入库单ID列表 :param include_voided: 是否包含已作废的地磅单 :return: {inbound_id: weighing_slip_dict} """ if not inbound_ids: return {} unique_ids = list({iid for iid in inbound_ids if iid}) if not unique_ids: return {} def _build_latest_map(rows) -> Dict[int, Dict]: latest = {} for row in rows: inbound_id = row.get('inbound_outbound_id') if inbound_id is None: continue existing = latest.get(inbound_id) if not existing or row.get('id', 0) > existing.get('id', 0): latest[inbound_id] = row return latest void_clause = "" if include_voided else "AND is_voided = 0" selected_fields = "id, inbound_outbound_id, net_weight, gross_weight, tare_weight, deduction, gross_weight_time, tare_weight_time" # 只从 MySQL 批量查询出入库单对应的最新地磅单 try: mysql_conn = self.get_mysql_connection() if not mysql_conn: logger.error("MySQL连接不可用,无法批量查询出入库关联地磅单汇总") return {} placeholders = ", ".join(["%s"] * len(unique_ids)) query = f""" SELECT {selected_fields} FROM weighing_slips WHERE inbound_outbound_id IN ({placeholders}) {void_clause} ORDER BY id DESC """ with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(query, tuple(unique_ids)) rows = mysql_cursor.fetchall() if not rows: return {} return _build_latest_map([dict(row) for row in rows]) except Exception as e: logger.error(f"批量查询地磅单失败: {str(e)}", exc_info=True) if not CONTINUE_ON_MYSQL_ERROR: raise return {} def get_weighing_slips_by_inbound_id(self, inbound_id: int, include_voided: bool = False) -> List[Dict]: """ 根据出入库单ID获取关联的地磅单列表 :param inbound_id: 出入库单ID :param include_voided: 是否包含作废记录 """ if not inbound_id: return [] void_clause = "" if include_voided else "AND is_voided = 0" order_clause = "ORDER BY created_at DESC, id DESC" try: mysql_conn = self.get_mysql_connection() if not mysql_conn: logger.error("MySQL连接不可用,无法查询出入库关联地磅单列表") return [] query = f""" SELECT * FROM weighing_slips WHERE inbound_outbound_id = %s {void_clause} {order_clause} """ with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(query, (inbound_id,)) rows = mysql_cursor.fetchall() return [dict(row) for row in rows] except Exception as e: logger.error(f"MySQL查询出入库关联地磅单列表失败: {str(e)}", exc_info=True) if not CONTINUE_ON_MYSQL_ERROR: raise return [] def get_today_weighing_slip_with_weight_by_vehicle(self, vehicle_no: str) -> Optional[Dict]: """ 查询当天该车牌下已填写毛重或皮重的地磅单(未作废),取最新一条。 用于出入库管理检索:判断当前正在称重的出入库单是否为用户输入的id。 :param vehicle_no: 车牌号 :return: 地磅单记录(含 inbound_outbound_id),不存在则返回 None """ if not (vehicle_no and vehicle_no.strip()): return None today_str = datetime.now().strftime("%Y-%m-%d") if not self.mysql_enabled: return None try: mysql_conn = self.get_mysql_connection() if not mysql_conn: return None with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" SELECT ws.* FROM weighing_slips ws INNER JOIN inbound_outbound io ON ws.inbound_outbound_id = io.id AND io.is_deleted = 0 WHERE io.vehicle_no = %s AND io.date = %s AND ws.is_voided = 0 AND (COALESCE(ws.gross_weight, 0) > 0 OR COALESCE(ws.tare_weight, 0) > 0) ORDER BY ws.id DESC LIMIT 1 """, (vehicle_no.strip(), today_str)) row = mysql_cursor.fetchone() if row: return dict(row) except Exception as e: logger.warning(f"MySQL查询当天车牌地磅单失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return None def get_today_incomplete_weighing_slips_by_vehicle(self, vehicle_no: str) -> List[Dict]: """ 查询当天该车牌下未完成的地磅单(未作废)。 未完成:有毛重没有皮重,或有皮重没有毛重。 :param vehicle_no: 车牌号 :return: 地磅单记录列表(含 inbound_outbound_id),按 id 倒序 """ if not (vehicle_no and vehicle_no.strip()): return [] today_str = datetime.now().strftime("%Y-%m-%d") if not self.mysql_enabled: return [] try: mysql_conn = self.get_mysql_connection() if not mysql_conn: return [] with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" SELECT ws.* FROM weighing_slips ws INNER JOIN inbound_outbound io ON ws.inbound_outbound_id = io.id AND io.is_deleted = 0 WHERE io.vehicle_no = %s AND io.date = %s AND ws.is_voided = 0 AND ( (COALESCE(ws.gross_weight, 0) > 0 AND (ws.tare_weight IS NULL OR COALESCE(ws.tare_weight, 0) = 0)) OR ((ws.gross_weight IS NULL OR COALESCE(ws.gross_weight, 0) = 0) AND COALESCE(ws.tare_weight, 0) > 0) ) ORDER BY ws.id DESC """, (vehicle_no.strip(), today_str)) rows = mysql_cursor.fetchall() return [dict(row) for row in rows] if rows else [] except Exception as e: logger.warning(f"MySQL查询当天车牌未完成地磅单失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return [] def void_weighing_slip(self, slip_id: int) -> bool: """ 作废地磅单 :param slip_id: 地磅单ID :return: 是否成功 """ success = False slip = self.get_weighing_slip_by_id(slip_id) plan_id = slip.get('purchase_plan_id') if slip else None plan_no = (slip.get('plan_no') or '').strip() if slip else None inbound_id = slip.get('inbound_outbound_id') if slip else None # 先操作MySQL if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" UPDATE weighing_slips SET is_voided = 1 WHERE id = %s """, (slip_id,)) affected_rows = mysql_cursor.rowcount mysql_conn.commit() if affected_rows > 0: success = True logger.info(f"MySQL作废地磅单成功: ID {slip_id}") else: logger.warning(f"MySQL作废地磅单: ID {slip_id} 未找到记录") else: logger.warning(f"MySQL连接失败,无法作废地磅单 ID {slip_id}") except Exception as e: logger.error(f"MySQL作废地磅单失败: ID {slip_id}, 错误: {str(e)}", exc_info=True) if not CONTINUE_ON_MYSQL_ERROR: raise # 已移除SQLite支持,仅使用MySQL if success: try: self._recalculate_slip_executed_quantities(plan_id=plan_id, plan_no=plan_no if plan_no else None) except Exception as e: logger.warning(f"重算地磅单已执行量失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise if plan_id and success: try: self.refresh_plan_execution_status(plan_id) except Exception as e: logger.warning(f"刷新计划状态失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise if inbound_id and success: try: self.refresh_inbound_status(inbound_id) except Exception as e: logger.warning(f"刷新出入库状态失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return success # ========== 公司名称相关操作 ========== def insert_company(self, name: str) -> int: """ 插入公司名称 :param name: 公司名称 :return: 插入记录的ID """ created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S') record_id = None # 先操作MySQL,获取MySQL生成的ID if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" INSERT INTO companies (name, is_deleted, created_at) VALUES (%s, %s, %s) """, (name, 0, created_at)) record_id = mysql_cursor.lastrowid mysql_conn.commit() except Exception as e: logger.warning(f"MySQL插入公司失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise if record_id is None: raise RuntimeError("无法插入公司:MySQL未启用或插入失败") return record_id def get_all_companies(self) -> List[Dict]: """ 获取所有公司名称 :return: 公司名称列表 """ # 只从 MySQL 获取公司列表(复用连接,必要时自动重连) try: mysql_conn = self.get_mysql_connection() if not mysql_conn: logger.error("MySQL连接不可用,无法获取公司列表") return [] # 确保事务已提交,并设置隔离级别为 READ COMMITTED mysql_conn.commit() with mysql_conn.cursor() as cursor: cursor.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED") with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" SELECT * FROM companies WHERE is_deleted = 0 ORDER BY name """) rows = mysql_cursor.fetchall() result = [dict(row) for row in rows] logger.info(f"✅ 从MySQL获取公司列表,共{len(result)}条记录") return result except Exception as query_error: logger.error(f"MySQL查询公司执行失败: {str(query_error)}", exc_info=True) if not CONTINUE_ON_MYSQL_ERROR: raise return [] def update_company(self, company_id: int, name: str) -> bool: """ 更新公司名称 :param company_id: 公司ID :param name: 新名称 :return: 是否成功 """ success = False # 先操作MySQL if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" UPDATE companies SET name = %s WHERE id = %s """, (name, company_id)) affected_rows = mysql_cursor.rowcount mysql_conn.commit() if affected_rows > 0: success = True logger.info(f"MySQL更新公司成功: ID {company_id}, 新名称: {name}") else: logger.warning(f"MySQL更新公司: ID {company_id} 未找到记录") else: logger.warning(f"MySQL连接失败,无法更新公司 ID {company_id}") except Exception as e: logger.error(f"MySQL更新公司失败: ID {company_id}, 错误: {str(e)}", exc_info=True) if not CONTINUE_ON_MYSQL_ERROR: raise return success def delete_company(self, company_id: int) -> bool: """ 删除公司名称 :param company_id: 公司ID :return: 是否成功 """ success = False # 先操作MySQL if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" UPDATE companies SET is_deleted = 1 WHERE id = %s """, (company_id,)) affected_rows = mysql_cursor.rowcount mysql_conn.commit() if affected_rows > 0: success = True logger.info(f"MySQL删除公司成功: ID {company_id}") else: logger.warning(f"MySQL删除公司: ID {company_id} 未找到记录") else: logger.warning(f"MySQL连接失败,无法删除公司 ID {company_id}") except Exception as e: logger.error(f"MySQL删除公司失败: ID {company_id}, 错误: {str(e)}", exc_info=True) if not CONTINUE_ON_MYSQL_ERROR: raise return success def is_company_used(self, company_id: int) -> bool: """ 检查公司是否被地磅单引用 :param company_id: 公司ID :return: 是否被引用 """ # 先尝试从MySQL查询 if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: # 获取公司名称 mysql_cursor.execute("SELECT name FROM companies WHERE id = %s", (company_id,)) row = mysql_cursor.fetchone() if not row: return False company_name = row['name'] # 检查是否在供货单位或收货单位中被使用 mysql_cursor.execute(""" SELECT COUNT(*) as count FROM weighing_slips WHERE supplier = %s OR consignee = %s """, (company_name, company_name)) result = mysql_cursor.fetchone() return result['count'] > 0 if result else False except Exception as e: logger.warning(f"MySQL检查公司使用情况失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return False def company_exists(self, name: str, exclude_id: Optional[int] = None, include_deleted: bool = False) -> bool: """ 检查公司名称是否存在 :param name: 公司名称 :param exclude_id: 排除的ID(用于修改时检查) :param include_deleted: 是否包含已删除记录 :return: 是否存在 """ # 先尝试从MySQL查询 if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: base_query = "SELECT COUNT(*) as count FROM companies WHERE name = %s" params = [name] if not include_deleted: base_query += " AND is_deleted = 0" if exclude_id: base_query += " AND id != %s" params.append(exclude_id) mysql_cursor.execute(base_query, tuple(params)) result = mysql_cursor.fetchone() return result['count'] > 0 if result else False except Exception as e: logger.warning(f"MySQL检查公司是否存在失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return False def reactivate_company(self, name: str) -> bool: """将已删除的公司名称恢复为可用""" if not name: return False restored = False if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" UPDATE companies SET is_deleted = 0 WHERE name = %s """, (name,)) if mysql_cursor.rowcount > 0: restored = True mysql_conn.commit() except Exception as e: logger.warning(f"MySQL恢复公司失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return restored def ensure_company_active(self, name: str) -> str: """ 确保公司名称处于可用状态 :return: 'created' | 'restored' | 'exists' | 'empty' """ if not name: return "empty" if self.company_exists(name): return "exists" if self.reactivate_company(name): return "restored" self.insert_company(name) return "created" # ========== 货物名称相关操作 ========== def insert_cargo(self, name: str) -> int: """ 插入货物名称 :param name: 货物名称 :return: 插入记录的ID """ created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S') record_id = None # 先操作MySQL,获取MySQL生成的ID if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" INSERT INTO cargos (name, is_deleted, created_at) VALUES (%s, %s, %s) """, (name, 0, created_at)) record_id = mysql_cursor.lastrowid mysql_conn.commit() except Exception as e: logger.warning(f"MySQL插入货物失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise if record_id is None: raise RuntimeError("无法插入货物:MySQL未启用或插入失败") return record_id def get_all_cargos(self) -> List[Dict]: """ 获取所有货物名称 :return: 货物名称列表 """ # 只从 MySQL 获取货物列表(复用连接,必要时自动重连) try: mysql_conn = self.get_mysql_connection() if not mysql_conn: logger.error("MySQL连接不可用,无法获取货物列表") return [] # 确保事务已提交,并设置隔离级别为 READ COMMITTED mysql_conn.commit() with mysql_conn.cursor() as cursor: cursor.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED") with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" SELECT * FROM cargos WHERE is_deleted = 0 ORDER BY name """) rows = mysql_cursor.fetchall() result = [dict(row) for row in rows] logger.info(f"✅ 从MySQL获取货物列表,共{len(result)}条记录") if result: logger.info(f"示例:id={result[0].get('id')}, name={result[0].get('name')}") return result except Exception as query_error: logger.error(f"MySQL查询货物执行失败: {str(query_error)}", exc_info=True) if not CONTINUE_ON_MYSQL_ERROR: raise return [] def update_cargo(self, cargo_id: int, name: str) -> bool: """ 更新货物名称 :param cargo_id: 货物ID :param name: 新名称 :return: 是否成功 """ success = False # 先操作MySQL if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" UPDATE cargos SET name = %s WHERE id = %s """, (name, cargo_id)) affected_rows = mysql_cursor.rowcount mysql_conn.commit() if affected_rows > 0: success = True logger.info(f"MySQL更新货物成功: ID {cargo_id}, 新名称: {name}") else: logger.warning(f"MySQL更新货物: ID {cargo_id} 未找到记录") else: logger.warning(f"MySQL连接失败,无法更新货物 ID {cargo_id}") except Exception as e: logger.error(f"MySQL更新货物失败: ID {cargo_id}, 错误: {str(e)}", exc_info=True) if not CONTINUE_ON_MYSQL_ERROR: raise return success def delete_cargo(self, cargo_id: int) -> bool: """ 删除货物名称 :param cargo_id: 货物ID :return: 是否成功 """ success = False # 先操作MySQL if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" UPDATE cargos SET is_deleted = 1 WHERE id = %s """, (cargo_id,)) affected_rows = mysql_cursor.rowcount mysql_conn.commit() if affected_rows > 0: success = True logger.info(f"MySQL删除货物成功: ID {cargo_id}") else: logger.warning(f"MySQL删除货物: ID {cargo_id} 未找到记录") else: logger.warning(f"MySQL连接失败,无法删除货物 ID {cargo_id}") except Exception as e: logger.error(f"MySQL删除货物失败: ID {cargo_id}, 错误: {str(e)}", exc_info=True) if not CONTINUE_ON_MYSQL_ERROR: raise return success def is_cargo_used(self, cargo_id: int) -> bool: """ 检查货物是否被地磅单引用 :param cargo_id: 货物ID :return: 是否被引用 """ # 先尝试从MySQL查询 if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: # 获取货物名称 mysql_cursor.execute("SELECT name FROM cargos WHERE id = %s", (cargo_id,)) row = mysql_cursor.fetchone() if not row: return False cargo_name = row['name'] # 检查是否在地磅单中被使用 mysql_cursor.execute(""" SELECT COUNT(*) as count FROM weighing_slips WHERE cargo_name = %s """, (cargo_name,)) result = mysql_cursor.fetchone() return result['count'] > 0 if result else False except Exception as e: logger.warning(f"MySQL检查货物使用情况失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return False def cargo_exists(self, name: str, exclude_id: Optional[int] = None, include_deleted: bool = False) -> bool: """ 检查货物名称是否存在 :param name: 货物名称 :param exclude_id: 排除的ID(用于修改时检查) :param include_deleted: 是否包含已删除记录 :return: 是否存在 """ # 先尝试从MySQL查询 if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: base_query = "SELECT COUNT(*) as count FROM cargos WHERE name = %s" params = [name] if not include_deleted: base_query += " AND is_deleted = 0" if exclude_id: base_query += " AND id != %s" params.append(exclude_id) mysql_cursor.execute(base_query, tuple(params)) result = mysql_cursor.fetchone() return result['count'] > 0 if result else False except Exception as e: logger.warning(f"MySQL检查货物是否存在失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return False def reactivate_cargo(self, name: str) -> bool: """将已删除的货物名称恢复为可用""" if not name: return False restored = False if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" UPDATE cargos SET is_deleted = 0 WHERE name = %s """, (name,)) if mysql_cursor.rowcount > 0: restored = True mysql_conn.commit() except Exception as e: logger.warning(f"MySQL恢复货物失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return restored def ensure_cargo_active(self, name: str) -> str: """ 确保货物名称处于可用状态 :return: 'created' | 'restored' | 'exists' | 'empty' """ if not name: return "empty" if self.cargo_exists(name): return "exists" if self.reactivate_cargo(name): return "restored" self.insert_cargo(name) return "created" # ========== 采购计划相关操作 ========== def generate_plan_no(self) -> str: """ 自动生成计划号 格式:SX-YYYYMMDDMMHHSS001 """ from datetime import datetime now = datetime.now() # 格式:YYYYMMDDMMHHSS (年月日分钟小时秒) timestamp = now.strftime('%Y%m%d%M%H%S') # 查询当天该时间戳下已存在的最大序号 prefix = f"SX-{timestamp}" # 查询当天所有以该前缀开头的计划号 today_prefix = f"SX-{now.strftime('%Y%m%d')}" # 先尝试从MySQL查询 if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" SELECT plan_no FROM purchase_plans WHERE plan_no LIKE %s AND is_deleted = 0 ORDER BY plan_no DESC LIMIT 1 """, (f"{today_prefix}%",)) row = mysql_cursor.fetchone() if row: last_plan_no = row['plan_no'] # 提取序号部分(最后3位) try: last_seq = int(last_plan_no[-3:]) new_seq = last_seq + 1 except: new_seq = 1 else: new_seq = 1 # 确保序号是3位数字 seq_str = f"{new_seq:03d}" return f"{prefix}{seq_str}" except Exception as e: logger.warning(f"MySQL查询计划号失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise # MySQL失败或未启用,返回默认序号 new_seq = 1 seq_str = f"{new_seq:03d}" return f"{prefix}{seq_str}" def insert_purchase_plan(self, data: Dict) -> int: """ 插入采购计划记录 :param data: 采购计划数据字典 :return: 插入记录的ID """ created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S') execution_status = self._get_waiting_status(data['business_type']) # 自动生成计划号(如果没有提供) plan_no = data.get('plan_no') if not plan_no: plan_no = self.generate_plan_no() # 使用start_date和end_date,如果没有则使用plan_date start_date = data.get('start_date') or data.get('plan_date', '') end_date = data.get('end_date') or data.get('plan_date', '') plan_date = data.get('plan_date') or start_date # 保留plan_date用于兼容 record_id = None # 先操作MySQL,获取MySQL生成的ID if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" INSERT INTO purchase_plans ( plan_no, plan_date, start_date, end_date, business_type, product, specification, planned_quantity, vehicle_no, customer_name, remarks, is_deleted, execution_status, executed_at, last_weighing_slip_id, executed_quantity, created_at ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """, ( plan_no, plan_date, start_date, end_date, data['business_type'], data['product'], data.get('specification', ''), data['planned_quantity'], data.get('vehicle_no', ''), # 提供默认值 data.get('customer_name', ''), data.get('remarks', ''), 0, execution_status, None, None, 0, created_at )) record_id = mysql_cursor.lastrowid mysql_conn.commit() except Exception as e: logger.warning(f"MySQL插入采购计划失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise if record_id is None: raise RuntimeError("无法插入采购计划:MySQL未启用或插入失败") return record_id def get_all_purchase_plans(self) -> List[Dict]: """ 获取所有采购计划记录 :return: 采购计划记录列表 """ # 仅使用MySQL查询 if self.mysql_enabled: try: # 复用已有 MySQL 连接,必要时由 get_mysql_connection 内部自动重连 mysql_conn = self.get_mysql_connection() if mysql_conn: try: # 确保事务已提交 mysql_conn.commit() # 设置隔离级别为READ COMMITTED with mysql_conn.cursor() as cursor: cursor.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED") with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" SELECT * FROM purchase_plans WHERE is_deleted = 0 ORDER BY plan_date DESC, created_at DESC """) rows = mysql_cursor.fetchall() result = [dict(row) for row in rows] logger.info(f"✅ 从MySQL获取采购计划列表,共{len(result)}条记录") return result except Exception as query_error: # 如果是超时错误,只记录警告,不打印完整堆栈 if "timed out" in str(query_error) or "Lost connection" in str(query_error): logger.warning(f"MySQL查询采购计划超时: {str(query_error)}") else: logger.error(f"MySQL查询采购计划执行失败: {str(query_error)}", exc_info=True) raise else: logger.warning("⚠️ MySQL连接不可用") except Exception as e: # 如果是超时错误,只记录简要警告 if "timed out" in str(e) or "Lost connection" in str(e): logger.warning(f"⚠️ MySQL查询采购计划超时,返回空列表") else: logger.warning(f"⚠️ MySQL查询采购计划失败,返回空列表: {str(e)}") # MySQL失败或未启用,返回空列表(已移除SQLite支持) logger.warning("⚠️ MySQL查询失败且已移除SQLite支持,返回空列表") return [] def get_purchase_plan_by_id(self, plan_id: int) -> Optional[Dict]: """ 根据ID获取采购计划记录 :param plan_id: 采购计划ID :return: 采购计划记录字典,如果不存在返回None """ # 先尝试从MySQL查询 if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute("SELECT * FROM purchase_plans WHERE id = %s", (plan_id,)) row = mysql_cursor.fetchone() if row: return dict(row) except Exception as e: logger.warning(f"MySQL查询采购计划失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return None def get_purchase_plan_by_plan_no(self, plan_no: str) -> Optional[Dict]: """ 根据计划号获取采购计划记录 :param plan_no: 计划号 :return: 采购计划记录字典,如果不存在返回None """ if not plan_no or not plan_no.strip(): return None plan_no = plan_no.strip() # 先尝试从MySQL查询 if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" SELECT * FROM purchase_plans WHERE plan_no = %s AND is_deleted = 0 LIMIT 1 """, (plan_no,)) row = mysql_cursor.fetchone() if row: return dict(row) except Exception as e: logger.warning(f"MySQL根据计划号查询采购计划失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return None def update_purchase_plan(self, plan_id: int, data: Dict) -> bool: """ 更新采购计划记录 :param plan_id: 采购计划ID :param data: 采购计划数据字典 :return: 是否成功 """ success = False # 先操作MySQL if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: # 使用start_date和end_date,如果没有则使用plan_date start_date = data.get('start_date') or data.get('plan_date', '') end_date = data.get('end_date') or data.get('plan_date', '') plan_date = data.get('plan_date') or start_date plan_no = data.get('plan_no', '') mysql_cursor.execute(""" UPDATE purchase_plans SET plan_no = %s, plan_date = %s, start_date = %s, end_date = %s, business_type = %s, product = %s, specification = %s, planned_quantity = %s, customer_name = %s, remarks = %s WHERE id = %s """, ( plan_no if plan_no else None, plan_date, start_date, end_date, data['business_type'], data['product'], data.get('specification', ''), data['planned_quantity'], data.get('customer_name', ''), data.get('remarks', ''), plan_id )) affected_rows = mysql_cursor.rowcount mysql_conn.commit() if affected_rows > 0: success = True logger.info(f"MySQL更新采购计划成功: ID {plan_id}") else: logger.warning(f"MySQL更新采购计划: ID {plan_id} 未找到记录") else: logger.warning(f"MySQL连接失败,无法更新采购计划 ID {plan_id}") except Exception as e: logger.error(f"MySQL更新采购计划失败: ID {plan_id}, 错误: {str(e)}", exc_info=True) if not CONTINUE_ON_MYSQL_ERROR: raise try: self.refresh_plan_execution_status(plan_id) except Exception as e: logger.warning(f"刷新采购计划状态失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return success def delete_purchase_plan(self, plan_id: int) -> bool: """ 虚拟删除采购计划(标记为已删除) :param plan_id: 采购计划ID :return: 是否成功 """ success = False # 先操作MySQL if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" UPDATE purchase_plans SET is_deleted = 1 WHERE id = %s """, (plan_id,)) affected_rows = mysql_cursor.rowcount mysql_conn.commit() if affected_rows > 0: success = True logger.info(f"MySQL虚拟删除采购计划成功: ID {plan_id}") else: logger.warning(f"MySQL虚拟删除采购计划: ID {plan_id} 未找到记录") else: logger.warning(f"MySQL连接失败,无法虚拟删除采购计划 ID {plan_id}") except Exception as e: logger.error(f"MySQL虚拟删除采购计划失败: ID {plan_id}, 错误: {str(e)}", exc_info=True) if not CONTINUE_ON_MYSQL_ERROR: raise return success # ========== 用户管理相关操作 ========== def ensure_default_admin(self): """确保默认管理员账号存在""" created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S') # 仅在 MySQL 中确保管理员存在 try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as cursor: cursor.execute("SELECT id FROM users WHERE username = %s", ('admin',)) if cursor.fetchone() is None: cursor.execute(""" INSERT INTO users (username, password, role, created_at) VALUES (%s, %s, %s, %s) """, ('admin', 'admin', 'admin', created_at)) mysql_conn.commit() logger.info("已创建默认MySQL管理员账号 admin/admin") except Exception as e: logger.warning(f"初始化MySQL管理员账号失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise def get_all_users(self) -> List[Dict]: """获取全部用户""" if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" SELECT id, username, role, created_at FROM users ORDER BY created_at DESC, id DESC """) rows = mysql_cursor.fetchall() return [dict(row) for row in rows] except Exception as e: logger.warning(f"MySQL获取用户列表失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return [] def user_exists(self, username: str, exclude_id: Optional[int] = None) -> bool: """判断用户名是否存在""" if not self.mysql_enabled: logger.warning("MySQL未启用,无法检查用户名") return False try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as cursor: if exclude_id is not None: cursor.execute(""" SELECT COUNT(*) as count FROM users WHERE username = %s AND id != %s """, (username, exclude_id)) else: cursor.execute(""" SELECT COUNT(*) as count FROM users WHERE username = %s """, (username,)) result = cursor.fetchone() return result['count'] > 0 if result else False except Exception as e: logger.warning(f"MySQL检查用户名失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return False def insert_user(self, username: str, password: str, role: str = 'user') -> int: """新增用户""" created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S') record_id = None if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as cursor: cursor.execute(""" INSERT INTO users (username, password, role, created_at) VALUES (%s, %s, %s, %s) """, (username, password, role, created_at)) record_id = cursor.lastrowid mysql_conn.commit() except Exception as e: logger.warning(f"MySQL新增用户失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise if record_id is None: raise RuntimeError("无法插入用户:MySQL未启用或插入失败") return record_id def update_user(self, user_id: int, username: str, role: str, password: Optional[str] = None) -> bool: """更新用户信息""" success = False if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as cursor: if password is not None: cursor.execute(""" UPDATE users SET username = %s, role = %s, password = %s WHERE id = %s """, (username, role, password, user_id)) else: cursor.execute(""" UPDATE users SET username = %s, role = %s WHERE id = %s """, (username, role, user_id)) mysql_conn.commit() success = True except Exception as e: logger.warning(f"MySQL更新用户失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return success def delete_user(self, user_id: int) -> bool: """删除用户,禁止删除默认管理员""" user = self.get_user_by_id(user_id) if not user: return False if user['username'] == 'admin': logger.warning("尝试删除默认管理员被阻止") return False success = False if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as cursor: cursor.execute("DELETE FROM users WHERE id = %s", (user_id,)) mysql_conn.commit() success = cursor.rowcount > 0 except Exception as e: logger.warning(f"MySQL删除用户失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return success def get_user_by_id(self, user_id: int) -> Optional[Dict]: """根据ID获取用户""" if not self.mysql_enabled: logger.warning("MySQL未启用,无法获取用户") return None user = None try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as cursor: cursor.execute(""" SELECT id, username, role, created_at FROM users WHERE id = %s """, (user_id,)) row = cursor.fetchone() if row: user = dict(row) except Exception as e: logger.warning(f"MySQL获取用户失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return user def authenticate_user(self, username: str, password: str) -> Optional[Dict]: """根据账号密码验证用户""" if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as cursor: cursor.execute(""" SELECT id, username, role FROM users WHERE username = %s AND password = %s """, (username, password)) row = cursor.fetchone() if row: return dict(row) except Exception as e: logger.warning(f"MySQL用户登录校验失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return None # ========== 出入库相关操作 ========== def insert_inbound_outbound(self, data: Dict) -> int: """ 插入出入库单记录 :param data: 出入库单数据字典 :return: 插入记录的ID """ created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S') status = self._get_waiting_status(data['business_type']) record_id = None # 只使用 MySQL,获取 MySQL 生成的自增 ID try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" INSERT INTO inbound_outbound ( date, partner_company, business_type, product, quantity, plan_no, batch_no, vehicle_no, status, remarks, purchase_plan_id, is_deleted, created_at ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """, ( data['date'], data['partner_company'], data['business_type'], data['product'], data['quantity'], data.get('plan_no', ''), data.get('batch_no', ''), data['vehicle_no'], status, data.get('remarks', ''), data.get('purchase_plan_id'), 0, created_at )) record_id = mysql_cursor.lastrowid mysql_conn.commit() except Exception as e: logger.error(f"MySQL插入出入库单失败: {str(e)}", exc_info=True) if not CONTINUE_ON_MYSQL_ERROR: raise # 如果关联了计划,刷新计划状态 if data.get('purchase_plan_id'): try: self.refresh_plan_execution_status(data['purchase_plan_id']) except Exception as e: logger.warning(f"刷新计划状态失败: {str(e)}") return record_id def get_all_inbound_outbound(self, keyword: Optional[str] = None) -> List[Dict]: """ 获取所有出入库单记录 :param keyword: 模糊检索往来单位/车牌号/产品 :return: 出入库单记录列表 """ keyword = (keyword or "").strip() # 仅使用MySQL查询 if not self.mysql_enabled: logger.warning("MySQL未启用,无法查询出入库单列表") return [] if self.mysql_enabled: try: # 复用已有 MySQL 连接,必要时由 get_mysql_connection 内部自动重连 mysql_conn = self.get_mysql_connection() if mysql_conn: try: mysql_conn.commit() with mysql_conn.cursor() as cursor: cursor.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED") with mysql_conn.cursor() as mysql_cursor: where_clause = "WHERE is_deleted = 0" params = [] if keyword: like_pattern = f"%{keyword}%" where_clause += " AND (partner_company LIKE %s OR vehicle_no LIKE %s OR product LIKE %s)" params = [like_pattern, like_pattern, like_pattern] query = f""" SELECT * FROM inbound_outbound {where_clause} ORDER BY date DESC, created_at DESC """ mysql_cursor.execute(query, params) rows = mysql_cursor.fetchall() result = [dict(row) for row in rows] logger.info(f"✅ 从MySQL获取出入库单列表,共{len(result)}条记录") return result except Exception as query_error: logger.error(f"MySQL查询出入库单执行失败: {str(query_error)}", exc_info=True) raise else: logger.warning("⚠️ MySQL连接不可用") return [] except Exception as e: logger.warning(f"⚠️ MySQL查询出入库单失败: {str(e)}", exc_info=True) return [] return [] def get_inbound_outbound_by_date(self, date_str: str) -> List[Dict]: """ 根据日期获取出入库单记录(用于当天出入库单卡片) :param date_str: 日期字符串,格式 YYYY-MM-DD :return: 出入库单记录列表 """ if not date_str or not self.mysql_enabled: return [] date_str = str(date_str).strip()[:10] if len(date_str) < 10: return [] try: mysql_conn = self.get_mysql_connection() if not mysql_conn: return [] mysql_conn.commit() with mysql_conn.cursor() as cursor: cursor.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED") with mysql_conn.cursor() as mysql_cursor: # 兼容 date 存为 'YYYY-MM-DD' 或 'YYYY-MM-DD HH:MM:SS' mysql_cursor.execute(""" SELECT * FROM inbound_outbound WHERE is_deleted = 0 AND (date = %s OR date LIKE %s) ORDER BY date DESC, created_at DESC """, (date_str, date_str + " %")) rows = mysql_cursor.fetchall() result = [dict(row) for row in rows] logger.info(f"✅ 从MySQL按日期获取出入库单,日期={date_str},共{len(result)}条") return result except Exception as e: logger.warning(f"MySQL按日期查询出入库单失败: {str(e)}", exc_info=True) return [] def get_inbound_outbound_by_id(self, inbound_id: int) -> Optional[Dict]: """ 根据ID获取出入库单记录 :param inbound_id: 出入库单ID :return: 出入库单记录字典,如果不存在返回None """ # 先尝试从MySQL查询 if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute("SELECT * FROM inbound_outbound WHERE id = %s", (inbound_id,)) row = mysql_cursor.fetchone() if row: return dict(row) except Exception as e: logger.warning(f"MySQL查询出入库单失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return None def get_inbound_outbound_by_plan_id(self, plan_id: int) -> List[Dict]: """ 根据计划ID获取所有关联的出入库单 :param plan_id: 计划ID :return: 出入库单记录列表 """ # 先尝试从MySQL查询 if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" SELECT * FROM inbound_outbound WHERE purchase_plan_id = %s AND is_deleted = 0 ORDER BY created_at DESC """, (plan_id,)) rows = mysql_cursor.fetchall() return [dict(row) for row in rows] except Exception as e: logger.warning(f"MySQL查询出入库单失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return [] def get_weighing_slips_by_plan_id(self, plan_id: int) -> List[Dict]: """ 根据计划ID获取关联的地磅单列表 :param plan_id: 计划ID :return: 地磅单记录列表 """ if not plan_id: return [] if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" SELECT * FROM weighing_slips WHERE purchase_plan_id = %s AND is_voided = 0 ORDER BY created_at DESC """, (plan_id,)) rows = mysql_cursor.fetchall() return [dict(row) for row in rows] except Exception as e: logger.warning(f"MySQL查询地磅单失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return [] def update_inbound_outbound(self, inbound_id: int, data: Dict) -> bool: """ 更新出入库单记录 :param inbound_id: 出入库单ID :param data: 更新后的出入库单数据 :return: 是否成功 """ existing = self.get_inbound_outbound_by_id(inbound_id) if not existing: return False status = data.get('status') if not status: status = self._get_waiting_status(data['business_type']) params = ( data['date'], data['partner_company'], data['business_type'], data['product'], data['quantity'], data.get('plan_no', ''), data.get('batch_no', ''), data['vehicle_no'], status, data.get('remarks', ''), data.get('purchase_plan_id'), inbound_id ) success = False if not self.mysql_enabled: logger.warning("MySQL未启用,无法更新出入库单") return False try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" UPDATE inbound_outbound SET date = %s, partner_company = %s, business_type = %s, product = %s, quantity = %s, plan_no = %s, batch_no = %s, vehicle_no = %s, status = %s, remarks = %s, purchase_plan_id = %s WHERE id = %s """, params) success = mysql_cursor.rowcount > 0 mysql_conn.commit() except Exception as e: logger.warning(f"MySQL更新出入库单失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return False # 已移除SQLite支持,仅使用MySQL # 如果关联了计划,刷新计划状态 old_plan_id = existing.get('purchase_plan_id') new_plan_id = data.get('purchase_plan_id') try: if old_plan_id and old_plan_id != new_plan_id: self.refresh_plan_execution_status(old_plan_id) if new_plan_id: self.refresh_plan_execution_status(new_plan_id) except Exception as e: logger.warning(f"刷新计划状态失败: {str(e)}") return success def delete_inbound_outbound(self, inbound_id: int) -> bool: """ 虚拟删除出入库单(标记为已删除) :param inbound_id: 出入库单ID :return: 是否成功 """ inbound = self.get_inbound_outbound_by_id(inbound_id) plan_id = inbound.get('purchase_plan_id') if inbound else None success = False # 先操作MySQL if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" UPDATE inbound_outbound SET is_deleted = 1 WHERE id = %s """, (inbound_id,)) affected_rows = mysql_cursor.rowcount mysql_conn.commit() if affected_rows > 0: success = True except Exception as e: logger.warning(f"MySQL删除出入库单失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise # 如果关联了计划,刷新计划状态 if plan_id and success: try: self.refresh_plan_execution_status(plan_id) except Exception as e: logger.warning(f"刷新计划状态失败: {str(e)}") return success def get_max_batch_no_sequence(self, date_str: str) -> int: """ 获取指定日期的最大批次号序号 :param date_str: 日期字符串,格式:YYYY-MM-DD :return: 最大序号,如果没有则返回0 """ # 提取日期部分(YYYYMMDD) date_part = date_str.replace('-', '') prefix = f"PC-{date_part}" max_sequence = 0 # 先尝试从MySQL查询 if self.mysql_enabled: try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" SELECT batch_no FROM inbound_outbound WHERE batch_no LIKE %s AND is_deleted = 0 ORDER BY batch_no DESC LIMIT 1 """, (f"{prefix}%",)) row = mysql_cursor.fetchone() if row: # MySQL返回的row可能是元组或字典,统一转换为字典处理 if isinstance(row, dict): batch_no = row.get('batch_no') else: batch_no = row[0] if row else None if batch_no: # 提取序号部分 try: sequence_str = batch_no.replace(prefix, '') sequence = int(sequence_str) max_sequence = max(max_sequence, sequence) except (ValueError, AttributeError): pass except Exception as e: logger.warning(f"MySQL查询批次号失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return max_sequence def refresh_inbound_status(self, inbound_id: int): """ 根据关联的地磅单计算出入库单状态 :param inbound_id: 出入库单ID """ inbound = self.get_inbound_outbound_by_id(inbound_id) if not inbound: return # 查询该出入库单关联的所有地磅单(仅使用MySQL) slips = [] if not self.mysql_enabled: logger.warning("MySQL未启用,无法刷新出入库状态") return try: mysql_conn = self.get_mysql_connection() if mysql_conn: with mysql_conn.cursor() as mysql_cursor: mysql_cursor.execute(""" SELECT * FROM weighing_slips WHERE inbound_outbound_id = %s AND is_voided = 0 ORDER BY id DESC """, (inbound_id,)) rows = mysql_cursor.fetchall() slips = [dict(row) for row in rows] except Exception as e: logger.warning(f"MySQL查询地磅单失败: {str(e)}") if not CONTINUE_ON_MYSQL_ERROR: raise return if not slips: # 没有地磅单,状态为待入库/待出库 status = self._get_waiting_status(inbound['business_type']) else: # 检查是否所有地磅单都已完成 # 必须满足:净重>0、毛重>0、皮重>0、毛重时间不为空、皮重时间不为空 all_done = all( slip['net_weight'] > 0 and slip.get('gross_weight', 0) > 0 and slip.get('tare_weight', 0) > 0 and slip.get('gross_weight_time') and slip.get('tare_weight_time') for slip in slips ) if all_done: status = self._get_done_status(inbound['business_type']) else: status = self._get_waiting_status(inbound['business_type']) # 更新状态 data = { 'date': inbound['date'], 'partner_company': inbound['partner_company'], 'business_type': inbound['business_type'], 'product': inbound['product'], 'quantity': inbound['quantity'], 'plan_no': inbound.get('plan_no', ''), 'batch_no': inbound.get('batch_no', ''), 'vehicle_no': inbound['vehicle_no'], 'status': status, 'remarks': inbound.get('remarks', ''), 'purchase_plan_id': inbound.get('purchase_plan_id') } self.update_inbound_outbound(inbound_id, data)