| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280 |
- """
- 采购计划Tab页面
- """
- from PyQt5.QtWidgets import (
- QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton,
- QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox, QDialog,
- QFormLayout, QComboBox, QDateEdit, QRadioButton, QButtonGroup,
- QDoubleSpinBox, QFileDialog, QTextEdit, QCompleter, QScrollArea,
- QGroupBox, QFrame
- )
- from PyQt5.QtCore import Qt, QDate, QDateTime, QTimer, pyqtSignal
- from PyQt5.QtGui import QFont, QKeySequence, QBrush, QColor
- from database import Database
- from .button_styles import apply_button_style, get_button_color_type
- import pandas as pd
- import time
- import logging
- from datetime import datetime
- from typing import Optional, Dict
- startup_logger = logging.getLogger('startup')
- class PurchasePlanTab(QWidget):
- """采购计划Tab"""
-
- def __init__(self, db: Database, main_window=None, current_user: Optional[Dict] = None):
- tab_start = time.time()
- super().__init__()
- self.db = db
- self.main_window = main_window # 保存主窗口引用,用于跳转到地磅单
- self.current_user = current_user or {}
- self._is_admin = self.current_user.get('role') == 'admin'
- self._all_plans = []
- self._displayed_plans = []
-
- ui_start = time.time()
- self.init_ui()
- startup_logger.info(f" 界面初始化 (耗时: {time.time() - ui_start:.3f}秒)")
-
- refresh_start = time.time()
- self.refresh_list()
- startup_logger.info(f" 数据加载 (耗时: {time.time() - refresh_start:.3f}秒)")
-
- def init_ui(self):
- """初始化界面"""
- layout = QVBoxLayout()
- layout.setSpacing(10)
- layout.setContentsMargins(15, 15, 15, 15)
-
- # 标题
- title = QLabel("计划管理")
- title_font = QFont("微软雅黑", 18, QFont.Bold)
- title.setFont(title_font)
- layout.addWidget(title)
-
- # 按钮区域
- button_layout = QHBoxLayout()
- button_layout.setSpacing(10)
-
- self.partner_search_input = QLineEdit()
- self.partner_search_input.setPlaceholderText("按往来单位模糊检索…")
- self.partner_search_input.setClearButtonEnabled(True)
- self.partner_search_input.setMinimumHeight(40)
- self.partner_search_input.setMinimumWidth(500)
- self.partner_search_input.setMaximumWidth(600)
- self.partner_search_input.setFont(QFont("微软雅黑", 15))
- self.partner_search_input.textChanged.connect(self._on_partner_search_changed)
-
- self.add_btn = QPushButton("新增")
- self.add_btn.setMinimumHeight(45)
- self.add_btn.setMinimumWidth(120)
- self.add_btn.setFont(QFont("微软雅黑", 16))
- apply_button_style(self.add_btn, 'green')
- self.add_btn.clicked.connect(self.add_plan)
- self.add_btn.setShortcut(QKeySequence("Ctrl+N"))
-
- self.edit_btn = QPushButton("修改")
- self.edit_btn.setMinimumHeight(45)
- self.edit_btn.setMinimumWidth(120)
- self.edit_btn.setFont(QFont("微软雅黑", 16))
- apply_button_style(self.edit_btn, 'normal')
- self.edit_btn.clicked.connect(self.edit_plan)
-
- self.delete_btn = QPushButton("删除")
- self.delete_btn.setMinimumHeight(45)
- self.delete_btn.setMinimumWidth(120)
- self.delete_btn.setFont(QFont("微软雅黑", 16))
- apply_button_style(self.delete_btn, 'normal')
- self.delete_btn.clicked.connect(self.delete_plan)
- if self._is_admin:
- self.delete_btn.setShortcut(QKeySequence("Delete"))
- else:
- self.delete_btn.hide()
- self.delete_btn.setEnabled(False)
-
- self.import_btn = QPushButton("Excel导入")
- self.import_btn.setMinimumHeight(45)
- self.import_btn.setMinimumWidth(120)
- self.import_btn.setFont(QFont("微软雅黑", 16))
- self.import_btn.setStyleSheet("border-radius: 5px;")
- self.import_btn.clicked.connect(self.import_excel)
- self.import_btn.setVisible(False) # 隐藏Excel导入按钮
-
- self.export_btn = QPushButton("导出Excel")
- self.export_btn.setMinimumHeight(45)
- self.export_btn.setMinimumWidth(140)
- self.export_btn.setFont(QFont("微软雅黑", 16))
- apply_button_style(self.export_btn, 'normal')
- self.export_btn.clicked.connect(self.export_to_excel)
-
- self.refresh_btn = QPushButton("刷新")
- self.refresh_btn.setMinimumHeight(45)
- self.refresh_btn.setMinimumWidth(120)
- self.refresh_btn.setFont(QFont("微软雅黑", 16))
- apply_button_style(self.refresh_btn, 'normal')
- self.refresh_btn.setEnabled(True) # 确保按钮是启用状态
- self.refresh_btn.clicked.connect(self.refresh_list)
- self.refresh_btn.setShortcut(QKeySequence("F5"))
-
- button_layout.addWidget(self.partner_search_input)
- button_layout.addWidget(self.add_btn)
- button_layout.addWidget(self.edit_btn)
- button_layout.addWidget(self.delete_btn)
- button_layout.addWidget(self.import_btn)
- button_layout.addWidget(self.export_btn)
- button_layout.addWidget(self.refresh_btn)
- button_layout.addStretch()
-
- layout.addLayout(button_layout)
-
- # 表格
- self.table = QTableWidget()
- self.table.setColumnCount(10)
- self.table.setHorizontalHeaderLabels([
- "计划号", "开始时间", "结束时间", "往来单位", "业务类型", "产品",
- "计划量(t)", "已执行量(t)", "状态", "操作"
- ])
- self.table.horizontalHeader().setFont(QFont("微软雅黑", 15, QFont.Bold))
- header = self.table.horizontalHeader()
- header.setSectionsMovable(False)
- header.setStretchLastSection(False)
- header.setSectionsClickable(False)
- self.column_width_ratios = [0.11, 0.11, 0.11, 0.16, 0.1, 0.12, 0.08, 0.08, 0.06, 0.17]
- self._user_resized_columns = False
- self._is_applying_column_widths = False
- for i in range(self.table.columnCount()):
- header.setSectionResizeMode(i, QHeaderView.Interactive)
- header.sectionResized.connect(self._on_section_resized)
- self._apply_table_column_widths(force=True)
- vertical_header = self.table.verticalHeader()
- vertical_header.setDefaultAlignment(Qt.AlignCenter)
- vertical_header.setFixedWidth(60)
- vertical_header.setSectionResizeMode(QHeaderView.ResizeToContents)
- self.table.setFont(QFont("微软雅黑", 15))
- self.table.setAlternatingRowColors(True)
- self.table.setSelectionBehavior(QTableWidget.SelectRows)
- self.table.setSelectionMode(QTableWidget.SingleSelection)
-
- layout.addWidget(self.table)
- self.setLayout(layout)
-
- def refresh_list(self):
- """刷新列表(批量刷新计划执行状态,避免 N 次数据库往返)"""
- plans = self.db.get_all_purchase_plans()
- plan_ids = [p.get("id") for p in plans if p.get("id")]
- if plan_ids:
- try:
- updated = self.db.refresh_all_plans_execution_status(plan_ids)
- for plan in plans:
- plan_id = plan.get("id")
- if plan_id and plan_id in updated:
- plan.update(updated[plan_id])
- except Exception:
- pass
- self._all_plans = [dict(p) for p in plans]
- self._apply_partner_filter()
-
- def _apply_partner_filter(self):
- keyword = (self.partner_search_input.text() or "").strip().lower()
- if not keyword:
- filtered = list(self._all_plans)
- else:
- filtered = [
- plan for plan in self._all_plans
- if keyword in (plan.get('customer_name', '') or '').lower()
- ]
- self._update_table(filtered)
-
- def _update_table(self, plans):
- self.table.setRowCount(len(plans))
- self._displayed_plans = plans
-
- for i, plan in enumerate(plans):
- self.table.setItem(i, 0, QTableWidgetItem(plan.get('plan_no', '')))
-
- start_date = plan.get('start_date') or plan.get('plan_date', '')
- self.table.setItem(i, 1, QTableWidgetItem(start_date))
-
- end_date = plan.get('end_date') or plan.get('plan_date', '')
- self.table.setItem(i, 2, QTableWidgetItem(end_date))
-
- self.table.setItem(i, 3, QTableWidgetItem(plan.get('customer_name', '')))
- self.table.setItem(i, 4, QTableWidgetItem(plan.get('business_type', '')))
- self.table.setItem(i, 5, QTableWidgetItem(plan.get('product', '')))
- planned_quantity = plan.get('planned_quantity')
- try:
- planned_quantity = float(planned_quantity)
- except (TypeError, ValueError):
- planned_quantity = 0.0
- self.table.setItem(i, 6, QTableWidgetItem(f"{planned_quantity:.3f}"))
-
- executed_quantity = plan.get('executed_quantity') or 0
- executed_tons = executed_quantity / 1000 if executed_quantity else 0
- self.table.setItem(i, 7, QTableWidgetItem(f"{executed_tons:.3f}"))
-
- status_text = plan.get('execution_status', '')
- status_item = QTableWidgetItem(status_text)
- # 移除状态文字颜色
- self.table.setItem(i, 8, status_item)
-
- btn_widget = QWidget()
- btn_layout = QHBoxLayout()
- btn_layout.setContentsMargins(5, 2, 5, 2)
-
- jump_btn = QPushButton("生成出入库单")
- jump_btn.setFont(QFont("微软雅黑", 14))
- apply_button_style(jump_btn, 'blue')
- jump_btn.clicked.connect(lambda checked, pid=plan.get('id'): self.jump_to_inbound_outbound(pid))
-
- view_btn = QPushButton("查看")
- view_btn.setFont(QFont("微软雅黑", 16))
- apply_button_style(view_btn, 'normal')
- view_btn.clicked.connect(lambda checked, pid=plan.get('id'): self.view_plan_details(pid))
-
- btn_layout.addWidget(view_btn)
- btn_layout.addWidget(jump_btn)
- btn_layout.addStretch()
- btn_widget.setLayout(btn_layout)
-
- self.table.setCellWidget(i, 9, btn_widget)
-
- self.table.resizeRowsToContents()
-
- def _on_partner_search_changed(self, _text: str):
- self._apply_partner_filter()
- def resizeEvent(self, event):
- super().resizeEvent(event)
- self._apply_table_column_widths()
-
- def showEvent(self, event):
- super().showEvent(event)
- QTimer.singleShot(0, lambda: self._apply_table_column_widths(force=True))
-
- def export_to_excel(self):
- """导出计划信息到Excel"""
- plans = self.db.get_all_purchase_plans()
- if not plans:
- QMessageBox.information(self, "提示", "暂无可导出的计划数据。")
- return
-
- default_name = f"计划管理导出_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
- file_path, _ = QFileDialog.getSaveFileName(
- self,
- "导出计划信息",
- default_name,
- "Excel Files (*.xlsx)"
- )
- if not file_path:
- return
- if not file_path.lower().endswith(".xlsx"):
- file_path += ".xlsx"
-
- export_rows = []
- for plan in plans:
- executed_quantity = plan.get('executed_quantity') or 0
- executed_tons = executed_quantity / 1000 if executed_quantity else 0
- export_rows.append({
- "计划号": plan.get('plan_no', ''),
- "往来单位": plan.get('customer_name', ''),
- "业务类型": plan.get('business_type', ''),
- "产品": plan.get('product', ''),
- "计划量(t)": round(plan.get('planned_quantity', 0), 3),
- "已执行量(t)": round(executed_tons, 3),
- "状态": plan.get('execution_status', ''),
- "开始时间": plan.get('start_date') or plan.get('plan_date', ''),
- "结束时间": plan.get('end_date') or plan.get('plan_date', ''),
- "备注": plan.get('remarks', '')
- })
-
- try:
- df = pd.DataFrame(export_rows)
- df.to_excel(file_path, index=False)
- QMessageBox.information(self, "导出成功", f"已导出 {len(export_rows)} 条计划记录。")
- except Exception as e:
- QMessageBox.critical(self, "导出失败", f"导出Excel失败:{str(e)}")
-
- def get_selected_plan_id(self) -> int:
- """获取选中的采购计划ID"""
- current_row = self.table.currentRow()
- if current_row < 0:
- return -1
-
- if current_row >= len(self._displayed_plans):
- return -1
-
- return self._displayed_plans[current_row].get('id', -1)
-
- def add_plan(self):
- """新增采购计划"""
- dialog = PurchasePlanDialog(self.db, parent=self)
- if dialog.exec_() == QDialog.Accepted:
- self.refresh_list()
-
- def edit_plan(self):
- """修改采购计划"""
- plan_id = self.get_selected_plan_id()
- if plan_id < 0:
- QMessageBox.warning(self, "提示", "请先选择要修改的采购计划")
- return
-
- plan = self.db.get_purchase_plan_by_id(plan_id)
- if not plan:
- QMessageBox.warning(self, "错误", "未找到该采购计划")
- return
-
- dialog = PurchasePlanDialog(self.db, plan=plan, parent=self)
- if dialog.exec_() == QDialog.Accepted:
- self.refresh_list()
-
- def delete_plan(self):
- """删除采购计划"""
- if not self._is_admin:
- QMessageBox.warning(self, "权限不足", "仅管理员可执行删除。")
- return
- plan_id = self.get_selected_plan_id()
- if plan_id < 0:
- QMessageBox.warning(self, "提示", "请先选择要删除的采购计划")
- return
-
- # 检查是否已经产生了出入库单
- inbound_list = self.db.get_inbound_outbound_by_plan_id(plan_id)
- if inbound_list:
- QMessageBox.warning(
- self, "无法删除",
- f"该计划已产生{len(inbound_list)}条出入库单,无法删除!\n请先删除相关的出入库单后再删除计划。"
- )
- return
-
- # 确认删除
- msg = QMessageBox()
- msg.setIcon(QMessageBox.Question)
- msg.setWindowTitle("确认")
- msg.setText("确定要删除该采购计划吗?")
- msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
- msg.setDefaultButton(QMessageBox.No)
- msg.button(QMessageBox.Yes).setText("是")
- msg.button(QMessageBox.No).setText("否")
- reply = msg.exec_()
-
- if reply == QMessageBox.Yes:
- if self.db.delete_purchase_plan(plan_id):
- QMessageBox.information(self, "成功", "删除成功!")
- self.refresh_list()
- else:
- QMessageBox.warning(self, "错误", "删除失败")
- def _on_section_resized(self, *_):
- if self._is_applying_column_widths:
- return
- self._user_resized_columns = True
- def _apply_table_column_widths(self, force: bool = False):
- if not hasattr(self, "table") or not hasattr(self, "column_width_ratios"):
- return
- if self._user_resized_columns and not force:
- return
- viewport_width = self.table.viewport().width()
- if viewport_width <= 0:
- return
- total_ratio = sum(self.column_width_ratios) or 1
- assigned_width = 0
- header = self.table.horizontalHeader()
- self._is_applying_column_widths = True
- header.blockSignals(True)
- try:
- for index, ratio in enumerate(self.column_width_ratios):
- if index == self.table.columnCount() - 1:
- width = viewport_width - assigned_width
- else:
- width = int(viewport_width * ratio / total_ratio)
- assigned_width += width
- self.table.setColumnWidth(index, max(width, 50))
- finally:
- header.blockSignals(False)
- self._is_applying_column_widths = False
-
- def import_excel(self):
- """导入Excel文件"""
- file_path, _ = QFileDialog.getOpenFileName(
- self, "选择Excel文件", "", "Excel Files (*.xlsx *.xls)"
- )
-
- if not file_path:
- return
-
- try:
- # 读取Excel文件(默认读取第一个sheet)
- # 先读取列名,确定规格列的位置
- df_temp = pd.read_excel(file_path, sheet_name=0, nrows=0)
- original_columns = df_temp.columns.tolist()
-
- # 构建converters字典,将规格列转换为字符串,保留原始格式
- converters = {}
- for col in original_columns:
- col_clean = col.strip().replace('\n', '').replace('\r', '')
- if col_clean == '规格':
- # 定义转换函数,将规格列转换为字符串
- def spec_converter(x):
- if pd.isna(x):
- return ''
- # 如果是数值类型(可能是百分比被转换成了小数),尝试恢复
- if isinstance(x, (int, float)):
- # 检查是否可能是百分比(0-1之间的小数)
- if 0 <= x <= 1:
- # 转换为百分比字符串
- return f"{x * 100:.0f}%"
- else:
- return str(x)
- return str(x)
- converters[col] = spec_converter
-
- # 读取Excel,使用converters确保规格列为字符串类型
- df = pd.read_excel(file_path, sheet_name=0, converters=converters)
-
- # 去除列名的前后空格和换行符
- df.columns = df.columns.str.strip().str.replace('\n', '').str.replace('\r', '')
-
- # 如果存在规格列,确保NaN值被转换为空字符串
- if '规格' in df.columns:
- df['规格'] = df['规格'].fillna('').astype(str)
-
- # 检查必需的列
- required_columns = ['开始时间', '结束时间', '业务类型', '产品', '计划量(t)']
- # 兼容旧格式:如果有"日期"列,也接受
- if '日期' in df.columns and '开始时间' not in df.columns:
- df['开始时间'] = df['日期']
- if '日期' in df.columns and '结束时间' not in df.columns:
- df['结束时间'] = df['日期']
-
- missing_columns = [col for col in required_columns if col not in df.columns]
-
- if missing_columns:
- # 显示实际读取到的列名,方便调试
- actual_columns = ', '.join(df.columns.tolist())
- QMessageBox.warning(
- self, "错误",
- f"Excel文件缺少必需的列:{', '.join(missing_columns)}\n\n"
- f"必需的列:{', '.join(required_columns)}\n"
- f"规格列为可选\n\n"
- f"实际读取到的列名:{actual_columns}"
- )
- return
-
- # 导入数据
- success_count = 0
- error_count = 0
- errors = []
-
- for index, row in df.iterrows():
- try:
- # 处理开始时间
- start_date = row['开始时间']
- if pd.isna(start_date):
- errors.append(f"第{index + 2}行:开始时间为空")
- error_count += 1
- continue
-
- # 转换为字符串格式
- if isinstance(start_date, pd.Timestamp):
- start_date = start_date.strftime('%Y-%m-%d')
- elif isinstance(start_date, datetime):
- start_date = start_date.strftime('%Y-%m-%d')
- else:
- start_date = str(start_date)
-
- # 处理结束时间
- end_date = row['结束时间']
- if pd.isna(end_date):
- errors.append(f"第{index + 2}行:结束时间为空")
- error_count += 1
- continue
-
- # 转换为字符串格式
- if isinstance(end_date, pd.Timestamp):
- end_date = end_date.strftime('%Y-%m-%d')
- elif isinstance(end_date, datetime):
- end_date = end_date.strftime('%Y-%m-%d')
- else:
- end_date = str(end_date)
-
- plan_date = start_date # 保留plan_date用于兼容
-
- # 处理业务类型
- business_type = str(row['业务类型']).strip()
- if business_type not in ['出库', '入库']:
- errors.append(f"第{index + 2}行:业务类型必须是'出库'或'入库'")
- error_count += 1
- continue
-
- # 处理产品
- product = str(row['产品']).strip()
- if not product:
- errors.append(f"第{index + 2}行:产品为空")
- error_count += 1
- continue
-
- # 处理计划量
- planned_quantity = float(row['计划量(t)'])
- if planned_quantity <= 0:
- errors.append(f"第{index + 2}行:计划量必须大于0")
- error_count += 1
- continue
-
- # 处理规格(可选)
- specification = ''
- if '规格' in df.columns and not pd.isna(row.get('规格')):
- specification = str(row['规格']).strip()
-
- # 处理客户名称(可选)
- customer_name = ''
- if '客户名称' in df.columns and not pd.isna(row.get('客户名称')):
- customer_name = str(row['客户名称']).strip()
- elif '客户' in df.columns and not pd.isna(row.get('客户')):
- customer_name = str(row['客户']).strip()
- elif '往来单位' in df.columns and not pd.isna(row.get('往来单位')):
- customer_name = str(row['往来单位']).strip()
-
- # 处理备注(可选)
- remarks = ''
- if '备注' in df.columns and not pd.isna(row.get('备注')):
- remarks = str(row['备注']).strip()
-
- # 插入数据
- data = {
- 'start_date': start_date,
- 'end_date': end_date,
- 'plan_date': plan_date,
- 'business_type': business_type,
- 'product': product,
- 'specification': specification,
- 'planned_quantity': planned_quantity,
- 'customer_name': customer_name,
- 'remarks': remarks
- }
-
- self.db.insert_purchase_plan(data)
- success_count += 1
-
- except Exception as e:
- errors.append(f"第{index + 2}行:{str(e)}")
- error_count += 1
-
- # 显示导入结果
- message = f"导入完成!\n成功:{success_count}条\n失败:{error_count}条"
- if errors:
- message += f"\n\n错误详情:\n" + "\n".join(errors[:10]) # 最多显示10个错误
- if len(errors) > 10:
- message += f"\n...还有{len(errors) - 10}个错误"
-
- if error_count > 0:
- QMessageBox.warning(self, "导入结果", message)
- else:
- QMessageBox.information(self, "导入成功", message)
-
- self.refresh_list()
-
- except Exception as e:
- QMessageBox.critical(self, "错误", f"导入失败:{str(e)}")
-
- def jump_to_inbound_outbound(self, plan_id: int):
- """从计划跳转到出入库模块,带数据校验"""
- plan = self.db.get_purchase_plan_by_id(plan_id)
- if not plan:
- QMessageBox.warning(self, "错误", "未找到该计划")
- return
-
- # 1. 校验产品(产品名称)
- product_name = plan.get('product', '').strip()
- if not product_name:
- QMessageBox.warning(self, "错误", "该计划缺少产品信息,请先补充后再跳转")
- return
-
- # 2. 校验往来单位(客户名称)
- partner_name = plan.get('customer_name', '').strip()
- if not partner_name:
- QMessageBox.warning(self, "错误", "该计划缺少往来单位信息,请先补充后再跳转")
- return
-
- # 3. 自动维护主数据(不存在则新增)
- auto_messages = []
-
- # 校验并确保产品在货物表中存在
- cargo_status = self.db.ensure_cargo_active(product_name)
- if cargo_status == "created":
- auto_messages.append(f"新增货物:{product_name}")
- elif cargo_status == "restored":
- auto_messages.append(f"恢复货物:{product_name}")
-
- # 校验并确保往来单位在公司表中存在
- company_status = self.db.ensure_company_active(partner_name)
- if company_status == "created":
- auto_messages.append(f"新增公司:{partner_name}")
- elif company_status == "restored":
- auto_messages.append(f"恢复公司:{partner_name}")
-
- # 如果有自动维护操作,提示用户
- if auto_messages:
- QMessageBox.information(
- self,
- "提示",
- "已自动维护以下主数据:\n" + "\n".join(auto_messages)
- )
-
- # 4. 切换到出入库tab
- if not self.main_window:
- QMessageBox.warning(self, "错误", "无法访问主窗口")
- return
-
- # 切换到出入库tab(假设是第2个tab,索引为1)
- inbound_tab_index = 1
- self.main_window.tab_widget.setCurrentIndex(inbound_tab_index)
-
- # 5. 获取出入库tab并刷新下拉列表
- inbound_tab = self.main_window.inbound_outbound_tab
- inbound_tab.refresh_dropdowns()
- inbound_tab.clear_form()
-
- # 6. 预填数据(日期保持空,等待用户自行选择)
- # 往来单位:从下拉列表中选择
- index = inbound_tab.partner_combo.findText(partner_name)
- if index >= 0:
- inbound_tab.partner_combo.setCurrentIndex(index)
-
- # 业务类型:根据计划的业务类型设置
- if plan['business_type'] == '入库':
- inbound_tab.business_inbound_radio.setChecked(True)
- elif plan['business_type'] == '出库':
- inbound_tab.business_outbound_radio.setChecked(True)
-
- # 产品:从下拉列表中选择
- index = inbound_tab.product_combo.findText(product_name)
- if index >= 0:
- inbound_tab.product_combo.setCurrentIndex(index)
-
- # 计划号:显示关联的计划号(只读)
- plan_no = plan.get('plan_no', '')
- if plan_no:
- inbound_tab.plan_no_display.setText(plan_no)
- else:
- inbound_tab.plan_no_display.setText("未关联")
-
- # 保存关联的计划ID,用于保存时关联
- inbound_tab.current_plan_id = plan_id
-
- def view_plan_details(self, plan_id: int):
- """查看计划详情"""
- if plan_id <= 0:
- QMessageBox.warning(self, "提示", "未找到计划ID")
- return
-
- try:
- self.db.refresh_plan_execution_status(plan_id)
- except Exception:
- pass
-
- plan = self.db.get_purchase_plan_by_id(plan_id)
- if not plan:
- QMessageBox.warning(self, "提示", "未找到该计划")
- return
-
- dialog = PlanDetailDialog(self.db, plan, parent=self)
- dialog.exec_()
- def _prepare_master_data(self, plan: dict) -> Optional[dict]:
- """
- 确保计划中的产品和往来单位已在货物/客户表中维护
- :return: 包含清洗后的产品、客户及固定公司名称
- """
- product_name = (plan.get('product') or '').strip()
- customer_name = (plan.get('customer_name') or '').strip()
- fixed_company_name = "安庆市山峡化工有限公司"
- if not product_name:
- QMessageBox.warning(self, "错误", "该计划缺少产品信息,请先补充后再跳转。")
- return None
-
- if not customer_name:
- QMessageBox.warning(self, "错误", "该计划缺少往来单位信息,请先补充后再跳转。")
- return None
-
- auto_messages = []
-
- try:
- cargo_status = self.db.ensure_cargo_active(product_name)
- if cargo_status == "created":
- auto_messages.append(f"新增货物“{product_name}”")
- elif cargo_status == "restored":
- auto_messages.append(f"恢复货物“{product_name}”")
-
- fixed_company_status = self.db.ensure_company_active(fixed_company_name)
- if fixed_company_status == "created":
- auto_messages.append(f"新增公司“{fixed_company_name}”")
- elif fixed_company_status == "restored":
- auto_messages.append(f"恢复公司“{fixed_company_name}”")
-
- customer_status = self.db.ensure_company_active(customer_name)
- if customer_status == "created":
- auto_messages.append(f"新增公司“{customer_name}”")
- elif customer_status == "restored":
- auto_messages.append(f"恢复公司“{customer_name}”")
- except Exception as e:
- QMessageBox.warning(self, "错误", f"自动维护货物/客户数据失败:{str(e)}")
- return None
-
- if auto_messages:
- QMessageBox.information(
- self,
- "提示",
- "已自动维护以下主数据:\n" + "\n".join(auto_messages)
- )
-
- return {
- 'product': product_name,
- 'customer': customer_name,
- 'fixed_company': fixed_company_name
- }
- class PurchasePlanDialog(QDialog):
- """采购计划编辑对话框"""
-
- def __init__(self, db: Database, plan=None, parent=None):
- super().__init__(parent)
- self.db = db
- self.plan = plan
- self.init_ui()
-
- def init_ui(self):
- """初始化对话框界面"""
- if self.plan:
- self.setWindowTitle("修改采购计划")
- else:
- self.setWindowTitle("新增采购计划")
-
- self.setMinimumWidth(500)
-
- layout = QVBoxLayout()
- layout.setSpacing(15)
- layout.setContentsMargins(20, 20, 20, 20)
-
- # 表单
- form_layout = QFormLayout()
- form_layout.setSpacing(15)
- required_label_style = ""
-
- # 计划号(只读,新增时自动生成,修改时显示)
- plan_no_label = QLabel("计划号:")
- plan_no_label.setFont(QFont("微软雅黑", 16))
- self.plan_no_display = QLabel("自动生成")
- self.plan_no_display.setMinimumHeight(45)
- self.plan_no_display.setFont(QFont("微软雅黑", 16))
- self.plan_no_display.setStyleSheet("padding: 5px; border: 1px solid #ccc;")
- form_layout.addRow(plan_no_label, self.plan_no_display)
-
- # 开始时间
- start_date_label = QLabel("开始时间 *:")
- start_date_label.setFont(QFont("微软雅黑", 16))
- start_date_label.setStyleSheet(required_label_style)
- self.start_date_input = QDateEdit()
- self.start_date_input.setMinimumHeight(45)
- self.start_date_input.setFont(QFont("微软雅黑", 16))
- self.start_date_input.setCalendarPopup(True)
- self.start_date_input.setDate(QDate.currentDate())
- self.start_date_input.setDisplayFormat("yyyy-MM-dd")
- form_layout.addRow(start_date_label, self.start_date_input)
-
- # 结束时间
- end_date_label = QLabel("结束时间 *:")
- end_date_label.setFont(QFont("微软雅黑", 16))
- end_date_label.setStyleSheet(required_label_style)
- self.end_date_input = QDateEdit()
- self.end_date_input.setMinimumHeight(45)
- self.end_date_input.setFont(QFont("微软雅黑", 16))
- self.end_date_input.setCalendarPopup(True)
- self.end_date_input.setDate(QDate.currentDate())
- self.end_date_input.setDisplayFormat("yyyy-MM-dd")
- form_layout.addRow(end_date_label, self.end_date_input)
-
- # 业务类型
- business_label = QLabel("业务类型 *:")
- business_label.setFont(QFont("微软雅黑", 16))
- business_label.setStyleSheet(required_label_style)
- self.business_type_group = QButtonGroup()
- self.business_sale_radio = QRadioButton("出库")
- self.business_purchase_radio = QRadioButton("入库")
- self.business_sale_radio.setFont(QFont("微软雅黑", 16))
- self.business_purchase_radio.setFont(QFont("微软雅黑", 16))
- # 移除颜色设置
- self.business_sale_radio.setStyleSheet("")
- self.business_purchase_radio.setStyleSheet("")
- self.business_type_group.addButton(self.business_sale_radio, 0)
- self.business_type_group.addButton(self.business_purchase_radio, 1)
- business_layout = QHBoxLayout()
- business_layout.addWidget(self.business_sale_radio)
- business_layout.addWidget(self.business_purchase_radio)
- business_layout.addStretch()
- business_widget = QWidget()
- business_widget.setLayout(business_layout)
- form_layout.addRow(business_label, business_widget)
-
- # 产品
- product_label = QLabel("产品 *:")
- product_label.setFont(QFont("微软雅黑", 16))
- product_label.setStyleSheet(required_label_style)
- self.product_combo = QComboBox()
- self.product_combo.setMinimumHeight(45)
- self.product_combo.setFont(QFont("微软雅黑", 16))
- self.product_combo.setEditable(True)
- self.product_combo.setInsertPolicy(QComboBox.NoInsert)
- form_layout.addRow(product_label, self.product_combo)
-
- # 计划量(t)
- quantity_label = QLabel("计划量(t) *:")
- quantity_label.setFont(QFont("微软雅黑", 16))
- quantity_label.setStyleSheet(required_label_style)
- self.quantity_input = QDoubleSpinBox()
- self.quantity_input.setMinimumHeight(45)
- self.quantity_input.setFont(QFont("微软雅黑", 16))
- self.quantity_input.setDecimals(3)
- self.quantity_input.setMinimum(0.001)
- self.quantity_input.setMaximum(999999)
- form_layout.addRow(quantity_label, self.quantity_input)
-
- # 计划量提示
- quantity_note = QLabel("计划量:对于单次运输就是单次的运输量,对于计划运输就是总的运输量")
- quantity_note.setFont(QFont("微软雅黑", 12))
- quantity_note.setStyleSheet("")
- quantity_note.setWordWrap(True)
- form_layout.addRow(QLabel(""), quantity_note)
-
- # 往来单位
- customer_label = QLabel("往来单位 *:")
- customer_label.setFont(QFont("微软雅黑", 16))
- customer_label.setStyleSheet(required_label_style)
- self.customer_combo = QComboBox()
- self.customer_combo.setMinimumHeight(45)
- self.customer_combo.setFont(QFont("微软雅黑", 16))
- self.customer_combo.setEditable(True)
- self.customer_combo.setInsertPolicy(QComboBox.NoInsert)
- form_layout.addRow(customer_label, self.customer_combo)
-
- # 备注
- remarks_label = QLabel("备注:")
- remarks_label.setFont(QFont("微软雅黑", 16))
- self.remarks_input = QTextEdit()
- self.remarks_input.setMinimumHeight(80)
- self.remarks_input.setFont(QFont("微软雅黑", 16))
- form_layout.addRow(remarks_label, self.remarks_input)
-
- self.load_dropdown_data()
-
- # 如果是在修改模式,填充数据
- if self.plan:
- # 显示计划号
- plan_no = self.plan.get('plan_no', '')
- if plan_no:
- self.plan_no_display.setText(plan_no)
- else:
- self.plan_no_display.setText("未生成")
-
- # 开始时间和结束时间
- start_date = self.plan.get('start_date') or self.plan.get('plan_date', '')
- if start_date:
- self.start_date_input.setDate(QDate.fromString(start_date, "yyyy-MM-dd"))
-
- end_date = self.plan.get('end_date') or self.plan.get('plan_date', '')
- if end_date:
- self.end_date_input.setDate(QDate.fromString(end_date, "yyyy-MM-dd"))
-
- if self.plan['business_type'] == '出库':
- self.business_sale_radio.setChecked(True)
- else:
- self.business_purchase_radio.setChecked(True)
- self._ensure_combo_value(self.product_combo, self.plan['product'])
- self.quantity_input.setValue(self.plan['planned_quantity'])
- self._ensure_combo_value(self.customer_combo, self.plan.get('customer_name', ''))
- self.remarks_input.setPlainText(self.plan.get('remarks', ''))
-
- layout.addLayout(form_layout)
-
- # 按钮
- button_layout = QHBoxLayout()
- button_layout.addStretch()
-
- ok_btn = QPushButton("确定")
- ok_btn.setMinimumHeight(45)
- ok_btn.setMinimumWidth(100)
- ok_btn.setFont(QFont("微软雅黑", 16))
- apply_button_style(ok_btn, 'green')
- ok_btn.clicked.connect(self.save)
-
- cancel_btn = QPushButton("取消")
- cancel_btn.setMinimumHeight(45)
- cancel_btn.setMinimumWidth(100)
- cancel_btn.setFont(QFont("微软雅黑", 16))
- apply_button_style(cancel_btn, 'normal')
- cancel_btn.clicked.connect(self.reject)
-
- button_layout.addWidget(ok_btn)
- button_layout.addWidget(cancel_btn)
-
- layout.addLayout(button_layout)
- self.setLayout(layout)
-
- def load_dropdown_data(self):
- """加载产品与往来单位下拉选项"""
- # 产品下拉来自货物维护
- self.product_combo.clear()
- self.product_combo.addItem("")
- product_names = [""]
- cargos = self.db.get_all_cargos()
- for cargo in cargos:
- name = cargo.get('name', '').strip()
- if name:
- self.product_combo.addItem(name)
- product_names.append(name)
- self.product_combo.setCurrentIndex(0)
- self._set_combo_completer(self.product_combo, product_names)
-
- # 往来单位下拉来自客户(沿用公司维护的数据)
- self.customer_combo.clear()
- self.customer_combo.addItem("")
- customer_names = [""]
- customers = self.db.get_all_companies()
- for customer in customers:
- name = customer.get('name', '').strip()
- if name:
- self.customer_combo.addItem(name)
- customer_names.append(name)
- self.customer_combo.setCurrentIndex(0)
- self._set_combo_completer(self.customer_combo, customer_names)
-
- def _ensure_combo_value(self, combo: QComboBox, value: str):
- """确保下拉框中存在给定的值并选中"""
- if not value:
- combo.setCurrentIndex(0)
- return
- index = combo.findText(value)
- if index < 0:
- combo.addItem(value)
- index = combo.findText(value)
- self._set_combo_completer(
- combo,
- [combo.itemText(i) for i in range(combo.count()) if combo.itemText(i)]
- )
- combo.setCurrentIndex(max(0, index))
-
- def _set_combo_completer(self, combo: QComboBox, options):
- """为下拉框配置模糊匹配的补全器"""
- cleaned = [opt for opt in options if opt]
- completer = QCompleter(cleaned, combo)
- completer.setFilterMode(Qt.MatchContains)
- completer.setCaseSensitivity(Qt.CaseInsensitive)
- completer.setCompletionMode(QCompleter.PopupCompletion)
- combo.setCompleter(completer)
-
- def save(self):
- """保存"""
- # 验证
- if not self.start_date_input.date().isValid():
- QMessageBox.warning(self, "验证失败", "请选择开始时间")
- return
-
- if not self.end_date_input.date().isValid():
- QMessageBox.warning(self, "验证失败", "请选择结束时间")
- return
-
- if not self.business_type_group.checkedButton():
- QMessageBox.warning(self, "验证失败", "请选择业务类型")
- return
-
- product = self.product_combo.currentText().strip()
- if not product:
- QMessageBox.warning(self, "验证失败", "产品不能为空")
- return
-
- if self.quantity_input.value() <= 0:
- QMessageBox.warning(self, "验证失败", "计划量必须大于0")
- return
-
- partner = self.customer_combo.currentText().strip()
- if not partner:
- QMessageBox.warning(self, "验证失败", "往来单位不能为空")
- return
-
- # 准备数据
- start_date = self.start_date_input.date().toString("yyyy-MM-dd")
- end_date = self.end_date_input.date().toString("yyyy-MM-dd")
- plan_date = start_date # 保留plan_date用于兼容
-
- data = {
- 'start_date': start_date,
- 'end_date': end_date,
- 'plan_date': plan_date,
- 'business_type': self.business_type_group.checkedButton().text(),
- 'product': product,
- 'specification': self.plan.get('specification', '') if self.plan else '',
- 'planned_quantity': self.quantity_input.value(),
- 'customer_name': partner,
- 'remarks': self.remarks_input.toPlainText().strip()
- }
-
- # 如果是修改模式,保留计划号
- if self.plan:
- plan_no = self.plan.get('plan_no', '')
- if plan_no:
- data['plan_no'] = plan_no
-
- # 保存
- if self.plan:
- # 修改模式
- if self.db.update_purchase_plan(self.plan['id'], data):
- QMessageBox.information(self, "成功", "修改成功!")
- self.accept()
- else:
- QMessageBox.warning(self, "错误", "修改失败")
- else:
- # 新增模式(计划号会自动生成)
- try:
- self.db.insert_purchase_plan(data)
- QMessageBox.information(self, "成功", "新增成功!")
- self.accept()
- except Exception as e:
- QMessageBox.critical(self, "错误", f"新增失败:{str(e)}")
- class PlanDetailDialog(QDialog):
- """计划详情对话框"""
-
- def __init__(self, db: Database, plan: dict, parent=None):
- super().__init__(parent)
- self.db = db
- self.plan = plan
- self.inbound_list = self.db.get_inbound_outbound_by_plan_id(plan['id'])
- self.slip_list = self.db.get_weighing_slips_by_plan_id(plan['id'])
- self.slips_by_inbound = self._group_slips_by_inbound()
- self.unlinked_slips = [slip for slip in self.slip_list if not slip.get('inbound_outbound_id')]
- self.init_ui()
-
- def _format_weight_in_tons(self, kg_value: float, digits: int = 3) -> str:
- """将公斤转换为吨并格式化"""
- if kg_value is None:
- kg_value = 0
- return f"{kg_value / 1000:.{digits}f}"
- def init_ui(self):
- plan_no = self.plan.get('plan_no') or f"ID-{self.plan.get('id')}"
- self.setWindowTitle(f"计划详情 - {plan_no}")
- self.resize(1080, 720)
-
- layout = QVBoxLayout()
- layout.setContentsMargins(20, 20, 20, 20)
- layout.setSpacing(12)
-
- scroll_area = QScrollArea()
- scroll_area.setWidgetResizable(True)
-
- content_widget = QWidget()
- content_layout = QVBoxLayout()
- content_layout.setSpacing(18)
-
- content_layout.addWidget(self._create_plan_info_group())
-
- if not self.inbound_list:
- empty_label = QLabel("暂无关联的出入库单。")
- empty_label.setFont(QFont("微软雅黑", 14))
- content_layout.addWidget(empty_label)
- else:
- for index, inbound in enumerate(self.inbound_list, start=1):
- content_layout.addWidget(self._create_inbound_slip_section(index, inbound))
-
- if self.unlinked_slips:
- content_layout.addWidget(self._create_unlinked_slip_section())
-
- content_layout.addStretch()
- content_widget.setLayout(content_layout)
- scroll_area.setWidget(content_widget)
-
- layout.addWidget(scroll_area)
-
- button_layout = QHBoxLayout()
- button_layout.addStretch()
- close_btn = QPushButton("关闭")
- close_btn.setMinimumHeight(40)
- close_btn.setMinimumWidth(120)
- close_btn.setFont(QFont("微软雅黑", 16))
- apply_button_style(close_btn, 'normal')
- close_btn.clicked.connect(self.accept)
- button_layout.addWidget(close_btn)
- layout.addLayout(button_layout)
-
- self.setLayout(layout)
-
- def _group_slips_by_inbound(self):
- grouped = {}
- for slip in self.slip_list:
- inbound_id = slip.get('inbound_outbound_id')
- if not inbound_id:
- continue
- grouped.setdefault(inbound_id, []).append(slip)
- return grouped
-
- def _create_plan_info_group(self) -> QGroupBox:
- group = QGroupBox("计划单信息")
- group.setFont(QFont("微软雅黑", 15, QFont.Bold))
- form = QFormLayout()
- form.setHorizontalSpacing(30)
- form.setVerticalSpacing(10)
-
- executed_kg = self.plan.get('executed_quantity') or 0
- executed_tons = executed_kg / 1000 if executed_kg else 0
- planned_tons = self.plan.get('planned_quantity') or 0
-
- rows = [
- ("计划号:", self.plan.get('plan_no', '未生成')),
- ("往来单位:", self.plan.get('customer_name', '')),
- ("业务类型:", self.plan.get('business_type', '')),
- ("产品:", self.plan.get('product', '')),
- ("计划量(t):", f"{planned_tons:.3f}"),
- ("已执行量(t):", f"{executed_tons:.3f}"),
- ("状态:", self.plan.get('execution_status', '')),
- ("开始时间:", self.plan.get('start_date') or self.plan.get('plan_date', '')),
- ("结束时间:", self.plan.get('end_date') or self.plan.get('plan_date', '')),
- ("备注:", self.plan.get('remarks', '') or '')
- ]
-
- for label, value in rows:
- lbl = QLabel(label)
- lbl.setFont(QFont("微软雅黑", 14, QFont.Bold))
- val = QLabel(str(value))
- val.setFont(QFont("微软雅黑", 14))
- val.setWordWrap(True)
- form.addRow(lbl, val)
-
- group.setLayout(form)
- return group
-
- def _create_inbound_slip_section(self, index: int, inbound: dict) -> QGroupBox:
- group = QGroupBox(f"出入库单 {index}")
- group.setFont(QFont("微软雅黑", 15, QFont.Bold))
- group_layout = QHBoxLayout()
- group_layout.setSpacing(20)
- group_layout.setContentsMargins(15, 15, 15, 15)
-
- inbound_widget = self._create_inbound_info_widget(inbound)
- slips_widget = self._create_slip_list_widget(self.slips_by_inbound.get(inbound.get('id'), []))
-
- group_layout.addWidget(inbound_widget, 1)
- group_layout.addWidget(slips_widget, 1)
- group.setLayout(group_layout)
- return group
-
- def _create_inbound_info_widget(self, inbound: dict) -> QWidget:
- widget = QWidget()
- form = QFormLayout()
- form.setHorizontalSpacing(20)
- form.setVerticalSpacing(8)
-
- rows = [
- ("日期:", inbound.get('date', '')),
- ("往来单位:", inbound.get('partner_company', '')),
- ("业务类型:", inbound.get('business_type', '')),
- ("产品:", inbound.get('product', '')),
- ("数量(t):", f"{inbound.get('quantity', 0):.3f}"),
- ("状态:", inbound.get('status', '')),
- ("批次号:", inbound.get('batch_no', '')),
- ("车牌号:", inbound.get('vehicle_no', '')),
- ("备注:", inbound.get('remarks', '') or '')
- ]
-
- for label, value in rows:
- lbl = QLabel(label)
- lbl.setFont(QFont("微软雅黑", 13, QFont.Bold))
- val = QLabel(str(value))
- val.setFont(QFont("微软雅黑", 13))
- val.setWordWrap(True)
- form.addRow(lbl, val)
-
- widget.setLayout(form)
- return widget
-
- def _create_slip_list_widget(self, slips: list) -> QWidget:
- widget = QWidget()
- layout = QVBoxLayout()
- layout.setSpacing(10)
-
- title = QLabel("地磅单信息")
- title.setFont(QFont("微软雅黑", 14, QFont.Bold))
- layout.addWidget(title)
-
- if not slips:
- empty = QLabel("暂无关联地磅单。")
- empty.setFont(QFont("微软雅黑", 13))
- layout.addWidget(empty)
- else:
- for idx, slip in enumerate(slips, start=1):
- slip_frame = QFrame()
- slip_frame.setFrameShape(QFrame.StyledPanel)
- slip_frame_layout = QFormLayout()
- slip_frame_layout.setHorizontalSpacing(18)
- slip_frame_layout.setVerticalSpacing(6)
-
- rows = [
- (f"地磅单 {idx}:", f"#{slip.get('id', '')}"),
- ("车牌号:", slip.get('vehicle_no', '')),
- ("货物:", slip.get('cargo_name', '')),
- ("业务类型:", slip.get('business_type', '')),
- ("毛重(t):", self._format_weight_in_tons(slip.get('gross_weight', 0))),
- ("皮重(t):", self._format_weight_in_tons(slip.get('tare_weight', 0))),
- ("净重(t):", self._format_weight_in_tons(slip.get('net_weight', 0))),
- ("扣量(t):", self._format_weight_in_tons(slip.get('deduction', 0))),
- ("过磅时间:", slip.get('created_at', ''))
- ]
-
- for label, value in rows:
- lbl = QLabel(label)
- lbl.setFont(QFont("微软雅黑", 12, QFont.Bold))
- val = QLabel(str(value))
- val.setFont(QFont("微软雅黑", 12))
- slip_frame_layout.addRow(lbl, val)
-
- slip_frame.setLayout(slip_frame_layout)
- layout.addWidget(slip_frame)
-
- widget.setLayout(layout)
- return widget
-
- def _create_unlinked_slip_section(self) -> QGroupBox:
- group = QGroupBox("未关联出入库单的地磅单")
- group.setFont(QFont("微软雅黑", 15, QFont.Bold))
- layout = QVBoxLayout()
- layout.setSpacing(10)
-
- for idx, slip in enumerate(self.unlinked_slips, start=1):
- slip_frame = QFrame()
- slip_frame.setFrameShape(QFrame.StyledPanel)
- slip_layout = QFormLayout()
- slip_layout.setHorizontalSpacing(18)
- slip_layout.setVerticalSpacing(6)
- rows = [
- (f"地磅单 {idx}:", f"#{slip.get('id', '')}"),
- ("车牌号:", slip.get('vehicle_no', '')),
- ("货物:", slip.get('cargo_name', '')),
- ("业务类型:", slip.get('business_type', '')),
- ("净重(t):", self._format_weight_in_tons(slip.get('net_weight', 0))),
- ("过磅时间:", slip.get('created_at', ''))
- ]
- for label, value in rows:
- lbl = QLabel(label)
- lbl.setFont(QFont("微软雅黑", 12, QFont.Bold))
- val = QLabel(str(value))
- val.setFont(QFont("微软雅黑", 12))
- slip_layout.addRow(lbl, val)
- slip_frame.setLayout(slip_layout)
- layout.addWidget(slip_frame)
-
- group.setLayout(layout)
- return group
|