| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782 |
- """
- 数据库操作模块
- 使用 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)
|