purchase_plan_tab.py 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  1. """
  2. 采购计划Tab页面
  3. """
  4. from PyQt5.QtWidgets import (
  5. QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton,
  6. QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox, QDialog,
  7. QFormLayout, QComboBox, QDateEdit, QRadioButton, QButtonGroup,
  8. QDoubleSpinBox, QFileDialog, QTextEdit, QCompleter, QScrollArea,
  9. QGroupBox, QFrame
  10. )
  11. from PyQt5.QtCore import Qt, QDate, QDateTime, QTimer, pyqtSignal
  12. from PyQt5.QtGui import QFont, QKeySequence, QBrush, QColor
  13. from database import Database
  14. from .button_styles import apply_button_style, get_button_color_type
  15. import pandas as pd
  16. import time
  17. import logging
  18. from datetime import datetime
  19. from typing import Optional, Dict
  20. startup_logger = logging.getLogger('startup')
  21. class PurchasePlanTab(QWidget):
  22. """采购计划Tab"""
  23. def __init__(self, db: Database, main_window=None, current_user: Optional[Dict] = None):
  24. tab_start = time.time()
  25. super().__init__()
  26. self.db = db
  27. self.main_window = main_window # 保存主窗口引用,用于跳转到地磅单
  28. self.current_user = current_user or {}
  29. self._is_admin = self.current_user.get('role') == 'admin'
  30. self._all_plans = []
  31. self._displayed_plans = []
  32. ui_start = time.time()
  33. self.init_ui()
  34. startup_logger.info(f" 界面初始化 (耗时: {time.time() - ui_start:.3f}秒)")
  35. refresh_start = time.time()
  36. self.refresh_list()
  37. startup_logger.info(f" 数据加载 (耗时: {time.time() - refresh_start:.3f}秒)")
  38. def init_ui(self):
  39. """初始化界面"""
  40. layout = QVBoxLayout()
  41. layout.setSpacing(10)
  42. layout.setContentsMargins(15, 15, 15, 15)
  43. # 标题
  44. title = QLabel("计划管理")
  45. title_font = QFont("微软雅黑", 18, QFont.Bold)
  46. title.setFont(title_font)
  47. layout.addWidget(title)
  48. # 按钮区域
  49. button_layout = QHBoxLayout()
  50. button_layout.setSpacing(10)
  51. self.partner_search_input = QLineEdit()
  52. self.partner_search_input.setPlaceholderText("按往来单位模糊检索…")
  53. self.partner_search_input.setClearButtonEnabled(True)
  54. self.partner_search_input.setMinimumHeight(40)
  55. self.partner_search_input.setMinimumWidth(500)
  56. self.partner_search_input.setMaximumWidth(600)
  57. self.partner_search_input.setFont(QFont("微软雅黑", 15))
  58. self.partner_search_input.textChanged.connect(self._on_partner_search_changed)
  59. self.add_btn = QPushButton("新增")
  60. self.add_btn.setMinimumHeight(45)
  61. self.add_btn.setMinimumWidth(120)
  62. self.add_btn.setFont(QFont("微软雅黑", 16))
  63. apply_button_style(self.add_btn, 'green')
  64. self.add_btn.clicked.connect(self.add_plan)
  65. self.add_btn.setShortcut(QKeySequence("Ctrl+N"))
  66. self.edit_btn = QPushButton("修改")
  67. self.edit_btn.setMinimumHeight(45)
  68. self.edit_btn.setMinimumWidth(120)
  69. self.edit_btn.setFont(QFont("微软雅黑", 16))
  70. apply_button_style(self.edit_btn, 'normal')
  71. self.edit_btn.clicked.connect(self.edit_plan)
  72. self.delete_btn = QPushButton("删除")
  73. self.delete_btn.setMinimumHeight(45)
  74. self.delete_btn.setMinimumWidth(120)
  75. self.delete_btn.setFont(QFont("微软雅黑", 16))
  76. apply_button_style(self.delete_btn, 'normal')
  77. self.delete_btn.clicked.connect(self.delete_plan)
  78. if self._is_admin:
  79. self.delete_btn.setShortcut(QKeySequence("Delete"))
  80. else:
  81. self.delete_btn.hide()
  82. self.delete_btn.setEnabled(False)
  83. self.import_btn = QPushButton("Excel导入")
  84. self.import_btn.setMinimumHeight(45)
  85. self.import_btn.setMinimumWidth(120)
  86. self.import_btn.setFont(QFont("微软雅黑", 16))
  87. self.import_btn.setStyleSheet("border-radius: 5px;")
  88. self.import_btn.clicked.connect(self.import_excel)
  89. self.import_btn.setVisible(False) # 隐藏Excel导入按钮
  90. self.export_btn = QPushButton("导出Excel")
  91. self.export_btn.setMinimumHeight(45)
  92. self.export_btn.setMinimumWidth(140)
  93. self.export_btn.setFont(QFont("微软雅黑", 16))
  94. apply_button_style(self.export_btn, 'normal')
  95. self.export_btn.clicked.connect(self.export_to_excel)
  96. self.refresh_btn = QPushButton("刷新")
  97. self.refresh_btn.setMinimumHeight(45)
  98. self.refresh_btn.setMinimumWidth(120)
  99. self.refresh_btn.setFont(QFont("微软雅黑", 16))
  100. apply_button_style(self.refresh_btn, 'normal')
  101. self.refresh_btn.setEnabled(True) # 确保按钮是启用状态
  102. self.refresh_btn.clicked.connect(self.refresh_list)
  103. self.refresh_btn.setShortcut(QKeySequence("F5"))
  104. button_layout.addWidget(self.partner_search_input)
  105. button_layout.addWidget(self.add_btn)
  106. button_layout.addWidget(self.edit_btn)
  107. button_layout.addWidget(self.delete_btn)
  108. button_layout.addWidget(self.import_btn)
  109. button_layout.addWidget(self.export_btn)
  110. button_layout.addWidget(self.refresh_btn)
  111. button_layout.addStretch()
  112. layout.addLayout(button_layout)
  113. # 表格
  114. self.table = QTableWidget()
  115. self.table.setColumnCount(10)
  116. self.table.setHorizontalHeaderLabels([
  117. "计划号", "开始时间", "结束时间", "往来单位", "业务类型", "产品",
  118. "计划量(t)", "已执行量(t)", "状态", "操作"
  119. ])
  120. self.table.horizontalHeader().setFont(QFont("微软雅黑", 15, QFont.Bold))
  121. header = self.table.horizontalHeader()
  122. header.setSectionsMovable(False)
  123. header.setStretchLastSection(False)
  124. header.setSectionsClickable(False)
  125. self.column_width_ratios = [0.11, 0.11, 0.11, 0.16, 0.1, 0.12, 0.08, 0.08, 0.06, 0.17]
  126. self._user_resized_columns = False
  127. self._is_applying_column_widths = False
  128. for i in range(self.table.columnCount()):
  129. header.setSectionResizeMode(i, QHeaderView.Interactive)
  130. header.sectionResized.connect(self._on_section_resized)
  131. self._apply_table_column_widths(force=True)
  132. vertical_header = self.table.verticalHeader()
  133. vertical_header.setDefaultAlignment(Qt.AlignCenter)
  134. vertical_header.setFixedWidth(60)
  135. vertical_header.setSectionResizeMode(QHeaderView.ResizeToContents)
  136. self.table.setFont(QFont("微软雅黑", 15))
  137. self.table.setAlternatingRowColors(True)
  138. self.table.setSelectionBehavior(QTableWidget.SelectRows)
  139. self.table.setSelectionMode(QTableWidget.SingleSelection)
  140. layout.addWidget(self.table)
  141. self.setLayout(layout)
  142. def refresh_list(self):
  143. """刷新列表(批量刷新计划执行状态,避免 N 次数据库往返)"""
  144. plans = self.db.get_all_purchase_plans()
  145. plan_ids = [p.get("id") for p in plans if p.get("id")]
  146. if plan_ids:
  147. try:
  148. updated = self.db.refresh_all_plans_execution_status(plan_ids)
  149. for plan in plans:
  150. plan_id = plan.get("id")
  151. if plan_id and plan_id in updated:
  152. plan.update(updated[plan_id])
  153. except Exception:
  154. pass
  155. self._all_plans = [dict(p) for p in plans]
  156. self._apply_partner_filter()
  157. def _apply_partner_filter(self):
  158. keyword = (self.partner_search_input.text() or "").strip().lower()
  159. if not keyword:
  160. filtered = list(self._all_plans)
  161. else:
  162. filtered = [
  163. plan for plan in self._all_plans
  164. if keyword in (plan.get('customer_name', '') or '').lower()
  165. ]
  166. self._update_table(filtered)
  167. def _update_table(self, plans):
  168. self.table.setRowCount(len(plans))
  169. self._displayed_plans = plans
  170. for i, plan in enumerate(plans):
  171. self.table.setItem(i, 0, QTableWidgetItem(plan.get('plan_no', '')))
  172. start_date = plan.get('start_date') or plan.get('plan_date', '')
  173. self.table.setItem(i, 1, QTableWidgetItem(start_date))
  174. end_date = plan.get('end_date') or plan.get('plan_date', '')
  175. self.table.setItem(i, 2, QTableWidgetItem(end_date))
  176. self.table.setItem(i, 3, QTableWidgetItem(plan.get('customer_name', '')))
  177. self.table.setItem(i, 4, QTableWidgetItem(plan.get('business_type', '')))
  178. self.table.setItem(i, 5, QTableWidgetItem(plan.get('product', '')))
  179. planned_quantity = plan.get('planned_quantity')
  180. try:
  181. planned_quantity = float(planned_quantity)
  182. except (TypeError, ValueError):
  183. planned_quantity = 0.0
  184. self.table.setItem(i, 6, QTableWidgetItem(f"{planned_quantity:.3f}"))
  185. executed_quantity = plan.get('executed_quantity') or 0
  186. executed_tons = executed_quantity / 1000 if executed_quantity else 0
  187. self.table.setItem(i, 7, QTableWidgetItem(f"{executed_tons:.3f}"))
  188. status_text = plan.get('execution_status', '')
  189. status_item = QTableWidgetItem(status_text)
  190. # 移除状态文字颜色
  191. self.table.setItem(i, 8, status_item)
  192. btn_widget = QWidget()
  193. btn_layout = QHBoxLayout()
  194. btn_layout.setContentsMargins(5, 2, 5, 2)
  195. jump_btn = QPushButton("生成出入库单")
  196. jump_btn.setFont(QFont("微软雅黑", 14))
  197. apply_button_style(jump_btn, 'blue')
  198. jump_btn.clicked.connect(lambda checked, pid=plan.get('id'): self.jump_to_inbound_outbound(pid))
  199. view_btn = QPushButton("查看")
  200. view_btn.setFont(QFont("微软雅黑", 16))
  201. apply_button_style(view_btn, 'normal')
  202. view_btn.clicked.connect(lambda checked, pid=plan.get('id'): self.view_plan_details(pid))
  203. btn_layout.addWidget(view_btn)
  204. btn_layout.addWidget(jump_btn)
  205. btn_layout.addStretch()
  206. btn_widget.setLayout(btn_layout)
  207. self.table.setCellWidget(i, 9, btn_widget)
  208. self.table.resizeRowsToContents()
  209. def _on_partner_search_changed(self, _text: str):
  210. self._apply_partner_filter()
  211. def resizeEvent(self, event):
  212. super().resizeEvent(event)
  213. self._apply_table_column_widths()
  214. def showEvent(self, event):
  215. super().showEvent(event)
  216. QTimer.singleShot(0, lambda: self._apply_table_column_widths(force=True))
  217. def export_to_excel(self):
  218. """导出计划信息到Excel"""
  219. plans = self.db.get_all_purchase_plans()
  220. if not plans:
  221. QMessageBox.information(self, "提示", "暂无可导出的计划数据。")
  222. return
  223. default_name = f"计划管理导出_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
  224. file_path, _ = QFileDialog.getSaveFileName(
  225. self,
  226. "导出计划信息",
  227. default_name,
  228. "Excel Files (*.xlsx)"
  229. )
  230. if not file_path:
  231. return
  232. if not file_path.lower().endswith(".xlsx"):
  233. file_path += ".xlsx"
  234. export_rows = []
  235. for plan in plans:
  236. executed_quantity = plan.get('executed_quantity') or 0
  237. executed_tons = executed_quantity / 1000 if executed_quantity else 0
  238. export_rows.append({
  239. "计划号": plan.get('plan_no', ''),
  240. "往来单位": plan.get('customer_name', ''),
  241. "业务类型": plan.get('business_type', ''),
  242. "产品": plan.get('product', ''),
  243. "计划量(t)": round(plan.get('planned_quantity', 0), 3),
  244. "已执行量(t)": round(executed_tons, 3),
  245. "状态": plan.get('execution_status', ''),
  246. "开始时间": plan.get('start_date') or plan.get('plan_date', ''),
  247. "结束时间": plan.get('end_date') or plan.get('plan_date', ''),
  248. "备注": plan.get('remarks', '')
  249. })
  250. try:
  251. df = pd.DataFrame(export_rows)
  252. df.to_excel(file_path, index=False)
  253. QMessageBox.information(self, "导出成功", f"已导出 {len(export_rows)} 条计划记录。")
  254. except Exception as e:
  255. QMessageBox.critical(self, "导出失败", f"导出Excel失败:{str(e)}")
  256. def get_selected_plan_id(self) -> int:
  257. """获取选中的采购计划ID"""
  258. current_row = self.table.currentRow()
  259. if current_row < 0:
  260. return -1
  261. if current_row >= len(self._displayed_plans):
  262. return -1
  263. return self._displayed_plans[current_row].get('id', -1)
  264. def add_plan(self):
  265. """新增采购计划"""
  266. dialog = PurchasePlanDialog(self.db, parent=self)
  267. if dialog.exec_() == QDialog.Accepted:
  268. self.refresh_list()
  269. def edit_plan(self):
  270. """修改采购计划"""
  271. plan_id = self.get_selected_plan_id()
  272. if plan_id < 0:
  273. QMessageBox.warning(self, "提示", "请先选择要修改的采购计划")
  274. return
  275. plan = self.db.get_purchase_plan_by_id(plan_id)
  276. if not plan:
  277. QMessageBox.warning(self, "错误", "未找到该采购计划")
  278. return
  279. dialog = PurchasePlanDialog(self.db, plan=plan, parent=self)
  280. if dialog.exec_() == QDialog.Accepted:
  281. self.refresh_list()
  282. def delete_plan(self):
  283. """删除采购计划"""
  284. if not self._is_admin:
  285. QMessageBox.warning(self, "权限不足", "仅管理员可执行删除。")
  286. return
  287. plan_id = self.get_selected_plan_id()
  288. if plan_id < 0:
  289. QMessageBox.warning(self, "提示", "请先选择要删除的采购计划")
  290. return
  291. # 检查是否已经产生了出入库单
  292. inbound_list = self.db.get_inbound_outbound_by_plan_id(plan_id)
  293. if inbound_list:
  294. QMessageBox.warning(
  295. self, "无法删除",
  296. f"该计划已产生{len(inbound_list)}条出入库单,无法删除!\n请先删除相关的出入库单后再删除计划。"
  297. )
  298. return
  299. # 确认删除
  300. msg = QMessageBox()
  301. msg.setIcon(QMessageBox.Question)
  302. msg.setWindowTitle("确认")
  303. msg.setText("确定要删除该采购计划吗?")
  304. msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
  305. msg.setDefaultButton(QMessageBox.No)
  306. msg.button(QMessageBox.Yes).setText("是")
  307. msg.button(QMessageBox.No).setText("否")
  308. reply = msg.exec_()
  309. if reply == QMessageBox.Yes:
  310. if self.db.delete_purchase_plan(plan_id):
  311. QMessageBox.information(self, "成功", "删除成功!")
  312. self.refresh_list()
  313. else:
  314. QMessageBox.warning(self, "错误", "删除失败")
  315. def _on_section_resized(self, *_):
  316. if self._is_applying_column_widths:
  317. return
  318. self._user_resized_columns = True
  319. def _apply_table_column_widths(self, force: bool = False):
  320. if not hasattr(self, "table") or not hasattr(self, "column_width_ratios"):
  321. return
  322. if self._user_resized_columns and not force:
  323. return
  324. viewport_width = self.table.viewport().width()
  325. if viewport_width <= 0:
  326. return
  327. total_ratio = sum(self.column_width_ratios) or 1
  328. assigned_width = 0
  329. header = self.table.horizontalHeader()
  330. self._is_applying_column_widths = True
  331. header.blockSignals(True)
  332. try:
  333. for index, ratio in enumerate(self.column_width_ratios):
  334. if index == self.table.columnCount() - 1:
  335. width = viewport_width - assigned_width
  336. else:
  337. width = int(viewport_width * ratio / total_ratio)
  338. assigned_width += width
  339. self.table.setColumnWidth(index, max(width, 50))
  340. finally:
  341. header.blockSignals(False)
  342. self._is_applying_column_widths = False
  343. def import_excel(self):
  344. """导入Excel文件"""
  345. file_path, _ = QFileDialog.getOpenFileName(
  346. self, "选择Excel文件", "", "Excel Files (*.xlsx *.xls)"
  347. )
  348. if not file_path:
  349. return
  350. try:
  351. # 读取Excel文件(默认读取第一个sheet)
  352. # 先读取列名,确定规格列的位置
  353. df_temp = pd.read_excel(file_path, sheet_name=0, nrows=0)
  354. original_columns = df_temp.columns.tolist()
  355. # 构建converters字典,将规格列转换为字符串,保留原始格式
  356. converters = {}
  357. for col in original_columns:
  358. col_clean = col.strip().replace('\n', '').replace('\r', '')
  359. if col_clean == '规格':
  360. # 定义转换函数,将规格列转换为字符串
  361. def spec_converter(x):
  362. if pd.isna(x):
  363. return ''
  364. # 如果是数值类型(可能是百分比被转换成了小数),尝试恢复
  365. if isinstance(x, (int, float)):
  366. # 检查是否可能是百分比(0-1之间的小数)
  367. if 0 <= x <= 1:
  368. # 转换为百分比字符串
  369. return f"{x * 100:.0f}%"
  370. else:
  371. return str(x)
  372. return str(x)
  373. converters[col] = spec_converter
  374. # 读取Excel,使用converters确保规格列为字符串类型
  375. df = pd.read_excel(file_path, sheet_name=0, converters=converters)
  376. # 去除列名的前后空格和换行符
  377. df.columns = df.columns.str.strip().str.replace('\n', '').str.replace('\r', '')
  378. # 如果存在规格列,确保NaN值被转换为空字符串
  379. if '规格' in df.columns:
  380. df['规格'] = df['规格'].fillna('').astype(str)
  381. # 检查必需的列
  382. required_columns = ['开始时间', '结束时间', '业务类型', '产品', '计划量(t)']
  383. # 兼容旧格式:如果有"日期"列,也接受
  384. if '日期' in df.columns and '开始时间' not in df.columns:
  385. df['开始时间'] = df['日期']
  386. if '日期' in df.columns and '结束时间' not in df.columns:
  387. df['结束时间'] = df['日期']
  388. missing_columns = [col for col in required_columns if col not in df.columns]
  389. if missing_columns:
  390. # 显示实际读取到的列名,方便调试
  391. actual_columns = ', '.join(df.columns.tolist())
  392. QMessageBox.warning(
  393. self, "错误",
  394. f"Excel文件缺少必需的列:{', '.join(missing_columns)}\n\n"
  395. f"必需的列:{', '.join(required_columns)}\n"
  396. f"规格列为可选\n\n"
  397. f"实际读取到的列名:{actual_columns}"
  398. )
  399. return
  400. # 导入数据
  401. success_count = 0
  402. error_count = 0
  403. errors = []
  404. for index, row in df.iterrows():
  405. try:
  406. # 处理开始时间
  407. start_date = row['开始时间']
  408. if pd.isna(start_date):
  409. errors.append(f"第{index + 2}行:开始时间为空")
  410. error_count += 1
  411. continue
  412. # 转换为字符串格式
  413. if isinstance(start_date, pd.Timestamp):
  414. start_date = start_date.strftime('%Y-%m-%d')
  415. elif isinstance(start_date, datetime):
  416. start_date = start_date.strftime('%Y-%m-%d')
  417. else:
  418. start_date = str(start_date)
  419. # 处理结束时间
  420. end_date = row['结束时间']
  421. if pd.isna(end_date):
  422. errors.append(f"第{index + 2}行:结束时间为空")
  423. error_count += 1
  424. continue
  425. # 转换为字符串格式
  426. if isinstance(end_date, pd.Timestamp):
  427. end_date = end_date.strftime('%Y-%m-%d')
  428. elif isinstance(end_date, datetime):
  429. end_date = end_date.strftime('%Y-%m-%d')
  430. else:
  431. end_date = str(end_date)
  432. plan_date = start_date # 保留plan_date用于兼容
  433. # 处理业务类型
  434. business_type = str(row['业务类型']).strip()
  435. if business_type not in ['出库', '入库']:
  436. errors.append(f"第{index + 2}行:业务类型必须是'出库'或'入库'")
  437. error_count += 1
  438. continue
  439. # 处理产品
  440. product = str(row['产品']).strip()
  441. if not product:
  442. errors.append(f"第{index + 2}行:产品为空")
  443. error_count += 1
  444. continue
  445. # 处理计划量
  446. planned_quantity = float(row['计划量(t)'])
  447. if planned_quantity <= 0:
  448. errors.append(f"第{index + 2}行:计划量必须大于0")
  449. error_count += 1
  450. continue
  451. # 处理规格(可选)
  452. specification = ''
  453. if '规格' in df.columns and not pd.isna(row.get('规格')):
  454. specification = str(row['规格']).strip()
  455. # 处理客户名称(可选)
  456. customer_name = ''
  457. if '客户名称' in df.columns and not pd.isna(row.get('客户名称')):
  458. customer_name = str(row['客户名称']).strip()
  459. elif '客户' in df.columns and not pd.isna(row.get('客户')):
  460. customer_name = str(row['客户']).strip()
  461. elif '往来单位' in df.columns and not pd.isna(row.get('往来单位')):
  462. customer_name = str(row['往来单位']).strip()
  463. # 处理备注(可选)
  464. remarks = ''
  465. if '备注' in df.columns and not pd.isna(row.get('备注')):
  466. remarks = str(row['备注']).strip()
  467. # 插入数据
  468. data = {
  469. 'start_date': start_date,
  470. 'end_date': end_date,
  471. 'plan_date': plan_date,
  472. 'business_type': business_type,
  473. 'product': product,
  474. 'specification': specification,
  475. 'planned_quantity': planned_quantity,
  476. 'customer_name': customer_name,
  477. 'remarks': remarks
  478. }
  479. self.db.insert_purchase_plan(data)
  480. success_count += 1
  481. except Exception as e:
  482. errors.append(f"第{index + 2}行:{str(e)}")
  483. error_count += 1
  484. # 显示导入结果
  485. message = f"导入完成!\n成功:{success_count}条\n失败:{error_count}条"
  486. if errors:
  487. message += f"\n\n错误详情:\n" + "\n".join(errors[:10]) # 最多显示10个错误
  488. if len(errors) > 10:
  489. message += f"\n...还有{len(errors) - 10}个错误"
  490. if error_count > 0:
  491. QMessageBox.warning(self, "导入结果", message)
  492. else:
  493. QMessageBox.information(self, "导入成功", message)
  494. self.refresh_list()
  495. except Exception as e:
  496. QMessageBox.critical(self, "错误", f"导入失败:{str(e)}")
  497. def jump_to_inbound_outbound(self, plan_id: int):
  498. """从计划跳转到出入库模块,带数据校验"""
  499. plan = self.db.get_purchase_plan_by_id(plan_id)
  500. if not plan:
  501. QMessageBox.warning(self, "错误", "未找到该计划")
  502. return
  503. # 1. 校验产品(产品名称)
  504. product_name = plan.get('product', '').strip()
  505. if not product_name:
  506. QMessageBox.warning(self, "错误", "该计划缺少产品信息,请先补充后再跳转")
  507. return
  508. # 2. 校验往来单位(客户名称)
  509. partner_name = plan.get('customer_name', '').strip()
  510. if not partner_name:
  511. QMessageBox.warning(self, "错误", "该计划缺少往来单位信息,请先补充后再跳转")
  512. return
  513. # 3. 自动维护主数据(不存在则新增)
  514. auto_messages = []
  515. # 校验并确保产品在货物表中存在
  516. cargo_status = self.db.ensure_cargo_active(product_name)
  517. if cargo_status == "created":
  518. auto_messages.append(f"新增货物:{product_name}")
  519. elif cargo_status == "restored":
  520. auto_messages.append(f"恢复货物:{product_name}")
  521. # 校验并确保往来单位在公司表中存在
  522. company_status = self.db.ensure_company_active(partner_name)
  523. if company_status == "created":
  524. auto_messages.append(f"新增公司:{partner_name}")
  525. elif company_status == "restored":
  526. auto_messages.append(f"恢复公司:{partner_name}")
  527. # 如果有自动维护操作,提示用户
  528. if auto_messages:
  529. QMessageBox.information(
  530. self,
  531. "提示",
  532. "已自动维护以下主数据:\n" + "\n".join(auto_messages)
  533. )
  534. # 4. 切换到出入库tab
  535. if not self.main_window:
  536. QMessageBox.warning(self, "错误", "无法访问主窗口")
  537. return
  538. # 切换到出入库tab(假设是第2个tab,索引为1)
  539. inbound_tab_index = 1
  540. self.main_window.tab_widget.setCurrentIndex(inbound_tab_index)
  541. # 5. 获取出入库tab并刷新下拉列表
  542. inbound_tab = self.main_window.inbound_outbound_tab
  543. inbound_tab.refresh_dropdowns()
  544. inbound_tab.clear_form()
  545. # 6. 预填数据(日期保持空,等待用户自行选择)
  546. # 往来单位:从下拉列表中选择
  547. index = inbound_tab.partner_combo.findText(partner_name)
  548. if index >= 0:
  549. inbound_tab.partner_combo.setCurrentIndex(index)
  550. # 业务类型:根据计划的业务类型设置
  551. if plan['business_type'] == '入库':
  552. inbound_tab.business_inbound_radio.setChecked(True)
  553. elif plan['business_type'] == '出库':
  554. inbound_tab.business_outbound_radio.setChecked(True)
  555. # 产品:从下拉列表中选择
  556. index = inbound_tab.product_combo.findText(product_name)
  557. if index >= 0:
  558. inbound_tab.product_combo.setCurrentIndex(index)
  559. # 计划号:显示关联的计划号(只读)
  560. plan_no = plan.get('plan_no', '')
  561. if plan_no:
  562. inbound_tab.plan_no_display.setText(plan_no)
  563. else:
  564. inbound_tab.plan_no_display.setText("未关联")
  565. # 保存关联的计划ID,用于保存时关联
  566. inbound_tab.current_plan_id = plan_id
  567. def view_plan_details(self, plan_id: int):
  568. """查看计划详情"""
  569. if plan_id <= 0:
  570. QMessageBox.warning(self, "提示", "未找到计划ID")
  571. return
  572. try:
  573. self.db.refresh_plan_execution_status(plan_id)
  574. except Exception:
  575. pass
  576. plan = self.db.get_purchase_plan_by_id(plan_id)
  577. if not plan:
  578. QMessageBox.warning(self, "提示", "未找到该计划")
  579. return
  580. dialog = PlanDetailDialog(self.db, plan, parent=self)
  581. dialog.exec_()
  582. def _prepare_master_data(self, plan: dict) -> Optional[dict]:
  583. """
  584. 确保计划中的产品和往来单位已在货物/客户表中维护
  585. :return: 包含清洗后的产品、客户及固定公司名称
  586. """
  587. product_name = (plan.get('product') or '').strip()
  588. customer_name = (plan.get('customer_name') or '').strip()
  589. fixed_company_name = "安庆市山峡化工有限公司"
  590. if not product_name:
  591. QMessageBox.warning(self, "错误", "该计划缺少产品信息,请先补充后再跳转。")
  592. return None
  593. if not customer_name:
  594. QMessageBox.warning(self, "错误", "该计划缺少往来单位信息,请先补充后再跳转。")
  595. return None
  596. auto_messages = []
  597. try:
  598. cargo_status = self.db.ensure_cargo_active(product_name)
  599. if cargo_status == "created":
  600. auto_messages.append(f"新增货物“{product_name}”")
  601. elif cargo_status == "restored":
  602. auto_messages.append(f"恢复货物“{product_name}”")
  603. fixed_company_status = self.db.ensure_company_active(fixed_company_name)
  604. if fixed_company_status == "created":
  605. auto_messages.append(f"新增公司“{fixed_company_name}”")
  606. elif fixed_company_status == "restored":
  607. auto_messages.append(f"恢复公司“{fixed_company_name}”")
  608. customer_status = self.db.ensure_company_active(customer_name)
  609. if customer_status == "created":
  610. auto_messages.append(f"新增公司“{customer_name}”")
  611. elif customer_status == "restored":
  612. auto_messages.append(f"恢复公司“{customer_name}”")
  613. except Exception as e:
  614. QMessageBox.warning(self, "错误", f"自动维护货物/客户数据失败:{str(e)}")
  615. return None
  616. if auto_messages:
  617. QMessageBox.information(
  618. self,
  619. "提示",
  620. "已自动维护以下主数据:\n" + "\n".join(auto_messages)
  621. )
  622. return {
  623. 'product': product_name,
  624. 'customer': customer_name,
  625. 'fixed_company': fixed_company_name
  626. }
  627. class PurchasePlanDialog(QDialog):
  628. """采购计划编辑对话框"""
  629. def __init__(self, db: Database, plan=None, parent=None):
  630. super().__init__(parent)
  631. self.db = db
  632. self.plan = plan
  633. self.init_ui()
  634. def init_ui(self):
  635. """初始化对话框界面"""
  636. if self.plan:
  637. self.setWindowTitle("修改采购计划")
  638. else:
  639. self.setWindowTitle("新增采购计划")
  640. self.setMinimumWidth(500)
  641. layout = QVBoxLayout()
  642. layout.setSpacing(15)
  643. layout.setContentsMargins(20, 20, 20, 20)
  644. # 表单
  645. form_layout = QFormLayout()
  646. form_layout.setSpacing(15)
  647. required_label_style = ""
  648. # 计划号(只读,新增时自动生成,修改时显示)
  649. plan_no_label = QLabel("计划号:")
  650. plan_no_label.setFont(QFont("微软雅黑", 16))
  651. self.plan_no_display = QLabel("自动生成")
  652. self.plan_no_display.setMinimumHeight(45)
  653. self.plan_no_display.setFont(QFont("微软雅黑", 16))
  654. self.plan_no_display.setStyleSheet("padding: 5px; border: 1px solid #ccc;")
  655. form_layout.addRow(plan_no_label, self.plan_no_display)
  656. # 开始时间
  657. start_date_label = QLabel("开始时间 *:")
  658. start_date_label.setFont(QFont("微软雅黑", 16))
  659. start_date_label.setStyleSheet(required_label_style)
  660. self.start_date_input = QDateEdit()
  661. self.start_date_input.setMinimumHeight(45)
  662. self.start_date_input.setFont(QFont("微软雅黑", 16))
  663. self.start_date_input.setCalendarPopup(True)
  664. self.start_date_input.setDate(QDate.currentDate())
  665. self.start_date_input.setDisplayFormat("yyyy-MM-dd")
  666. form_layout.addRow(start_date_label, self.start_date_input)
  667. # 结束时间
  668. end_date_label = QLabel("结束时间 *:")
  669. end_date_label.setFont(QFont("微软雅黑", 16))
  670. end_date_label.setStyleSheet(required_label_style)
  671. self.end_date_input = QDateEdit()
  672. self.end_date_input.setMinimumHeight(45)
  673. self.end_date_input.setFont(QFont("微软雅黑", 16))
  674. self.end_date_input.setCalendarPopup(True)
  675. self.end_date_input.setDate(QDate.currentDate())
  676. self.end_date_input.setDisplayFormat("yyyy-MM-dd")
  677. form_layout.addRow(end_date_label, self.end_date_input)
  678. # 业务类型
  679. business_label = QLabel("业务类型 *:")
  680. business_label.setFont(QFont("微软雅黑", 16))
  681. business_label.setStyleSheet(required_label_style)
  682. self.business_type_group = QButtonGroup()
  683. self.business_sale_radio = QRadioButton("出库")
  684. self.business_purchase_radio = QRadioButton("入库")
  685. self.business_sale_radio.setFont(QFont("微软雅黑", 16))
  686. self.business_purchase_radio.setFont(QFont("微软雅黑", 16))
  687. # 移除颜色设置
  688. self.business_sale_radio.setStyleSheet("")
  689. self.business_purchase_radio.setStyleSheet("")
  690. self.business_type_group.addButton(self.business_sale_radio, 0)
  691. self.business_type_group.addButton(self.business_purchase_radio, 1)
  692. business_layout = QHBoxLayout()
  693. business_layout.addWidget(self.business_sale_radio)
  694. business_layout.addWidget(self.business_purchase_radio)
  695. business_layout.addStretch()
  696. business_widget = QWidget()
  697. business_widget.setLayout(business_layout)
  698. form_layout.addRow(business_label, business_widget)
  699. # 产品
  700. product_label = QLabel("产品 *:")
  701. product_label.setFont(QFont("微软雅黑", 16))
  702. product_label.setStyleSheet(required_label_style)
  703. self.product_combo = QComboBox()
  704. self.product_combo.setMinimumHeight(45)
  705. self.product_combo.setFont(QFont("微软雅黑", 16))
  706. self.product_combo.setEditable(True)
  707. self.product_combo.setInsertPolicy(QComboBox.NoInsert)
  708. form_layout.addRow(product_label, self.product_combo)
  709. # 计划量(t)
  710. quantity_label = QLabel("计划量(t) *:")
  711. quantity_label.setFont(QFont("微软雅黑", 16))
  712. quantity_label.setStyleSheet(required_label_style)
  713. self.quantity_input = QDoubleSpinBox()
  714. self.quantity_input.setMinimumHeight(45)
  715. self.quantity_input.setFont(QFont("微软雅黑", 16))
  716. self.quantity_input.setDecimals(3)
  717. self.quantity_input.setMinimum(0.001)
  718. self.quantity_input.setMaximum(999999)
  719. form_layout.addRow(quantity_label, self.quantity_input)
  720. # 计划量提示
  721. quantity_note = QLabel("计划量:对于单次运输就是单次的运输量,对于计划运输就是总的运输量")
  722. quantity_note.setFont(QFont("微软雅黑", 12))
  723. quantity_note.setStyleSheet("")
  724. quantity_note.setWordWrap(True)
  725. form_layout.addRow(QLabel(""), quantity_note)
  726. # 往来单位
  727. customer_label = QLabel("往来单位 *:")
  728. customer_label.setFont(QFont("微软雅黑", 16))
  729. customer_label.setStyleSheet(required_label_style)
  730. self.customer_combo = QComboBox()
  731. self.customer_combo.setMinimumHeight(45)
  732. self.customer_combo.setFont(QFont("微软雅黑", 16))
  733. self.customer_combo.setEditable(True)
  734. self.customer_combo.setInsertPolicy(QComboBox.NoInsert)
  735. form_layout.addRow(customer_label, self.customer_combo)
  736. # 备注
  737. remarks_label = QLabel("备注:")
  738. remarks_label.setFont(QFont("微软雅黑", 16))
  739. self.remarks_input = QTextEdit()
  740. self.remarks_input.setMinimumHeight(80)
  741. self.remarks_input.setFont(QFont("微软雅黑", 16))
  742. form_layout.addRow(remarks_label, self.remarks_input)
  743. self.load_dropdown_data()
  744. # 如果是在修改模式,填充数据
  745. if self.plan:
  746. # 显示计划号
  747. plan_no = self.plan.get('plan_no', '')
  748. if plan_no:
  749. self.plan_no_display.setText(plan_no)
  750. else:
  751. self.plan_no_display.setText("未生成")
  752. # 开始时间和结束时间
  753. start_date = self.plan.get('start_date') or self.plan.get('plan_date', '')
  754. if start_date:
  755. self.start_date_input.setDate(QDate.fromString(start_date, "yyyy-MM-dd"))
  756. end_date = self.plan.get('end_date') or self.plan.get('plan_date', '')
  757. if end_date:
  758. self.end_date_input.setDate(QDate.fromString(end_date, "yyyy-MM-dd"))
  759. if self.plan['business_type'] == '出库':
  760. self.business_sale_radio.setChecked(True)
  761. else:
  762. self.business_purchase_radio.setChecked(True)
  763. self._ensure_combo_value(self.product_combo, self.plan['product'])
  764. self.quantity_input.setValue(self.plan['planned_quantity'])
  765. self._ensure_combo_value(self.customer_combo, self.plan.get('customer_name', ''))
  766. self.remarks_input.setPlainText(self.plan.get('remarks', ''))
  767. layout.addLayout(form_layout)
  768. # 按钮
  769. button_layout = QHBoxLayout()
  770. button_layout.addStretch()
  771. ok_btn = QPushButton("确定")
  772. ok_btn.setMinimumHeight(45)
  773. ok_btn.setMinimumWidth(100)
  774. ok_btn.setFont(QFont("微软雅黑", 16))
  775. apply_button_style(ok_btn, 'green')
  776. ok_btn.clicked.connect(self.save)
  777. cancel_btn = QPushButton("取消")
  778. cancel_btn.setMinimumHeight(45)
  779. cancel_btn.setMinimumWidth(100)
  780. cancel_btn.setFont(QFont("微软雅黑", 16))
  781. apply_button_style(cancel_btn, 'normal')
  782. cancel_btn.clicked.connect(self.reject)
  783. button_layout.addWidget(ok_btn)
  784. button_layout.addWidget(cancel_btn)
  785. layout.addLayout(button_layout)
  786. self.setLayout(layout)
  787. def load_dropdown_data(self):
  788. """加载产品与往来单位下拉选项"""
  789. # 产品下拉来自货物维护
  790. self.product_combo.clear()
  791. self.product_combo.addItem("")
  792. product_names = [""]
  793. cargos = self.db.get_all_cargos()
  794. for cargo in cargos:
  795. name = cargo.get('name', '').strip()
  796. if name:
  797. self.product_combo.addItem(name)
  798. product_names.append(name)
  799. self.product_combo.setCurrentIndex(0)
  800. self._set_combo_completer(self.product_combo, product_names)
  801. # 往来单位下拉来自客户(沿用公司维护的数据)
  802. self.customer_combo.clear()
  803. self.customer_combo.addItem("")
  804. customer_names = [""]
  805. customers = self.db.get_all_companies()
  806. for customer in customers:
  807. name = customer.get('name', '').strip()
  808. if name:
  809. self.customer_combo.addItem(name)
  810. customer_names.append(name)
  811. self.customer_combo.setCurrentIndex(0)
  812. self._set_combo_completer(self.customer_combo, customer_names)
  813. def _ensure_combo_value(self, combo: QComboBox, value: str):
  814. """确保下拉框中存在给定的值并选中"""
  815. if not value:
  816. combo.setCurrentIndex(0)
  817. return
  818. index = combo.findText(value)
  819. if index < 0:
  820. combo.addItem(value)
  821. index = combo.findText(value)
  822. self._set_combo_completer(
  823. combo,
  824. [combo.itemText(i) for i in range(combo.count()) if combo.itemText(i)]
  825. )
  826. combo.setCurrentIndex(max(0, index))
  827. def _set_combo_completer(self, combo: QComboBox, options):
  828. """为下拉框配置模糊匹配的补全器"""
  829. cleaned = [opt for opt in options if opt]
  830. completer = QCompleter(cleaned, combo)
  831. completer.setFilterMode(Qt.MatchContains)
  832. completer.setCaseSensitivity(Qt.CaseInsensitive)
  833. completer.setCompletionMode(QCompleter.PopupCompletion)
  834. combo.setCompleter(completer)
  835. def save(self):
  836. """保存"""
  837. # 验证
  838. if not self.start_date_input.date().isValid():
  839. QMessageBox.warning(self, "验证失败", "请选择开始时间")
  840. return
  841. if not self.end_date_input.date().isValid():
  842. QMessageBox.warning(self, "验证失败", "请选择结束时间")
  843. return
  844. if not self.business_type_group.checkedButton():
  845. QMessageBox.warning(self, "验证失败", "请选择业务类型")
  846. return
  847. product = self.product_combo.currentText().strip()
  848. if not product:
  849. QMessageBox.warning(self, "验证失败", "产品不能为空")
  850. return
  851. if self.quantity_input.value() <= 0:
  852. QMessageBox.warning(self, "验证失败", "计划量必须大于0")
  853. return
  854. partner = self.customer_combo.currentText().strip()
  855. if not partner:
  856. QMessageBox.warning(self, "验证失败", "往来单位不能为空")
  857. return
  858. # 准备数据
  859. start_date = self.start_date_input.date().toString("yyyy-MM-dd")
  860. end_date = self.end_date_input.date().toString("yyyy-MM-dd")
  861. plan_date = start_date # 保留plan_date用于兼容
  862. data = {
  863. 'start_date': start_date,
  864. 'end_date': end_date,
  865. 'plan_date': plan_date,
  866. 'business_type': self.business_type_group.checkedButton().text(),
  867. 'product': product,
  868. 'specification': self.plan.get('specification', '') if self.plan else '',
  869. 'planned_quantity': self.quantity_input.value(),
  870. 'customer_name': partner,
  871. 'remarks': self.remarks_input.toPlainText().strip()
  872. }
  873. # 如果是修改模式,保留计划号
  874. if self.plan:
  875. plan_no = self.plan.get('plan_no', '')
  876. if plan_no:
  877. data['plan_no'] = plan_no
  878. # 保存
  879. if self.plan:
  880. # 修改模式
  881. if self.db.update_purchase_plan(self.plan['id'], data):
  882. QMessageBox.information(self, "成功", "修改成功!")
  883. self.accept()
  884. else:
  885. QMessageBox.warning(self, "错误", "修改失败")
  886. else:
  887. # 新增模式(计划号会自动生成)
  888. try:
  889. self.db.insert_purchase_plan(data)
  890. QMessageBox.information(self, "成功", "新增成功!")
  891. self.accept()
  892. except Exception as e:
  893. QMessageBox.critical(self, "错误", f"新增失败:{str(e)}")
  894. class PlanDetailDialog(QDialog):
  895. """计划详情对话框"""
  896. def __init__(self, db: Database, plan: dict, parent=None):
  897. super().__init__(parent)
  898. self.db = db
  899. self.plan = plan
  900. self.inbound_list = self.db.get_inbound_outbound_by_plan_id(plan['id'])
  901. self.slip_list = self.db.get_weighing_slips_by_plan_id(plan['id'])
  902. self.slips_by_inbound = self._group_slips_by_inbound()
  903. self.unlinked_slips = [slip for slip in self.slip_list if not slip.get('inbound_outbound_id')]
  904. self.init_ui()
  905. def _format_weight_in_tons(self, kg_value: float, digits: int = 3) -> str:
  906. """将公斤转换为吨并格式化"""
  907. if kg_value is None:
  908. kg_value = 0
  909. return f"{kg_value / 1000:.{digits}f}"
  910. def init_ui(self):
  911. plan_no = self.plan.get('plan_no') or f"ID-{self.plan.get('id')}"
  912. self.setWindowTitle(f"计划详情 - {plan_no}")
  913. self.resize(1080, 720)
  914. layout = QVBoxLayout()
  915. layout.setContentsMargins(20, 20, 20, 20)
  916. layout.setSpacing(12)
  917. scroll_area = QScrollArea()
  918. scroll_area.setWidgetResizable(True)
  919. content_widget = QWidget()
  920. content_layout = QVBoxLayout()
  921. content_layout.setSpacing(18)
  922. content_layout.addWidget(self._create_plan_info_group())
  923. if not self.inbound_list:
  924. empty_label = QLabel("暂无关联的出入库单。")
  925. empty_label.setFont(QFont("微软雅黑", 14))
  926. content_layout.addWidget(empty_label)
  927. else:
  928. for index, inbound in enumerate(self.inbound_list, start=1):
  929. content_layout.addWidget(self._create_inbound_slip_section(index, inbound))
  930. if self.unlinked_slips:
  931. content_layout.addWidget(self._create_unlinked_slip_section())
  932. content_layout.addStretch()
  933. content_widget.setLayout(content_layout)
  934. scroll_area.setWidget(content_widget)
  935. layout.addWidget(scroll_area)
  936. button_layout = QHBoxLayout()
  937. button_layout.addStretch()
  938. close_btn = QPushButton("关闭")
  939. close_btn.setMinimumHeight(40)
  940. close_btn.setMinimumWidth(120)
  941. close_btn.setFont(QFont("微软雅黑", 16))
  942. apply_button_style(close_btn, 'normal')
  943. close_btn.clicked.connect(self.accept)
  944. button_layout.addWidget(close_btn)
  945. layout.addLayout(button_layout)
  946. self.setLayout(layout)
  947. def _group_slips_by_inbound(self):
  948. grouped = {}
  949. for slip in self.slip_list:
  950. inbound_id = slip.get('inbound_outbound_id')
  951. if not inbound_id:
  952. continue
  953. grouped.setdefault(inbound_id, []).append(slip)
  954. return grouped
  955. def _create_plan_info_group(self) -> QGroupBox:
  956. group = QGroupBox("计划单信息")
  957. group.setFont(QFont("微软雅黑", 15, QFont.Bold))
  958. form = QFormLayout()
  959. form.setHorizontalSpacing(30)
  960. form.setVerticalSpacing(10)
  961. executed_kg = self.plan.get('executed_quantity') or 0
  962. executed_tons = executed_kg / 1000 if executed_kg else 0
  963. planned_tons = self.plan.get('planned_quantity') or 0
  964. rows = [
  965. ("计划号:", self.plan.get('plan_no', '未生成')),
  966. ("往来单位:", self.plan.get('customer_name', '')),
  967. ("业务类型:", self.plan.get('business_type', '')),
  968. ("产品:", self.plan.get('product', '')),
  969. ("计划量(t):", f"{planned_tons:.3f}"),
  970. ("已执行量(t):", f"{executed_tons:.3f}"),
  971. ("状态:", self.plan.get('execution_status', '')),
  972. ("开始时间:", self.plan.get('start_date') or self.plan.get('plan_date', '')),
  973. ("结束时间:", self.plan.get('end_date') or self.plan.get('plan_date', '')),
  974. ("备注:", self.plan.get('remarks', '') or '')
  975. ]
  976. for label, value in rows:
  977. lbl = QLabel(label)
  978. lbl.setFont(QFont("微软雅黑", 14, QFont.Bold))
  979. val = QLabel(str(value))
  980. val.setFont(QFont("微软雅黑", 14))
  981. val.setWordWrap(True)
  982. form.addRow(lbl, val)
  983. group.setLayout(form)
  984. return group
  985. def _create_inbound_slip_section(self, index: int, inbound: dict) -> QGroupBox:
  986. group = QGroupBox(f"出入库单 {index}")
  987. group.setFont(QFont("微软雅黑", 15, QFont.Bold))
  988. group_layout = QHBoxLayout()
  989. group_layout.setSpacing(20)
  990. group_layout.setContentsMargins(15, 15, 15, 15)
  991. inbound_widget = self._create_inbound_info_widget(inbound)
  992. slips_widget = self._create_slip_list_widget(self.slips_by_inbound.get(inbound.get('id'), []))
  993. group_layout.addWidget(inbound_widget, 1)
  994. group_layout.addWidget(slips_widget, 1)
  995. group.setLayout(group_layout)
  996. return group
  997. def _create_inbound_info_widget(self, inbound: dict) -> QWidget:
  998. widget = QWidget()
  999. form = QFormLayout()
  1000. form.setHorizontalSpacing(20)
  1001. form.setVerticalSpacing(8)
  1002. rows = [
  1003. ("日期:", inbound.get('date', '')),
  1004. ("往来单位:", inbound.get('partner_company', '')),
  1005. ("业务类型:", inbound.get('business_type', '')),
  1006. ("产品:", inbound.get('product', '')),
  1007. ("数量(t):", f"{inbound.get('quantity', 0):.3f}"),
  1008. ("状态:", inbound.get('status', '')),
  1009. ("批次号:", inbound.get('batch_no', '')),
  1010. ("车牌号:", inbound.get('vehicle_no', '')),
  1011. ("备注:", inbound.get('remarks', '') or '')
  1012. ]
  1013. for label, value in rows:
  1014. lbl = QLabel(label)
  1015. lbl.setFont(QFont("微软雅黑", 13, QFont.Bold))
  1016. val = QLabel(str(value))
  1017. val.setFont(QFont("微软雅黑", 13))
  1018. val.setWordWrap(True)
  1019. form.addRow(lbl, val)
  1020. widget.setLayout(form)
  1021. return widget
  1022. def _create_slip_list_widget(self, slips: list) -> QWidget:
  1023. widget = QWidget()
  1024. layout = QVBoxLayout()
  1025. layout.setSpacing(10)
  1026. title = QLabel("地磅单信息")
  1027. title.setFont(QFont("微软雅黑", 14, QFont.Bold))
  1028. layout.addWidget(title)
  1029. if not slips:
  1030. empty = QLabel("暂无关联地磅单。")
  1031. empty.setFont(QFont("微软雅黑", 13))
  1032. layout.addWidget(empty)
  1033. else:
  1034. for idx, slip in enumerate(slips, start=1):
  1035. slip_frame = QFrame()
  1036. slip_frame.setFrameShape(QFrame.StyledPanel)
  1037. slip_frame_layout = QFormLayout()
  1038. slip_frame_layout.setHorizontalSpacing(18)
  1039. slip_frame_layout.setVerticalSpacing(6)
  1040. rows = [
  1041. (f"地磅单 {idx}:", f"#{slip.get('id', '')}"),
  1042. ("车牌号:", slip.get('vehicle_no', '')),
  1043. ("货物:", slip.get('cargo_name', '')),
  1044. ("业务类型:", slip.get('business_type', '')),
  1045. ("毛重(t):", self._format_weight_in_tons(slip.get('gross_weight', 0))),
  1046. ("皮重(t):", self._format_weight_in_tons(slip.get('tare_weight', 0))),
  1047. ("净重(t):", self._format_weight_in_tons(slip.get('net_weight', 0))),
  1048. ("扣量(t):", self._format_weight_in_tons(slip.get('deduction', 0))),
  1049. ("过磅时间:", slip.get('created_at', ''))
  1050. ]
  1051. for label, value in rows:
  1052. lbl = QLabel(label)
  1053. lbl.setFont(QFont("微软雅黑", 12, QFont.Bold))
  1054. val = QLabel(str(value))
  1055. val.setFont(QFont("微软雅黑", 12))
  1056. slip_frame_layout.addRow(lbl, val)
  1057. slip_frame.setLayout(slip_frame_layout)
  1058. layout.addWidget(slip_frame)
  1059. widget.setLayout(layout)
  1060. return widget
  1061. def _create_unlinked_slip_section(self) -> QGroupBox:
  1062. group = QGroupBox("未关联出入库单的地磅单")
  1063. group.setFont(QFont("微软雅黑", 15, QFont.Bold))
  1064. layout = QVBoxLayout()
  1065. layout.setSpacing(10)
  1066. for idx, slip in enumerate(self.unlinked_slips, start=1):
  1067. slip_frame = QFrame()
  1068. slip_frame.setFrameShape(QFrame.StyledPanel)
  1069. slip_layout = QFormLayout()
  1070. slip_layout.setHorizontalSpacing(18)
  1071. slip_layout.setVerticalSpacing(6)
  1072. rows = [
  1073. (f"地磅单 {idx}:", f"#{slip.get('id', '')}"),
  1074. ("车牌号:", slip.get('vehicle_no', '')),
  1075. ("货物:", slip.get('cargo_name', '')),
  1076. ("业务类型:", slip.get('business_type', '')),
  1077. ("净重(t):", self._format_weight_in_tons(slip.get('net_weight', 0))),
  1078. ("过磅时间:", slip.get('created_at', ''))
  1079. ]
  1080. for label, value in rows:
  1081. lbl = QLabel(label)
  1082. lbl.setFont(QFont("微软雅黑", 12, QFont.Bold))
  1083. val = QLabel(str(value))
  1084. val.setFont(QFont("微软雅黑", 12))
  1085. slip_layout.addRow(lbl, val)
  1086. slip_frame.setLayout(slip_layout)
  1087. layout.addWidget(slip_frame)
  1088. group.setLayout(layout)
  1089. return group