database.py 116 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782
  1. """
  2. 数据库操作模块
  3. 使用 MySQL 存储地磅单、公司名称、货物名称、用户等所有业务数据
  4. (已移除 SQLite,当前工程仅支持 MySQL)
  5. """
  6. import os
  7. import sys
  8. import time
  9. from datetime import datetime
  10. from typing import List, Dict, Optional, Tuple
  11. import logging
  12. # 尝试导入MySQL相关模块
  13. try:
  14. import pymysql
  15. PYMySQL_AVAILABLE = True
  16. except ImportError:
  17. PYMySQL_AVAILABLE = False
  18. # 尝试导入配置模块
  19. try:
  20. import config
  21. MYSQL_ENABLED = getattr(config, 'ENABLE_MYSQL', False) and PYMySQL_AVAILABLE
  22. MYSQL_CONFIG = getattr(config, 'MYSQL_CONFIG', {})
  23. CONTINUE_ON_MYSQL_ERROR = getattr(config, 'CONTINUE_ON_MYSQL_ERROR', True)
  24. except ImportError:
  25. MYSQL_ENABLED = False
  26. MYSQL_CONFIG = {}
  27. CONTINUE_ON_MYSQL_ERROR = True
  28. # 配置日志 - 设置为INFO级别以便看到MySQL操作信息
  29. logging.basicConfig(
  30. level=logging.INFO,
  31. format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
  32. )
  33. logger = logging.getLogger(__name__)
  34. def get_base_path():
  35. """
  36. 获取程序运行的基础路径
  37. 在开发环境中返回脚本所在目录,在打包后返回exe所在目录
  38. """
  39. if getattr(sys, 'frozen', False):
  40. # 打包后的exe环境
  41. return os.path.dirname(sys.executable)
  42. else:
  43. # 开发环境
  44. return os.path.dirname(os.path.abspath(__file__))
  45. class Database:
  46. WAITING_STATUS_MAP = {
  47. '入库': '待入库',
  48. '出库': '待出库'
  49. }
  50. IN_PROGRESS_STATUS_MAP = {
  51. '入库': '入库中',
  52. '出库': '出库中'
  53. }
  54. DONE_STATUS_MAP = {
  55. '入库': '已完成',
  56. '出库': '已完成'
  57. }
  58. EXCEEDED_STATUS_MAP = {
  59. '入库': '已超额',
  60. '出库': '已超额'
  61. }
  62. """数据库操作类,仅支持 MySQL 存储"""
  63. def __init__(self, db_path: str = None):
  64. """
  65. 初始化数据库连接
  66. :param db_path: 兼容旧版本参数(已废弃,不再使用 SQLite 文件)
  67. """
  68. import time
  69. init_start = time.time()
  70. logger.info("📦 开始初始化数据库...")
  71. # 兼容旧版本属性,占位,不再实际使用 SQLite 文件
  72. self.db_path = db_path
  73. if db_path:
  74. logger.info(f" (兼容信息) 传入的本地数据库路径已忽略: {db_path}")
  75. self.mysql_enabled = MYSQL_ENABLED
  76. logger.info(f" MySQL支持: {'启用' if self.mysql_enabled else '禁用'}")
  77. self.mysql_connection = None
  78. if not self.mysql_enabled:
  79. logger.error("当前工程已移除 SQLite,必须启用 MySQL 才能正常运行,请在 config.py 中将 ENABLE_MYSQL 设置为 True")
  80. raise RuntimeError("必须启用 MySQL(ENABLE_MYSQL = True)")
  81. db_init_start = time.time()
  82. logger.info(" 开始初始化 MySQL 数据库表结构(如有需要)...")
  83. self.init_database()
  84. logger.info(f" ✅ MySQL 数据库初始化流程执行完成 (耗时: {time.time() - db_init_start:.3f}秒)")
  85. logger.info(f"✅ 数据库对象创建完成 (总耗时: {time.time() - init_start:.3f}秒)")
  86. def _get_waiting_status(self, business_type: str) -> str:
  87. return self.WAITING_STATUS_MAP.get(business_type, '待入库')
  88. def _get_in_progress_status(self, business_type: str) -> str:
  89. return self.IN_PROGRESS_STATUS_MAP.get(business_type, '入库中')
  90. def _get_done_status(self, business_type: str) -> str:
  91. return self.DONE_STATUS_MAP.get(business_type, '已完成')
  92. def _get_exceeded_status(self, business_type: str) -> str:
  93. return self.EXCEEDED_STATUS_MAP.get(business_type, '已超额')
  94. def _update_plan_status(self, plan_id: int, status: str,
  95. executed_at: Optional[str], slip_id: Optional[int],
  96. executed_quantity: Optional[float]):
  97. """更新采购计划状态(仅 MySQL)"""
  98. if not plan_id:
  99. return
  100. try:
  101. mysql_conn = self.get_mysql_connection()
  102. if mysql_conn:
  103. with mysql_conn.cursor() as mysql_cursor:
  104. mysql_cursor.execute("""
  105. UPDATE purchase_plans
  106. SET execution_status = %s, executed_at = %s, last_weighing_slip_id = %s,
  107. executed_quantity = %s
  108. WHERE id = %s
  109. """, (status, executed_at, slip_id, executed_quantity, plan_id))
  110. mysql_conn.commit()
  111. except Exception as e:
  112. logger.warning(f"MySQL更新计划状态失败: {str(e)}")
  113. if not CONTINUE_ON_MYSQL_ERROR:
  114. raise
  115. def _get_latest_active_slip_for_plan(self, plan_id: int) -> Optional[Dict]:
  116. """获取计划最新且未作废的地磅单(仅 MySQL)"""
  117. try:
  118. mysql_conn = self.get_mysql_connection()
  119. if not mysql_conn:
  120. return None
  121. with mysql_conn.cursor() as mysql_cursor:
  122. mysql_cursor.execute("""
  123. SELECT * FROM weighing_slips
  124. WHERE purchase_plan_id = %s AND is_voided = 0
  125. ORDER BY id DESC
  126. LIMIT 1
  127. """, (plan_id,))
  128. row = mysql_cursor.fetchone()
  129. return dict(row) if row else None
  130. except Exception as e:
  131. logger.warning(f"MySQL获取最新地磅单失败: {str(e)}")
  132. if not CONTINUE_ON_MYSQL_ERROR:
  133. raise
  134. return None
  135. def refresh_plan_execution_status(self, plan_id: int):
  136. """根据地磅单净重累加刷新计划状态"""
  137. if not plan_id:
  138. return
  139. plan = self.get_purchase_plan_by_id(plan_id)
  140. if not plan:
  141. return
  142. # 计算已执行量(通过地磅单的净重数据累加,单位:kg)
  143. executed_quantity = self._calculate_execution_quantity(plan_id)
  144. # 计划量(单位:t,需要转换为kg)
  145. planned_quantity_kg = plan.get('planned_quantity', 0) * 1000
  146. # 根据已执行量和计划量比较得出状态
  147. if executed_quantity == 0:
  148. # 已执行量=0 -> 待入库/待出库
  149. status = self._get_waiting_status(plan['business_type'])
  150. elif executed_quantity > 0 and executed_quantity < planned_quantity_kg:
  151. # 已执行量>0且<计划量 -> 入库中/出库中
  152. status = self._get_in_progress_status(plan['business_type'])
  153. elif executed_quantity == planned_quantity_kg:
  154. # 已执行量=计划量 -> 已完成
  155. status = self._get_done_status(plan['business_type'])
  156. else: # executed_quantity > planned_quantity_kg
  157. # 已执行量>计划量 -> 已超额
  158. status = self._get_exceeded_status(plan['business_type'])
  159. # 获取最新地磅单的时间
  160. latest_slip = self._get_latest_active_slip_for_plan(plan_id)
  161. executed_at = latest_slip.get('created_at') if latest_slip else None
  162. slip_id = latest_slip.get('id') if latest_slip else None
  163. self._update_plan_status(plan_id, status, executed_at, slip_id, executed_quantity)
  164. def refresh_all_plans_execution_status(self, plan_ids: List[int]) -> Dict[int, Dict]:
  165. """
  166. 批量刷新多个计划的执行状态(一次连接内完成),减少登录/刷新时的数据库往返。
  167. 返回 {plan_id: {execution_status, executed_quantity, executed_at, last_weighing_slip_id}}
  168. """
  169. if not plan_ids:
  170. return {}
  171. plan_ids = list({int(pid) for pid in plan_ids if pid})
  172. if not plan_ids or not self.mysql_enabled:
  173. return {}
  174. try:
  175. mysql_conn = self.get_mysql_connection()
  176. if not mysql_conn:
  177. return {}
  178. with mysql_conn.cursor() as cur:
  179. placeholders = ", ".join(["%s"] * len(plan_ids))
  180. cur.execute(
  181. f"SELECT id, business_type, planned_quantity FROM purchase_plans WHERE id IN ({placeholders})",
  182. tuple(plan_ids),
  183. )
  184. plans_rows = {row["id"]: dict(row) for row in cur.fetchall()}
  185. if not plans_rows:
  186. return {}
  187. cur.execute(
  188. f"""
  189. SELECT purchase_plan_id, COALESCE(SUM(net_weight), 0) as total_weight
  190. FROM weighing_slips
  191. WHERE purchase_plan_id IN ({placeholders}) AND is_voided = 0
  192. GROUP BY purchase_plan_id
  193. """,
  194. tuple(plan_ids),
  195. )
  196. executed_map = {
  197. row["purchase_plan_id"]: float(row["total_weight"] or 0)
  198. for row in cur.fetchall()
  199. }
  200. cur.execute(
  201. f"""
  202. SELECT purchase_plan_id, id, created_at
  203. FROM weighing_slips
  204. WHERE is_voided = 0 AND purchase_plan_id IN ({placeholders})
  205. ORDER BY purchase_plan_id, id DESC
  206. """,
  207. tuple(plan_ids),
  208. )
  209. latest_slips = {}
  210. for row in cur.fetchall():
  211. pid = row["purchase_plan_id"]
  212. if pid not in latest_slips:
  213. latest_slips[pid] = {"id": row["id"], "created_at": row.get("created_at")}
  214. updates = []
  215. result = {}
  216. for pid in plan_ids:
  217. plan_row = plans_rows.get(pid)
  218. if not plan_row:
  219. continue
  220. planned_quantity_kg = (plan_row.get("planned_quantity") or 0) * 1000
  221. executed_quantity = executed_map.get(pid, 0.0)
  222. business_type = plan_row.get("business_type") or ""
  223. if executed_quantity == 0:
  224. status = self._get_waiting_status(business_type)
  225. elif executed_quantity > 0 and executed_quantity < planned_quantity_kg:
  226. status = self._get_in_progress_status(business_type)
  227. elif executed_quantity == planned_quantity_kg:
  228. status = self._get_done_status(business_type)
  229. else:
  230. status = self._get_exceeded_status(business_type)
  231. slip_info = latest_slips.get(pid)
  232. executed_at = slip_info["created_at"] if slip_info else None
  233. slip_id = slip_info["id"] if slip_info else None
  234. updates.append((status, executed_at, slip_id, executed_quantity, pid))
  235. result[pid] = {
  236. "execution_status": status,
  237. "executed_quantity": executed_quantity,
  238. "executed_at": executed_at,
  239. "last_weighing_slip_id": slip_id,
  240. }
  241. cur.executemany(
  242. """
  243. UPDATE purchase_plans
  244. SET execution_status = %s, executed_at = %s, last_weighing_slip_id = %s, executed_quantity = %s
  245. WHERE id = %s
  246. """,
  247. updates,
  248. )
  249. mysql_conn.commit()
  250. return result
  251. except Exception as e:
  252. logger.warning(f"MySQL批量刷新计划状态失败: {str(e)}")
  253. if not CONTINUE_ON_MYSQL_ERROR:
  254. raise
  255. return {}
  256. def link_plan_with_slip(self, plan_id: int, slip_id: int):
  257. """在保存地磅单后关联计划状态"""
  258. if not plan_id:
  259. return
  260. self.refresh_plan_execution_status(plan_id)
  261. def _calculate_execution_quantity(self, plan_id: int) -> float:
  262. """统计计划已执行量(kg)- 通过地磅单的净重数据累加(仅 MySQL)"""
  263. try:
  264. mysql_conn = self.get_mysql_connection()
  265. if not mysql_conn:
  266. return 0.0
  267. with mysql_conn.cursor() as mysql_cursor:
  268. mysql_cursor.execute("""
  269. SELECT COALESCE(SUM(net_weight), 0) as total_weight
  270. FROM weighing_slips
  271. WHERE purchase_plan_id = %s AND is_voided = 0
  272. """, (plan_id,))
  273. row = mysql_cursor.fetchone()
  274. if row:
  275. return float(row['total_weight'] if row['total_weight'] is not None else 0.0)
  276. except Exception as e:
  277. logger.warning(f"MySQL计算已执行量失败: {str(e)}")
  278. if not CONTINUE_ON_MYSQL_ERROR:
  279. raise
  280. return 0.0
  281. def _recalculate_slip_executed_quantities(self, plan_id: Optional[int] = None, plan_no: Optional[str] = None):
  282. """
  283. 根据创建时间对同一计划下的地磅单逐条累加净重,回写已执行量
  284. :param plan_id: 采购计划ID
  285. :param plan_no: 计划号
  286. """
  287. plan_no = plan_no.strip() if isinstance(plan_no, str) else None
  288. if not plan_id and not plan_no:
  289. return
  290. conditions = []
  291. params: List = []
  292. if plan_id:
  293. conditions.append("purchase_plan_id = ?")
  294. params.append(plan_id)
  295. if plan_no:
  296. conditions.append("(plan_no = ? AND plan_no <> '')")
  297. params.append(plan_no)
  298. if not conditions:
  299. return
  300. # 使用MySQL查询
  301. if not self.mysql_enabled:
  302. logger.warning("MySQL未启用,无法重算已执行量")
  303. return
  304. try:
  305. mysql_conn = self.get_mysql_connection()
  306. if not mysql_conn:
  307. logger.warning("无法获取MySQL连接,无法重算已执行量")
  308. return
  309. with mysql_conn.cursor() as cursor:
  310. # 构建WHERE条件
  311. where_parts = []
  312. query_params = []
  313. if plan_id:
  314. where_parts.append("purchase_plan_id = %s")
  315. query_params.append(plan_id)
  316. if plan_no:
  317. where_parts.append("(plan_no = %s AND plan_no <> '')")
  318. query_params.append(plan_no)
  319. if not where_parts:
  320. return
  321. where_clause = " OR ".join(where_parts)
  322. # 查询地磅单
  323. cursor.execute(f"""
  324. SELECT id, net_weight, created_at
  325. FROM weighing_slips
  326. WHERE is_voided = 0 AND ({where_clause})
  327. ORDER BY
  328. CASE WHEN created_at IS NULL OR created_at = '' THEN 1 ELSE 0 END,
  329. created_at ASC,
  330. id ASC
  331. """, query_params)
  332. rows = cursor.fetchall()
  333. cumulative = 0.0
  334. updates = []
  335. for row in rows:
  336. net_weight = row.get('net_weight') if row.get('net_weight') is not None else 0.0
  337. if net_weight < 0:
  338. net_weight = 0.0
  339. cumulative += float(net_weight)
  340. updates.append((cumulative, row['id']))
  341. if updates:
  342. cursor.executemany("""
  343. UPDATE weighing_slips
  344. SET executed_quantity = %s
  345. WHERE id = %s
  346. """, updates)
  347. mysql_conn.commit()
  348. except Exception as e:
  349. logger.warning(f"重算已执行量失败: {str(e)}")
  350. if not CONTINUE_ON_MYSQL_ERROR:
  351. raise
  352. def get_mysql_connection(self, force_reconnect: bool = False):
  353. """
  354. 获取MySQL数据库连接
  355. :param force_reconnect: 是否强制重新连接(用于确保读取最新数据)
  356. :return: MySQL连接对象
  357. """
  358. if not self.mysql_enabled:
  359. return None
  360. try:
  361. # 如果强制重新连接,先关闭旧连接
  362. if force_reconnect and self.mysql_connection is not None:
  363. try:
  364. self.mysql_connection.close()
  365. logger.info("强制重新建立MySQL连接以获取最新数据")
  366. except:
  367. pass
  368. self.mysql_connection = None
  369. # 检查连接是否存在且有效
  370. if self.mysql_connection is None:
  371. self.mysql_connection = pymysql.connect(
  372. host=MYSQL_CONFIG.get('host', 'localhost'),
  373. port=MYSQL_CONFIG.get('port', 3306),
  374. user=MYSQL_CONFIG.get('user', 'root'),
  375. password=MYSQL_CONFIG.get('password', ''),
  376. database=MYSQL_CONFIG.get('database', 'dibang'),
  377. charset=MYSQL_CONFIG.get('charset', 'utf8mb4'),
  378. cursorclass=pymysql.cursors.DictCursor,
  379. autocommit=False,
  380. connect_timeout=5, # 连接超时5秒
  381. read_timeout=10, # 读取超时10秒
  382. write_timeout=10 # 写入超时10秒
  383. )
  384. else:
  385. # 检查连接是否有效
  386. try:
  387. self.mysql_connection.ping(reconnect=True)
  388. except Exception as ping_error:
  389. # 连接失效,重新连接
  390. logger.info(f"MySQL连接失效,重新连接: {str(ping_error)}")
  391. try:
  392. self.mysql_connection.close()
  393. except:
  394. pass
  395. self.mysql_connection = pymysql.connect(
  396. host=MYSQL_CONFIG.get('host', 'localhost'),
  397. port=MYSQL_CONFIG.get('port', 3306),
  398. user=MYSQL_CONFIG.get('user', 'root'),
  399. password=MYSQL_CONFIG.get('password', ''),
  400. database=MYSQL_CONFIG.get('database', 'dibang'),
  401. charset=MYSQL_CONFIG.get('charset', 'utf8mb4'),
  402. cursorclass=pymysql.cursors.DictCursor,
  403. autocommit=False,
  404. connect_timeout=5, # 连接超时5秒
  405. read_timeout=10, # 读取超时10秒
  406. write_timeout=10 # 写入超时10秒
  407. )
  408. return self.mysql_connection
  409. except Exception as e:
  410. logger.warning(f"MySQL连接失败: {str(e)}")
  411. if not CONTINUE_ON_MYSQL_ERROR:
  412. raise
  413. return None
  414. def _execute_mysql(self, sql: str, params: tuple = None):
  415. """执行MySQL语句(内部方法)"""
  416. if not self.mysql_enabled:
  417. return
  418. conn = self.get_mysql_connection()
  419. if conn is None:
  420. return
  421. try:
  422. with conn.cursor() as cursor:
  423. cursor.execute(sql, params)
  424. conn.commit()
  425. except Exception as e:
  426. logger.warning(f"MySQL执行失败: {str(e)}, SQL: {sql}")
  427. if not CONTINUE_ON_MYSQL_ERROR:
  428. raise
  429. try:
  430. conn.rollback()
  431. except:
  432. pass
  433. def init_database(self):
  434. """
  435. 初始化数据库表结构(仅 MySQL)
  436. - 创建/升级 MySQL 表结构
  437. - 确保默认管理员存在
  438. """
  439. # 使用原有的 MySQL 初始化逻辑
  440. self._init_mysql_database()
  441. # 确保默认管理员存在(仅 MySQL)
  442. self.ensure_default_admin()
  443. def _init_mysql_database(self):
  444. """初始化MySQL数据库表结构"""
  445. conn = self.get_mysql_connection()
  446. if conn is None:
  447. return
  448. try:
  449. with conn.cursor() as cursor:
  450. # 创建地磅单表
  451. cursor.execute("""
  452. CREATE TABLE IF NOT EXISTS weighing_slips (
  453. id INT PRIMARY KEY AUTO_INCREMENT,
  454. vehicle_no VARCHAR(255) NOT NULL,
  455. plan_no VARCHAR(255),
  456. cargo_name VARCHAR(255) NOT NULL,
  457. business_type VARCHAR(255) NOT NULL,
  458. batch_no VARCHAR(255),
  459. supplier VARCHAR(255) NOT NULL,
  460. consignee VARCHAR(255) NOT NULL,
  461. gross_weight DOUBLE NOT NULL,
  462. gross_weight_time VARCHAR(255) NOT NULL,
  463. tare_weight DOUBLE NOT NULL,
  464. tare_weight_time VARCHAR(255) NOT NULL,
  465. deduction DOUBLE DEFAULT 0,
  466. net_weight DOUBLE NOT NULL,
  467. planned_quantity DOUBLE,
  468. executed_quantity DOUBLE,
  469. weighing_point VARCHAR(255) DEFAULT '山峡地磅',
  470. remarks TEXT,
  471. is_voided INT DEFAULT 0,
  472. created_at VARCHAR(255) NOT NULL
  473. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  474. """)
  475. # 创建公司名称表
  476. cursor.execute("""
  477. CREATE TABLE IF NOT EXISTS companies (
  478. id INT PRIMARY KEY AUTO_INCREMENT,
  479. name VARCHAR(255) NOT NULL UNIQUE,
  480. is_deleted INT DEFAULT 0,
  481. created_at VARCHAR(255) NOT NULL
  482. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  483. """)
  484. # 创建货物名称表
  485. cursor.execute("""
  486. CREATE TABLE IF NOT EXISTS cargos (
  487. id INT PRIMARY KEY AUTO_INCREMENT,
  488. name VARCHAR(255) NOT NULL UNIQUE,
  489. is_deleted INT DEFAULT 0,
  490. created_at VARCHAR(255) NOT NULL
  491. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  492. """)
  493. # 创建采购计划表
  494. cursor.execute("""
  495. CREATE TABLE IF NOT EXISTS purchase_plans (
  496. id INT PRIMARY KEY AUTO_INCREMENT,
  497. plan_date VARCHAR(255) NOT NULL,
  498. business_type VARCHAR(255) NOT NULL,
  499. product VARCHAR(255) NOT NULL,
  500. specification VARCHAR(255),
  501. planned_quantity DOUBLE NOT NULL,
  502. vehicle_no VARCHAR(255) DEFAULT '' COMMENT '车牌号(保留字段,不再使用)',
  503. customer_name VARCHAR(255),
  504. remarks TEXT,
  505. is_deleted INT DEFAULT 0,
  506. execution_status VARCHAR(50),
  507. executed_at VARCHAR(255),
  508. last_weighing_slip_id INT,
  509. executed_quantity DOUBLE DEFAULT 0,
  510. created_at VARCHAR(255) NOT NULL
  511. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  512. """)
  513. # 创建用户表
  514. cursor.execute("""
  515. CREATE TABLE IF NOT EXISTS users (
  516. id INT PRIMARY KEY AUTO_INCREMENT,
  517. username VARCHAR(255) NOT NULL UNIQUE,
  518. password VARCHAR(255) NOT NULL,
  519. role VARCHAR(50) NOT NULL DEFAULT 'user',
  520. created_at VARCHAR(255) NOT NULL
  521. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  522. """)
  523. # 检查并添加customer_name字段(如果不存在)
  524. try:
  525. cursor.execute("ALTER TABLE purchase_plans ADD COLUMN customer_name VARCHAR(255)")
  526. except:
  527. pass # 字段已存在,忽略错误
  528. # 检查并添加remarks字段(如果不存在)
  529. try:
  530. cursor.execute("ALTER TABLE purchase_plans ADD COLUMN remarks TEXT")
  531. except:
  532. pass
  533. # 检查并添加is_deleted字段
  534. try:
  535. cursor.execute("ALTER TABLE purchase_plans ADD COLUMN is_deleted INT DEFAULT 0")
  536. cursor.execute("UPDATE purchase_plans SET is_deleted = 0 WHERE is_deleted IS NULL")
  537. except:
  538. pass
  539. # companies 表补充 is_deleted
  540. try:
  541. cursor.execute("ALTER TABLE companies ADD COLUMN is_deleted INT DEFAULT 0")
  542. cursor.execute("UPDATE companies SET is_deleted = 0 WHERE is_deleted IS NULL")
  543. except:
  544. pass
  545. # cargos 表补充 is_deleted
  546. try:
  547. cursor.execute("ALTER TABLE cargos ADD COLUMN is_deleted INT DEFAULT 0")
  548. cursor.execute("UPDATE cargos SET is_deleted = 0 WHERE is_deleted IS NULL")
  549. except:
  550. pass
  551. # purchase_plans execution_status
  552. try:
  553. cursor.execute("ALTER TABLE purchase_plans ADD COLUMN execution_status VARCHAR(50)")
  554. except:
  555. pass
  556. # purchase_plans vehicle_no 设置默认值(如果已存在表)
  557. try:
  558. cursor.execute("ALTER TABLE purchase_plans MODIFY vehicle_no VARCHAR(255) DEFAULT ''")
  559. except:
  560. pass # 如果失败(比如字段已存在且有不同约束),忽略错误
  561. # purchase_plans executed_at
  562. try:
  563. cursor.execute("ALTER TABLE purchase_plans ADD COLUMN executed_at VARCHAR(255)")
  564. except:
  565. pass
  566. # purchase_plans last_weighing_slip_id
  567. try:
  568. cursor.execute("ALTER TABLE purchase_plans ADD COLUMN last_weighing_slip_id INT")
  569. except:
  570. pass
  571. # purchase_plans executed_quantity
  572. try:
  573. cursor.execute("ALTER TABLE purchase_plans ADD COLUMN executed_quantity DOUBLE DEFAULT 0")
  574. except:
  575. pass
  576. # weighing_slips purchase_plan_id
  577. try:
  578. cursor.execute("ALTER TABLE weighing_slips ADD COLUMN purchase_plan_id INT")
  579. except:
  580. pass
  581. # 创建出入库表
  582. cursor.execute("""
  583. CREATE TABLE IF NOT EXISTS inbound_outbound (
  584. id INT PRIMARY KEY AUTO_INCREMENT,
  585. date VARCHAR(255) NOT NULL,
  586. partner_company VARCHAR(255) NOT NULL,
  587. business_type VARCHAR(255) NOT NULL,
  588. product VARCHAR(255) NOT NULL,
  589. quantity DOUBLE NOT NULL,
  590. plan_no VARCHAR(255),
  591. batch_no VARCHAR(255),
  592. vehicle_no VARCHAR(255) NOT NULL,
  593. status VARCHAR(50),
  594. remarks TEXT,
  595. purchase_plan_id INT,
  596. is_deleted INT DEFAULT 0,
  597. created_at VARCHAR(255) NOT NULL
  598. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  599. """)
  600. # purchase_plans 表添加 plan_no 字段
  601. try:
  602. cursor.execute("ALTER TABLE purchase_plans ADD COLUMN plan_no VARCHAR(255)")
  603. except:
  604. pass
  605. # purchase_plans 表添加 start_date 和 end_date 字段
  606. try:
  607. cursor.execute("ALTER TABLE purchase_plans ADD COLUMN start_date VARCHAR(255)")
  608. except:
  609. pass
  610. try:
  611. cursor.execute("ALTER TABLE purchase_plans ADD COLUMN end_date VARCHAR(255)")
  612. except:
  613. pass
  614. # weighing_slips 表添加 inbound_outbound_id 字段
  615. try:
  616. cursor.execute("ALTER TABLE weighing_slips ADD COLUMN inbound_outbound_id INT")
  617. except:
  618. pass
  619. # weighing_slips 表添加 current_quantity 字段(本次量,单位:kg)
  620. try:
  621. cursor.execute("ALTER TABLE weighing_slips ADD COLUMN current_quantity DOUBLE")
  622. except:
  623. pass
  624. # 初始化MySQL execution_status
  625. cursor.execute("""
  626. UPDATE purchase_plans
  627. SET execution_status = CASE business_type
  628. WHEN '入库' THEN '待入库'
  629. WHEN '出库' THEN '待出库'
  630. ELSE '待入库'
  631. END
  632. WHERE execution_status IS NULL OR execution_status = ''
  633. """)
  634. cursor.execute("""
  635. UPDATE purchase_plans
  636. SET executed_quantity = 0
  637. WHERE executed_quantity IS NULL
  638. """)
  639. # 将现有plan_date复制到start_date和end_date
  640. cursor.execute("""
  641. UPDATE purchase_plans
  642. SET start_date = plan_date, end_date = plan_date
  643. WHERE (start_date IS NULL OR end_date IS NULL) AND plan_date IS NOT NULL
  644. """)
  645. conn.commit()
  646. except Exception as e:
  647. logger.warning(f"MySQL表初始化失败: {str(e)}")
  648. if not CONTINUE_ON_MYSQL_ERROR:
  649. raise
  650. try:
  651. conn.rollback()
  652. except:
  653. pass
  654. def _sync_mysql_to_sqlite(self):
  655. """
  656. 兼容保留的方法(已废弃)
  657. 目前工程已不再使用 SQLite,仅保留空实现以避免旧代码引用报错。
  658. """
  659. logger.info("当前版本已不再从 MySQL 同步数据到 SQLite,_sync_mysql_to_sqlite 将被忽略。")
  660. # ========== 地磅单相关操作 ==========
  661. def insert_weighing_slip(self, data: Dict) -> int:
  662. """
  663. 插入地磅单记录
  664. :param data: 地磅单数据字典
  665. :return: 插入记录的ID
  666. """
  667. # 计算净重
  668. net_weight = data['gross_weight'] - data['tare_weight'] - data.get('deduction', 0)
  669. created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  670. inbound_id = data.get('inbound_outbound_id')
  671. if inbound_id:
  672. existing_slip = self.get_weighing_slip_by_inbound_id(inbound_id, include_voided=False)
  673. if existing_slip:
  674. raise ValueError("该出入库单已关联有效的地磅单,请先作废或解除关联后再新增。")
  675. record_id = None
  676. # 先操作MySQL,获取MySQL生成的ID
  677. if self.mysql_enabled:
  678. try:
  679. mysql_conn = self.get_mysql_connection()
  680. if mysql_conn:
  681. with mysql_conn.cursor() as mysql_cursor:
  682. mysql_cursor.execute("""
  683. INSERT INTO weighing_slips (
  684. vehicle_no, plan_no, cargo_name, business_type, batch_no,
  685. supplier, consignee, gross_weight, gross_weight_time,
  686. tare_weight, tare_weight_time, deduction, net_weight,
  687. planned_quantity, executed_quantity, purchase_plan_id,
  688. inbound_outbound_id, weighing_point, remarks, current_quantity,
  689. is_voided, created_at
  690. ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
  691. """, (
  692. data['vehicle_no'],
  693. data.get('plan_no', ''),
  694. data['cargo_name'],
  695. data['business_type'],
  696. data.get('batch_no', ''),
  697. data['supplier'],
  698. data['consignee'],
  699. data['gross_weight'],
  700. data['gross_weight_time'],
  701. data['tare_weight'],
  702. data['tare_weight_time'],
  703. data.get('deduction', 0),
  704. net_weight,
  705. data.get('planned_quantity'),
  706. data.get('executed_quantity'),
  707. data.get('purchase_plan_id'),
  708. data.get('inbound_outbound_id'),
  709. data.get('weighing_point', '山峡地磅'),
  710. data.get('remarks', ''),
  711. data.get('current_quantity'),
  712. 0, # is_voided
  713. created_at
  714. ))
  715. record_id = mysql_cursor.lastrowid
  716. mysql_conn.commit()
  717. except Exception as e:
  718. logger.warning(f"MySQL插入地磅单失败: {str(e)}")
  719. if not CONTINUE_ON_MYSQL_ERROR:
  720. raise
  721. if record_id is None:
  722. raise RuntimeError("无法插入地磅单:MySQL未启用或插入失败")
  723. # 按创建时间重新计算同一计划下所有地磅单的已执行量
  724. plan_no_value = data.get('plan_no')
  725. self._recalculate_slip_executed_quantities(
  726. plan_id=data.get('purchase_plan_id'),
  727. plan_no=plan_no_value if plan_no_value else None
  728. )
  729. # 如果关联了出入库单,刷新出入库单状态
  730. if data.get('inbound_outbound_id'):
  731. try:
  732. self.refresh_inbound_status(data['inbound_outbound_id'])
  733. except Exception as e:
  734. logger.warning(f"刷新出入库单状态失败: {str(e)}")
  735. if not CONTINUE_ON_MYSQL_ERROR:
  736. raise
  737. # 如果关联了计划,刷新计划状态(通过出入库单)
  738. if data.get('purchase_plan_id'):
  739. try:
  740. self.refresh_plan_execution_status(data['purchase_plan_id'])
  741. except Exception as e:
  742. logger.warning(f"刷新计划状态失败: {str(e)}")
  743. if not CONTINUE_ON_MYSQL_ERROR:
  744. raise
  745. return record_id
  746. def update_weighing_slip(self, slip_id: int, data: Dict) -> bool:
  747. """
  748. 更新地磅单记录
  749. :param slip_id: 地磅单ID
  750. :param data: 更新后的地磅单数据
  751. """
  752. existing = self.get_weighing_slip_by_id(slip_id)
  753. if not existing:
  754. return False
  755. old_plan_id = existing.get('purchase_plan_id')
  756. old_plan_no = (existing.get('plan_no') or '').strip()
  757. new_plan_id = data.get('purchase_plan_id')
  758. new_plan_no = (data.get('plan_no') or '').strip()
  759. net_weight = data['gross_weight'] - data['tare_weight'] - data.get('deduction', 0)
  760. weighing_point = data.get('weighing_point', existing.get('weighing_point', '山峡地磅'))
  761. new_inbound_id = data.get('inbound_outbound_id')
  762. if new_inbound_id:
  763. conflict_slip = self.get_weighing_slip_by_inbound_id(new_inbound_id, include_voided=False)
  764. if conflict_slip and conflict_slip['id'] != slip_id:
  765. raise ValueError("该出入库单已关联其他地磅单,无法重复关联。")
  766. params = (
  767. data['vehicle_no'],
  768. data.get('plan_no', ''),
  769. data['cargo_name'],
  770. data['business_type'],
  771. data.get('batch_no', ''),
  772. data['supplier'],
  773. data['consignee'],
  774. data['gross_weight'],
  775. data.get('gross_weight_time', ''),
  776. data['tare_weight'],
  777. data.get('tare_weight_time', ''),
  778. data.get('deduction', 0),
  779. net_weight,
  780. data.get('planned_quantity'),
  781. data.get('executed_quantity'),
  782. data.get('purchase_plan_id'),
  783. data.get('inbound_outbound_id'),
  784. weighing_point,
  785. data.get('remarks', ''),
  786. data.get('current_quantity'),
  787. slip_id
  788. )
  789. mysql_success = False
  790. if self.mysql_enabled:
  791. try:
  792. mysql_conn = self.get_mysql_connection()
  793. if mysql_conn:
  794. with mysql_conn.cursor() as mysql_cursor:
  795. mysql_cursor.execute("""
  796. UPDATE weighing_slips SET
  797. vehicle_no = %s,
  798. plan_no = %s,
  799. cargo_name = %s,
  800. business_type = %s,
  801. batch_no = %s,
  802. supplier = %s,
  803. consignee = %s,
  804. gross_weight = %s,
  805. gross_weight_time = %s,
  806. tare_weight = %s,
  807. tare_weight_time = %s,
  808. deduction = %s,
  809. net_weight = %s,
  810. planned_quantity = %s,
  811. executed_quantity = %s,
  812. purchase_plan_id = %s,
  813. inbound_outbound_id = %s,
  814. weighing_point = %s,
  815. remarks = %s,
  816. current_quantity = %s
  817. WHERE id = %s
  818. """, params)
  819. mysql_success = mysql_cursor.rowcount > 0
  820. mysql_conn.commit()
  821. except Exception as e:
  822. logger.warning(f"MySQL更新地磅单失败: {str(e)}")
  823. if not CONTINUE_ON_MYSQL_ERROR:
  824. raise
  825. return False
  826. if not self.mysql_enabled:
  827. logger.warning("MySQL未启用,无法更新地磅单")
  828. return False
  829. normalized_new_plan_no = new_plan_no if new_plan_no else None
  830. normalized_old_plan_no = old_plan_no if old_plan_no else None
  831. self._recalculate_slip_executed_quantities(plan_id=new_plan_id, plan_no=normalized_new_plan_no)
  832. if (old_plan_id or normalized_old_plan_no) and (old_plan_id, normalized_old_plan_no) != (new_plan_id, normalized_new_plan_no):
  833. self._recalculate_slip_executed_quantities(plan_id=old_plan_id, plan_no=normalized_old_plan_no)
  834. # 如果关联了出入库单,刷新出入库单状态
  835. old_inbound_id = existing.get('inbound_outbound_id')
  836. new_inbound_id = data.get('inbound_outbound_id')
  837. try:
  838. if old_inbound_id and old_inbound_id != new_inbound_id:
  839. self.refresh_inbound_status(old_inbound_id)
  840. if new_inbound_id:
  841. self.refresh_inbound_status(new_inbound_id)
  842. except Exception as e:
  843. logger.warning(f"刷新出入库单状态失败: {str(e)}")
  844. if not CONTINUE_ON_MYSQL_ERROR:
  845. raise
  846. # 如果关联了计划,刷新计划状态(通过出入库单)
  847. try:
  848. if old_plan_id and old_plan_id != new_plan_id:
  849. self.refresh_plan_execution_status(old_plan_id)
  850. if new_plan_id:
  851. self.refresh_plan_execution_status(new_plan_id)
  852. except Exception as e:
  853. logger.warning(f"刷新计划状态失败: {str(e)}")
  854. if not CONTINUE_ON_MYSQL_ERROR:
  855. raise
  856. return mysql_success
  857. def get_all_weighing_slips(self, include_voided: bool = False, keyword: Optional[str] = None) -> List[Dict]:
  858. """
  859. 获取所有地磅单记录
  860. :param include_voided: 是否包含作废的记录
  861. :return: 地磅单记录列表(从出入库单关联获取 date 字段,别名为 inbound_date)
  862. """
  863. search_text = (keyword or "").strip()
  864. like_value = f"%{search_text}%" if search_text else None
  865. # 仅使用MySQL查询
  866. if not self.mysql_enabled:
  867. logger.warning("MySQL未启用,无法查询地磅单列表")
  868. return []
  869. if self.mysql_enabled:
  870. try:
  871. # 复用已有 MySQL 连接,必要时由 get_mysql_connection 内部自动重连
  872. mysql_conn = self.get_mysql_connection()
  873. if mysql_conn:
  874. try:
  875. # 确保事务已提交
  876. mysql_conn.commit()
  877. # 设置隔离级别为READ COMMITTED
  878. with mysql_conn.cursor() as cursor:
  879. cursor.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED")
  880. with mysql_conn.cursor() as mysql_cursor:
  881. # 通过出入库单表关联获取日期字段(inbound_outbound.date → inbound_date)
  882. if include_voided:
  883. base_query = """
  884. SELECT ws.*, io.date AS inbound_date
  885. FROM weighing_slips ws
  886. LEFT JOIN inbound_outbound io ON ws.inbound_outbound_id = io.id
  887. """
  888. where_clause = ""
  889. else:
  890. base_query = """
  891. SELECT ws.*, io.date AS inbound_date
  892. FROM weighing_slips ws
  893. LEFT JOIN inbound_outbound io ON ws.inbound_outbound_id = io.id
  894. """
  895. where_clause = "WHERE ws.is_voided = 0"
  896. params: Tuple = ()
  897. if like_value:
  898. search_clause = (
  899. "ws.supplier LIKE %s OR ws.consignee LIKE %s "
  900. "OR ws.vehicle_no LIKE %s OR ws.cargo_name LIKE %s"
  901. )
  902. if where_clause:
  903. where_clause = f"{where_clause} AND ({search_clause})"
  904. else:
  905. where_clause = f"WHERE ({search_clause})"
  906. params = (like_value, like_value, like_value, like_value)
  907. # 按关联的出入库单日期、创建时间、毛重时间、皮重时间倒序排列
  908. order_clause = (
  909. "ORDER BY io.date DESC, ws.created_at DESC, "
  910. "ws.gross_weight_time DESC, ws.tare_weight_time DESC, ws.id DESC"
  911. )
  912. mysql_cursor.execute(f"{base_query} {where_clause} {order_clause}", params)
  913. rows = mysql_cursor.fetchall()
  914. result = [dict(row) for row in rows]
  915. logger.info(f"✅ 从MySQL获取地磅单列表,共{len(result)}条记录")
  916. return result
  917. except Exception as query_error:
  918. logger.error(f"MySQL查询地磅单执行失败: {str(query_error)}", exc_info=True)
  919. raise
  920. else:
  921. logger.warning("⚠️ MySQL连接不可用")
  922. return []
  923. except Exception as e:
  924. logger.warning(f"⚠️ MySQL查询地磅单失败: {str(e)}", exc_info=True)
  925. return []
  926. return []
  927. def get_weighing_slip_by_id(self, slip_id: int) -> Optional[Dict]:
  928. """
  929. 根据ID获取地磅单记录
  930. :param slip_id: 地磅单ID
  931. :return: 地磅单记录字典,如果不存在返回None
  932. """
  933. # 仅使用MySQL查询
  934. if not self.mysql_enabled:
  935. logger.warning("MySQL未启用,无法查询地磅单")
  936. return None
  937. try:
  938. mysql_conn = self.get_mysql_connection()
  939. if mysql_conn:
  940. with mysql_conn.cursor() as mysql_cursor:
  941. mysql_cursor.execute("SELECT * FROM weighing_slips WHERE id = %s", (slip_id,))
  942. row = mysql_cursor.fetchone()
  943. if row:
  944. return dict(row)
  945. except Exception as e:
  946. logger.warning(f"MySQL查询地磅单失败: {str(e)}")
  947. if not CONTINUE_ON_MYSQL_ERROR:
  948. raise
  949. return None
  950. def get_weighing_slip_by_inbound_id(self, inbound_id: int, include_voided: bool = False) -> Optional[Dict]:
  951. """
  952. 根据出入库单ID获取关联的地磅单
  953. :param inbound_id: 出入库单ID
  954. :param include_voided: 是否包含已作废的地磅单
  955. """
  956. if not inbound_id:
  957. return None
  958. if self.mysql_enabled:
  959. try:
  960. mysql_conn = self.get_mysql_connection()
  961. if mysql_conn:
  962. with mysql_conn.cursor() as mysql_cursor:
  963. query = """
  964. SELECT * FROM weighing_slips
  965. WHERE inbound_outbound_id = %s
  966. """
  967. if not include_voided:
  968. query += " AND is_voided = 0"
  969. query += " ORDER BY id DESC LIMIT 1"
  970. mysql_cursor.execute(query, (inbound_id,))
  971. row = mysql_cursor.fetchone()
  972. if row:
  973. return dict(row)
  974. except Exception as e:
  975. # 如果是超时错误,只记录简要警告
  976. if "timed out" in str(e) or "Lost connection" in str(e):
  977. logger.debug(f"MySQL查询出入库关联地磅单超时: {str(e)}")
  978. else:
  979. logger.warning(f"MySQL查询出入库关联地磅单失败: {str(e)}")
  980. if not CONTINUE_ON_MYSQL_ERROR:
  981. raise
  982. # MySQL失败或未启用,返回None(已移除SQLite支持)
  983. logger.warning("⚠️ MySQL查询失败且已移除SQLite支持,返回None")
  984. return None
  985. def get_weighing_slip_summary_by_inbound_ids(
  986. self,
  987. inbound_ids: List[int],
  988. include_voided: bool = False
  989. ) -> Dict[int, Dict]:
  990. """
  991. 批量获取出入库单关联的最新地磅单概要(净重、毛重、皮重)
  992. :param inbound_ids: 出入库单ID列表
  993. :param include_voided: 是否包含已作废的地磅单
  994. :return: {inbound_id: weighing_slip_dict}
  995. """
  996. if not inbound_ids:
  997. return {}
  998. unique_ids = list({iid for iid in inbound_ids if iid})
  999. if not unique_ids:
  1000. return {}
  1001. def _build_latest_map(rows) -> Dict[int, Dict]:
  1002. latest = {}
  1003. for row in rows:
  1004. inbound_id = row.get('inbound_outbound_id')
  1005. if inbound_id is None:
  1006. continue
  1007. existing = latest.get(inbound_id)
  1008. if not existing or row.get('id', 0) > existing.get('id', 0):
  1009. latest[inbound_id] = row
  1010. return latest
  1011. void_clause = "" if include_voided else "AND is_voided = 0"
  1012. selected_fields = "id, inbound_outbound_id, net_weight, gross_weight, tare_weight, deduction, gross_weight_time, tare_weight_time"
  1013. # 只从 MySQL 批量查询出入库单对应的最新地磅单
  1014. try:
  1015. mysql_conn = self.get_mysql_connection()
  1016. if not mysql_conn:
  1017. logger.error("MySQL连接不可用,无法批量查询出入库关联地磅单汇总")
  1018. return {}
  1019. placeholders = ", ".join(["%s"] * len(unique_ids))
  1020. query = f"""
  1021. SELECT {selected_fields}
  1022. FROM weighing_slips
  1023. WHERE inbound_outbound_id IN ({placeholders}) {void_clause}
  1024. ORDER BY id DESC
  1025. """
  1026. with mysql_conn.cursor() as mysql_cursor:
  1027. mysql_cursor.execute(query, tuple(unique_ids))
  1028. rows = mysql_cursor.fetchall()
  1029. if not rows:
  1030. return {}
  1031. return _build_latest_map([dict(row) for row in rows])
  1032. except Exception as e:
  1033. logger.error(f"批量查询地磅单失败: {str(e)}", exc_info=True)
  1034. if not CONTINUE_ON_MYSQL_ERROR:
  1035. raise
  1036. return {}
  1037. def get_weighing_slips_by_inbound_id(self, inbound_id: int, include_voided: bool = False) -> List[Dict]:
  1038. """
  1039. 根据出入库单ID获取关联的地磅单列表
  1040. :param inbound_id: 出入库单ID
  1041. :param include_voided: 是否包含作废记录
  1042. """
  1043. if not inbound_id:
  1044. return []
  1045. void_clause = "" if include_voided else "AND is_voided = 0"
  1046. order_clause = "ORDER BY created_at DESC, id DESC"
  1047. try:
  1048. mysql_conn = self.get_mysql_connection()
  1049. if not mysql_conn:
  1050. logger.error("MySQL连接不可用,无法查询出入库关联地磅单列表")
  1051. return []
  1052. query = f"""
  1053. SELECT * FROM weighing_slips
  1054. WHERE inbound_outbound_id = %s {void_clause}
  1055. {order_clause}
  1056. """
  1057. with mysql_conn.cursor() as mysql_cursor:
  1058. mysql_cursor.execute(query, (inbound_id,))
  1059. rows = mysql_cursor.fetchall()
  1060. return [dict(row) for row in rows]
  1061. except Exception as e:
  1062. logger.error(f"MySQL查询出入库关联地磅单列表失败: {str(e)}", exc_info=True)
  1063. if not CONTINUE_ON_MYSQL_ERROR:
  1064. raise
  1065. return []
  1066. def get_today_weighing_slip_with_weight_by_vehicle(self, vehicle_no: str) -> Optional[Dict]:
  1067. """
  1068. 查询当天该车牌下已填写毛重或皮重的地磅单(未作废),取最新一条。
  1069. 用于出入库管理检索:判断当前正在称重的出入库单是否为用户输入的id。
  1070. :param vehicle_no: 车牌号
  1071. :return: 地磅单记录(含 inbound_outbound_id),不存在则返回 None
  1072. """
  1073. if not (vehicle_no and vehicle_no.strip()):
  1074. return None
  1075. today_str = datetime.now().strftime("%Y-%m-%d")
  1076. if not self.mysql_enabled:
  1077. return None
  1078. try:
  1079. mysql_conn = self.get_mysql_connection()
  1080. if not mysql_conn:
  1081. return None
  1082. with mysql_conn.cursor() as mysql_cursor:
  1083. mysql_cursor.execute("""
  1084. SELECT ws.* FROM weighing_slips ws
  1085. INNER JOIN inbound_outbound io ON ws.inbound_outbound_id = io.id AND io.is_deleted = 0
  1086. WHERE io.vehicle_no = %s AND io.date = %s
  1087. AND ws.is_voided = 0
  1088. AND (COALESCE(ws.gross_weight, 0) > 0 OR COALESCE(ws.tare_weight, 0) > 0)
  1089. ORDER BY ws.id DESC
  1090. LIMIT 1
  1091. """, (vehicle_no.strip(), today_str))
  1092. row = mysql_cursor.fetchone()
  1093. if row:
  1094. return dict(row)
  1095. except Exception as e:
  1096. logger.warning(f"MySQL查询当天车牌地磅单失败: {str(e)}")
  1097. if not CONTINUE_ON_MYSQL_ERROR:
  1098. raise
  1099. return None
  1100. def get_today_incomplete_weighing_slips_by_vehicle(self, vehicle_no: str) -> List[Dict]:
  1101. """
  1102. 查询当天该车牌下未完成的地磅单(未作废)。
  1103. 未完成:有毛重没有皮重,或有皮重没有毛重。
  1104. :param vehicle_no: 车牌号
  1105. :return: 地磅单记录列表(含 inbound_outbound_id),按 id 倒序
  1106. """
  1107. if not (vehicle_no and vehicle_no.strip()):
  1108. return []
  1109. today_str = datetime.now().strftime("%Y-%m-%d")
  1110. if not self.mysql_enabled:
  1111. return []
  1112. try:
  1113. mysql_conn = self.get_mysql_connection()
  1114. if not mysql_conn:
  1115. return []
  1116. with mysql_conn.cursor() as mysql_cursor:
  1117. mysql_cursor.execute("""
  1118. SELECT ws.* FROM weighing_slips ws
  1119. INNER JOIN inbound_outbound io ON ws.inbound_outbound_id = io.id AND io.is_deleted = 0
  1120. WHERE io.vehicle_no = %s AND io.date = %s
  1121. AND ws.is_voided = 0
  1122. AND (
  1123. (COALESCE(ws.gross_weight, 0) > 0 AND (ws.tare_weight IS NULL OR COALESCE(ws.tare_weight, 0) = 0))
  1124. OR
  1125. ((ws.gross_weight IS NULL OR COALESCE(ws.gross_weight, 0) = 0) AND COALESCE(ws.tare_weight, 0) > 0)
  1126. )
  1127. ORDER BY ws.id DESC
  1128. """, (vehicle_no.strip(), today_str))
  1129. rows = mysql_cursor.fetchall()
  1130. return [dict(row) for row in rows] if rows else []
  1131. except Exception as e:
  1132. logger.warning(f"MySQL查询当天车牌未完成地磅单失败: {str(e)}")
  1133. if not CONTINUE_ON_MYSQL_ERROR:
  1134. raise
  1135. return []
  1136. def void_weighing_slip(self, slip_id: int) -> bool:
  1137. """
  1138. 作废地磅单
  1139. :param slip_id: 地磅单ID
  1140. :return: 是否成功
  1141. """
  1142. success = False
  1143. slip = self.get_weighing_slip_by_id(slip_id)
  1144. plan_id = slip.get('purchase_plan_id') if slip else None
  1145. plan_no = (slip.get('plan_no') or '').strip() if slip else None
  1146. inbound_id = slip.get('inbound_outbound_id') if slip else None
  1147. # 先操作MySQL
  1148. if self.mysql_enabled:
  1149. try:
  1150. mysql_conn = self.get_mysql_connection()
  1151. if mysql_conn:
  1152. with mysql_conn.cursor() as mysql_cursor:
  1153. mysql_cursor.execute("""
  1154. UPDATE weighing_slips
  1155. SET is_voided = 1
  1156. WHERE id = %s
  1157. """, (slip_id,))
  1158. affected_rows = mysql_cursor.rowcount
  1159. mysql_conn.commit()
  1160. if affected_rows > 0:
  1161. success = True
  1162. logger.info(f"MySQL作废地磅单成功: ID {slip_id}")
  1163. else:
  1164. logger.warning(f"MySQL作废地磅单: ID {slip_id} 未找到记录")
  1165. else:
  1166. logger.warning(f"MySQL连接失败,无法作废地磅单 ID {slip_id}")
  1167. except Exception as e:
  1168. logger.error(f"MySQL作废地磅单失败: ID {slip_id}, 错误: {str(e)}", exc_info=True)
  1169. if not CONTINUE_ON_MYSQL_ERROR:
  1170. raise
  1171. # 已移除SQLite支持,仅使用MySQL
  1172. if success:
  1173. try:
  1174. self._recalculate_slip_executed_quantities(plan_id=plan_id, plan_no=plan_no if plan_no else None)
  1175. except Exception as e:
  1176. logger.warning(f"重算地磅单已执行量失败: {str(e)}")
  1177. if not CONTINUE_ON_MYSQL_ERROR:
  1178. raise
  1179. if plan_id and success:
  1180. try:
  1181. self.refresh_plan_execution_status(plan_id)
  1182. except Exception as e:
  1183. logger.warning(f"刷新计划状态失败: {str(e)}")
  1184. if not CONTINUE_ON_MYSQL_ERROR:
  1185. raise
  1186. if inbound_id and success:
  1187. try:
  1188. self.refresh_inbound_status(inbound_id)
  1189. except Exception as e:
  1190. logger.warning(f"刷新出入库状态失败: {str(e)}")
  1191. if not CONTINUE_ON_MYSQL_ERROR:
  1192. raise
  1193. return success
  1194. # ========== 公司名称相关操作 ==========
  1195. def insert_company(self, name: str) -> int:
  1196. """
  1197. 插入公司名称
  1198. :param name: 公司名称
  1199. :return: 插入记录的ID
  1200. """
  1201. created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  1202. record_id = None
  1203. # 先操作MySQL,获取MySQL生成的ID
  1204. if self.mysql_enabled:
  1205. try:
  1206. mysql_conn = self.get_mysql_connection()
  1207. if mysql_conn:
  1208. with mysql_conn.cursor() as mysql_cursor:
  1209. mysql_cursor.execute("""
  1210. INSERT INTO companies (name, is_deleted, created_at)
  1211. VALUES (%s, %s, %s)
  1212. """, (name, 0, created_at))
  1213. record_id = mysql_cursor.lastrowid
  1214. mysql_conn.commit()
  1215. except Exception as e:
  1216. logger.warning(f"MySQL插入公司失败: {str(e)}")
  1217. if not CONTINUE_ON_MYSQL_ERROR:
  1218. raise
  1219. if record_id is None:
  1220. raise RuntimeError("无法插入公司:MySQL未启用或插入失败")
  1221. return record_id
  1222. def get_all_companies(self) -> List[Dict]:
  1223. """
  1224. 获取所有公司名称
  1225. :return: 公司名称列表
  1226. """
  1227. # 只从 MySQL 获取公司列表(复用连接,必要时自动重连)
  1228. try:
  1229. mysql_conn = self.get_mysql_connection()
  1230. if not mysql_conn:
  1231. logger.error("MySQL连接不可用,无法获取公司列表")
  1232. return []
  1233. # 确保事务已提交,并设置隔离级别为 READ COMMITTED
  1234. mysql_conn.commit()
  1235. with mysql_conn.cursor() as cursor:
  1236. cursor.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED")
  1237. with mysql_conn.cursor() as mysql_cursor:
  1238. mysql_cursor.execute("""
  1239. SELECT * FROM companies
  1240. WHERE is_deleted = 0
  1241. ORDER BY name
  1242. """)
  1243. rows = mysql_cursor.fetchall()
  1244. result = [dict(row) for row in rows]
  1245. logger.info(f"✅ 从MySQL获取公司列表,共{len(result)}条记录")
  1246. return result
  1247. except Exception as query_error:
  1248. logger.error(f"MySQL查询公司执行失败: {str(query_error)}", exc_info=True)
  1249. if not CONTINUE_ON_MYSQL_ERROR:
  1250. raise
  1251. return []
  1252. def update_company(self, company_id: int, name: str) -> bool:
  1253. """
  1254. 更新公司名称
  1255. :param company_id: 公司ID
  1256. :param name: 新名称
  1257. :return: 是否成功
  1258. """
  1259. success = False
  1260. # 先操作MySQL
  1261. if self.mysql_enabled:
  1262. try:
  1263. mysql_conn = self.get_mysql_connection()
  1264. if mysql_conn:
  1265. with mysql_conn.cursor() as mysql_cursor:
  1266. mysql_cursor.execute("""
  1267. UPDATE companies
  1268. SET name = %s
  1269. WHERE id = %s
  1270. """, (name, company_id))
  1271. affected_rows = mysql_cursor.rowcount
  1272. mysql_conn.commit()
  1273. if affected_rows > 0:
  1274. success = True
  1275. logger.info(f"MySQL更新公司成功: ID {company_id}, 新名称: {name}")
  1276. else:
  1277. logger.warning(f"MySQL更新公司: ID {company_id} 未找到记录")
  1278. else:
  1279. logger.warning(f"MySQL连接失败,无法更新公司 ID {company_id}")
  1280. except Exception as e:
  1281. logger.error(f"MySQL更新公司失败: ID {company_id}, 错误: {str(e)}", exc_info=True)
  1282. if not CONTINUE_ON_MYSQL_ERROR:
  1283. raise
  1284. return success
  1285. def delete_company(self, company_id: int) -> bool:
  1286. """
  1287. 删除公司名称
  1288. :param company_id: 公司ID
  1289. :return: 是否成功
  1290. """
  1291. success = False
  1292. # 先操作MySQL
  1293. if self.mysql_enabled:
  1294. try:
  1295. mysql_conn = self.get_mysql_connection()
  1296. if mysql_conn:
  1297. with mysql_conn.cursor() as mysql_cursor:
  1298. mysql_cursor.execute("""
  1299. UPDATE companies
  1300. SET is_deleted = 1
  1301. WHERE id = %s
  1302. """, (company_id,))
  1303. affected_rows = mysql_cursor.rowcount
  1304. mysql_conn.commit()
  1305. if affected_rows > 0:
  1306. success = True
  1307. logger.info(f"MySQL删除公司成功: ID {company_id}")
  1308. else:
  1309. logger.warning(f"MySQL删除公司: ID {company_id} 未找到记录")
  1310. else:
  1311. logger.warning(f"MySQL连接失败,无法删除公司 ID {company_id}")
  1312. except Exception as e:
  1313. logger.error(f"MySQL删除公司失败: ID {company_id}, 错误: {str(e)}", exc_info=True)
  1314. if not CONTINUE_ON_MYSQL_ERROR:
  1315. raise
  1316. return success
  1317. def is_company_used(self, company_id: int) -> bool:
  1318. """
  1319. 检查公司是否被地磅单引用
  1320. :param company_id: 公司ID
  1321. :return: 是否被引用
  1322. """
  1323. # 先尝试从MySQL查询
  1324. if self.mysql_enabled:
  1325. try:
  1326. mysql_conn = self.get_mysql_connection()
  1327. if mysql_conn:
  1328. with mysql_conn.cursor() as mysql_cursor:
  1329. # 获取公司名称
  1330. mysql_cursor.execute("SELECT name FROM companies WHERE id = %s", (company_id,))
  1331. row = mysql_cursor.fetchone()
  1332. if not row:
  1333. return False
  1334. company_name = row['name']
  1335. # 检查是否在供货单位或收货单位中被使用
  1336. mysql_cursor.execute("""
  1337. SELECT COUNT(*) as count FROM weighing_slips
  1338. WHERE supplier = %s OR consignee = %s
  1339. """, (company_name, company_name))
  1340. result = mysql_cursor.fetchone()
  1341. return result['count'] > 0 if result else False
  1342. except Exception as e:
  1343. logger.warning(f"MySQL检查公司使用情况失败: {str(e)}")
  1344. if not CONTINUE_ON_MYSQL_ERROR:
  1345. raise
  1346. return False
  1347. def company_exists(self, name: str, exclude_id: Optional[int] = None, include_deleted: bool = False) -> bool:
  1348. """
  1349. 检查公司名称是否存在
  1350. :param name: 公司名称
  1351. :param exclude_id: 排除的ID(用于修改时检查)
  1352. :param include_deleted: 是否包含已删除记录
  1353. :return: 是否存在
  1354. """
  1355. # 先尝试从MySQL查询
  1356. if self.mysql_enabled:
  1357. try:
  1358. mysql_conn = self.get_mysql_connection()
  1359. if mysql_conn:
  1360. with mysql_conn.cursor() as mysql_cursor:
  1361. base_query = "SELECT COUNT(*) as count FROM companies WHERE name = %s"
  1362. params = [name]
  1363. if not include_deleted:
  1364. base_query += " AND is_deleted = 0"
  1365. if exclude_id:
  1366. base_query += " AND id != %s"
  1367. params.append(exclude_id)
  1368. mysql_cursor.execute(base_query, tuple(params))
  1369. result = mysql_cursor.fetchone()
  1370. return result['count'] > 0 if result else False
  1371. except Exception as e:
  1372. logger.warning(f"MySQL检查公司是否存在失败: {str(e)}")
  1373. if not CONTINUE_ON_MYSQL_ERROR:
  1374. raise
  1375. return False
  1376. def reactivate_company(self, name: str) -> bool:
  1377. """将已删除的公司名称恢复为可用"""
  1378. if not name:
  1379. return False
  1380. restored = False
  1381. if self.mysql_enabled:
  1382. try:
  1383. mysql_conn = self.get_mysql_connection()
  1384. if mysql_conn:
  1385. with mysql_conn.cursor() as mysql_cursor:
  1386. mysql_cursor.execute("""
  1387. UPDATE companies SET is_deleted = 0 WHERE name = %s
  1388. """, (name,))
  1389. if mysql_cursor.rowcount > 0:
  1390. restored = True
  1391. mysql_conn.commit()
  1392. except Exception as e:
  1393. logger.warning(f"MySQL恢复公司失败: {str(e)}")
  1394. if not CONTINUE_ON_MYSQL_ERROR:
  1395. raise
  1396. return restored
  1397. def ensure_company_active(self, name: str) -> str:
  1398. """
  1399. 确保公司名称处于可用状态
  1400. :return: 'created' | 'restored' | 'exists' | 'empty'
  1401. """
  1402. if not name:
  1403. return "empty"
  1404. if self.company_exists(name):
  1405. return "exists"
  1406. if self.reactivate_company(name):
  1407. return "restored"
  1408. self.insert_company(name)
  1409. return "created"
  1410. # ========== 货物名称相关操作 ==========
  1411. def insert_cargo(self, name: str) -> int:
  1412. """
  1413. 插入货物名称
  1414. :param name: 货物名称
  1415. :return: 插入记录的ID
  1416. """
  1417. created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  1418. record_id = None
  1419. # 先操作MySQL,获取MySQL生成的ID
  1420. if self.mysql_enabled:
  1421. try:
  1422. mysql_conn = self.get_mysql_connection()
  1423. if mysql_conn:
  1424. with mysql_conn.cursor() as mysql_cursor:
  1425. mysql_cursor.execute("""
  1426. INSERT INTO cargos (name, is_deleted, created_at)
  1427. VALUES (%s, %s, %s)
  1428. """, (name, 0, created_at))
  1429. record_id = mysql_cursor.lastrowid
  1430. mysql_conn.commit()
  1431. except Exception as e:
  1432. logger.warning(f"MySQL插入货物失败: {str(e)}")
  1433. if not CONTINUE_ON_MYSQL_ERROR:
  1434. raise
  1435. if record_id is None:
  1436. raise RuntimeError("无法插入货物:MySQL未启用或插入失败")
  1437. return record_id
  1438. def get_all_cargos(self) -> List[Dict]:
  1439. """
  1440. 获取所有货物名称
  1441. :return: 货物名称列表
  1442. """
  1443. # 只从 MySQL 获取货物列表(复用连接,必要时自动重连)
  1444. try:
  1445. mysql_conn = self.get_mysql_connection()
  1446. if not mysql_conn:
  1447. logger.error("MySQL连接不可用,无法获取货物列表")
  1448. return []
  1449. # 确保事务已提交,并设置隔离级别为 READ COMMITTED
  1450. mysql_conn.commit()
  1451. with mysql_conn.cursor() as cursor:
  1452. cursor.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED")
  1453. with mysql_conn.cursor() as mysql_cursor:
  1454. mysql_cursor.execute("""
  1455. SELECT * FROM cargos
  1456. WHERE is_deleted = 0
  1457. ORDER BY name
  1458. """)
  1459. rows = mysql_cursor.fetchall()
  1460. result = [dict(row) for row in rows]
  1461. logger.info(f"✅ 从MySQL获取货物列表,共{len(result)}条记录")
  1462. if result:
  1463. logger.info(f"示例:id={result[0].get('id')}, name={result[0].get('name')}")
  1464. return result
  1465. except Exception as query_error:
  1466. logger.error(f"MySQL查询货物执行失败: {str(query_error)}", exc_info=True)
  1467. if not CONTINUE_ON_MYSQL_ERROR:
  1468. raise
  1469. return []
  1470. def update_cargo(self, cargo_id: int, name: str) -> bool:
  1471. """
  1472. 更新货物名称
  1473. :param cargo_id: 货物ID
  1474. :param name: 新名称
  1475. :return: 是否成功
  1476. """
  1477. success = False
  1478. # 先操作MySQL
  1479. if self.mysql_enabled:
  1480. try:
  1481. mysql_conn = self.get_mysql_connection()
  1482. if mysql_conn:
  1483. with mysql_conn.cursor() as mysql_cursor:
  1484. mysql_cursor.execute("""
  1485. UPDATE cargos
  1486. SET name = %s
  1487. WHERE id = %s
  1488. """, (name, cargo_id))
  1489. affected_rows = mysql_cursor.rowcount
  1490. mysql_conn.commit()
  1491. if affected_rows > 0:
  1492. success = True
  1493. logger.info(f"MySQL更新货物成功: ID {cargo_id}, 新名称: {name}")
  1494. else:
  1495. logger.warning(f"MySQL更新货物: ID {cargo_id} 未找到记录")
  1496. else:
  1497. logger.warning(f"MySQL连接失败,无法更新货物 ID {cargo_id}")
  1498. except Exception as e:
  1499. logger.error(f"MySQL更新货物失败: ID {cargo_id}, 错误: {str(e)}", exc_info=True)
  1500. if not CONTINUE_ON_MYSQL_ERROR:
  1501. raise
  1502. return success
  1503. def delete_cargo(self, cargo_id: int) -> bool:
  1504. """
  1505. 删除货物名称
  1506. :param cargo_id: 货物ID
  1507. :return: 是否成功
  1508. """
  1509. success = False
  1510. # 先操作MySQL
  1511. if self.mysql_enabled:
  1512. try:
  1513. mysql_conn = self.get_mysql_connection()
  1514. if mysql_conn:
  1515. with mysql_conn.cursor() as mysql_cursor:
  1516. mysql_cursor.execute("""
  1517. UPDATE cargos
  1518. SET is_deleted = 1
  1519. WHERE id = %s
  1520. """, (cargo_id,))
  1521. affected_rows = mysql_cursor.rowcount
  1522. mysql_conn.commit()
  1523. if affected_rows > 0:
  1524. success = True
  1525. logger.info(f"MySQL删除货物成功: ID {cargo_id}")
  1526. else:
  1527. logger.warning(f"MySQL删除货物: ID {cargo_id} 未找到记录")
  1528. else:
  1529. logger.warning(f"MySQL连接失败,无法删除货物 ID {cargo_id}")
  1530. except Exception as e:
  1531. logger.error(f"MySQL删除货物失败: ID {cargo_id}, 错误: {str(e)}", exc_info=True)
  1532. if not CONTINUE_ON_MYSQL_ERROR:
  1533. raise
  1534. return success
  1535. def is_cargo_used(self, cargo_id: int) -> bool:
  1536. """
  1537. 检查货物是否被地磅单引用
  1538. :param cargo_id: 货物ID
  1539. :return: 是否被引用
  1540. """
  1541. # 先尝试从MySQL查询
  1542. if self.mysql_enabled:
  1543. try:
  1544. mysql_conn = self.get_mysql_connection()
  1545. if mysql_conn:
  1546. with mysql_conn.cursor() as mysql_cursor:
  1547. # 获取货物名称
  1548. mysql_cursor.execute("SELECT name FROM cargos WHERE id = %s", (cargo_id,))
  1549. row = mysql_cursor.fetchone()
  1550. if not row:
  1551. return False
  1552. cargo_name = row['name']
  1553. # 检查是否在地磅单中被使用
  1554. mysql_cursor.execute("""
  1555. SELECT COUNT(*) as count FROM weighing_slips
  1556. WHERE cargo_name = %s
  1557. """, (cargo_name,))
  1558. result = mysql_cursor.fetchone()
  1559. return result['count'] > 0 if result else False
  1560. except Exception as e:
  1561. logger.warning(f"MySQL检查货物使用情况失败: {str(e)}")
  1562. if not CONTINUE_ON_MYSQL_ERROR:
  1563. raise
  1564. return False
  1565. def cargo_exists(self, name: str, exclude_id: Optional[int] = None, include_deleted: bool = False) -> bool:
  1566. """
  1567. 检查货物名称是否存在
  1568. :param name: 货物名称
  1569. :param exclude_id: 排除的ID(用于修改时检查)
  1570. :param include_deleted: 是否包含已删除记录
  1571. :return: 是否存在
  1572. """
  1573. # 先尝试从MySQL查询
  1574. if self.mysql_enabled:
  1575. try:
  1576. mysql_conn = self.get_mysql_connection()
  1577. if mysql_conn:
  1578. with mysql_conn.cursor() as mysql_cursor:
  1579. base_query = "SELECT COUNT(*) as count FROM cargos WHERE name = %s"
  1580. params = [name]
  1581. if not include_deleted:
  1582. base_query += " AND is_deleted = 0"
  1583. if exclude_id:
  1584. base_query += " AND id != %s"
  1585. params.append(exclude_id)
  1586. mysql_cursor.execute(base_query, tuple(params))
  1587. result = mysql_cursor.fetchone()
  1588. return result['count'] > 0 if result else False
  1589. except Exception as e:
  1590. logger.warning(f"MySQL检查货物是否存在失败: {str(e)}")
  1591. if not CONTINUE_ON_MYSQL_ERROR:
  1592. raise
  1593. return False
  1594. def reactivate_cargo(self, name: str) -> bool:
  1595. """将已删除的货物名称恢复为可用"""
  1596. if not name:
  1597. return False
  1598. restored = False
  1599. if self.mysql_enabled:
  1600. try:
  1601. mysql_conn = self.get_mysql_connection()
  1602. if mysql_conn:
  1603. with mysql_conn.cursor() as mysql_cursor:
  1604. mysql_cursor.execute("""
  1605. UPDATE cargos SET is_deleted = 0 WHERE name = %s
  1606. """, (name,))
  1607. if mysql_cursor.rowcount > 0:
  1608. restored = True
  1609. mysql_conn.commit()
  1610. except Exception as e:
  1611. logger.warning(f"MySQL恢复货物失败: {str(e)}")
  1612. if not CONTINUE_ON_MYSQL_ERROR:
  1613. raise
  1614. return restored
  1615. def ensure_cargo_active(self, name: str) -> str:
  1616. """
  1617. 确保货物名称处于可用状态
  1618. :return: 'created' | 'restored' | 'exists' | 'empty'
  1619. """
  1620. if not name:
  1621. return "empty"
  1622. if self.cargo_exists(name):
  1623. return "exists"
  1624. if self.reactivate_cargo(name):
  1625. return "restored"
  1626. self.insert_cargo(name)
  1627. return "created"
  1628. # ========== 采购计划相关操作 ==========
  1629. def generate_plan_no(self) -> str:
  1630. """
  1631. 自动生成计划号
  1632. 格式:SX-YYYYMMDDMMHHSS001
  1633. """
  1634. from datetime import datetime
  1635. now = datetime.now()
  1636. # 格式:YYYYMMDDMMHHSS (年月日分钟小时秒)
  1637. timestamp = now.strftime('%Y%m%d%M%H%S')
  1638. # 查询当天该时间戳下已存在的最大序号
  1639. prefix = f"SX-{timestamp}"
  1640. # 查询当天所有以该前缀开头的计划号
  1641. today_prefix = f"SX-{now.strftime('%Y%m%d')}"
  1642. # 先尝试从MySQL查询
  1643. if self.mysql_enabled:
  1644. try:
  1645. mysql_conn = self.get_mysql_connection()
  1646. if mysql_conn:
  1647. with mysql_conn.cursor() as mysql_cursor:
  1648. mysql_cursor.execute("""
  1649. SELECT plan_no FROM purchase_plans
  1650. WHERE plan_no LIKE %s AND is_deleted = 0
  1651. ORDER BY plan_no DESC
  1652. LIMIT 1
  1653. """, (f"{today_prefix}%",))
  1654. row = mysql_cursor.fetchone()
  1655. if row:
  1656. last_plan_no = row['plan_no']
  1657. # 提取序号部分(最后3位)
  1658. try:
  1659. last_seq = int(last_plan_no[-3:])
  1660. new_seq = last_seq + 1
  1661. except:
  1662. new_seq = 1
  1663. else:
  1664. new_seq = 1
  1665. # 确保序号是3位数字
  1666. seq_str = f"{new_seq:03d}"
  1667. return f"{prefix}{seq_str}"
  1668. except Exception as e:
  1669. logger.warning(f"MySQL查询计划号失败: {str(e)}")
  1670. if not CONTINUE_ON_MYSQL_ERROR:
  1671. raise
  1672. # MySQL失败或未启用,返回默认序号
  1673. new_seq = 1
  1674. seq_str = f"{new_seq:03d}"
  1675. return f"{prefix}{seq_str}"
  1676. def insert_purchase_plan(self, data: Dict) -> int:
  1677. """
  1678. 插入采购计划记录
  1679. :param data: 采购计划数据字典
  1680. :return: 插入记录的ID
  1681. """
  1682. created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  1683. execution_status = self._get_waiting_status(data['business_type'])
  1684. # 自动生成计划号(如果没有提供)
  1685. plan_no = data.get('plan_no')
  1686. if not plan_no:
  1687. plan_no = self.generate_plan_no()
  1688. # 使用start_date和end_date,如果没有则使用plan_date
  1689. start_date = data.get('start_date') or data.get('plan_date', '')
  1690. end_date = data.get('end_date') or data.get('plan_date', '')
  1691. plan_date = data.get('plan_date') or start_date # 保留plan_date用于兼容
  1692. record_id = None
  1693. # 先操作MySQL,获取MySQL生成的ID
  1694. if self.mysql_enabled:
  1695. try:
  1696. mysql_conn = self.get_mysql_connection()
  1697. if mysql_conn:
  1698. with mysql_conn.cursor() as mysql_cursor:
  1699. mysql_cursor.execute("""
  1700. INSERT INTO purchase_plans (
  1701. plan_no, plan_date, start_date, end_date, business_type, product, specification,
  1702. planned_quantity, vehicle_no, customer_name, remarks,
  1703. is_deleted, execution_status, executed_at, last_weighing_slip_id,
  1704. executed_quantity, created_at
  1705. ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
  1706. """, (
  1707. plan_no,
  1708. plan_date,
  1709. start_date,
  1710. end_date,
  1711. data['business_type'],
  1712. data['product'],
  1713. data.get('specification', ''),
  1714. data['planned_quantity'],
  1715. data.get('vehicle_no', ''), # 提供默认值
  1716. data.get('customer_name', ''),
  1717. data.get('remarks', ''),
  1718. 0,
  1719. execution_status,
  1720. None,
  1721. None,
  1722. 0,
  1723. created_at
  1724. ))
  1725. record_id = mysql_cursor.lastrowid
  1726. mysql_conn.commit()
  1727. except Exception as e:
  1728. logger.warning(f"MySQL插入采购计划失败: {str(e)}")
  1729. if not CONTINUE_ON_MYSQL_ERROR:
  1730. raise
  1731. if record_id is None:
  1732. raise RuntimeError("无法插入采购计划:MySQL未启用或插入失败")
  1733. return record_id
  1734. def get_all_purchase_plans(self) -> List[Dict]:
  1735. """
  1736. 获取所有采购计划记录
  1737. :return: 采购计划记录列表
  1738. """
  1739. # 仅使用MySQL查询
  1740. if self.mysql_enabled:
  1741. try:
  1742. # 复用已有 MySQL 连接,必要时由 get_mysql_connection 内部自动重连
  1743. mysql_conn = self.get_mysql_connection()
  1744. if mysql_conn:
  1745. try:
  1746. # 确保事务已提交
  1747. mysql_conn.commit()
  1748. # 设置隔离级别为READ COMMITTED
  1749. with mysql_conn.cursor() as cursor:
  1750. cursor.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED")
  1751. with mysql_conn.cursor() as mysql_cursor:
  1752. mysql_cursor.execute("""
  1753. SELECT * FROM purchase_plans
  1754. WHERE is_deleted = 0
  1755. ORDER BY plan_date DESC, created_at DESC
  1756. """)
  1757. rows = mysql_cursor.fetchall()
  1758. result = [dict(row) for row in rows]
  1759. logger.info(f"✅ 从MySQL获取采购计划列表,共{len(result)}条记录")
  1760. return result
  1761. except Exception as query_error:
  1762. # 如果是超时错误,只记录警告,不打印完整堆栈
  1763. if "timed out" in str(query_error) or "Lost connection" in str(query_error):
  1764. logger.warning(f"MySQL查询采购计划超时: {str(query_error)}")
  1765. else:
  1766. logger.error(f"MySQL查询采购计划执行失败: {str(query_error)}", exc_info=True)
  1767. raise
  1768. else:
  1769. logger.warning("⚠️ MySQL连接不可用")
  1770. except Exception as e:
  1771. # 如果是超时错误,只记录简要警告
  1772. if "timed out" in str(e) or "Lost connection" in str(e):
  1773. logger.warning(f"⚠️ MySQL查询采购计划超时,返回空列表")
  1774. else:
  1775. logger.warning(f"⚠️ MySQL查询采购计划失败,返回空列表: {str(e)}")
  1776. # MySQL失败或未启用,返回空列表(已移除SQLite支持)
  1777. logger.warning("⚠️ MySQL查询失败且已移除SQLite支持,返回空列表")
  1778. return []
  1779. def get_purchase_plan_by_id(self, plan_id: int) -> Optional[Dict]:
  1780. """
  1781. 根据ID获取采购计划记录
  1782. :param plan_id: 采购计划ID
  1783. :return: 采购计划记录字典,如果不存在返回None
  1784. """
  1785. # 先尝试从MySQL查询
  1786. if self.mysql_enabled:
  1787. try:
  1788. mysql_conn = self.get_mysql_connection()
  1789. if mysql_conn:
  1790. with mysql_conn.cursor() as mysql_cursor:
  1791. mysql_cursor.execute("SELECT * FROM purchase_plans WHERE id = %s", (plan_id,))
  1792. row = mysql_cursor.fetchone()
  1793. if row:
  1794. return dict(row)
  1795. except Exception as e:
  1796. logger.warning(f"MySQL查询采购计划失败: {str(e)}")
  1797. if not CONTINUE_ON_MYSQL_ERROR:
  1798. raise
  1799. return None
  1800. def get_purchase_plan_by_plan_no(self, plan_no: str) -> Optional[Dict]:
  1801. """
  1802. 根据计划号获取采购计划记录
  1803. :param plan_no: 计划号
  1804. :return: 采购计划记录字典,如果不存在返回None
  1805. """
  1806. if not plan_no or not plan_no.strip():
  1807. return None
  1808. plan_no = plan_no.strip()
  1809. # 先尝试从MySQL查询
  1810. if self.mysql_enabled:
  1811. try:
  1812. mysql_conn = self.get_mysql_connection()
  1813. if mysql_conn:
  1814. with mysql_conn.cursor() as mysql_cursor:
  1815. mysql_cursor.execute("""
  1816. SELECT * FROM purchase_plans
  1817. WHERE plan_no = %s AND is_deleted = 0
  1818. LIMIT 1
  1819. """, (plan_no,))
  1820. row = mysql_cursor.fetchone()
  1821. if row:
  1822. return dict(row)
  1823. except Exception as e:
  1824. logger.warning(f"MySQL根据计划号查询采购计划失败: {str(e)}")
  1825. if not CONTINUE_ON_MYSQL_ERROR:
  1826. raise
  1827. return None
  1828. def update_purchase_plan(self, plan_id: int, data: Dict) -> bool:
  1829. """
  1830. 更新采购计划记录
  1831. :param plan_id: 采购计划ID
  1832. :param data: 采购计划数据字典
  1833. :return: 是否成功
  1834. """
  1835. success = False
  1836. # 先操作MySQL
  1837. if self.mysql_enabled:
  1838. try:
  1839. mysql_conn = self.get_mysql_connection()
  1840. if mysql_conn:
  1841. with mysql_conn.cursor() as mysql_cursor:
  1842. # 使用start_date和end_date,如果没有则使用plan_date
  1843. start_date = data.get('start_date') or data.get('plan_date', '')
  1844. end_date = data.get('end_date') or data.get('plan_date', '')
  1845. plan_date = data.get('plan_date') or start_date
  1846. plan_no = data.get('plan_no', '')
  1847. mysql_cursor.execute("""
  1848. UPDATE purchase_plans
  1849. SET plan_no = %s, plan_date = %s, start_date = %s, end_date = %s,
  1850. business_type = %s, product = %s,
  1851. specification = %s, planned_quantity = %s,
  1852. customer_name = %s, remarks = %s
  1853. WHERE id = %s
  1854. """, (
  1855. plan_no if plan_no else None,
  1856. plan_date,
  1857. start_date,
  1858. end_date,
  1859. data['business_type'],
  1860. data['product'],
  1861. data.get('specification', ''),
  1862. data['planned_quantity'],
  1863. data.get('customer_name', ''),
  1864. data.get('remarks', ''),
  1865. plan_id
  1866. ))
  1867. affected_rows = mysql_cursor.rowcount
  1868. mysql_conn.commit()
  1869. if affected_rows > 0:
  1870. success = True
  1871. logger.info(f"MySQL更新采购计划成功: ID {plan_id}")
  1872. else:
  1873. logger.warning(f"MySQL更新采购计划: ID {plan_id} 未找到记录")
  1874. else:
  1875. logger.warning(f"MySQL连接失败,无法更新采购计划 ID {plan_id}")
  1876. except Exception as e:
  1877. logger.error(f"MySQL更新采购计划失败: ID {plan_id}, 错误: {str(e)}", exc_info=True)
  1878. if not CONTINUE_ON_MYSQL_ERROR:
  1879. raise
  1880. try:
  1881. self.refresh_plan_execution_status(plan_id)
  1882. except Exception as e:
  1883. logger.warning(f"刷新采购计划状态失败: {str(e)}")
  1884. if not CONTINUE_ON_MYSQL_ERROR:
  1885. raise
  1886. return success
  1887. def delete_purchase_plan(self, plan_id: int) -> bool:
  1888. """
  1889. 虚拟删除采购计划(标记为已删除)
  1890. :param plan_id: 采购计划ID
  1891. :return: 是否成功
  1892. """
  1893. success = False
  1894. # 先操作MySQL
  1895. if self.mysql_enabled:
  1896. try:
  1897. mysql_conn = self.get_mysql_connection()
  1898. if mysql_conn:
  1899. with mysql_conn.cursor() as mysql_cursor:
  1900. mysql_cursor.execute("""
  1901. UPDATE purchase_plans
  1902. SET is_deleted = 1
  1903. WHERE id = %s
  1904. """, (plan_id,))
  1905. affected_rows = mysql_cursor.rowcount
  1906. mysql_conn.commit()
  1907. if affected_rows > 0:
  1908. success = True
  1909. logger.info(f"MySQL虚拟删除采购计划成功: ID {plan_id}")
  1910. else:
  1911. logger.warning(f"MySQL虚拟删除采购计划: ID {plan_id} 未找到记录")
  1912. else:
  1913. logger.warning(f"MySQL连接失败,无法虚拟删除采购计划 ID {plan_id}")
  1914. except Exception as e:
  1915. logger.error(f"MySQL虚拟删除采购计划失败: ID {plan_id}, 错误: {str(e)}", exc_info=True)
  1916. if not CONTINUE_ON_MYSQL_ERROR:
  1917. raise
  1918. return success
  1919. # ========== 用户管理相关操作 ==========
  1920. def ensure_default_admin(self):
  1921. """确保默认管理员账号存在"""
  1922. created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  1923. # 仅在 MySQL 中确保管理员存在
  1924. try:
  1925. mysql_conn = self.get_mysql_connection()
  1926. if mysql_conn:
  1927. with mysql_conn.cursor() as cursor:
  1928. cursor.execute("SELECT id FROM users WHERE username = %s", ('admin',))
  1929. if cursor.fetchone() is None:
  1930. cursor.execute("""
  1931. INSERT INTO users (username, password, role, created_at)
  1932. VALUES (%s, %s, %s, %s)
  1933. """, ('admin', 'admin', 'admin', created_at))
  1934. mysql_conn.commit()
  1935. logger.info("已创建默认MySQL管理员账号 admin/admin")
  1936. except Exception as e:
  1937. logger.warning(f"初始化MySQL管理员账号失败: {str(e)}")
  1938. if not CONTINUE_ON_MYSQL_ERROR:
  1939. raise
  1940. def get_all_users(self) -> List[Dict]:
  1941. """获取全部用户"""
  1942. if self.mysql_enabled:
  1943. try:
  1944. mysql_conn = self.get_mysql_connection()
  1945. if mysql_conn:
  1946. with mysql_conn.cursor() as mysql_cursor:
  1947. mysql_cursor.execute("""
  1948. SELECT id, username, role, created_at
  1949. FROM users
  1950. ORDER BY created_at DESC, id DESC
  1951. """)
  1952. rows = mysql_cursor.fetchall()
  1953. return [dict(row) for row in rows]
  1954. except Exception as e:
  1955. logger.warning(f"MySQL获取用户列表失败: {str(e)}")
  1956. if not CONTINUE_ON_MYSQL_ERROR:
  1957. raise
  1958. return []
  1959. def user_exists(self, username: str, exclude_id: Optional[int] = None) -> bool:
  1960. """判断用户名是否存在"""
  1961. if not self.mysql_enabled:
  1962. logger.warning("MySQL未启用,无法检查用户名")
  1963. return False
  1964. try:
  1965. mysql_conn = self.get_mysql_connection()
  1966. if mysql_conn:
  1967. with mysql_conn.cursor() as cursor:
  1968. if exclude_id is not None:
  1969. cursor.execute("""
  1970. SELECT COUNT(*) as count FROM users
  1971. WHERE username = %s AND id != %s
  1972. """, (username, exclude_id))
  1973. else:
  1974. cursor.execute("""
  1975. SELECT COUNT(*) as count FROM users
  1976. WHERE username = %s
  1977. """, (username,))
  1978. result = cursor.fetchone()
  1979. return result['count'] > 0 if result else False
  1980. except Exception as e:
  1981. logger.warning(f"MySQL检查用户名失败: {str(e)}")
  1982. if not CONTINUE_ON_MYSQL_ERROR:
  1983. raise
  1984. return False
  1985. def insert_user(self, username: str, password: str, role: str = 'user') -> int:
  1986. """新增用户"""
  1987. created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  1988. record_id = None
  1989. if self.mysql_enabled:
  1990. try:
  1991. mysql_conn = self.get_mysql_connection()
  1992. if mysql_conn:
  1993. with mysql_conn.cursor() as cursor:
  1994. cursor.execute("""
  1995. INSERT INTO users (username, password, role, created_at)
  1996. VALUES (%s, %s, %s, %s)
  1997. """, (username, password, role, created_at))
  1998. record_id = cursor.lastrowid
  1999. mysql_conn.commit()
  2000. except Exception as e:
  2001. logger.warning(f"MySQL新增用户失败: {str(e)}")
  2002. if not CONTINUE_ON_MYSQL_ERROR:
  2003. raise
  2004. if record_id is None:
  2005. raise RuntimeError("无法插入用户:MySQL未启用或插入失败")
  2006. return record_id
  2007. def update_user(self, user_id: int, username: str, role: str, password: Optional[str] = None) -> bool:
  2008. """更新用户信息"""
  2009. success = False
  2010. if self.mysql_enabled:
  2011. try:
  2012. mysql_conn = self.get_mysql_connection()
  2013. if mysql_conn:
  2014. with mysql_conn.cursor() as cursor:
  2015. if password is not None:
  2016. cursor.execute("""
  2017. UPDATE users
  2018. SET username = %s, role = %s, password = %s
  2019. WHERE id = %s
  2020. """, (username, role, password, user_id))
  2021. else:
  2022. cursor.execute("""
  2023. UPDATE users
  2024. SET username = %s, role = %s
  2025. WHERE id = %s
  2026. """, (username, role, user_id))
  2027. mysql_conn.commit()
  2028. success = True
  2029. except Exception as e:
  2030. logger.warning(f"MySQL更新用户失败: {str(e)}")
  2031. if not CONTINUE_ON_MYSQL_ERROR:
  2032. raise
  2033. return success
  2034. def delete_user(self, user_id: int) -> bool:
  2035. """删除用户,禁止删除默认管理员"""
  2036. user = self.get_user_by_id(user_id)
  2037. if not user:
  2038. return False
  2039. if user['username'] == 'admin':
  2040. logger.warning("尝试删除默认管理员被阻止")
  2041. return False
  2042. success = False
  2043. if self.mysql_enabled:
  2044. try:
  2045. mysql_conn = self.get_mysql_connection()
  2046. if mysql_conn:
  2047. with mysql_conn.cursor() as cursor:
  2048. cursor.execute("DELETE FROM users WHERE id = %s", (user_id,))
  2049. mysql_conn.commit()
  2050. success = cursor.rowcount > 0
  2051. except Exception as e:
  2052. logger.warning(f"MySQL删除用户失败: {str(e)}")
  2053. if not CONTINUE_ON_MYSQL_ERROR:
  2054. raise
  2055. return success
  2056. def get_user_by_id(self, user_id: int) -> Optional[Dict]:
  2057. """根据ID获取用户"""
  2058. if not self.mysql_enabled:
  2059. logger.warning("MySQL未启用,无法获取用户")
  2060. return None
  2061. user = None
  2062. try:
  2063. mysql_conn = self.get_mysql_connection()
  2064. if mysql_conn:
  2065. with mysql_conn.cursor() as cursor:
  2066. cursor.execute("""
  2067. SELECT id, username, role, created_at
  2068. FROM users
  2069. WHERE id = %s
  2070. """, (user_id,))
  2071. row = cursor.fetchone()
  2072. if row:
  2073. user = dict(row)
  2074. except Exception as e:
  2075. logger.warning(f"MySQL获取用户失败: {str(e)}")
  2076. if not CONTINUE_ON_MYSQL_ERROR:
  2077. raise
  2078. return user
  2079. def authenticate_user(self, username: str, password: str) -> Optional[Dict]:
  2080. """根据账号密码验证用户"""
  2081. if self.mysql_enabled:
  2082. try:
  2083. mysql_conn = self.get_mysql_connection()
  2084. if mysql_conn:
  2085. with mysql_conn.cursor() as cursor:
  2086. cursor.execute("""
  2087. SELECT id, username, role
  2088. FROM users
  2089. WHERE username = %s AND password = %s
  2090. """, (username, password))
  2091. row = cursor.fetchone()
  2092. if row:
  2093. return dict(row)
  2094. except Exception as e:
  2095. logger.warning(f"MySQL用户登录校验失败: {str(e)}")
  2096. if not CONTINUE_ON_MYSQL_ERROR:
  2097. raise
  2098. return None
  2099. # ========== 出入库相关操作 ==========
  2100. def insert_inbound_outbound(self, data: Dict) -> int:
  2101. """
  2102. 插入出入库单记录
  2103. :param data: 出入库单数据字典
  2104. :return: 插入记录的ID
  2105. """
  2106. created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  2107. status = self._get_waiting_status(data['business_type'])
  2108. record_id = None
  2109. # 只使用 MySQL,获取 MySQL 生成的自增 ID
  2110. try:
  2111. mysql_conn = self.get_mysql_connection()
  2112. if mysql_conn:
  2113. with mysql_conn.cursor() as mysql_cursor:
  2114. mysql_cursor.execute("""
  2115. INSERT INTO inbound_outbound (
  2116. date, partner_company, business_type, product, quantity,
  2117. plan_no, batch_no, vehicle_no, status, remarks,
  2118. purchase_plan_id, is_deleted, created_at
  2119. ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
  2120. """, (
  2121. data['date'],
  2122. data['partner_company'],
  2123. data['business_type'],
  2124. data['product'],
  2125. data['quantity'],
  2126. data.get('plan_no', ''),
  2127. data.get('batch_no', ''),
  2128. data['vehicle_no'],
  2129. status,
  2130. data.get('remarks', ''),
  2131. data.get('purchase_plan_id'),
  2132. 0,
  2133. created_at
  2134. ))
  2135. record_id = mysql_cursor.lastrowid
  2136. mysql_conn.commit()
  2137. except Exception as e:
  2138. logger.error(f"MySQL插入出入库单失败: {str(e)}", exc_info=True)
  2139. if not CONTINUE_ON_MYSQL_ERROR:
  2140. raise
  2141. # 如果关联了计划,刷新计划状态
  2142. if data.get('purchase_plan_id'):
  2143. try:
  2144. self.refresh_plan_execution_status(data['purchase_plan_id'])
  2145. except Exception as e:
  2146. logger.warning(f"刷新计划状态失败: {str(e)}")
  2147. return record_id
  2148. def get_all_inbound_outbound(self, keyword: Optional[str] = None) -> List[Dict]:
  2149. """
  2150. 获取所有出入库单记录
  2151. :param keyword: 模糊检索往来单位/车牌号/产品
  2152. :return: 出入库单记录列表
  2153. """
  2154. keyword = (keyword or "").strip()
  2155. # 仅使用MySQL查询
  2156. if not self.mysql_enabled:
  2157. logger.warning("MySQL未启用,无法查询出入库单列表")
  2158. return []
  2159. if self.mysql_enabled:
  2160. try:
  2161. # 复用已有 MySQL 连接,必要时由 get_mysql_connection 内部自动重连
  2162. mysql_conn = self.get_mysql_connection()
  2163. if mysql_conn:
  2164. try:
  2165. mysql_conn.commit()
  2166. with mysql_conn.cursor() as cursor:
  2167. cursor.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED")
  2168. with mysql_conn.cursor() as mysql_cursor:
  2169. where_clause = "WHERE is_deleted = 0"
  2170. params = []
  2171. if keyword:
  2172. like_pattern = f"%{keyword}%"
  2173. where_clause += " AND (partner_company LIKE %s OR vehicle_no LIKE %s OR product LIKE %s)"
  2174. params = [like_pattern, like_pattern, like_pattern]
  2175. query = f"""
  2176. SELECT * FROM inbound_outbound
  2177. {where_clause}
  2178. ORDER BY date DESC, created_at DESC
  2179. """
  2180. mysql_cursor.execute(query, params)
  2181. rows = mysql_cursor.fetchall()
  2182. result = [dict(row) for row in rows]
  2183. logger.info(f"✅ 从MySQL获取出入库单列表,共{len(result)}条记录")
  2184. return result
  2185. except Exception as query_error:
  2186. logger.error(f"MySQL查询出入库单执行失败: {str(query_error)}", exc_info=True)
  2187. raise
  2188. else:
  2189. logger.warning("⚠️ MySQL连接不可用")
  2190. return []
  2191. except Exception as e:
  2192. logger.warning(f"⚠️ MySQL查询出入库单失败: {str(e)}", exc_info=True)
  2193. return []
  2194. return []
  2195. def get_inbound_outbound_by_date(self, date_str: str) -> List[Dict]:
  2196. """
  2197. 根据日期获取出入库单记录(用于当天出入库单卡片)
  2198. :param date_str: 日期字符串,格式 YYYY-MM-DD
  2199. :return: 出入库单记录列表
  2200. """
  2201. if not date_str or not self.mysql_enabled:
  2202. return []
  2203. date_str = str(date_str).strip()[:10]
  2204. if len(date_str) < 10:
  2205. return []
  2206. try:
  2207. mysql_conn = self.get_mysql_connection()
  2208. if not mysql_conn:
  2209. return []
  2210. mysql_conn.commit()
  2211. with mysql_conn.cursor() as cursor:
  2212. cursor.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED")
  2213. with mysql_conn.cursor() as mysql_cursor:
  2214. # 兼容 date 存为 'YYYY-MM-DD' 或 'YYYY-MM-DD HH:MM:SS'
  2215. mysql_cursor.execute("""
  2216. SELECT * FROM inbound_outbound
  2217. WHERE is_deleted = 0
  2218. AND (date = %s OR date LIKE %s)
  2219. ORDER BY date DESC, created_at DESC
  2220. """, (date_str, date_str + " %"))
  2221. rows = mysql_cursor.fetchall()
  2222. result = [dict(row) for row in rows]
  2223. logger.info(f"✅ 从MySQL按日期获取出入库单,日期={date_str},共{len(result)}条")
  2224. return result
  2225. except Exception as e:
  2226. logger.warning(f"MySQL按日期查询出入库单失败: {str(e)}", exc_info=True)
  2227. return []
  2228. def get_inbound_outbound_by_id(self, inbound_id: int) -> Optional[Dict]:
  2229. """
  2230. 根据ID获取出入库单记录
  2231. :param inbound_id: 出入库单ID
  2232. :return: 出入库单记录字典,如果不存在返回None
  2233. """
  2234. # 先尝试从MySQL查询
  2235. if self.mysql_enabled:
  2236. try:
  2237. mysql_conn = self.get_mysql_connection()
  2238. if mysql_conn:
  2239. with mysql_conn.cursor() as mysql_cursor:
  2240. mysql_cursor.execute("SELECT * FROM inbound_outbound WHERE id = %s", (inbound_id,))
  2241. row = mysql_cursor.fetchone()
  2242. if row:
  2243. return dict(row)
  2244. except Exception as e:
  2245. logger.warning(f"MySQL查询出入库单失败: {str(e)}")
  2246. if not CONTINUE_ON_MYSQL_ERROR:
  2247. raise
  2248. return None
  2249. def get_inbound_outbound_by_plan_id(self, plan_id: int) -> List[Dict]:
  2250. """
  2251. 根据计划ID获取所有关联的出入库单
  2252. :param plan_id: 计划ID
  2253. :return: 出入库单记录列表
  2254. """
  2255. # 先尝试从MySQL查询
  2256. if self.mysql_enabled:
  2257. try:
  2258. mysql_conn = self.get_mysql_connection()
  2259. if mysql_conn:
  2260. with mysql_conn.cursor() as mysql_cursor:
  2261. mysql_cursor.execute("""
  2262. SELECT * FROM inbound_outbound
  2263. WHERE purchase_plan_id = %s AND is_deleted = 0
  2264. ORDER BY created_at DESC
  2265. """, (plan_id,))
  2266. rows = mysql_cursor.fetchall()
  2267. return [dict(row) for row in rows]
  2268. except Exception as e:
  2269. logger.warning(f"MySQL查询出入库单失败: {str(e)}")
  2270. if not CONTINUE_ON_MYSQL_ERROR:
  2271. raise
  2272. return []
  2273. def get_weighing_slips_by_plan_id(self, plan_id: int) -> List[Dict]:
  2274. """
  2275. 根据计划ID获取关联的地磅单列表
  2276. :param plan_id: 计划ID
  2277. :return: 地磅单记录列表
  2278. """
  2279. if not plan_id:
  2280. return []
  2281. if self.mysql_enabled:
  2282. try:
  2283. mysql_conn = self.get_mysql_connection()
  2284. if mysql_conn:
  2285. with mysql_conn.cursor() as mysql_cursor:
  2286. mysql_cursor.execute("""
  2287. SELECT * FROM weighing_slips
  2288. WHERE purchase_plan_id = %s AND is_voided = 0
  2289. ORDER BY created_at DESC
  2290. """, (plan_id,))
  2291. rows = mysql_cursor.fetchall()
  2292. return [dict(row) for row in rows]
  2293. except Exception as e:
  2294. logger.warning(f"MySQL查询地磅单失败: {str(e)}")
  2295. if not CONTINUE_ON_MYSQL_ERROR:
  2296. raise
  2297. return []
  2298. def update_inbound_outbound(self, inbound_id: int, data: Dict) -> bool:
  2299. """
  2300. 更新出入库单记录
  2301. :param inbound_id: 出入库单ID
  2302. :param data: 更新后的出入库单数据
  2303. :return: 是否成功
  2304. """
  2305. existing = self.get_inbound_outbound_by_id(inbound_id)
  2306. if not existing:
  2307. return False
  2308. status = data.get('status')
  2309. if not status:
  2310. status = self._get_waiting_status(data['business_type'])
  2311. params = (
  2312. data['date'],
  2313. data['partner_company'],
  2314. data['business_type'],
  2315. data['product'],
  2316. data['quantity'],
  2317. data.get('plan_no', ''),
  2318. data.get('batch_no', ''),
  2319. data['vehicle_no'],
  2320. status,
  2321. data.get('remarks', ''),
  2322. data.get('purchase_plan_id'),
  2323. inbound_id
  2324. )
  2325. success = False
  2326. if not self.mysql_enabled:
  2327. logger.warning("MySQL未启用,无法更新出入库单")
  2328. return False
  2329. try:
  2330. mysql_conn = self.get_mysql_connection()
  2331. if mysql_conn:
  2332. with mysql_conn.cursor() as mysql_cursor:
  2333. mysql_cursor.execute("""
  2334. UPDATE inbound_outbound SET
  2335. date = %s,
  2336. partner_company = %s,
  2337. business_type = %s,
  2338. product = %s,
  2339. quantity = %s,
  2340. plan_no = %s,
  2341. batch_no = %s,
  2342. vehicle_no = %s,
  2343. status = %s,
  2344. remarks = %s,
  2345. purchase_plan_id = %s
  2346. WHERE id = %s
  2347. """, params)
  2348. success = mysql_cursor.rowcount > 0
  2349. mysql_conn.commit()
  2350. except Exception as e:
  2351. logger.warning(f"MySQL更新出入库单失败: {str(e)}")
  2352. if not CONTINUE_ON_MYSQL_ERROR:
  2353. raise
  2354. return False
  2355. # 已移除SQLite支持,仅使用MySQL
  2356. # 如果关联了计划,刷新计划状态
  2357. old_plan_id = existing.get('purchase_plan_id')
  2358. new_plan_id = data.get('purchase_plan_id')
  2359. try:
  2360. if old_plan_id and old_plan_id != new_plan_id:
  2361. self.refresh_plan_execution_status(old_plan_id)
  2362. if new_plan_id:
  2363. self.refresh_plan_execution_status(new_plan_id)
  2364. except Exception as e:
  2365. logger.warning(f"刷新计划状态失败: {str(e)}")
  2366. return success
  2367. def delete_inbound_outbound(self, inbound_id: int) -> bool:
  2368. """
  2369. 虚拟删除出入库单(标记为已删除)
  2370. :param inbound_id: 出入库单ID
  2371. :return: 是否成功
  2372. """
  2373. inbound = self.get_inbound_outbound_by_id(inbound_id)
  2374. plan_id = inbound.get('purchase_plan_id') if inbound else None
  2375. success = False
  2376. # 先操作MySQL
  2377. if self.mysql_enabled:
  2378. try:
  2379. mysql_conn = self.get_mysql_connection()
  2380. if mysql_conn:
  2381. with mysql_conn.cursor() as mysql_cursor:
  2382. mysql_cursor.execute("""
  2383. UPDATE inbound_outbound
  2384. SET is_deleted = 1
  2385. WHERE id = %s
  2386. """, (inbound_id,))
  2387. affected_rows = mysql_cursor.rowcount
  2388. mysql_conn.commit()
  2389. if affected_rows > 0:
  2390. success = True
  2391. except Exception as e:
  2392. logger.warning(f"MySQL删除出入库单失败: {str(e)}")
  2393. if not CONTINUE_ON_MYSQL_ERROR:
  2394. raise
  2395. # 如果关联了计划,刷新计划状态
  2396. if plan_id and success:
  2397. try:
  2398. self.refresh_plan_execution_status(plan_id)
  2399. except Exception as e:
  2400. logger.warning(f"刷新计划状态失败: {str(e)}")
  2401. return success
  2402. def get_max_batch_no_sequence(self, date_str: str) -> int:
  2403. """
  2404. 获取指定日期的最大批次号序号
  2405. :param date_str: 日期字符串,格式:YYYY-MM-DD
  2406. :return: 最大序号,如果没有则返回0
  2407. """
  2408. # 提取日期部分(YYYYMMDD)
  2409. date_part = date_str.replace('-', '')
  2410. prefix = f"PC-{date_part}"
  2411. max_sequence = 0
  2412. # 先尝试从MySQL查询
  2413. if self.mysql_enabled:
  2414. try:
  2415. mysql_conn = self.get_mysql_connection()
  2416. if mysql_conn:
  2417. with mysql_conn.cursor() as mysql_cursor:
  2418. mysql_cursor.execute("""
  2419. SELECT batch_no FROM inbound_outbound
  2420. WHERE batch_no LIKE %s AND is_deleted = 0
  2421. ORDER BY batch_no DESC
  2422. LIMIT 1
  2423. """, (f"{prefix}%",))
  2424. row = mysql_cursor.fetchone()
  2425. if row:
  2426. # MySQL返回的row可能是元组或字典,统一转换为字典处理
  2427. if isinstance(row, dict):
  2428. batch_no = row.get('batch_no')
  2429. else:
  2430. batch_no = row[0] if row else None
  2431. if batch_no:
  2432. # 提取序号部分
  2433. try:
  2434. sequence_str = batch_no.replace(prefix, '')
  2435. sequence = int(sequence_str)
  2436. max_sequence = max(max_sequence, sequence)
  2437. except (ValueError, AttributeError):
  2438. pass
  2439. except Exception as e:
  2440. logger.warning(f"MySQL查询批次号失败: {str(e)}")
  2441. if not CONTINUE_ON_MYSQL_ERROR:
  2442. raise
  2443. return max_sequence
  2444. def refresh_inbound_status(self, inbound_id: int):
  2445. """
  2446. 根据关联的地磅单计算出入库单状态
  2447. :param inbound_id: 出入库单ID
  2448. """
  2449. inbound = self.get_inbound_outbound_by_id(inbound_id)
  2450. if not inbound:
  2451. return
  2452. # 查询该出入库单关联的所有地磅单(仅使用MySQL)
  2453. slips = []
  2454. if not self.mysql_enabled:
  2455. logger.warning("MySQL未启用,无法刷新出入库状态")
  2456. return
  2457. try:
  2458. mysql_conn = self.get_mysql_connection()
  2459. if mysql_conn:
  2460. with mysql_conn.cursor() as mysql_cursor:
  2461. mysql_cursor.execute("""
  2462. SELECT * FROM weighing_slips
  2463. WHERE inbound_outbound_id = %s AND is_voided = 0
  2464. ORDER BY id DESC
  2465. """, (inbound_id,))
  2466. rows = mysql_cursor.fetchall()
  2467. slips = [dict(row) for row in rows]
  2468. except Exception as e:
  2469. logger.warning(f"MySQL查询地磅单失败: {str(e)}")
  2470. if not CONTINUE_ON_MYSQL_ERROR:
  2471. raise
  2472. return
  2473. if not slips:
  2474. # 没有地磅单,状态为待入库/待出库
  2475. status = self._get_waiting_status(inbound['business_type'])
  2476. else:
  2477. # 检查是否所有地磅单都已完成
  2478. # 必须满足:净重>0、毛重>0、皮重>0、毛重时间不为空、皮重时间不为空
  2479. all_done = all(
  2480. slip['net_weight'] > 0 and
  2481. slip.get('gross_weight', 0) > 0 and
  2482. slip.get('tare_weight', 0) > 0 and
  2483. slip.get('gross_weight_time') and
  2484. slip.get('tare_weight_time')
  2485. for slip in slips
  2486. )
  2487. if all_done:
  2488. status = self._get_done_status(inbound['business_type'])
  2489. else:
  2490. status = self._get_waiting_status(inbound['business_type'])
  2491. # 更新状态
  2492. data = {
  2493. 'date': inbound['date'],
  2494. 'partner_company': inbound['partner_company'],
  2495. 'business_type': inbound['business_type'],
  2496. 'product': inbound['product'],
  2497. 'quantity': inbound['quantity'],
  2498. 'plan_no': inbound.get('plan_no', ''),
  2499. 'batch_no': inbound.get('batch_no', ''),
  2500. 'vehicle_no': inbound['vehicle_no'],
  2501. 'status': status,
  2502. 'remarks': inbound.get('remarks', ''),
  2503. 'purchase_plan_id': inbound.get('purchase_plan_id')
  2504. }
  2505. self.update_inbound_outbound(inbound_id, data)