| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912 |
- """
- 地磅单管理Tab页面
- """
- from PyQt5.QtWidgets import (
- QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QComboBox,
- QRadioButton, QButtonGroup, QDateTimeEdit, QTextEdit, QPushButton,
- QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox, QDialog,
- QFormLayout, QSplitter, QGroupBox, QDoubleSpinBox, QGridLayout,
- QFileDialog, QSizePolicy, QCheckBox, QScrollArea, QFrame
- )
- from PyQt5.QtCore import Qt, QDateTime, pyqtSignal, QTimer, QEvent
- from PyQt5.QtGui import QFont, QColor, QBrush, QKeyEvent, QKeySequence
- from datetime import datetime
- from typing import Tuple, Optional
- import logging
- import sip
- import time
- from database import Database
- from utils.printer import Printer
- from .button_styles import apply_button_style, get_button_color_type
- import pandas as pd
- logger = logging.getLogger(__name__)
- startup_logger = logging.getLogger('startup')
- DEFAULT_PRINT_COPIES = 1
- def kg_to_tons(value: Optional[float]) -> Optional[float]:
- if value is None:
- return None
- return value / 1000.0
- def tons_to_kg(value: Optional[float]) -> Optional[float]:
- if value is None:
- return None
- return value * 1000.0
- class EmptyDoubleSpinBox(QDoubleSpinBox):
- """自定义QDoubleSpinBox,当值为-1时显示为空"""
-
- def textFromValue(self, value: float) -> str:
- """重写文本显示方法,当值为-1时返回空字符串"""
- if value == -1:
- return ""
- return super().textFromValue(value)
-
- def valueFromText(self, text: str) -> float:
- """重写文本解析方法,当文本为空时返回-1"""
- if not text or text.strip() == "":
- return -1
- return super().valueFromText(text)
- class EmptyDateTimeEdit(QDateTimeEdit):
- """自定义QDateTimeEdit,当日期时间为空值时显示为空字符串"""
-
- def __init__(self, parent=None):
- super().__init__(parent)
- self._is_empty = True
- self._placeholder_datetime = QDateTime.fromString("2000-01-01 00:00:00", "yyyy-MM-dd HH:mm:ss")
- super().setDateTime(self._placeholder_datetime)
- self._sync_line_edit()
-
- def _sync_line_edit(self):
- """根据当前空状态同步行编辑器的显示"""
- line_edit = self.lineEdit()
- if not line_edit:
- return
- if self._is_empty:
- line_edit.setText("")
- else:
- line_edit.setText(super().textFromDateTime(super().dateTime()))
-
- def setDateTime(self, date_time: QDateTime):
- """重写设置日期时间方法,支持显示为空"""
- if not date_time.isValid():
- self._is_empty = True
- super().setDateTime(self._placeholder_datetime)
- self._sync_line_edit()
- return
-
- self._is_empty = False
- super().setDateTime(date_time)
- self._sync_line_edit()
-
- def dateTime(self) -> QDateTime:
- """当为空时返回一个无效的QDateTime"""
- if self._is_empty:
- return QDateTime()
- return super().dateTime()
-
- def textFromDateTime(self, date_time: QDateTime) -> str:
- """空状态显示为空字符串"""
- if self._is_empty:
- return ""
- return super().textFromDateTime(date_time)
- class WeighingTab(QWidget):
- """地磅单管理Tab"""
-
- def __init__(self, db: Database):
- tab_start = time.time()
- super().__init__()
- self.db = db
- self.printer = Printer()
- self.print_copies = DEFAULT_PRINT_COPIES
- self._is_clearing_form = False
- self.current_plan: Optional[dict] = None
- self.current_inbound_id: Optional[int] = None
- self.editing_slip_id: Optional[int] = None
-
- ui_start = time.time()
- self.init_ui()
- startup_logger.info(f" 界面初始化 (耗时: {time.time() - ui_start:.3f}秒)")
-
- dropdown_start = time.time()
- self.refresh_dropdowns()
- startup_logger.info(f" 下拉框数据加载 (耗时: {time.time() - dropdown_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(10, 10, 10, 10)
-
- # 创建分割器:上部自适应高度,下部占据剩余空间
- splitter = QSplitter(Qt.Vertical)
-
- self.form_widget = self.create_form_widget()
- self.form_widget.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
- self._update_form_widget_height()
- splitter.addWidget(self.form_widget)
-
- list_widget = self.create_list_widget()
- splitter.addWidget(list_widget)
-
- splitter.setStretchFactor(0, 0)
- splitter.setStretchFactor(1, 1)
-
- layout.addWidget(splitter)
- self.setLayout(layout)
-
- def create_form_widget(self) -> QWidget:
- """创建地磅单填写表单(左侧读数区 + 右侧填写区)"""
- widget = QWidget()
- layout = QVBoxLayout()
- layout.setSpacing(8)
- layout.setContentsMargins(10, 10, 10, 10)
-
- # 标题
- title = QLabel("地磅单填写")
- title_font = QFont("微软雅黑", 16, QFont.Bold)
- title.setFont(title_font)
- layout.addWidget(title)
-
- # 顶部内容区域:左侧地磅读数区 + 右侧表单填写区
- content_layout = QHBoxLayout()
- content_layout.setSpacing(16)
-
- # =========================
- # 左侧:地磅读数区域
- # =========================
- left_group = QGroupBox("地磅读数")
- left_layout = QVBoxLayout()
- left_layout.setContentsMargins(10, 10, 10, 10)
- left_layout.setSpacing(12)
- # 读数显示(单位 kg)
- self.scale_display_label = QLabel("0.00 kg")
- self.scale_display_label.setAlignment(Qt.AlignCenter)
- self.scale_display_label.setMinimumHeight(80)
- self.scale_display_label.setFont(QFont("微软雅黑", 24, QFont.Bold))
- self.scale_display_label.setStyleSheet("border-radius: 6px; border: 2px solid #424242; padding: 8px;")
- # 按钮区域:读毛重 / 读皮重
- self.read_gross_btn = QPushButton("读毛重")
- self.read_gross_btn.setMinimumHeight(40)
- self.read_gross_btn.setFont(QFont("微软雅黑", 14, QFont.Bold))
- apply_button_style(self.read_gross_btn, 'blue')
- self.read_tare_btn = QPushButton("读皮重")
- self.read_tare_btn.setMinimumHeight(40)
- self.read_tare_btn.setFont(QFont("微软雅黑", 14, QFont.Bold))
- apply_button_style(self.read_tare_btn, 'blue')
- read_btn_layout = QHBoxLayout()
- read_btn_layout.setSpacing(12)
- read_btn_layout.addWidget(self.read_gross_btn)
- read_btn_layout.addWidget(self.read_tare_btn)
- left_layout.addWidget(self.scale_display_label)
- left_layout.addLayout(read_btn_layout)
- left_layout.addStretch()
- left_group.setLayout(left_layout)
- # =========================
- # 右侧:表单填写区域(原有表单)
- # =========================
- right_widget = QWidget()
- right_layout = QVBoxLayout()
- right_layout.setContentsMargins(0, 0, 0, 0)
- right_layout.setSpacing(0)
- # 表单区域 - 使用网格布局,一行放4个字段(8列,label+控件各占1列)
- form_layout = QGridLayout()
- form_layout.setSpacing(12)
- form_layout.setColumnStretch(1, 1)
- form_layout.setColumnStretch(3, 1)
- form_layout.setColumnStretch(5, 1)
- form_layout.setColumnStretch(7, 1)
-
- # 创建控件
- # 必填字段在前,非必填字段在后
- # 必填字段label为红色,非必填字段label为黑色
- row = 0
-
- # 第一行:车号(必填)、货物名称(必填)、业务类型(必填)
- # 车号(必填)
- vehicle_label = QLabel("<span style='color: red;'>车号 *</span>:")
- vehicle_label.setFont(QFont("微软雅黑", 16))
- vehicle_label.setTextFormat(Qt.RichText)
- self.vehicle_no_input = QLineEdit()
- self.vehicle_no_input.setMinimumHeight(40)
- self.vehicle_no_input.setFont(QFont("微软雅黑", 16))
- form_layout.addWidget(vehicle_label, row, 0)
- form_layout.addWidget(self.vehicle_no_input, row, 1)
-
- # 货物名称(必填)
- cargo_label = QLabel("<span style='color: red;'>货物名称 *</span>:")
- cargo_label.setFont(QFont("微软雅黑", 16))
- cargo_label.setTextFormat(Qt.RichText)
- self.cargo_combo = QComboBox()
- self.cargo_combo.setMinimumHeight(40)
- self.cargo_combo.setFont(QFont("微软雅黑", 16))
- self.cargo_combo.setEditable(False)
- form_layout.addWidget(cargo_label, row, 2)
- form_layout.addWidget(self.cargo_combo, row, 3)
- # 业务类型(必填)- 选中的显示为红色
- business_label = QLabel("<span style='color: red;'>业务类型 *</span>:")
- business_label.setFont(QFont("微软雅黑", 16))
- business_label.setTextFormat(Qt.RichText)
- 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.addWidget(business_label, row, 4)
- form_layout.addWidget(business_widget, row, 5)
-
- row += 1
-
- # 第二行:供货单位(必填)、收货单位(必填)、批号(非必填)、计划关联信息
- supplier_label = QLabel("<span style='color: red;'>供货单位 *</span>:")
- supplier_label.setFont(QFont("微软雅黑", 16))
- supplier_label.setTextFormat(Qt.RichText)
- self.supplier_combo = QComboBox()
- self.supplier_combo.setMinimumHeight(40)
- self.supplier_combo.setFont(QFont("微软雅黑", 16))
- self.supplier_combo.setEditable(False)
- form_layout.addWidget(supplier_label, row, 0)
- form_layout.addWidget(self.supplier_combo, row, 1)
-
- consignee_label = QLabel("<span style='color: red;'>收货单位 *</span>:")
- consignee_label.setFont(QFont("微软雅黑", 16))
- consignee_label.setTextFormat(Qt.RichText)
- self.consignee_combo = QComboBox()
- self.consignee_combo.setMinimumHeight(40)
- self.consignee_combo.setFont(QFont("微软雅黑", 16))
- self.consignee_combo.setEditable(False)
- form_layout.addWidget(consignee_label, row, 2)
- form_layout.addWidget(self.consignee_combo, row, 3)
-
- # 计划号(非必填)- 移动到原批号位置
- plan_label = QLabel("计划号:")
- plan_label.setFont(QFont("微软雅黑", 16))
- self.plan_no_input = QLineEdit()
- self.plan_no_input.setMinimumHeight(40)
- self.plan_no_input.setFont(QFont("微软雅黑", 16))
- # 添加计划号变化监听,自动查询计划并填充计划量和已执行量
- self.plan_no_input.textChanged.connect(self.on_plan_no_changed)
- form_layout.addWidget(plan_label, row, 4)
- form_layout.addWidget(self.plan_no_input, row, 5)
-
- # 批号 - 移动到原“关联计划”位置
- batch_label = QLabel("批号:")
- batch_label.setFont(QFont("微软雅黑", 16))
- self.batch_no_input = QLineEdit()
- self.batch_no_input.setMinimumHeight(40)
- self.batch_no_input.setFont(QFont("微软雅黑", 16))
- form_layout.addWidget(batch_label, row, 6)
- form_layout.addWidget(self.batch_no_input, row, 7)
-
- # 计划关联信息控件仍保留,但不加入布局,用于后台逻辑显示状态
- plan_bind_label = QLabel("关联计划:")
- plan_bind_label.setFont(QFont("微软雅黑", 16))
- self.plan_binding_label = QLabel("未关联")
- self.plan_binding_label.setMinimumHeight(40)
- self.plan_binding_label.setFont(QFont("微软雅黑", 16))
- self.plan_binding_label.setStyleSheet("")
-
- row += 1
-
- # 第三行:毛重(必填)、毛重时间(必填)、备注(占两个元素的宽度)
- gross_weight_label = QLabel("<span style='color: red;'>毛重(kg) *</span>:")
- gross_weight_label.setFont(QFont("微软雅黑", 16))
- gross_weight_label.setTextFormat(Qt.RichText)
- self.gross_weight_input = EmptyDoubleSpinBox()
- self.gross_weight_input.setMinimumHeight(40)
- self.gross_weight_input.setFont(QFont("微软雅黑", 16))
- self.gross_weight_input.setDecimals(2)
- self.gross_weight_input.setMinimum(-1)
- self.gross_weight_input.setMaximum(999999)
- self.gross_weight_input.setSpecialValueText("")
- self.gross_weight_input.setValue(-1)
- self.gross_weight_input.valueChanged.connect(self.on_gross_weight_changed)
- form_layout.addWidget(gross_weight_label, row, 0)
- form_layout.addWidget(self.gross_weight_input, row, 1)
-
- gross_time_label = QLabel("<span style='color: red;'>毛重时间 *</span>:")
- gross_time_label.setFont(QFont("微软雅黑", 16))
- gross_time_label.setTextFormat(Qt.RichText)
- self.gross_weight_time = EmptyDateTimeEdit()
- self.gross_weight_time.setMinimumHeight(40)
- self.gross_weight_time.setFont(QFont("微软雅黑", 16))
- self.gross_weight_time.setCalendarPopup(True)
- # 不设置默认时间,使用一个无效的日期时间表示未设置
- self.gross_weight_time.setDateTime(QDateTime())
- self.gross_weight_time.setDisplayFormat("yyyy-MM-dd HH:mm:ss")
- # 强制清空显示
- if self.gross_weight_time.lineEdit():
- self.gross_weight_time.lineEdit().setText("")
- QTimer.singleShot(0, lambda: self.gross_weight_time.lineEdit().setText("") if self.gross_weight_time.lineEdit() else None)
- # 直接使用时间控件,占一整列宽度
- form_layout.addWidget(gross_time_label, row, 2)
- form_layout.addWidget(self.gross_weight_time, row, 3)
-
- # 备注(占两个元素的宽度,即4列)
- remarks_label = QLabel("备注:")
- remarks_label.setFont(QFont("微软雅黑", 16))
- self.remarks_input = QTextEdit()
- self.remarks_input.setFixedHeight(self.batch_no_input.minimumHeight() + 5)
- self.remarks_input.setFont(QFont("微软雅黑", 16))
- form_layout.addWidget(remarks_label, row, 4)
- form_layout.addWidget(self.remarks_input, row, 5, 1, 3)
-
- row += 1
-
- # 第四行:皮重(必填)、皮重时间(必填)、计划量、已执行量
- tare_weight_label = QLabel("<span style='color: red;'>皮重(kg) *</span>:")
- tare_weight_label.setFont(QFont("微软雅黑", 16))
- tare_weight_label.setTextFormat(Qt.RichText)
- self.tare_weight_input = EmptyDoubleSpinBox()
- self.tare_weight_input.setMinimumHeight(40)
- self.tare_weight_input.setFont(QFont("微软雅黑", 16))
- self.tare_weight_input.setDecimals(2)
- self.tare_weight_input.setMinimum(-1)
- self.tare_weight_input.setMaximum(999999)
- self.tare_weight_input.setSpecialValueText("")
- self.tare_weight_input.setValue(-1)
- self.tare_weight_input.valueChanged.connect(self.on_tare_weight_changed)
- form_layout.addWidget(tare_weight_label, row, 0)
- form_layout.addWidget(self.tare_weight_input, row, 1)
-
- tare_time_label = QLabel("<span style='color: red;'>皮重时间 *</span>:")
- tare_time_label.setFont(QFont("微软雅黑", 16))
- tare_time_label.setTextFormat(Qt.RichText)
- self.tare_weight_time = EmptyDateTimeEdit()
- self.tare_weight_time.setMinimumHeight(40)
- self.tare_weight_time.setFont(QFont("微软雅黑", 16))
- self.tare_weight_time.setCalendarPopup(True)
- # 不设置默认时间,使用一个无效的日期时间表示未设置
- self.tare_weight_time.setDateTime(QDateTime())
- self.tare_weight_time.setDisplayFormat("yyyy-MM-dd HH:mm:ss")
- # 强制清空显示
- if self.tare_weight_time.lineEdit():
- self.tare_weight_time.lineEdit().setText("")
- QTimer.singleShot(0, lambda: self.tare_weight_time.lineEdit().setText("") if self.tare_weight_time.lineEdit() else None)
- # 直接使用时间控件,占一整列宽度
- form_layout.addWidget(tare_time_label, row, 2)
- form_layout.addWidget(self.tare_weight_time, row, 3)
-
- planned_label = QLabel("计划量(t):")
- planned_label.setFont(QFont("微软雅黑", 16))
- self.planned_quantity_input = EmptyDoubleSpinBox()
- self.planned_quantity_input.setMinimumHeight(40)
- self.planned_quantity_input.setFont(QFont("微软雅黑", 16))
- self.planned_quantity_input.setDecimals(3)
- self.planned_quantity_input.setMinimum(-1)
- self.planned_quantity_input.setMaximum(999999)
- self.planned_quantity_input.setSpecialValueText("")
- self.planned_quantity_input.setValue(-1)
- form_layout.addWidget(planned_label, row, 4)
- form_layout.addWidget(self.planned_quantity_input, row, 5)
-
- executed_label = QLabel("已执行量(t):")
- executed_label.setFont(QFont("微软雅黑", 16))
- self.executed_quantity_input = EmptyDoubleSpinBox()
- self.executed_quantity_input.setMinimumHeight(40)
- self.executed_quantity_input.setFont(QFont("微软雅黑", 16))
- self.executed_quantity_input.setDecimals(3)
- self.executed_quantity_input.setMinimum(-1)
- self.executed_quantity_input.setMaximum(999999)
- self.executed_quantity_input.setSpecialValueText("")
- self.executed_quantity_input.setValue(-1)
- form_layout.addWidget(executed_label, row, 6)
- form_layout.addWidget(self.executed_quantity_input, row, 7)
-
- row += 1
-
- # 第五行:扣杂、净重(只读)、本次量
- deduction_label = QLabel("扣杂(kg):")
- deduction_label.setFont(QFont("微软雅黑", 16))
- self.deduction_input = EmptyDoubleSpinBox()
- self.deduction_input.setMinimumHeight(40)
- self.deduction_input.setFont(QFont("微软雅黑", 16))
- self.deduction_input.setDecimals(2)
- self.deduction_input.setMinimum(-1)
- self.deduction_input.setMaximum(999999)
- self.deduction_input.setSpecialValueText("")
- self.deduction_input.setValue(-1)
- self.deduction_input.valueChanged.connect(self.calculate_net_weight)
- form_layout.addWidget(deduction_label, row, 0)
- form_layout.addWidget(self.deduction_input, row, 1)
-
- net_weight_label = QLabel("净重(t):")
- net_weight_label.setFont(QFont("微软雅黑", 16))
- self.net_weight_label = QLabel("0.000 t")
- self.net_weight_label.setMinimumHeight(40)
- self.net_weight_label.setFont(QFont("微软雅黑", 16))
- self.net_weight_label.setStyleSheet("padding: 5px; border: 1px solid #ccc;")
- form_layout.addWidget(net_weight_label, row, 2)
- form_layout.addWidget(self.net_weight_label, row, 3)
-
- # 本次量(kg)
- current_quantity_label = QLabel("本次量(t):")
- current_quantity_label.setFont(QFont("微软雅黑", 16))
- self.current_quantity_input = EmptyDoubleSpinBox()
- self.current_quantity_input.setMinimumHeight(40)
- self.current_quantity_input.setFont(QFont("微软雅黑", 16))
- self.current_quantity_input.setDecimals(3)
- self.current_quantity_input.setMinimum(-1)
- self.current_quantity_input.setMaximum(999999)
- self.current_quantity_input.setSpecialValueText("")
- self.current_quantity_input.setValue(-1)
- form_layout.addWidget(current_quantity_label, row, 4)
- form_layout.addWidget(self.current_quantity_input, row, 5)
-
- # 按钮区域
- row += 1
- button_layout = QHBoxLayout()
- button_layout.addStretch()
-
- self.save_btn = QPushButton("保存")
- self.save_btn.setMinimumHeight(35)
- self.save_btn.setMinimumWidth(120)
- self.save_btn.setFont(QFont("微软雅黑", 14, QFont.Bold))
- apply_button_style(self.save_btn, 'green')
- self.save_btn.clicked.connect(self.save_weighing_slip)
- # 添加快捷键
- self.save_btn.setShortcut(QKeySequence("Ctrl+S"))
-
- self.clear_btn = QPushButton("清空")
- self.clear_btn.setMinimumHeight(35)
- self.clear_btn.setMinimumWidth(120)
- self.clear_btn.setFont(QFont("微软雅黑", 14))
- apply_button_style(self.clear_btn, 'normal')
- self.clear_btn.clicked.connect(self.clear_form)
-
- button_layout.addWidget(self.save_btn)
- button_layout.addWidget(self.clear_btn)
- button_layout.addStretch()
-
- button_widget = QWidget()
- button_widget.setLayout(button_layout)
- form_layout.addWidget(button_widget, row, 0, 1, 8)
-
- # 将表单布局加入右侧容器
- right_layout.addLayout(form_layout)
- right_widget.setLayout(right_layout)
- # 将左右区域加入水平布局
- content_layout.addWidget(left_group)
- content_layout.addWidget(right_widget)
- # 右侧填写区域整体略窄于原先的满宽,给左侧读数区留出空间
- content_layout.setStretch(0, 1)
- content_layout.setStretch(1, 3)
- # 顶部内容区域加入主布局
- layout.addLayout(content_layout)
-
- # 包装在GroupBox中
- group_box = QGroupBox()
- group_box.setLayout(layout)
-
- return group_box
-
- def create_list_widget(self) -> QWidget:
- """创建地磅单记录列表"""
- widget = QWidget()
- layout = QVBoxLayout()
- layout.setContentsMargins(10, 10, 10, 10)
-
- # 标题和刷新按钮区域
- title_layout = QHBoxLayout()
- title = QLabel("地磅单记录列表")
- title_font = QFont("微软雅黑", 18, QFont.Bold)
- title.setFont(title_font)
- title_layout.addWidget(title)
- title_layout.addStretch()
- # 视图切换按钮:列表 / 卡片
- # 默认使用卡片视图,方便一屏查看更多信息
- self.view_mode = "card"
- self.table_view_btn = QPushButton("列表视图")
- self.table_view_btn.setCheckable(True)
- self.table_view_btn.setChecked(False)
- self.table_view_btn.setFont(QFont("微软雅黑", 13))
- apply_button_style(self.table_view_btn, 'normal')
- self.card_view_btn = QPushButton("卡片视图")
- self.card_view_btn.setCheckable(True)
- self.card_view_btn.setFont(QFont("微软雅黑", 13))
- apply_button_style(self.card_view_btn, 'normal')
- self.table_view_btn.clicked.connect(lambda: self._switch_view_mode("table"))
- self.card_view_btn.clicked.connect(lambda: self._switch_view_mode("card"))
- title_layout.addWidget(self.table_view_btn)
- title_layout.addWidget(self.card_view_btn)
- # 只显示毛重或皮重未完成的勾选框(默认勾选)
- self.incomplete_only_checkbox = QCheckBox("仅显示毛重/皮重未完成")
- self.incomplete_only_checkbox.setChecked(True)
- self.incomplete_only_checkbox.setFont(QFont("微软雅黑", 13))
- self.incomplete_only_checkbox.stateChanged.connect(lambda _: self.refresh_list())
- title_layout.addWidget(self.incomplete_only_checkbox)
-
- self.search_input = QLineEdit()
- self.search_input.setPlaceholderText("检索供货/收货单位、车牌、货物")
- self.search_input.setMinimumHeight(36)
- self.search_input.setMinimumWidth(500)
- self.search_input.setMaximumWidth(600)
- self.search_input.setFont(QFont("微软雅黑", 14))
- self.search_input.setClearButtonEnabled(True)
- self.search_input.textChanged.connect(lambda _: self.refresh_list())
- title_layout.addWidget(self.search_input)
- self.export_btn = QPushButton("导出Excel")
- self.export_btn.setMinimumHeight(40)
- self.export_btn.setMinimumWidth(120)
- self.export_btn.setFont(QFont("微软雅黑", 16))
- apply_button_style(self.export_btn, 'normal')
- self.export_btn.clicked.connect(self.export_to_excel)
- title_layout.addWidget(self.export_btn)
-
- self.refresh_btn = QPushButton("刷新")
- self.refresh_btn.setMinimumHeight(40)
- self.refresh_btn.setMinimumWidth(100)
- 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"))
- title_layout.addWidget(self.refresh_btn)
-
- layout.addLayout(title_layout)
-
- # 表格视图
- self.table = QTableWidget()
- # 列顺序:日期、车号、货物名称、业务类型、供货单位、收货单位、毛重/时间、皮重/时间、扣杂、净重、本次量、操作
- self.table.setColumnCount(14)
- self.table.setHorizontalHeaderLabels([
- "日期", "车号", "货物名称", "业务类型", "供货单位", "收货单位",
- "毛重(t)", "毛重时间", "皮重(t)", "皮重时间", "扣杂(t)", "净重(t)", "本次量(t)", "操作"
- ])
- header = self.table.horizontalHeader()
- header.setFont(QFont("微软雅黑", 15, QFont.Bold))
- header.setSectionsMovable(False)
- header.setStretchLastSection(False)
- header.setSectionsClickable(False)
- self.column_width_ratios = [
- 0.08, 0.08, 0.12, 0.08, 0.1, 0.1, 0.07,
- 0.08, 0.07, 0.08, 0.06, 0.07, 0.08, 0.15
- ]
- 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)
-
- layout.addWidget(self.table)
- # 卡片视图:使用 QScrollArea + 容器布局
- self.card_scroll_area = QScrollArea()
- self.card_scroll_area.setWidgetResizable(True)
- self.card_scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
- self.card_container = QWidget()
- # 卡片区域使用网格布局,一行放多个卡片
- self.card_layout = QGridLayout()
- # 外边距和间距都设置为 4px,保证 5 个卡片之间用 4px 作为间隔
- self.card_layout.setContentsMargins(4, 4, 4, 4)
- self.card_layout.setHorizontalSpacing(4)
- self.card_layout.setVerticalSpacing(10)
- self.card_container.setLayout(self.card_layout)
- # 一行放 5 个卡片
- self.card_columns = 5
- # 当前卡片控件缓存,用于窗口大小变化时调整宽度
- self._card_widgets = []
- self.card_scroll_area.setWidget(self.card_container)
- # 默认采用卡片视图,表格视图在需要时再显示
- self.card_scroll_area.setVisible(True)
- layout.addWidget(self.card_scroll_area)
-
- widget.setLayout(layout)
- return widget
-
- def calculate_net_weight(self):
- """计算净重"""
- gross = self._get_weight_input_value(self.gross_weight_input) or 0
- tare = self._get_weight_input_value(self.tare_weight_input) or 0
- deduction = self._get_deduction_value()
- net = gross - tare - deduction
- net_tons = kg_to_tons(net)
- if net_tons is None:
- net_tons = 0
- self.net_weight_label.setText(f"{net_tons:.3f} t")
- def on_gross_weight_changed(self, value: float):
- """毛重改变时自动更新时间"""
- self.calculate_net_weight()
- self._maybe_update_weight_time(value, self.gross_weight_time)
- def on_tare_weight_changed(self, value: float):
- """皮重改变时自动更新时间"""
- self.calculate_net_weight()
- self._maybe_update_weight_time(value, self.tare_weight_time)
- def _maybe_update_weight_time(self, value: float, time_edit: EmptyDateTimeEdit):
- """根据重量变化自动填充或清空时间"""
- if self._is_clearing_form:
- return
- if value > 0:
- self._set_time_to_now(time_edit)
- elif value < 0:
- self._clear_time_edit(time_edit)
- def _set_time_to_now(self, time_edit: EmptyDateTimeEdit):
- """将指定时间控件设置为当前时间"""
- current_dt = QDateTime.currentDateTime()
- time_edit.setDateTime(current_dt)
- def _clear_time_edit(self, time_edit: EmptyDateTimeEdit):
- """清空时间控件"""
- time_edit.setDateTime(QDateTime())
-
- def _get_weight_input_value(self, spinbox: EmptyDoubleSpinBox) -> Optional[float]:
- """获取重量输入的实际值,未填则返回None"""
- value = spinbox.value()
- return value if value >= 0 else None
-
- def _get_deduction_value(self) -> float:
- """获取扣杂值,未填返回0"""
- value = self.deduction_input.value()
- return value if value >= 0 else 0
-
- def _get_datetime_text(self, time_edit: EmptyDateTimeEdit) -> str:
- """获取时间控件的文本"""
- line_edit = time_edit.lineEdit()
- return line_edit.text().strip() if line_edit else ""
-
- def _get_datetime_str(self, time_edit: EmptyDateTimeEdit) -> str:
- """将时间控件转换为字符串"""
- if time_edit.dateTime().isValid() and self._get_datetime_text(time_edit):
- return time_edit.dateTime().toString("yyyy-MM-dd HH:mm:ss")
- return ""
-
- def _set_datetime_from_str(self, time_edit: EmptyDateTimeEdit, value: str):
- """根据字符串设置时间控件"""
- if value:
- dt = QDateTime.fromString(value, "yyyy-MM-dd HH:mm:ss")
- if dt.isValid():
- time_edit.setDateTime(dt)
- return
- self._clear_time_edit(time_edit)
- if time_edit.lineEdit():
- time_edit.lineEdit().setText("")
-
- def _ensure_combo_value(self, combo: QComboBox, value: str):
- """确保下拉框中存在指定值并选中"""
- if value is None:
- combo.setCurrentIndex(0)
- return
- text = value.strip()
- if not text:
- combo.setCurrentIndex(0)
- return
- index = combo.findText(text)
- if index < 0:
- combo.addItem(text)
- index = combo.findText(text)
- combo.setCurrentIndex(max(0, index))
-
- @staticmethod
- def _ton_value_from_kg(value: Optional[float]):
- tons = kg_to_tons(value)
- if tons is None:
- return ""
- return round(tons, 3)
-
- def refresh_dropdowns(self):
- """刷新下拉列表"""
- # 刷新货物名称
- self.cargo_combo.clear()
- self.cargo_combo.addItem("") # 添加一个空选项
- cargos = self.db.get_all_cargos()
- for cargo in cargos:
- self.cargo_combo.addItem(cargo['name'])
- self.cargo_combo.setCurrentIndex(0) # 默认选中空选项
-
- # 刷新公司名称(供货单位和收货单位共用)
- self.supplier_combo.clear()
- self.supplier_combo.addItem("") # 添加一个空选项
- self.consignee_combo.clear()
- self.consignee_combo.addItem("") # 添加一个空选项
- companies = self.db.get_all_companies()
- for company in companies:
- self.supplier_combo.addItem(company['name'])
- self.consignee_combo.addItem(company['name'])
- self.supplier_combo.setCurrentIndex(0) # 默认选中空选项
- self.consignee_combo.setCurrentIndex(0) # 默认选中空选项
-
- def refresh_list(self):
- """刷新地磅单记录列表"""
- keyword = self.search_input.text().strip() if hasattr(self, "search_input") else ""
- slips = self.db.get_all_weighing_slips(keyword=keyword if keyword else None)
- # 勾选时,仅显示毛重或皮重任一未完成(为空/未填)的记录
- if hasattr(self, "incomplete_only_checkbox") and self.incomplete_only_checkbox.isChecked():
- def _is_completed(slip: dict) -> bool:
- gross_weight = slip.get('gross_weight')
- tare_weight = slip.get('tare_weight')
- gross_time = (slip.get('gross_weight_time') or "").strip()
- tare_time = (slip.get('tare_weight_time') or "").strip()
- gross_ok = (gross_weight is not None and gross_weight > 0) or bool(gross_time)
- tare_ok = (tare_weight is not None and tare_weight > 0) or bool(tare_time)
- # 两者都完成才算完整;否则视为未完成
- return gross_ok and tare_ok
- slips = [s for s in slips if not _is_completed(s)]
- # 根据关联出入库单日期、创建时间、毛重时间、皮重时间倒序排列(后端已按该规则排序,这里再兜底一次)
- def _sort_key(s: dict):
- # inbound_date 为关联出入库单的日期("yyyy-MM-dd"),其余时间字段为 "yyyy-MM-dd HH:mm:ss" 字符串
- inbound_date = s.get('inbound_date') or ""
- created = s.get('created_at') or ""
- gross_t = s.get('gross_weight_time') or ""
- tare_t = s.get('tare_weight_time') or ""
- return (inbound_date, created, gross_t, tare_t)
- slips = sorted(slips, key=_sort_key, reverse=True)
- # 缓存当前列表数据,供卡片视图复用
- self._current_slips = slips
- # 根据当前视图模式渲染
- if getattr(self, "view_mode", "table") == "card":
- self._refresh_card_view()
- else:
- self._refresh_table_view()
- def _refresh_table_view(self):
- """以表格形式渲染地磅单列表"""
- slips = getattr(self, "_current_slips", [])
- self.table.setRowCount(len(slips))
- today_str = datetime.now().strftime("%Y-%m-%d")
- # 移除背景色设置
-
- for i, slip in enumerate(slips):
- # 日期(优先使用关联出入库单的 date 字段,其次使用地磅单创建日期的日期部分)
- inbound_date = (slip.get('inbound_date') or "").strip()
- if not inbound_date:
- created_at = (slip.get('created_at') or "").strip()
- inbound_date = created_at.split(" ")[0] if created_at else "-"
- self.table.setItem(i, 0, QTableWidgetItem(inbound_date))
-
- # 车号
- self.table.setItem(i, 1, QTableWidgetItem(slip['vehicle_no']))
-
- # 货物名称
- self.table.setItem(i, 2, QTableWidgetItem(slip['cargo_name']))
-
- # 业务类型
- self.table.setItem(i, 3, QTableWidgetItem(slip['business_type']))
-
- # 供货单位
- self.table.setItem(i, 4, QTableWidgetItem(slip['supplier']))
-
- # 收货单位
- self.table.setItem(i, 5, QTableWidgetItem(slip['consignee']))
-
- # 毛重
- gross_display = "-"
- gross_weight = slip.get('gross_weight')
- if gross_weight is not None and (gross_weight > 0 or slip.get('gross_weight_time')):
- gross_display = f"{kg_to_tons(gross_weight):.3f}"
- self.table.setItem(i, 6, QTableWidgetItem(gross_display))
-
- # 毛重时间
- gross_time_display = slip['gross_weight_time'] if slip['gross_weight_time'] else "-"
- self.table.setItem(i, 7, QTableWidgetItem(gross_time_display))
-
- # 皮重
- tare_display = "-"
- tare_weight = slip.get('tare_weight')
- if tare_weight is not None and (tare_weight > 0 or slip.get('tare_weight_time')):
- tare_display = f"{kg_to_tons(tare_weight):.3f}"
- self.table.setItem(i, 8, QTableWidgetItem(tare_display))
-
- # 皮重时间
- tare_time_display = slip['tare_weight_time'] if slip['tare_weight_time'] else "-"
- self.table.setItem(i, 9, QTableWidgetItem(tare_time_display))
-
- # 扣杂
- deduction_display = "-"
- deduction_value = slip.get('deduction')
- if deduction_value is not None and deduction_value >= 0:
- deduction_display = f"{kg_to_tons(deduction_value):.3f}"
- self.table.setItem(i, 10, QTableWidgetItem(deduction_display))
-
- # 净重
- if slip['is_voided']:
- net_weight_item = QTableWidgetItem("[作废]")
- # 移除作废单文字颜色
- else:
- net_weight = slip.get('net_weight')
- if net_weight is None or net_weight <= 0:
- net_display = "-"
- else:
- net_display = f"{kg_to_tons(net_weight):.3f}"
- net_weight_item = QTableWidgetItem(net_display)
- self.table.setItem(i, 11, net_weight_item)
-
- # 本次量(kg)
- current_quantity = slip.get('current_quantity')
- if current_quantity is not None and current_quantity >= 0:
- current_quantity_display = f"{kg_to_tons(current_quantity):.3f}"
- else:
- current_quantity_display = "-"
- self.table.setItem(i, 12, QTableWidgetItem(current_quantity_display))
-
- # 操作按钮
- btn_widget = QWidget()
- btn_layout = QHBoxLayout()
- btn_layout.setContentsMargins(5, 2, 5, 2)
-
- edit_btn = QPushButton("编辑")
- edit_btn.setFont(QFont("微软雅黑", 14))
- apply_button_style(edit_btn, 'normal')
- edit_btn.clicked.connect(lambda checked, sid=slip['id']: self.start_editing_slip(sid))
- edit_btn.setEnabled(not slip['is_voided'])
-
- detail_btn = QPushButton("查看")
- detail_btn.setFont(QFont("微软雅黑", 14))
- apply_button_style(detail_btn, 'normal')
- detail_btn.clicked.connect(lambda checked, sid=slip['id']: self.show_detail(sid))
-
- preview_btn = QPushButton("打印")
- preview_btn.setFont(QFont("微软雅黑", 14))
- apply_button_style(preview_btn, 'blue')
- preview_btn.clicked.connect(lambda checked, sid=slip['id']: self.preview_slip(sid))
-
- void_btn = QPushButton("作废")
- void_btn.setFont(QFont("微软雅黑", 14))
- apply_button_style(void_btn, 'normal')
- void_btn.clicked.connect(lambda checked, sid=slip['id']: self.void_slip(sid))
-
- if slip['is_voided']:
- void_btn.setEnabled(False)
- void_btn.setText("已作废")
-
- btn_layout.addWidget(edit_btn)
- btn_layout.addWidget(detail_btn)
- btn_layout.addWidget(preview_btn)
- btn_layout.addWidget(void_btn)
- btn_widget.setLayout(btn_layout)
-
- self.table.setCellWidget(i, 13, btn_widget)
-
- # 判断是否是当天称重
- is_today_weight = any(
- (slip.get(field) or "").startswith(today_str)
- for field in ('gross_weight_time', 'tare_weight_time')
- )
-
- # 移除当天高亮和作废单背景色设置
-
- self.table.resizeRowsToContents()
- QTimer.singleShot(0, self.table.resizeRowsToContents)
- self._apply_table_column_widths()
- # 只在表格视图下显示表格、隐藏卡片区域
- if hasattr(self, "card_scroll_area"):
- self.table.setVisible(True)
- self.card_scroll_area.setVisible(False)
- def _refresh_card_view(self):
- """以卡片形式渲染地磅单列表"""
- slips = getattr(self, "_current_slips", [])
- today_str = datetime.now().strftime("%Y-%m-%d")
- # 清空旧卡片(网格布局)
- while self.card_layout.count():
- item = self.card_layout.takeAt(0)
- w = item.widget()
- if w is not None:
- w.deleteLater()
- # 清空旧的卡片缓存,避免引用到已销毁的 QFrame
- self._card_widgets = []
- for idx, slip in enumerate(slips):
- card = QFrame()
- card.setFrameShape(QFrame.StyledPanel)
- card.setFrameShadow(QFrame.Raised)
- card.setStyleSheet("border: 1px solid #ccc; border-radius: 6px;")
- # 控制卡片高度为固定值,宽度由布局和窗口大小动态控制
- card.setFixedHeight(220)
- card_layout = QVBoxLayout()
- card_layout.setContentsMargins(10, 8, 10, 8)
- card_layout.setSpacing(4)
- # 顶部行:日期(重点) + 业务类型 + 右上角“查看/作废”文字按钮
- top_layout = QHBoxLayout()
- # 靠近右上角,缩小整体内部间距
- top_layout.setContentsMargins(0, 0, 0, 0)
- # 顶部整体不使用默认间距,改为在日期和业务类型之间手动插入 10px 间距
- top_layout.setSpacing(0)
- inbound_date = (slip.get('inbound_date') or "").strip()
- if not inbound_date:
- created_at = (slip.get('created_at') or "").strip()
- inbound_date = created_at.split(" ")[0] if created_at else "-"
- date_label = QLabel(inbound_date)
- # 日期加粗显示,去掉自身边框,仅依赖卡片大边框
- date_label.setFont(QFont("微软雅黑", 14, QFont.Bold))
- date_label.setStyleSheet("border: none;")
- business_type = slip.get('business_type', '')
- biz_label = QLabel(business_type)
- # 入库/出库字体加粗并用不同颜色区分,同时去掉自身边框
- biz_label.setFont(QFont("微软雅黑", 12, QFont.Bold))
- biz_label.setStyleSheet("border: none;")
- # 顶部右侧:查看、作废两个“文字链接”样式的按钮,便于紧贴右上角
- detail_btn = QPushButton("查看")
- detail_btn.setFont(QFont("微软雅黑", 11))
- detail_btn.setFlat(True)
- detail_btn.setCursor(Qt.PointingHandCursor)
- # 链接风格:蓝色、无边框、透明背景
- detail_btn.setStyleSheet("border: none; background: transparent; padding: 0px;")
- detail_btn.clicked.connect(lambda checked, sid=slip['id']: self.show_detail(sid))
- void_btn = QPushButton("作废")
- void_btn.setFont(QFont("微软雅黑", 11))
- void_btn.setFlat(True)
- void_btn.setCursor(Qt.PointingHandCursor)
- # 作废按钮使用红色文字链接风格
- void_btn.setStyleSheet("border: none; background: transparent; padding: 0px;")
- void_btn.clicked.connect(lambda checked, sid=slip['id']: self.void_slip(sid))
- top_layout.addWidget(date_label)
- # 日期与“入库/出库”标签之间增加 10px 间距
- top_layout.addSpacing(10)
- top_layout.addWidget(biz_label)
- top_layout.addStretch()
- # 右上角两个“文字链接”之间保留约 20px 的间距
- top_layout.addWidget(detail_btn)
- top_layout.addSpacing(20)
- top_layout.addWidget(void_btn)
- # 中间行:车牌号(重点)、右侧为“产品名称 + 本次量”(上下两行)
- middle_layout = QHBoxLayout()
- plate_label = QLabel(slip.get('vehicle_no', ''))
- # 车牌号加粗显示,去掉自身边框
- plate_label.setFont(QFont("微软雅黑", 20, QFont.Bold))
- plate_label.setStyleSheet("border: none;")
- cargo_label = QLabel(slip.get('cargo_name', ''))
- # 产品名称加粗显示,去掉自身边框
- cargo_label.setFont(QFont("微软雅黑", 12, QFont.Bold))
- cargo_label.setStyleSheet("border: none;")
- # 占位的本次量标签,具体文本后面根据 current_text 设置
- current_label = QLabel()
- current_label.setFont(QFont("微软雅黑", 12))
- current_label.setStyleSheet("border: none;")
- # 第三行:供货 / 收货单位(核心信息)
- company_layout = QHBoxLayout()
- company_text = f"{slip.get('supplier', '')} → {slip.get('consignee', '')}"
- company_label = QLabel(company_text)
- company_label.setFont(QFont("微软雅黑", 12))
- company_label.setStyleSheet("border: none;")
- company_layout.addWidget(company_label)
- company_layout.addStretch()
- # 第四行:毛重 / 皮重 / 净重(核心信息)
- gross_weight = slip.get('gross_weight')
- tare_weight = slip.get('tare_weight')
- net_weight = slip.get('net_weight')
- current_quantity = slip.get('current_quantity')
- if slip.get('is_voided'):
- gross_text = "[作废]"
- tare_text = "[作废]"
- net_text = "[作废]"
- current_text = "[作废]"
- else:
- if gross_weight is not None and gross_weight > 0:
- gross_text = f"{kg_to_tons(gross_weight):.3f} t"
- else:
- gross_text = "-"
- if tare_weight is not None and tare_weight > 0:
- tare_text = f"{kg_to_tons(tare_weight):.3f} t"
- else:
- tare_text = "-"
- if net_weight is not None and net_weight > 0:
- net_text = f"{kg_to_tons(net_weight):.3f} t"
- else:
- net_text = "-"
- if current_quantity is not None and current_quantity >= 0:
- current_text = f"{kg_to_tons(current_quantity):.3f} t"
- else:
- current_text = "-"
- # 设置中间区域:右侧为“产品名称 + 本次量”,上下两行
- current_label.setText(f"本次: {current_text}")
- product_layout = QVBoxLayout()
- product_layout.setContentsMargins(0, 0, 0, 0)
- product_layout.setSpacing(2)
- product_layout.addWidget(cargo_label)
- product_layout.addWidget(current_label)
- middle_layout.addWidget(plate_label, stretch=1)
- middle_layout.addLayout(product_layout, stretch=1)
- middle_layout.addStretch()
- # 重量行:毛重 / 皮重 / 净重(文案中带“重”字)
- weight_line_label = QLabel(f"毛重: {gross_text} 皮重: {tare_text} 净重: {net_text}")
- weight_line_label.setFont(QFont("微软雅黑", 12))
- weight_line_label.setStyleSheet("border: none;")
- # 第五行:备注(如过长,可自动换行)(核心信息)
- remarks = (slip.get('remarks') or "").strip()
- if not remarks:
- remarks = "-"
- remarks_label = QLabel(f"备注: {remarks}")
- remarks_label.setFont(QFont("微软雅黑", 11))
- remarks_label.setStyleSheet("border: none;")
- remarks_label.setWordWrap(True)
- # 底部行:主要操作按钮(编辑、打印),一行仅两个按钮,并整体左右居中
- btn_layout = QHBoxLayout()
- btn_layout.setContentsMargins(0, 0, 0, 0)
- # 两个按钮之间留 10px 间距,这样每个按钮实际宽度约为
- # (可用总宽度 - 10) / 2,即“各占 1/2 宽度 - 10px(用于间距)”
- btn_layout.setSpacing(10)
- # 左右各加一个 stretch,使两个按钮整体水平居中
- btn_layout.addStretch()
- edit_btn = QPushButton("编辑")
- # 编辑按钮:字体稍大,尺寸更大,方便点击
- edit_btn.setFont(QFont("微软雅黑", 13))
- apply_button_style(edit_btn, 'normal')
- edit_btn.clicked.connect(lambda checked, sid=slip['id']: self.start_editing_slip(sid))
- edit_btn.setEnabled(not slip.get('is_voided'))
- preview_btn = QPushButton("打印")
- # 打印按钮:与编辑按钮同级别,字体稍大,尺寸更大
- preview_btn.setFont(QFont("微软雅黑", 13))
- apply_button_style(preview_btn, 'blue')
- preview_btn.clicked.connect(lambda checked, sid=slip['id']: self.preview_slip(sid))
- # 分别设置按钮的最小尺寸:编辑/打印更大,并允许水平扩展
- edit_btn.setMinimumWidth(130)
- edit_btn.setMinimumHeight(38)
- edit_btn.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
- preview_btn.setMinimumWidth(130)
- preview_btn.setMinimumHeight(38)
- preview_btn.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
- # 底部只放主要操作:编辑、打印,一行两个大按钮均分宽度,整体居中
- btn_layout.addWidget(edit_btn)
- btn_layout.addWidget(preview_btn)
- btn_layout.addStretch()
- # 判断当天称重,高亮卡片背景(仅调整背景,不改变字体颜色)
- is_today_weight = any(
- (slip.get(field) or "").startswith(today_str)
- for field in ('gross_weight_time', 'tare_weight_time')
- )
- # 移除当天高亮和作废单背景色
- card.setStyleSheet("border: 1px solid #ccc; border-radius: 6px;")
- card_layout.addLayout(top_layout)
- card_layout.addLayout(middle_layout) # 车牌号 + 产品
- card_layout.addLayout(company_layout) # 供货单位 -> 收货单位
- card_layout.addWidget(weight_line_label) # 毛重 + 净重 + 本次量
- card_layout.addWidget(remarks_label) # 备注
- card_layout.addLayout(btn_layout)
- card.setLayout(card_layout)
- # 记录卡片控件,便于统一调整宽度
- if not hasattr(self, "_card_widgets"):
- self._card_widgets = []
- self._card_widgets.append(card)
- # 添加到网格布局:一行多个(由 self.card_columns 控制)
- col_count = getattr(self, "card_columns", 3) or 3
- row = idx // col_count
- col = idx % col_count
- self.card_layout.addWidget(card, row, col)
- # 刷新完后根据当前宽度调整卡片宽度
- self._update_card_widths()
- # 显示卡片区域、隐藏表格
- self.table.setVisible(False)
- self.card_scroll_area.setVisible(True)
- def resizeEvent(self, event):
- super().resizeEvent(event)
- # 仅在表格视图下调整列宽
- if getattr(self, "view_mode", "table") == "table":
- self._apply_table_column_widths()
- else:
- # 卡片视图下根据当前宽度调整卡片宽度
- self._update_card_widths()
- self._update_form_widget_height()
-
- def showEvent(self, event):
- super().showEvent(event)
- if getattr(self, "view_mode", "table") == "table":
- QTimer.singleShot(0, lambda: self._apply_table_column_widths(force=True))
- def _on_section_resized(self, *_):
- # 仅在表格视图下记录用户手动调整列宽
- if getattr(self, "view_mode", "table") != "table":
- return
- if getattr(self, "_is_applying_column_widths", False):
- 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 getattr(self, "view_mode", "table") != "table":
- return
- if getattr(self, "_user_resized_columns", False) 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, 70))
- # 像素级微调:
- # - 日期列宽度在计算结果基础上增加 20 像素
- # - 毛重/皮重列宽度在计算结果基础上各减少 10 像素
- # (三列整体保持总宽度不变)
- # 列索引:0 = 日期, 6 = 毛重(t), 8 = 皮重(t)
- date_col_index = 0
- gross_col_index = 6
- tare_col_index = 8
- # 当前宽度
- date_width = self.table.columnWidth(date_col_index)
- gross_width = self.table.columnWidth(gross_col_index)
- tare_width = self.table.columnWidth(tare_col_index)
- # 目标宽度(注意仍然要遵守最小宽度 70 像素)
- self.table.setColumnWidth(date_col_index, max(date_width + 20, 70))
- self.table.setColumnWidth(gross_col_index, max(gross_width - 10, 70))
- self.table.setColumnWidth(tare_col_index, max(tare_width - 10, 70))
- finally:
- header.blockSignals(False)
- self._is_applying_column_widths = False
- def _update_form_widget_height(self):
- if not hasattr(self, "form_widget") or not self.form_widget:
- return
- hint_height = self.form_widget.sizeHint().height()
- if hint_height > 0:
- self.form_widget.setMaximumHeight(hint_height)
- def _update_card_widths(self):
- """根据当前滚动区域宽度,动态设置卡片宽度:
- 一行 5 个卡片,每个宽度约等于(总宽度 / 5) - 4px(用于卡片间间隔)"""
- # 仅在卡片视图下生效
- if getattr(self, "view_mode", "table") == "table":
- return
- if not hasattr(self, "card_scroll_area") or not hasattr(self, "card_layout"):
- return
- if not hasattr(self, "_card_widgets") or not self._card_widgets:
- return
- viewport = self.card_scroll_area.viewport()
- total_width = viewport.width()
- if total_width <= 0:
- return
- # 计算可用宽度:去掉左右外边距
- margins = self.card_layout.contentsMargins()
- available_width = total_width - margins.left() - margins.right()
- if available_width <= 0:
- return
- col_count = getattr(self, "card_columns", 5) or 5
- # 列间距(卡片间的空隙)
- h_spacing = self.card_layout.horizontalSpacing() or 0
- # 总间隔宽度 = (列数 - 1) * spacing
- total_spacing = (col_count - 1) * h_spacing
- if available_width <= total_spacing:
- return
- # 每个卡片的目标宽度:剩余宽度平均分到 5 列,再略减一点,避免溢出
- card_width = int((available_width - total_spacing) / col_count)
- if card_width <= 0:
- return
- # 过滤掉已经被 Qt 销毁的卡片对象,避免 RuntimeError
- alive_cards = []
- for card in self._card_widgets:
- if card is None:
- continue
- # sip.isdeleted 用来判断底层 C++ 对象是否已经被销毁
- if sip.isdeleted(card):
- continue
- alive_cards.append(card)
- card.setMinimumWidth(card_width)
- card.setMaximumWidth(card_width)
- # 用仅包含存活对象的列表替换原缓存
- self._card_widgets = alive_cards
- def event(self, event):
- screen_change_event = getattr(QEvent, "ScreenChangeInternal", None)
- event_types = (
- QEvent.FontChange,
- QEvent.ApplicationFontChange,
- QEvent.StyleChange,
- )
- if screen_change_event is not None:
- event_types = event_types + (screen_change_event,)
- if event.type() in event_types:
- QTimer.singleShot(0, self._update_form_widget_height)
- return super().event(event)
- def _switch_view_mode(self, mode: str):
- """切换列表展示模式:table / card"""
- if mode == self.view_mode:
- return
- self.view_mode = mode
- # 同步按钮选中状态
- if mode == "table":
- self.table_view_btn.setChecked(True)
- self.card_view_btn.setChecked(False)
- # 重新以表格方式渲染
- self._refresh_table_view()
- else:
- self.table_view_btn.setChecked(False)
- self.card_view_btn.setChecked(True)
- # 重新以卡片方式渲染
- self._refresh_card_view()
-
- def export_to_excel(self):
- """导出地磅单信息"""
- slips = self.db.get_all_weighing_slips(include_voided=False)
- if not slips:
- 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 slip in slips:
- current_quantity_ton = kg_to_tons(slip.get('current_quantity'))
- export_rows.append({
- "地磅单ID": slip.get('id'),
- "计划号": slip.get('plan_no', ''),
- "批次号": slip.get('batch_no', ''),
- "车号": slip.get('vehicle_no', ''),
- "货物名称": slip.get('cargo_name', ''),
- "业务类型": slip.get('business_type', ''),
- "供货单位": slip.get('supplier', ''),
- "收货单位": slip.get('consignee', ''),
- "毛重(t)": self._ton_value_from_kg(slip.get('gross_weight')),
- "毛重时间": slip.get('gross_weight_time', ''),
- "皮重(t)": self._ton_value_from_kg(slip.get('tare_weight')),
- "皮重时间": slip.get('tare_weight_time', ''),
- "扣杂(t)": self._ton_value_from_kg(slip.get('deduction')),
- "净重(t)": self._ton_value_from_kg(slip.get('net_weight')),
- "本次量(t)": round(current_quantity_ton, 3) if current_quantity_ton is not None else "",
- "称重时间": slip.get('created_at', ''),
- "备注": slip.get('remarks', ''),
- "已执行量(kg)": slip.get('executed_quantity', ''),
- "是否作废": "是" if slip.get('is_voided') else "否"
- })
-
- 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 validate_form(self) -> Tuple[bool, str]:
- """验证表单数据"""
- # 清除之前的错误样式
- self.clear_error_styles()
-
- if not self.vehicle_no_input.text().strip():
- self.set_error_style(self.vehicle_no_input)
- return False, "请填写车号"
-
- if self.cargo_combo.currentIndex() <= 0 or not self.cargo_combo.currentText().strip():
- self.set_error_style(self.cargo_combo)
- return False, "请选择货物名称"
-
- if not self.business_type_group.checkedButton():
- return False, "请选择业务类型"
-
- if self.supplier_combo.currentIndex() <= 0 or not self.supplier_combo.currentText().strip():
- self.set_error_style(self.supplier_combo)
- return False, "请选择供货单位"
-
- if self.consignee_combo.currentIndex() <= 0 or not self.consignee_combo.currentText().strip():
- self.set_error_style(self.consignee_combo)
- return False, "请选择收货单位"
-
- gross_value = self._get_weight_input_value(self.gross_weight_input)
- tare_value = self._get_weight_input_value(self.tare_weight_input)
-
- gross_time_text = self._get_datetime_text(self.gross_weight_time)
- tare_time_text = self._get_datetime_text(self.tare_weight_time)
-
- gross_time_valid = self.gross_weight_time.dateTime().isValid() and bool(gross_time_text)
- tare_time_valid = self.tare_weight_time.dateTime().isValid() and bool(tare_time_text)
-
- if gross_value is not None and gross_value <= 0:
- self.set_error_style(self.gross_weight_input)
- return False, "毛重必须大于0"
- if tare_value is not None and tare_value <= 0:
- self.set_error_style(self.tare_weight_input)
- return False, "皮重必须大于0"
-
- if gross_value is not None and not gross_time_valid:
- self.set_error_style(self.gross_weight_time)
- return False, "已填写毛重后必须填写毛重时间"
- if gross_time_valid and gross_value is None:
- self.set_error_style(self.gross_weight_input)
- return False, "填写毛重时间前需要填写毛重"
-
- if tare_value is not None and not tare_time_valid:
- self.set_error_style(self.tare_weight_time)
- return False, "已填写皮重后必须填写皮重时间"
- if tare_time_valid and tare_value is None:
- self.set_error_style(self.tare_weight_input)
- return False, "填写皮重时间前需要填写皮重"
-
- if gross_value is not None and tare_value is not None:
- deduction = self._get_deduction_value()
- net_weight = gross_value - tare_value - deduction
- if net_weight <= 0:
- return False, "净重必须大于0,请检查毛重、皮重和扣杂的数值"
-
- return True, ""
-
- def set_error_style(self, widget):
- """设置错误样式(红色边框)"""
- widget.setStyleSheet("border: 2px solid red;")
-
- def clear_error_styles(self):
- """清除所有错误样式"""
- self.vehicle_no_input.setStyleSheet("")
- self.cargo_combo.setStyleSheet("")
- self.supplier_combo.setStyleSheet("")
- self.consignee_combo.setStyleSheet("")
- self.gross_weight_input.setStyleSheet("")
- self.tare_weight_input.setStyleSheet("")
- self.gross_weight_time.setStyleSheet("")
- self.tare_weight_time.setStyleSheet("")
-
- def save_weighing_slip(self):
- """保存地磅单"""
- # 验证
- valid, error_msg = self.validate_form()
- if not valid:
- QMessageBox.warning(self, "验证失败", error_msg)
- return
-
- gross_value = self._get_weight_input_value(self.gross_weight_input)
- tare_value = self._get_weight_input_value(self.tare_weight_input)
- deduction_value = self._get_deduction_value()
-
- gross_weight = gross_value if gross_value is not None else 0
- tare_weight = tare_value if tare_value is not None else 0
-
- planned_quantity_value = self.planned_quantity_input.value()
- planned_quantity_tons = planned_quantity_value if planned_quantity_value >= 0 else None
- planned_quantity = tons_to_kg(planned_quantity_tons) if planned_quantity_tons is not None else None
-
- executed_quantity_value = self.executed_quantity_input.value()
- executed_quantity_tons = executed_quantity_value if executed_quantity_value >= 0 else None
- executed_quantity = tons_to_kg(executed_quantity_tons) if executed_quantity_tons is not None else None
-
- current_quantity_value = self.current_quantity_input.value()
- current_quantity_tons = current_quantity_value if current_quantity_value >= 0 else None
- current_quantity = tons_to_kg(current_quantity_tons) if current_quantity_tons is not None else None
-
- data = {
- 'vehicle_no': self.vehicle_no_input.text().strip(),
- 'plan_no': self.plan_no_input.text().strip(),
- 'cargo_name': self.cargo_combo.currentText(),
- 'business_type': self.business_type_group.checkedButton().text(),
- 'batch_no': self.batch_no_input.text().strip(),
- 'supplier': self.supplier_combo.currentText(),
- 'consignee': self.consignee_combo.currentText(),
- 'gross_weight': gross_weight,
- 'gross_weight_time': self._get_datetime_str(self.gross_weight_time),
- 'tare_weight': tare_weight,
- 'tare_weight_time': self._get_datetime_str(self.tare_weight_time),
- 'deduction': deduction_value,
- 'planned_quantity': planned_quantity,
- 'executed_quantity': executed_quantity,
- 'current_quantity': current_quantity,
- 'remarks': self.remarks_input.toPlainText().strip(),
- 'purchase_plan_id': self.current_plan['id'] if self.current_plan and self.current_plan.get('id') else None,
- 'inbound_outbound_id': self.current_inbound_id,
- 'weighing_point': self.current_plan.get('weighing_point') if self.current_plan and self.current_plan.get('weighing_point') else '山峡地磅'
- }
-
- try:
- operation_success = False
- if self.editing_slip_id:
- operation_success = self.db.update_weighing_slip(self.editing_slip_id, data)
- if not operation_success:
- QMessageBox.warning(self, "提示", "未能更新地磅单,请重试。")
- return
- QMessageBox.information(self, "成功", "地磅单更新成功!")
- else:
- self.db.insert_weighing_slip(data)
- operation_success = True
- QMessageBox.information(self, "成功", "地磅单保存成功!")
-
- if operation_success:
- self.clear_error_styles() # 清除错误样式
- self.clear_form()
- self.refresh_list()
- except ValueError as e:
- QMessageBox.warning(self, "提示", str(e))
- except Exception as e:
- QMessageBox.critical(self, "错误", f"保存失败:{str(e)}")
-
- def clear_form(self):
- """清空表单"""
- self._is_clearing_form = True
- try:
- self.editing_slip_id = None
- self.save_btn.setText("保存")
- self.vehicle_no_input.clear()
- self.plan_no_input.clear()
- # 清空货物名称、供货单位、收货单位(设置为第一个空选项)
- if self.cargo_combo.count() > 0:
- self.cargo_combo.setCurrentIndex(0)
- if self.supplier_combo.count() > 0:
- self.supplier_combo.setCurrentIndex(0)
- if self.consignee_combo.count() > 0:
- self.consignee_combo.setCurrentIndex(0)
- # 不设置业务类型默认选中
- if self.business_type_group.checkedButton():
- self.business_type_group.setExclusive(False)
- self.business_type_group.checkedButton().setChecked(False)
- self.business_type_group.setExclusive(True)
- self.batch_no_input.clear()
- self.gross_weight_input.setValue(-1)
- # 不设置毛重时间默认值,使用无效日期时间
- self.gross_weight_time.setDateTime(QDateTime())
- if self.gross_weight_time.lineEdit():
- self.gross_weight_time.lineEdit().setText("")
- # 延迟清空,确保显示被正确清空
- QTimer.singleShot(0, lambda: self.gross_weight_time.lineEdit().setText("") if self.gross_weight_time.lineEdit() else None)
- self.tare_weight_input.setValue(-1)
- # 不设置皮重时间默认值,使用无效日期时间
- self.tare_weight_time.setDateTime(QDateTime())
- if self.tare_weight_time.lineEdit():
- self.tare_weight_time.lineEdit().setText("")
- # 延迟清空,确保显示被正确清空
- QTimer.singleShot(0, lambda: self.tare_weight_time.lineEdit().setText("") if self.tare_weight_time.lineEdit() else None)
- self.deduction_input.setValue(-1)
- self.net_weight_label.setText("0.000 t")
- self.planned_quantity_input.setValue(-1)
- self.executed_quantity_input.setValue(-1)
- self.current_quantity_input.setValue(-1)
- self.remarks_input.clear()
- self.clear_plan_binding()
- self.current_inbound_id = None
- finally:
- self._is_clearing_form = False
-
- def clear_plan_binding(self):
- """清空关联的采购计划"""
- self.current_plan = None
- if hasattr(self, 'plan_binding_label'):
- self.plan_binding_label.setText("未关联")
- self.plan_binding_label.setStyleSheet("")
-
- def set_source_plan(self, plan: dict):
- """设置当前关联的采购计划"""
- self.current_plan = plan
- if not hasattr(self, 'plan_binding_label'):
- return
- parts = [f"ID {plan.get('id', '')}", plan.get('business_type', '')]
- if plan.get('customer_name'):
- parts.append(plan['customer_name'])
- if plan.get('execution_status'):
- parts.append(plan['execution_status'])
- self.plan_binding_label.setText(" · ".join([p for p in parts if p]))
- status = plan.get('execution_status', '')
- # 移除状态文字颜色
-
- # 同步已执行量(kg)
- executed_qty = plan.get('executed_quantity')
- executed_qty_tons = kg_to_tons(executed_qty) if executed_qty is not None else None
- if executed_qty_tons is not None and executed_qty_tons >= 0:
- self.executed_quantity_input.setValue(executed_qty_tons)
- else:
- self.executed_quantity_input.setValue(-1)
-
- def show_detail(self, slip_id: int):
- """显示地磅单详情"""
- slip = self.db.get_weighing_slip_by_id(slip_id)
- if not slip:
- QMessageBox.warning(self, "错误", "未找到该地磅单")
- return
-
- dialog = DetailDialog(slip, self.db, self)
- dialog.exec_()
-
- def preview_slip(self, slip_id: int):
- """预览地磅单"""
- slip = self.db.get_weighing_slip_by_id(slip_id)
- if not slip:
- QMessageBox.warning(self, "错误", "未找到该地磅单")
- return
-
- try:
- self.printer.preview_weighing_slip(
- slip, copies=self.print_copies
- )
- except Exception as e:
- QMessageBox.critical(self, "错误", f"预览失败:{str(e)}")
-
- def start_editing_slip(self, slip_id: int):
- """进入编辑模式并回显表单"""
- slip = self.db.get_weighing_slip_by_id(slip_id)
- if not slip:
- QMessageBox.warning(self, "错误", "未找到该地磅单")
- return
- if slip.get('is_voided'):
- QMessageBox.warning(self, "提示", "已作废的地磅单不可编辑")
- return
-
- executed_quantity = slip.get('executed_quantity')
- self.clear_error_styles()
- self._is_clearing_form = True
- try:
- self.editing_slip_id = slip_id
- self.save_btn.setText("更新")
-
- self.vehicle_no_input.setText(slip.get('vehicle_no', ''))
- plan_no = slip.get('plan_no', '')
- self.plan_no_input.setText(plan_no)
- self.batch_no_input.setText(slip.get('batch_no', ''))
-
- business_type = slip.get('business_type')
- if business_type == '出库':
- self.business_sale_radio.setChecked(True)
- elif business_type == '入库':
- self.business_purchase_radio.setChecked(True)
- else:
- if self.business_type_group.checkedButton():
- self.business_type_group.setExclusive(False)
- self.business_type_group.checkedButton().setChecked(False)
- self.business_type_group.setExclusive(True)
-
- self._ensure_combo_value(self.cargo_combo, slip.get('cargo_name', ''))
- self._ensure_combo_value(self.supplier_combo, slip.get('supplier', ''))
- self._ensure_combo_value(self.consignee_combo, slip.get('consignee', ''))
-
- gross_should_empty = slip.get('gross_weight', 0) <= 0 and not slip.get('gross_weight_time')
- self.gross_weight_input.setValue(slip.get('gross_weight', 0) if not gross_should_empty else -1)
- self._set_datetime_from_str(self.gross_weight_time, slip.get('gross_weight_time', ''))
-
- tare_should_empty = slip.get('tare_weight', 0) <= 0 and not slip.get('tare_weight_time')
- self.tare_weight_input.setValue(slip.get('tare_weight', 0) if not tare_should_empty else -1)
- self._set_datetime_from_str(self.tare_weight_time, slip.get('tare_weight_time', ''))
-
- deduction_value = slip.get('deduction')
- self.deduction_input.setValue(deduction_value if deduction_value is not None else -1)
-
- planned_quantity = slip.get('planned_quantity')
- planned_quantity_tons = kg_to_tons(planned_quantity) if planned_quantity is not None else None
- self.planned_quantity_input.setValue(planned_quantity_tons if planned_quantity_tons is not None else -1)
-
- executed_quantity_tons = kg_to_tons(executed_quantity) if executed_quantity is not None else None
- self.executed_quantity_input.setValue(executed_quantity_tons if executed_quantity_tons is not None else -1)
-
- current_quantity = slip.get('current_quantity')
- current_quantity_tons = kg_to_tons(current_quantity) if current_quantity is not None else None
- self.current_quantity_input.setValue(current_quantity_tons if current_quantity_tons is not None else -1)
-
- self.remarks_input.setPlainText(slip.get('remarks', ''))
- finally:
- self._is_clearing_form = False
-
- # 设置关联的出入库单ID
- self.current_inbound_id = slip.get('inbound_outbound_id')
-
- # 优先通过purchase_plan_id查询计划,如果没有则通过计划号查询
- linked_plan = None
- if slip.get('purchase_plan_id'):
- linked_plan = self.db.get_purchase_plan_by_id(slip['purchase_plan_id'])
- if not linked_plan:
- linked_plan = {
- 'id': slip['purchase_plan_id'],
- 'business_type': slip.get('business_type', ''),
- 'customer_name': slip.get('consignee', '') if slip.get('business_type') == '出库' else slip.get('supplier', ''),
- 'execution_status': ''
- }
- elif plan_no:
- # 如果没有purchase_plan_id,通过计划号查询
- linked_plan = self.db.get_purchase_plan_by_plan_no(plan_no)
-
- if linked_plan:
- self.set_source_plan(linked_plan)
- # 如果通过计划号查询到计划,更新计划量和已执行量
- # 注意:已执行量优先使用计划中的值,如果没有则使用地磅单中的值
- if plan_no and linked_plan:
- planned_quantity_t = linked_plan.get('planned_quantity')
- if planned_quantity_t is not None:
- self.planned_quantity_input.setValue(planned_quantity_t)
- # 已执行量:优先使用计划中的值,如果没有则使用地磅单中的值
- executed_quantity_kg = linked_plan.get('executed_quantity')
- executed_quantity_t = kg_to_tons(executed_quantity_kg) if executed_quantity_kg is not None else None
- if executed_quantity_t is not None:
- self.executed_quantity_input.setValue(executed_quantity_t)
- elif executed_quantity_tons is not None:
- self.executed_quantity_input.setValue(executed_quantity_tons)
- else:
- self.clear_plan_binding()
- # 如果没有关联计划,使用地磅单中的已执行量
- if executed_quantity_tons is not None:
- self.executed_quantity_input.setValue(executed_quantity_tons)
-
- self.calculate_net_weight()
-
- def print_slip(self, slip_id: int):
- """打印地磅单"""
- slip = self.db.get_weighing_slip_by_id(slip_id)
- if not slip:
- QMessageBox.warning(self, "错误", "未找到该地磅单")
- return
-
- try:
- self.printer.print_weighing_slip(
- slip, copies=self.print_copies
- )
- QMessageBox.information(self, "成功", "打印任务已发送")
- except Exception as e:
- QMessageBox.critical(self, "错误", f"打印失败:{str(e)}")
-
- def void_slip(self, slip_id: int):
- """作废地磅单"""
- 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.void_weighing_slip(slip_id):
- QMessageBox.information(self, "成功", "地磅单已作废")
- self.refresh_list()
- else:
- QMessageBox.warning(self, "错误", "作废失败")
-
- def has_unsaved_weight_data(self) -> bool:
- """检查是否有未保存的重量数据(皮重或毛重任何一个有数据)"""
- gross_value = self._get_weight_input_value(self.gross_weight_input)
- tare_value = self._get_weight_input_value(self.tare_weight_input)
-
- # 如果皮重或毛重任何一个有数据(值大于0),返回True
- return (gross_value is not None and gross_value > 0) or \
- (tare_value is not None and tare_value > 0)
-
- def on_plan_no_changed(self, text: str):
- """计划号输入变化时,自动查询计划并填充计划量和已执行量"""
- # 如果正在清空表单,不执行查询
- if self._is_clearing_form:
- return
-
- plan_no = text.strip()
-
- # 如果计划号为空,清空计划量和已执行量
- if not plan_no:
- self.planned_quantity_input.setValue(-1)
- self.executed_quantity_input.setValue(-1)
- self.clear_plan_binding()
- return
-
- # 查询计划
- try:
- plan = self.db.get_purchase_plan_by_plan_no(plan_no)
- if plan:
- # 找到计划,填充计划量和已执行量
- planned_quantity_t = plan.get('planned_quantity')
- if planned_quantity_t is not None and planned_quantity_t >= 0:
- self.planned_quantity_input.setValue(planned_quantity_t)
- else:
- self.planned_quantity_input.setValue(-1)
-
- executed_quantity_kg = plan.get('executed_quantity')
- executed_quantity_t = kg_to_tons(executed_quantity_kg) if executed_quantity_kg is not None else None
- if executed_quantity_t is not None and executed_quantity_t >= 0:
- self.executed_quantity_input.setValue(executed_quantity_t)
- else:
- self.executed_quantity_input.setValue(-1)
-
- # 设置关联的计划
- self.set_source_plan(plan)
- else:
- # 未找到计划,清空计划量和已执行量
- self.planned_quantity_input.setValue(-1)
- self.executed_quantity_input.setValue(-1)
- self.clear_plan_binding()
- except Exception as e:
- # 查询失败,不影响用户输入
- logger.warning(f"查询计划失败: {str(e)}")
- self.planned_quantity_input.setValue(-1)
- self.executed_quantity_input.setValue(-1)
- self.clear_plan_binding()
- class DetailDialog(QDialog):
- """地磅单详情对话框"""
-
- def __init__(self, slip: dict, db: Database, parent=None):
- super().__init__(parent)
- self.slip = slip
- self.db = db
- self.printer = Printer()
- self.print_copies = getattr(parent, "print_copies", DEFAULT_PRINT_COPIES)
- self.init_ui()
-
- def init_ui(self):
- """初始化对话框界面"""
- self.setWindowTitle("地磅单详情")
- self.setMinimumWidth(500)
-
- layout = QVBoxLayout()
- layout.setSpacing(10)
- layout.setContentsMargins(20, 20, 20, 20)
-
- # 显示详情信息(只读)
- form_layout = QFormLayout()
- form_layout.setSpacing(10)
- label_font = QFont("微软雅黑", 16)
- gross_t = kg_to_tons(self.slip.get('gross_weight'))
- tare_t = kg_to_tons(self.slip.get('tare_weight'))
- net_t = kg_to_tons(self.slip.get('net_weight'))
- current_t = kg_to_tons(self.slip.get('current_quantity')) if self.slip.get('current_quantity') is not None else None
- planned_t = kg_to_tons(self.slip.get('planned_quantity')) if self.slip.get('planned_quantity') is not None else None
- executed_t = kg_to_tons(self.slip.get('executed_quantity')) if self.slip.get('executed_quantity') is not None else None
- deduction_t = kg_to_tons(self.slip.get('deduction')) if self.slip.get('deduction') is not None else None
-
- fields = [
- ("车号", self.slip['vehicle_no']),
- ("计划号", self.slip.get('plan_no', '')),
- ("货物名称", self.slip['cargo_name']),
- ("业务类型", self.slip['business_type']),
- ("批号", self.slip.get('batch_no', '')),
- ("供货单位", self.slip['supplier']),
- ("收货单位", self.slip['consignee']),
- ("毛重(t)", f"{gross_t:.3f}" if gross_t is not None else ""),
- ("毛重时间", self.slip['gross_weight_time']),
- ("皮重(t)", f"{tare_t:.3f}" if tare_t is not None else ""),
- ("皮重时间", self.slip['tare_weight_time']),
- ("扣杂(t)", f"{deduction_t:.3f}" if deduction_t is not None else ""),
- ("净重(t)", f"{net_t:.3f}" if net_t is not None else ""),
- ("本次量(t)", f"{current_t:.3f}" if current_t is not None else ""),
- ("计划量(t)", f"{planned_t:.3f}" if planned_t is not None else ""),
- ("已执行量(t)", f"{executed_t:.3f}" if executed_t is not None else ""),
- ("磅点", self.slip.get('weighing_point', '山峡地磅')),
- ("备注", self.slip.get('remarks', ''))
- ]
-
- for label, value in fields:
- label_widget = QLabel(f"{label}:")
- label_widget.setFont(label_font)
- value_label = QLabel(str(value) if value else "")
- value_label.setFont(QFont("微软雅黑", 15))
- form_layout.addRow(label_widget, value_label)
-
- layout.addLayout(form_layout)
-
- # 按钮
- button_layout = QHBoxLayout()
- button_layout.addStretch()
-
- preview_btn = QPushButton("打印")
- preview_btn.setMinimumHeight(40)
- preview_btn.setMinimumWidth(100)
- preview_btn.setFont(QFont("微软雅黑", 15))
- apply_button_style(preview_btn, 'blue')
- preview_btn.clicked.connect(self.preview_slip)
-
- close_btn = QPushButton("关闭")
- close_btn.setMinimumHeight(40)
- close_btn.setMinimumWidth(100)
- close_btn.setFont(QFont("微软雅黑", 15))
- apply_button_style(close_btn, 'normal')
- close_btn.clicked.connect(self.accept)
-
- button_layout.addWidget(preview_btn)
- button_layout.addWidget(close_btn)
-
- layout.addLayout(button_layout)
- self.setLayout(layout)
-
- def preview_slip(self):
- """预览地磅单(按钮文本为打印)"""
- try:
- self.printer.preview_weighing_slip(
- self.slip, copies=self.print_copies
- )
- except Exception as e:
- QMessageBox.critical(self, "错误", f"预览失败:{str(e)}")
|