weighing_tab.py 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912
  1. """
  2. 地磅单管理Tab页面
  3. """
  4. from PyQt5.QtWidgets import (
  5. QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QComboBox,
  6. QRadioButton, QButtonGroup, QDateTimeEdit, QTextEdit, QPushButton,
  7. QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox, QDialog,
  8. QFormLayout, QSplitter, QGroupBox, QDoubleSpinBox, QGridLayout,
  9. QFileDialog, QSizePolicy, QCheckBox, QScrollArea, QFrame
  10. )
  11. from PyQt5.QtCore import Qt, QDateTime, pyqtSignal, QTimer, QEvent
  12. from PyQt5.QtGui import QFont, QColor, QBrush, QKeyEvent, QKeySequence
  13. from datetime import datetime
  14. from typing import Tuple, Optional
  15. import logging
  16. import sip
  17. import time
  18. from database import Database
  19. from utils.printer import Printer
  20. from .button_styles import apply_button_style, get_button_color_type
  21. import pandas as pd
  22. logger = logging.getLogger(__name__)
  23. startup_logger = logging.getLogger('startup')
  24. DEFAULT_PRINT_COPIES = 1
  25. def kg_to_tons(value: Optional[float]) -> Optional[float]:
  26. if value is None:
  27. return None
  28. return value / 1000.0
  29. def tons_to_kg(value: Optional[float]) -> Optional[float]:
  30. if value is None:
  31. return None
  32. return value * 1000.0
  33. class EmptyDoubleSpinBox(QDoubleSpinBox):
  34. """自定义QDoubleSpinBox,当值为-1时显示为空"""
  35. def textFromValue(self, value: float) -> str:
  36. """重写文本显示方法,当值为-1时返回空字符串"""
  37. if value == -1:
  38. return ""
  39. return super().textFromValue(value)
  40. def valueFromText(self, text: str) -> float:
  41. """重写文本解析方法,当文本为空时返回-1"""
  42. if not text or text.strip() == "":
  43. return -1
  44. return super().valueFromText(text)
  45. class EmptyDateTimeEdit(QDateTimeEdit):
  46. """自定义QDateTimeEdit,当日期时间为空值时显示为空字符串"""
  47. def __init__(self, parent=None):
  48. super().__init__(parent)
  49. self._is_empty = True
  50. self._placeholder_datetime = QDateTime.fromString("2000-01-01 00:00:00", "yyyy-MM-dd HH:mm:ss")
  51. super().setDateTime(self._placeholder_datetime)
  52. self._sync_line_edit()
  53. def _sync_line_edit(self):
  54. """根据当前空状态同步行编辑器的显示"""
  55. line_edit = self.lineEdit()
  56. if not line_edit:
  57. return
  58. if self._is_empty:
  59. line_edit.setText("")
  60. else:
  61. line_edit.setText(super().textFromDateTime(super().dateTime()))
  62. def setDateTime(self, date_time: QDateTime):
  63. """重写设置日期时间方法,支持显示为空"""
  64. if not date_time.isValid():
  65. self._is_empty = True
  66. super().setDateTime(self._placeholder_datetime)
  67. self._sync_line_edit()
  68. return
  69. self._is_empty = False
  70. super().setDateTime(date_time)
  71. self._sync_line_edit()
  72. def dateTime(self) -> QDateTime:
  73. """当为空时返回一个无效的QDateTime"""
  74. if self._is_empty:
  75. return QDateTime()
  76. return super().dateTime()
  77. def textFromDateTime(self, date_time: QDateTime) -> str:
  78. """空状态显示为空字符串"""
  79. if self._is_empty:
  80. return ""
  81. return super().textFromDateTime(date_time)
  82. class WeighingTab(QWidget):
  83. """地磅单管理Tab"""
  84. def __init__(self, db: Database):
  85. tab_start = time.time()
  86. super().__init__()
  87. self.db = db
  88. self.printer = Printer()
  89. self.print_copies = DEFAULT_PRINT_COPIES
  90. self._is_clearing_form = False
  91. self.current_plan: Optional[dict] = None
  92. self.current_inbound_id: Optional[int] = None
  93. self.editing_slip_id: Optional[int] = None
  94. ui_start = time.time()
  95. self.init_ui()
  96. startup_logger.info(f" 界面初始化 (耗时: {time.time() - ui_start:.3f}秒)")
  97. dropdown_start = time.time()
  98. self.refresh_dropdowns()
  99. startup_logger.info(f" 下拉框数据加载 (耗时: {time.time() - dropdown_start:.3f}秒)")
  100. refresh_start = time.time()
  101. self.refresh_list()
  102. startup_logger.info(f" 列表数据加载 (耗时: {time.time() - refresh_start:.3f}秒)")
  103. def init_ui(self):
  104. """初始化界面"""
  105. layout = QVBoxLayout()
  106. layout.setSpacing(10)
  107. layout.setContentsMargins(10, 10, 10, 10)
  108. # 创建分割器:上部自适应高度,下部占据剩余空间
  109. splitter = QSplitter(Qt.Vertical)
  110. self.form_widget = self.create_form_widget()
  111. self.form_widget.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
  112. self._update_form_widget_height()
  113. splitter.addWidget(self.form_widget)
  114. list_widget = self.create_list_widget()
  115. splitter.addWidget(list_widget)
  116. splitter.setStretchFactor(0, 0)
  117. splitter.setStretchFactor(1, 1)
  118. layout.addWidget(splitter)
  119. self.setLayout(layout)
  120. def create_form_widget(self) -> QWidget:
  121. """创建地磅单填写表单(左侧读数区 + 右侧填写区)"""
  122. widget = QWidget()
  123. layout = QVBoxLayout()
  124. layout.setSpacing(8)
  125. layout.setContentsMargins(10, 10, 10, 10)
  126. # 标题
  127. title = QLabel("地磅单填写")
  128. title_font = QFont("微软雅黑", 16, QFont.Bold)
  129. title.setFont(title_font)
  130. layout.addWidget(title)
  131. # 顶部内容区域:左侧地磅读数区 + 右侧表单填写区
  132. content_layout = QHBoxLayout()
  133. content_layout.setSpacing(16)
  134. # =========================
  135. # 左侧:地磅读数区域
  136. # =========================
  137. left_group = QGroupBox("地磅读数")
  138. left_layout = QVBoxLayout()
  139. left_layout.setContentsMargins(10, 10, 10, 10)
  140. left_layout.setSpacing(12)
  141. # 读数显示(单位 kg)
  142. self.scale_display_label = QLabel("0.00 kg")
  143. self.scale_display_label.setAlignment(Qt.AlignCenter)
  144. self.scale_display_label.setMinimumHeight(80)
  145. self.scale_display_label.setFont(QFont("微软雅黑", 24, QFont.Bold))
  146. self.scale_display_label.setStyleSheet("border-radius: 6px; border: 2px solid #424242; padding: 8px;")
  147. # 按钮区域:读毛重 / 读皮重
  148. self.read_gross_btn = QPushButton("读毛重")
  149. self.read_gross_btn.setMinimumHeight(40)
  150. self.read_gross_btn.setFont(QFont("微软雅黑", 14, QFont.Bold))
  151. apply_button_style(self.read_gross_btn, 'blue')
  152. self.read_tare_btn = QPushButton("读皮重")
  153. self.read_tare_btn.setMinimumHeight(40)
  154. self.read_tare_btn.setFont(QFont("微软雅黑", 14, QFont.Bold))
  155. apply_button_style(self.read_tare_btn, 'blue')
  156. read_btn_layout = QHBoxLayout()
  157. read_btn_layout.setSpacing(12)
  158. read_btn_layout.addWidget(self.read_gross_btn)
  159. read_btn_layout.addWidget(self.read_tare_btn)
  160. left_layout.addWidget(self.scale_display_label)
  161. left_layout.addLayout(read_btn_layout)
  162. left_layout.addStretch()
  163. left_group.setLayout(left_layout)
  164. # =========================
  165. # 右侧:表单填写区域(原有表单)
  166. # =========================
  167. right_widget = QWidget()
  168. right_layout = QVBoxLayout()
  169. right_layout.setContentsMargins(0, 0, 0, 0)
  170. right_layout.setSpacing(0)
  171. # 表单区域 - 使用网格布局,一行放4个字段(8列,label+控件各占1列)
  172. form_layout = QGridLayout()
  173. form_layout.setSpacing(12)
  174. form_layout.setColumnStretch(1, 1)
  175. form_layout.setColumnStretch(3, 1)
  176. form_layout.setColumnStretch(5, 1)
  177. form_layout.setColumnStretch(7, 1)
  178. # 创建控件
  179. # 必填字段在前,非必填字段在后
  180. # 必填字段label为红色,非必填字段label为黑色
  181. row = 0
  182. # 第一行:车号(必填)、货物名称(必填)、业务类型(必填)
  183. # 车号(必填)
  184. vehicle_label = QLabel("<span style='color: red;'>车号 *</span>:")
  185. vehicle_label.setFont(QFont("微软雅黑", 16))
  186. vehicle_label.setTextFormat(Qt.RichText)
  187. self.vehicle_no_input = QLineEdit()
  188. self.vehicle_no_input.setMinimumHeight(40)
  189. self.vehicle_no_input.setFont(QFont("微软雅黑", 16))
  190. form_layout.addWidget(vehicle_label, row, 0)
  191. form_layout.addWidget(self.vehicle_no_input, row, 1)
  192. # 货物名称(必填)
  193. cargo_label = QLabel("<span style='color: red;'>货物名称 *</span>:")
  194. cargo_label.setFont(QFont("微软雅黑", 16))
  195. cargo_label.setTextFormat(Qt.RichText)
  196. self.cargo_combo = QComboBox()
  197. self.cargo_combo.setMinimumHeight(40)
  198. self.cargo_combo.setFont(QFont("微软雅黑", 16))
  199. self.cargo_combo.setEditable(False)
  200. form_layout.addWidget(cargo_label, row, 2)
  201. form_layout.addWidget(self.cargo_combo, row, 3)
  202. # 业务类型(必填)- 选中的显示为红色
  203. business_label = QLabel("<span style='color: red;'>业务类型 *</span>:")
  204. business_label.setFont(QFont("微软雅黑", 16))
  205. business_label.setTextFormat(Qt.RichText)
  206. self.business_type_group = QButtonGroup()
  207. self.business_sale_radio = QRadioButton("出库")
  208. self.business_purchase_radio = QRadioButton("入库")
  209. self.business_sale_radio.setFont(QFont("微软雅黑", 16))
  210. self.business_purchase_radio.setFont(QFont("微软雅黑", 16))
  211. # 设置选中时显示为红色
  212. self.business_sale_radio.setStyleSheet("")
  213. self.business_purchase_radio.setStyleSheet("")
  214. self.business_type_group.addButton(self.business_sale_radio, 0)
  215. self.business_type_group.addButton(self.business_purchase_radio, 1)
  216. business_layout = QHBoxLayout()
  217. business_layout.addWidget(self.business_sale_radio)
  218. business_layout.addWidget(self.business_purchase_radio)
  219. business_layout.addStretch()
  220. business_widget = QWidget()
  221. business_widget.setLayout(business_layout)
  222. form_layout.addWidget(business_label, row, 4)
  223. form_layout.addWidget(business_widget, row, 5)
  224. row += 1
  225. # 第二行:供货单位(必填)、收货单位(必填)、批号(非必填)、计划关联信息
  226. supplier_label = QLabel("<span style='color: red;'>供货单位 *</span>:")
  227. supplier_label.setFont(QFont("微软雅黑", 16))
  228. supplier_label.setTextFormat(Qt.RichText)
  229. self.supplier_combo = QComboBox()
  230. self.supplier_combo.setMinimumHeight(40)
  231. self.supplier_combo.setFont(QFont("微软雅黑", 16))
  232. self.supplier_combo.setEditable(False)
  233. form_layout.addWidget(supplier_label, row, 0)
  234. form_layout.addWidget(self.supplier_combo, row, 1)
  235. consignee_label = QLabel("<span style='color: red;'>收货单位 *</span>:")
  236. consignee_label.setFont(QFont("微软雅黑", 16))
  237. consignee_label.setTextFormat(Qt.RichText)
  238. self.consignee_combo = QComboBox()
  239. self.consignee_combo.setMinimumHeight(40)
  240. self.consignee_combo.setFont(QFont("微软雅黑", 16))
  241. self.consignee_combo.setEditable(False)
  242. form_layout.addWidget(consignee_label, row, 2)
  243. form_layout.addWidget(self.consignee_combo, row, 3)
  244. # 计划号(非必填)- 移动到原批号位置
  245. plan_label = QLabel("计划号:")
  246. plan_label.setFont(QFont("微软雅黑", 16))
  247. self.plan_no_input = QLineEdit()
  248. self.plan_no_input.setMinimumHeight(40)
  249. self.plan_no_input.setFont(QFont("微软雅黑", 16))
  250. # 添加计划号变化监听,自动查询计划并填充计划量和已执行量
  251. self.plan_no_input.textChanged.connect(self.on_plan_no_changed)
  252. form_layout.addWidget(plan_label, row, 4)
  253. form_layout.addWidget(self.plan_no_input, row, 5)
  254. # 批号 - 移动到原“关联计划”位置
  255. batch_label = QLabel("批号:")
  256. batch_label.setFont(QFont("微软雅黑", 16))
  257. self.batch_no_input = QLineEdit()
  258. self.batch_no_input.setMinimumHeight(40)
  259. self.batch_no_input.setFont(QFont("微软雅黑", 16))
  260. form_layout.addWidget(batch_label, row, 6)
  261. form_layout.addWidget(self.batch_no_input, row, 7)
  262. # 计划关联信息控件仍保留,但不加入布局,用于后台逻辑显示状态
  263. plan_bind_label = QLabel("关联计划:")
  264. plan_bind_label.setFont(QFont("微软雅黑", 16))
  265. self.plan_binding_label = QLabel("未关联")
  266. self.plan_binding_label.setMinimumHeight(40)
  267. self.plan_binding_label.setFont(QFont("微软雅黑", 16))
  268. self.plan_binding_label.setStyleSheet("")
  269. row += 1
  270. # 第三行:毛重(必填)、毛重时间(必填)、备注(占两个元素的宽度)
  271. gross_weight_label = QLabel("<span style='color: red;'>毛重(kg) *</span>:")
  272. gross_weight_label.setFont(QFont("微软雅黑", 16))
  273. gross_weight_label.setTextFormat(Qt.RichText)
  274. self.gross_weight_input = EmptyDoubleSpinBox()
  275. self.gross_weight_input.setMinimumHeight(40)
  276. self.gross_weight_input.setFont(QFont("微软雅黑", 16))
  277. self.gross_weight_input.setDecimals(2)
  278. self.gross_weight_input.setMinimum(-1)
  279. self.gross_weight_input.setMaximum(999999)
  280. self.gross_weight_input.setSpecialValueText("")
  281. self.gross_weight_input.setValue(-1)
  282. self.gross_weight_input.valueChanged.connect(self.on_gross_weight_changed)
  283. form_layout.addWidget(gross_weight_label, row, 0)
  284. form_layout.addWidget(self.gross_weight_input, row, 1)
  285. gross_time_label = QLabel("<span style='color: red;'>毛重时间 *</span>:")
  286. gross_time_label.setFont(QFont("微软雅黑", 16))
  287. gross_time_label.setTextFormat(Qt.RichText)
  288. self.gross_weight_time = EmptyDateTimeEdit()
  289. self.gross_weight_time.setMinimumHeight(40)
  290. self.gross_weight_time.setFont(QFont("微软雅黑", 16))
  291. self.gross_weight_time.setCalendarPopup(True)
  292. # 不设置默认时间,使用一个无效的日期时间表示未设置
  293. self.gross_weight_time.setDateTime(QDateTime())
  294. self.gross_weight_time.setDisplayFormat("yyyy-MM-dd HH:mm:ss")
  295. # 强制清空显示
  296. if self.gross_weight_time.lineEdit():
  297. self.gross_weight_time.lineEdit().setText("")
  298. QTimer.singleShot(0, lambda: self.gross_weight_time.lineEdit().setText("") if self.gross_weight_time.lineEdit() else None)
  299. # 直接使用时间控件,占一整列宽度
  300. form_layout.addWidget(gross_time_label, row, 2)
  301. form_layout.addWidget(self.gross_weight_time, row, 3)
  302. # 备注(占两个元素的宽度,即4列)
  303. remarks_label = QLabel("备注:")
  304. remarks_label.setFont(QFont("微软雅黑", 16))
  305. self.remarks_input = QTextEdit()
  306. self.remarks_input.setFixedHeight(self.batch_no_input.minimumHeight() + 5)
  307. self.remarks_input.setFont(QFont("微软雅黑", 16))
  308. form_layout.addWidget(remarks_label, row, 4)
  309. form_layout.addWidget(self.remarks_input, row, 5, 1, 3)
  310. row += 1
  311. # 第四行:皮重(必填)、皮重时间(必填)、计划量、已执行量
  312. tare_weight_label = QLabel("<span style='color: red;'>皮重(kg) *</span>:")
  313. tare_weight_label.setFont(QFont("微软雅黑", 16))
  314. tare_weight_label.setTextFormat(Qt.RichText)
  315. self.tare_weight_input = EmptyDoubleSpinBox()
  316. self.tare_weight_input.setMinimumHeight(40)
  317. self.tare_weight_input.setFont(QFont("微软雅黑", 16))
  318. self.tare_weight_input.setDecimals(2)
  319. self.tare_weight_input.setMinimum(-1)
  320. self.tare_weight_input.setMaximum(999999)
  321. self.tare_weight_input.setSpecialValueText("")
  322. self.tare_weight_input.setValue(-1)
  323. self.tare_weight_input.valueChanged.connect(self.on_tare_weight_changed)
  324. form_layout.addWidget(tare_weight_label, row, 0)
  325. form_layout.addWidget(self.tare_weight_input, row, 1)
  326. tare_time_label = QLabel("<span style='color: red;'>皮重时间 *</span>:")
  327. tare_time_label.setFont(QFont("微软雅黑", 16))
  328. tare_time_label.setTextFormat(Qt.RichText)
  329. self.tare_weight_time = EmptyDateTimeEdit()
  330. self.tare_weight_time.setMinimumHeight(40)
  331. self.tare_weight_time.setFont(QFont("微软雅黑", 16))
  332. self.tare_weight_time.setCalendarPopup(True)
  333. # 不设置默认时间,使用一个无效的日期时间表示未设置
  334. self.tare_weight_time.setDateTime(QDateTime())
  335. self.tare_weight_time.setDisplayFormat("yyyy-MM-dd HH:mm:ss")
  336. # 强制清空显示
  337. if self.tare_weight_time.lineEdit():
  338. self.tare_weight_time.lineEdit().setText("")
  339. QTimer.singleShot(0, lambda: self.tare_weight_time.lineEdit().setText("") if self.tare_weight_time.lineEdit() else None)
  340. # 直接使用时间控件,占一整列宽度
  341. form_layout.addWidget(tare_time_label, row, 2)
  342. form_layout.addWidget(self.tare_weight_time, row, 3)
  343. planned_label = QLabel("计划量(t):")
  344. planned_label.setFont(QFont("微软雅黑", 16))
  345. self.planned_quantity_input = EmptyDoubleSpinBox()
  346. self.planned_quantity_input.setMinimumHeight(40)
  347. self.planned_quantity_input.setFont(QFont("微软雅黑", 16))
  348. self.planned_quantity_input.setDecimals(3)
  349. self.planned_quantity_input.setMinimum(-1)
  350. self.planned_quantity_input.setMaximum(999999)
  351. self.planned_quantity_input.setSpecialValueText("")
  352. self.planned_quantity_input.setValue(-1)
  353. form_layout.addWidget(planned_label, row, 4)
  354. form_layout.addWidget(self.planned_quantity_input, row, 5)
  355. executed_label = QLabel("已执行量(t):")
  356. executed_label.setFont(QFont("微软雅黑", 16))
  357. self.executed_quantity_input = EmptyDoubleSpinBox()
  358. self.executed_quantity_input.setMinimumHeight(40)
  359. self.executed_quantity_input.setFont(QFont("微软雅黑", 16))
  360. self.executed_quantity_input.setDecimals(3)
  361. self.executed_quantity_input.setMinimum(-1)
  362. self.executed_quantity_input.setMaximum(999999)
  363. self.executed_quantity_input.setSpecialValueText("")
  364. self.executed_quantity_input.setValue(-1)
  365. form_layout.addWidget(executed_label, row, 6)
  366. form_layout.addWidget(self.executed_quantity_input, row, 7)
  367. row += 1
  368. # 第五行:扣杂、净重(只读)、本次量
  369. deduction_label = QLabel("扣杂(kg):")
  370. deduction_label.setFont(QFont("微软雅黑", 16))
  371. self.deduction_input = EmptyDoubleSpinBox()
  372. self.deduction_input.setMinimumHeight(40)
  373. self.deduction_input.setFont(QFont("微软雅黑", 16))
  374. self.deduction_input.setDecimals(2)
  375. self.deduction_input.setMinimum(-1)
  376. self.deduction_input.setMaximum(999999)
  377. self.deduction_input.setSpecialValueText("")
  378. self.deduction_input.setValue(-1)
  379. self.deduction_input.valueChanged.connect(self.calculate_net_weight)
  380. form_layout.addWidget(deduction_label, row, 0)
  381. form_layout.addWidget(self.deduction_input, row, 1)
  382. net_weight_label = QLabel("净重(t):")
  383. net_weight_label.setFont(QFont("微软雅黑", 16))
  384. self.net_weight_label = QLabel("0.000 t")
  385. self.net_weight_label.setMinimumHeight(40)
  386. self.net_weight_label.setFont(QFont("微软雅黑", 16))
  387. self.net_weight_label.setStyleSheet("padding: 5px; border: 1px solid #ccc;")
  388. form_layout.addWidget(net_weight_label, row, 2)
  389. form_layout.addWidget(self.net_weight_label, row, 3)
  390. # 本次量(kg)
  391. current_quantity_label = QLabel("本次量(t):")
  392. current_quantity_label.setFont(QFont("微软雅黑", 16))
  393. self.current_quantity_input = EmptyDoubleSpinBox()
  394. self.current_quantity_input.setMinimumHeight(40)
  395. self.current_quantity_input.setFont(QFont("微软雅黑", 16))
  396. self.current_quantity_input.setDecimals(3)
  397. self.current_quantity_input.setMinimum(-1)
  398. self.current_quantity_input.setMaximum(999999)
  399. self.current_quantity_input.setSpecialValueText("")
  400. self.current_quantity_input.setValue(-1)
  401. form_layout.addWidget(current_quantity_label, row, 4)
  402. form_layout.addWidget(self.current_quantity_input, row, 5)
  403. # 按钮区域
  404. row += 1
  405. button_layout = QHBoxLayout()
  406. button_layout.addStretch()
  407. self.save_btn = QPushButton("保存")
  408. self.save_btn.setMinimumHeight(35)
  409. self.save_btn.setMinimumWidth(120)
  410. self.save_btn.setFont(QFont("微软雅黑", 14, QFont.Bold))
  411. apply_button_style(self.save_btn, 'green')
  412. self.save_btn.clicked.connect(self.save_weighing_slip)
  413. # 添加快捷键
  414. self.save_btn.setShortcut(QKeySequence("Ctrl+S"))
  415. self.clear_btn = QPushButton("清空")
  416. self.clear_btn.setMinimumHeight(35)
  417. self.clear_btn.setMinimumWidth(120)
  418. self.clear_btn.setFont(QFont("微软雅黑", 14))
  419. apply_button_style(self.clear_btn, 'normal')
  420. self.clear_btn.clicked.connect(self.clear_form)
  421. button_layout.addWidget(self.save_btn)
  422. button_layout.addWidget(self.clear_btn)
  423. button_layout.addStretch()
  424. button_widget = QWidget()
  425. button_widget.setLayout(button_layout)
  426. form_layout.addWidget(button_widget, row, 0, 1, 8)
  427. # 将表单布局加入右侧容器
  428. right_layout.addLayout(form_layout)
  429. right_widget.setLayout(right_layout)
  430. # 将左右区域加入水平布局
  431. content_layout.addWidget(left_group)
  432. content_layout.addWidget(right_widget)
  433. # 右侧填写区域整体略窄于原先的满宽,给左侧读数区留出空间
  434. content_layout.setStretch(0, 1)
  435. content_layout.setStretch(1, 3)
  436. # 顶部内容区域加入主布局
  437. layout.addLayout(content_layout)
  438. # 包装在GroupBox中
  439. group_box = QGroupBox()
  440. group_box.setLayout(layout)
  441. return group_box
  442. def create_list_widget(self) -> QWidget:
  443. """创建地磅单记录列表"""
  444. widget = QWidget()
  445. layout = QVBoxLayout()
  446. layout.setContentsMargins(10, 10, 10, 10)
  447. # 标题和刷新按钮区域
  448. title_layout = QHBoxLayout()
  449. title = QLabel("地磅单记录列表")
  450. title_font = QFont("微软雅黑", 18, QFont.Bold)
  451. title.setFont(title_font)
  452. title_layout.addWidget(title)
  453. title_layout.addStretch()
  454. # 视图切换按钮:列表 / 卡片
  455. # 默认使用卡片视图,方便一屏查看更多信息
  456. self.view_mode = "card"
  457. self.table_view_btn = QPushButton("列表视图")
  458. self.table_view_btn.setCheckable(True)
  459. self.table_view_btn.setChecked(False)
  460. self.table_view_btn.setFont(QFont("微软雅黑", 13))
  461. apply_button_style(self.table_view_btn, 'normal')
  462. self.card_view_btn = QPushButton("卡片视图")
  463. self.card_view_btn.setCheckable(True)
  464. self.card_view_btn.setFont(QFont("微软雅黑", 13))
  465. apply_button_style(self.card_view_btn, 'normal')
  466. self.table_view_btn.clicked.connect(lambda: self._switch_view_mode("table"))
  467. self.card_view_btn.clicked.connect(lambda: self._switch_view_mode("card"))
  468. title_layout.addWidget(self.table_view_btn)
  469. title_layout.addWidget(self.card_view_btn)
  470. # 只显示毛重或皮重未完成的勾选框(默认勾选)
  471. self.incomplete_only_checkbox = QCheckBox("仅显示毛重/皮重未完成")
  472. self.incomplete_only_checkbox.setChecked(True)
  473. self.incomplete_only_checkbox.setFont(QFont("微软雅黑", 13))
  474. self.incomplete_only_checkbox.stateChanged.connect(lambda _: self.refresh_list())
  475. title_layout.addWidget(self.incomplete_only_checkbox)
  476. self.search_input = QLineEdit()
  477. self.search_input.setPlaceholderText("检索供货/收货单位、车牌、货物")
  478. self.search_input.setMinimumHeight(36)
  479. self.search_input.setMinimumWidth(500)
  480. self.search_input.setMaximumWidth(600)
  481. self.search_input.setFont(QFont("微软雅黑", 14))
  482. self.search_input.setClearButtonEnabled(True)
  483. self.search_input.textChanged.connect(lambda _: self.refresh_list())
  484. title_layout.addWidget(self.search_input)
  485. self.export_btn = QPushButton("导出Excel")
  486. self.export_btn.setMinimumHeight(40)
  487. self.export_btn.setMinimumWidth(120)
  488. self.export_btn.setFont(QFont("微软雅黑", 16))
  489. apply_button_style(self.export_btn, 'normal')
  490. self.export_btn.clicked.connect(self.export_to_excel)
  491. title_layout.addWidget(self.export_btn)
  492. self.refresh_btn = QPushButton("刷新")
  493. self.refresh_btn.setMinimumHeight(40)
  494. self.refresh_btn.setMinimumWidth(100)
  495. self.refresh_btn.setFont(QFont("微软雅黑", 16))
  496. apply_button_style(self.refresh_btn, 'normal')
  497. self.refresh_btn.setEnabled(True) # 确保按钮是启用状态
  498. self.refresh_btn.clicked.connect(self.refresh_list)
  499. self.refresh_btn.setShortcut(QKeySequence("F5"))
  500. title_layout.addWidget(self.refresh_btn)
  501. layout.addLayout(title_layout)
  502. # 表格视图
  503. self.table = QTableWidget()
  504. # 列顺序:日期、车号、货物名称、业务类型、供货单位、收货单位、毛重/时间、皮重/时间、扣杂、净重、本次量、操作
  505. self.table.setColumnCount(14)
  506. self.table.setHorizontalHeaderLabels([
  507. "日期", "车号", "货物名称", "业务类型", "供货单位", "收货单位",
  508. "毛重(t)", "毛重时间", "皮重(t)", "皮重时间", "扣杂(t)", "净重(t)", "本次量(t)", "操作"
  509. ])
  510. header = self.table.horizontalHeader()
  511. header.setFont(QFont("微软雅黑", 15, QFont.Bold))
  512. header.setSectionsMovable(False)
  513. header.setStretchLastSection(False)
  514. header.setSectionsClickable(False)
  515. self.column_width_ratios = [
  516. 0.08, 0.08, 0.12, 0.08, 0.1, 0.1, 0.07,
  517. 0.08, 0.07, 0.08, 0.06, 0.07, 0.08, 0.15
  518. ]
  519. self._user_resized_columns = False
  520. self._is_applying_column_widths = False
  521. for i in range(self.table.columnCount()):
  522. header.setSectionResizeMode(i, QHeaderView.Interactive)
  523. header.sectionResized.connect(self._on_section_resized)
  524. self._apply_table_column_widths(force=True)
  525. vertical_header = self.table.verticalHeader()
  526. vertical_header.setDefaultAlignment(Qt.AlignCenter)
  527. vertical_header.setFixedWidth(60)
  528. vertical_header.setSectionResizeMode(QHeaderView.ResizeToContents)
  529. self.table.setFont(QFont("微软雅黑", 15))
  530. self.table.setAlternatingRowColors(True)
  531. self.table.setSelectionBehavior(QTableWidget.SelectRows)
  532. layout.addWidget(self.table)
  533. # 卡片视图:使用 QScrollArea + 容器布局
  534. self.card_scroll_area = QScrollArea()
  535. self.card_scroll_area.setWidgetResizable(True)
  536. self.card_scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
  537. self.card_container = QWidget()
  538. # 卡片区域使用网格布局,一行放多个卡片
  539. self.card_layout = QGridLayout()
  540. # 外边距和间距都设置为 4px,保证 5 个卡片之间用 4px 作为间隔
  541. self.card_layout.setContentsMargins(4, 4, 4, 4)
  542. self.card_layout.setHorizontalSpacing(4)
  543. self.card_layout.setVerticalSpacing(10)
  544. self.card_container.setLayout(self.card_layout)
  545. # 一行放 5 个卡片
  546. self.card_columns = 5
  547. # 当前卡片控件缓存,用于窗口大小变化时调整宽度
  548. self._card_widgets = []
  549. self.card_scroll_area.setWidget(self.card_container)
  550. # 默认采用卡片视图,表格视图在需要时再显示
  551. self.card_scroll_area.setVisible(True)
  552. layout.addWidget(self.card_scroll_area)
  553. widget.setLayout(layout)
  554. return widget
  555. def calculate_net_weight(self):
  556. """计算净重"""
  557. gross = self._get_weight_input_value(self.gross_weight_input) or 0
  558. tare = self._get_weight_input_value(self.tare_weight_input) or 0
  559. deduction = self._get_deduction_value()
  560. net = gross - tare - deduction
  561. net_tons = kg_to_tons(net)
  562. if net_tons is None:
  563. net_tons = 0
  564. self.net_weight_label.setText(f"{net_tons:.3f} t")
  565. def on_gross_weight_changed(self, value: float):
  566. """毛重改变时自动更新时间"""
  567. self.calculate_net_weight()
  568. self._maybe_update_weight_time(value, self.gross_weight_time)
  569. def on_tare_weight_changed(self, value: float):
  570. """皮重改变时自动更新时间"""
  571. self.calculate_net_weight()
  572. self._maybe_update_weight_time(value, self.tare_weight_time)
  573. def _maybe_update_weight_time(self, value: float, time_edit: EmptyDateTimeEdit):
  574. """根据重量变化自动填充或清空时间"""
  575. if self._is_clearing_form:
  576. return
  577. if value > 0:
  578. self._set_time_to_now(time_edit)
  579. elif value < 0:
  580. self._clear_time_edit(time_edit)
  581. def _set_time_to_now(self, time_edit: EmptyDateTimeEdit):
  582. """将指定时间控件设置为当前时间"""
  583. current_dt = QDateTime.currentDateTime()
  584. time_edit.setDateTime(current_dt)
  585. def _clear_time_edit(self, time_edit: EmptyDateTimeEdit):
  586. """清空时间控件"""
  587. time_edit.setDateTime(QDateTime())
  588. def _get_weight_input_value(self, spinbox: EmptyDoubleSpinBox) -> Optional[float]:
  589. """获取重量输入的实际值,未填则返回None"""
  590. value = spinbox.value()
  591. return value if value >= 0 else None
  592. def _get_deduction_value(self) -> float:
  593. """获取扣杂值,未填返回0"""
  594. value = self.deduction_input.value()
  595. return value if value >= 0 else 0
  596. def _get_datetime_text(self, time_edit: EmptyDateTimeEdit) -> str:
  597. """获取时间控件的文本"""
  598. line_edit = time_edit.lineEdit()
  599. return line_edit.text().strip() if line_edit else ""
  600. def _get_datetime_str(self, time_edit: EmptyDateTimeEdit) -> str:
  601. """将时间控件转换为字符串"""
  602. if time_edit.dateTime().isValid() and self._get_datetime_text(time_edit):
  603. return time_edit.dateTime().toString("yyyy-MM-dd HH:mm:ss")
  604. return ""
  605. def _set_datetime_from_str(self, time_edit: EmptyDateTimeEdit, value: str):
  606. """根据字符串设置时间控件"""
  607. if value:
  608. dt = QDateTime.fromString(value, "yyyy-MM-dd HH:mm:ss")
  609. if dt.isValid():
  610. time_edit.setDateTime(dt)
  611. return
  612. self._clear_time_edit(time_edit)
  613. if time_edit.lineEdit():
  614. time_edit.lineEdit().setText("")
  615. def _ensure_combo_value(self, combo: QComboBox, value: str):
  616. """确保下拉框中存在指定值并选中"""
  617. if value is None:
  618. combo.setCurrentIndex(0)
  619. return
  620. text = value.strip()
  621. if not text:
  622. combo.setCurrentIndex(0)
  623. return
  624. index = combo.findText(text)
  625. if index < 0:
  626. combo.addItem(text)
  627. index = combo.findText(text)
  628. combo.setCurrentIndex(max(0, index))
  629. @staticmethod
  630. def _ton_value_from_kg(value: Optional[float]):
  631. tons = kg_to_tons(value)
  632. if tons is None:
  633. return ""
  634. return round(tons, 3)
  635. def refresh_dropdowns(self):
  636. """刷新下拉列表"""
  637. # 刷新货物名称
  638. self.cargo_combo.clear()
  639. self.cargo_combo.addItem("") # 添加一个空选项
  640. cargos = self.db.get_all_cargos()
  641. for cargo in cargos:
  642. self.cargo_combo.addItem(cargo['name'])
  643. self.cargo_combo.setCurrentIndex(0) # 默认选中空选项
  644. # 刷新公司名称(供货单位和收货单位共用)
  645. self.supplier_combo.clear()
  646. self.supplier_combo.addItem("") # 添加一个空选项
  647. self.consignee_combo.clear()
  648. self.consignee_combo.addItem("") # 添加一个空选项
  649. companies = self.db.get_all_companies()
  650. for company in companies:
  651. self.supplier_combo.addItem(company['name'])
  652. self.consignee_combo.addItem(company['name'])
  653. self.supplier_combo.setCurrentIndex(0) # 默认选中空选项
  654. self.consignee_combo.setCurrentIndex(0) # 默认选中空选项
  655. def refresh_list(self):
  656. """刷新地磅单记录列表"""
  657. keyword = self.search_input.text().strip() if hasattr(self, "search_input") else ""
  658. slips = self.db.get_all_weighing_slips(keyword=keyword if keyword else None)
  659. # 勾选时,仅显示毛重或皮重任一未完成(为空/未填)的记录
  660. if hasattr(self, "incomplete_only_checkbox") and self.incomplete_only_checkbox.isChecked():
  661. def _is_completed(slip: dict) -> bool:
  662. gross_weight = slip.get('gross_weight')
  663. tare_weight = slip.get('tare_weight')
  664. gross_time = (slip.get('gross_weight_time') or "").strip()
  665. tare_time = (slip.get('tare_weight_time') or "").strip()
  666. gross_ok = (gross_weight is not None and gross_weight > 0) or bool(gross_time)
  667. tare_ok = (tare_weight is not None and tare_weight > 0) or bool(tare_time)
  668. # 两者都完成才算完整;否则视为未完成
  669. return gross_ok and tare_ok
  670. slips = [s for s in slips if not _is_completed(s)]
  671. # 根据关联出入库单日期、创建时间、毛重时间、皮重时间倒序排列(后端已按该规则排序,这里再兜底一次)
  672. def _sort_key(s: dict):
  673. # inbound_date 为关联出入库单的日期("yyyy-MM-dd"),其余时间字段为 "yyyy-MM-dd HH:mm:ss" 字符串
  674. inbound_date = s.get('inbound_date') or ""
  675. created = s.get('created_at') or ""
  676. gross_t = s.get('gross_weight_time') or ""
  677. tare_t = s.get('tare_weight_time') or ""
  678. return (inbound_date, created, gross_t, tare_t)
  679. slips = sorted(slips, key=_sort_key, reverse=True)
  680. # 缓存当前列表数据,供卡片视图复用
  681. self._current_slips = slips
  682. # 根据当前视图模式渲染
  683. if getattr(self, "view_mode", "table") == "card":
  684. self._refresh_card_view()
  685. else:
  686. self._refresh_table_view()
  687. def _refresh_table_view(self):
  688. """以表格形式渲染地磅单列表"""
  689. slips = getattr(self, "_current_slips", [])
  690. self.table.setRowCount(len(slips))
  691. today_str = datetime.now().strftime("%Y-%m-%d")
  692. # 移除背景色设置
  693. for i, slip in enumerate(slips):
  694. # 日期(优先使用关联出入库单的 date 字段,其次使用地磅单创建日期的日期部分)
  695. inbound_date = (slip.get('inbound_date') or "").strip()
  696. if not inbound_date:
  697. created_at = (slip.get('created_at') or "").strip()
  698. inbound_date = created_at.split(" ")[0] if created_at else "-"
  699. self.table.setItem(i, 0, QTableWidgetItem(inbound_date))
  700. # 车号
  701. self.table.setItem(i, 1, QTableWidgetItem(slip['vehicle_no']))
  702. # 货物名称
  703. self.table.setItem(i, 2, QTableWidgetItem(slip['cargo_name']))
  704. # 业务类型
  705. self.table.setItem(i, 3, QTableWidgetItem(slip['business_type']))
  706. # 供货单位
  707. self.table.setItem(i, 4, QTableWidgetItem(slip['supplier']))
  708. # 收货单位
  709. self.table.setItem(i, 5, QTableWidgetItem(slip['consignee']))
  710. # 毛重
  711. gross_display = "-"
  712. gross_weight = slip.get('gross_weight')
  713. if gross_weight is not None and (gross_weight > 0 or slip.get('gross_weight_time')):
  714. gross_display = f"{kg_to_tons(gross_weight):.3f}"
  715. self.table.setItem(i, 6, QTableWidgetItem(gross_display))
  716. # 毛重时间
  717. gross_time_display = slip['gross_weight_time'] if slip['gross_weight_time'] else "-"
  718. self.table.setItem(i, 7, QTableWidgetItem(gross_time_display))
  719. # 皮重
  720. tare_display = "-"
  721. tare_weight = slip.get('tare_weight')
  722. if tare_weight is not None and (tare_weight > 0 or slip.get('tare_weight_time')):
  723. tare_display = f"{kg_to_tons(tare_weight):.3f}"
  724. self.table.setItem(i, 8, QTableWidgetItem(tare_display))
  725. # 皮重时间
  726. tare_time_display = slip['tare_weight_time'] if slip['tare_weight_time'] else "-"
  727. self.table.setItem(i, 9, QTableWidgetItem(tare_time_display))
  728. # 扣杂
  729. deduction_display = "-"
  730. deduction_value = slip.get('deduction')
  731. if deduction_value is not None and deduction_value >= 0:
  732. deduction_display = f"{kg_to_tons(deduction_value):.3f}"
  733. self.table.setItem(i, 10, QTableWidgetItem(deduction_display))
  734. # 净重
  735. if slip['is_voided']:
  736. net_weight_item = QTableWidgetItem("[作废]")
  737. # 移除作废单文字颜色
  738. else:
  739. net_weight = slip.get('net_weight')
  740. if net_weight is None or net_weight <= 0:
  741. net_display = "-"
  742. else:
  743. net_display = f"{kg_to_tons(net_weight):.3f}"
  744. net_weight_item = QTableWidgetItem(net_display)
  745. self.table.setItem(i, 11, net_weight_item)
  746. # 本次量(kg)
  747. current_quantity = slip.get('current_quantity')
  748. if current_quantity is not None and current_quantity >= 0:
  749. current_quantity_display = f"{kg_to_tons(current_quantity):.3f}"
  750. else:
  751. current_quantity_display = "-"
  752. self.table.setItem(i, 12, QTableWidgetItem(current_quantity_display))
  753. # 操作按钮
  754. btn_widget = QWidget()
  755. btn_layout = QHBoxLayout()
  756. btn_layout.setContentsMargins(5, 2, 5, 2)
  757. edit_btn = QPushButton("编辑")
  758. edit_btn.setFont(QFont("微软雅黑", 14))
  759. apply_button_style(edit_btn, 'normal')
  760. edit_btn.clicked.connect(lambda checked, sid=slip['id']: self.start_editing_slip(sid))
  761. edit_btn.setEnabled(not slip['is_voided'])
  762. detail_btn = QPushButton("查看")
  763. detail_btn.setFont(QFont("微软雅黑", 14))
  764. apply_button_style(detail_btn, 'normal')
  765. detail_btn.clicked.connect(lambda checked, sid=slip['id']: self.show_detail(sid))
  766. preview_btn = QPushButton("打印")
  767. preview_btn.setFont(QFont("微软雅黑", 14))
  768. apply_button_style(preview_btn, 'blue')
  769. preview_btn.clicked.connect(lambda checked, sid=slip['id']: self.preview_slip(sid))
  770. void_btn = QPushButton("作废")
  771. void_btn.setFont(QFont("微软雅黑", 14))
  772. apply_button_style(void_btn, 'normal')
  773. void_btn.clicked.connect(lambda checked, sid=slip['id']: self.void_slip(sid))
  774. if slip['is_voided']:
  775. void_btn.setEnabled(False)
  776. void_btn.setText("已作废")
  777. btn_layout.addWidget(edit_btn)
  778. btn_layout.addWidget(detail_btn)
  779. btn_layout.addWidget(preview_btn)
  780. btn_layout.addWidget(void_btn)
  781. btn_widget.setLayout(btn_layout)
  782. self.table.setCellWidget(i, 13, btn_widget)
  783. # 判断是否是当天称重
  784. is_today_weight = any(
  785. (slip.get(field) or "").startswith(today_str)
  786. for field in ('gross_weight_time', 'tare_weight_time')
  787. )
  788. # 移除当天高亮和作废单背景色设置
  789. self.table.resizeRowsToContents()
  790. QTimer.singleShot(0, self.table.resizeRowsToContents)
  791. self._apply_table_column_widths()
  792. # 只在表格视图下显示表格、隐藏卡片区域
  793. if hasattr(self, "card_scroll_area"):
  794. self.table.setVisible(True)
  795. self.card_scroll_area.setVisible(False)
  796. def _refresh_card_view(self):
  797. """以卡片形式渲染地磅单列表"""
  798. slips = getattr(self, "_current_slips", [])
  799. today_str = datetime.now().strftime("%Y-%m-%d")
  800. # 清空旧卡片(网格布局)
  801. while self.card_layout.count():
  802. item = self.card_layout.takeAt(0)
  803. w = item.widget()
  804. if w is not None:
  805. w.deleteLater()
  806. # 清空旧的卡片缓存,避免引用到已销毁的 QFrame
  807. self._card_widgets = []
  808. for idx, slip in enumerate(slips):
  809. card = QFrame()
  810. card.setFrameShape(QFrame.StyledPanel)
  811. card.setFrameShadow(QFrame.Raised)
  812. card.setStyleSheet("border: 1px solid #ccc; border-radius: 6px;")
  813. # 控制卡片高度为固定值,宽度由布局和窗口大小动态控制
  814. card.setFixedHeight(220)
  815. card_layout = QVBoxLayout()
  816. card_layout.setContentsMargins(10, 8, 10, 8)
  817. card_layout.setSpacing(4)
  818. # 顶部行:日期(重点) + 业务类型 + 右上角“查看/作废”文字按钮
  819. top_layout = QHBoxLayout()
  820. # 靠近右上角,缩小整体内部间距
  821. top_layout.setContentsMargins(0, 0, 0, 0)
  822. # 顶部整体不使用默认间距,改为在日期和业务类型之间手动插入 10px 间距
  823. top_layout.setSpacing(0)
  824. inbound_date = (slip.get('inbound_date') or "").strip()
  825. if not inbound_date:
  826. created_at = (slip.get('created_at') or "").strip()
  827. inbound_date = created_at.split(" ")[0] if created_at else "-"
  828. date_label = QLabel(inbound_date)
  829. # 日期加粗显示,去掉自身边框,仅依赖卡片大边框
  830. date_label.setFont(QFont("微软雅黑", 14, QFont.Bold))
  831. date_label.setStyleSheet("border: none;")
  832. business_type = slip.get('business_type', '')
  833. biz_label = QLabel(business_type)
  834. # 入库/出库字体加粗并用不同颜色区分,同时去掉自身边框
  835. biz_label.setFont(QFont("微软雅黑", 12, QFont.Bold))
  836. biz_label.setStyleSheet("border: none;")
  837. # 顶部右侧:查看、作废两个“文字链接”样式的按钮,便于紧贴右上角
  838. detail_btn = QPushButton("查看")
  839. detail_btn.setFont(QFont("微软雅黑", 11))
  840. detail_btn.setFlat(True)
  841. detail_btn.setCursor(Qt.PointingHandCursor)
  842. # 链接风格:蓝色、无边框、透明背景
  843. detail_btn.setStyleSheet("border: none; background: transparent; padding: 0px;")
  844. detail_btn.clicked.connect(lambda checked, sid=slip['id']: self.show_detail(sid))
  845. void_btn = QPushButton("作废")
  846. void_btn.setFont(QFont("微软雅黑", 11))
  847. void_btn.setFlat(True)
  848. void_btn.setCursor(Qt.PointingHandCursor)
  849. # 作废按钮使用红色文字链接风格
  850. void_btn.setStyleSheet("border: none; background: transparent; padding: 0px;")
  851. void_btn.clicked.connect(lambda checked, sid=slip['id']: self.void_slip(sid))
  852. top_layout.addWidget(date_label)
  853. # 日期与“入库/出库”标签之间增加 10px 间距
  854. top_layout.addSpacing(10)
  855. top_layout.addWidget(biz_label)
  856. top_layout.addStretch()
  857. # 右上角两个“文字链接”之间保留约 20px 的间距
  858. top_layout.addWidget(detail_btn)
  859. top_layout.addSpacing(20)
  860. top_layout.addWidget(void_btn)
  861. # 中间行:车牌号(重点)、右侧为“产品名称 + 本次量”(上下两行)
  862. middle_layout = QHBoxLayout()
  863. plate_label = QLabel(slip.get('vehicle_no', ''))
  864. # 车牌号加粗显示,去掉自身边框
  865. plate_label.setFont(QFont("微软雅黑", 20, QFont.Bold))
  866. plate_label.setStyleSheet("border: none;")
  867. cargo_label = QLabel(slip.get('cargo_name', ''))
  868. # 产品名称加粗显示,去掉自身边框
  869. cargo_label.setFont(QFont("微软雅黑", 12, QFont.Bold))
  870. cargo_label.setStyleSheet("border: none;")
  871. # 占位的本次量标签,具体文本后面根据 current_text 设置
  872. current_label = QLabel()
  873. current_label.setFont(QFont("微软雅黑", 12))
  874. current_label.setStyleSheet("border: none;")
  875. # 第三行:供货 / 收货单位(核心信息)
  876. company_layout = QHBoxLayout()
  877. company_text = f"{slip.get('supplier', '')} → {slip.get('consignee', '')}"
  878. company_label = QLabel(company_text)
  879. company_label.setFont(QFont("微软雅黑", 12))
  880. company_label.setStyleSheet("border: none;")
  881. company_layout.addWidget(company_label)
  882. company_layout.addStretch()
  883. # 第四行:毛重 / 皮重 / 净重(核心信息)
  884. gross_weight = slip.get('gross_weight')
  885. tare_weight = slip.get('tare_weight')
  886. net_weight = slip.get('net_weight')
  887. current_quantity = slip.get('current_quantity')
  888. if slip.get('is_voided'):
  889. gross_text = "[作废]"
  890. tare_text = "[作废]"
  891. net_text = "[作废]"
  892. current_text = "[作废]"
  893. else:
  894. if gross_weight is not None and gross_weight > 0:
  895. gross_text = f"{kg_to_tons(gross_weight):.3f} t"
  896. else:
  897. gross_text = "-"
  898. if tare_weight is not None and tare_weight > 0:
  899. tare_text = f"{kg_to_tons(tare_weight):.3f} t"
  900. else:
  901. tare_text = "-"
  902. if net_weight is not None and net_weight > 0:
  903. net_text = f"{kg_to_tons(net_weight):.3f} t"
  904. else:
  905. net_text = "-"
  906. if current_quantity is not None and current_quantity >= 0:
  907. current_text = f"{kg_to_tons(current_quantity):.3f} t"
  908. else:
  909. current_text = "-"
  910. # 设置中间区域:右侧为“产品名称 + 本次量”,上下两行
  911. current_label.setText(f"本次: {current_text}")
  912. product_layout = QVBoxLayout()
  913. product_layout.setContentsMargins(0, 0, 0, 0)
  914. product_layout.setSpacing(2)
  915. product_layout.addWidget(cargo_label)
  916. product_layout.addWidget(current_label)
  917. middle_layout.addWidget(plate_label, stretch=1)
  918. middle_layout.addLayout(product_layout, stretch=1)
  919. middle_layout.addStretch()
  920. # 重量行:毛重 / 皮重 / 净重(文案中带“重”字)
  921. weight_line_label = QLabel(f"毛重: {gross_text} 皮重: {tare_text} 净重: {net_text}")
  922. weight_line_label.setFont(QFont("微软雅黑", 12))
  923. weight_line_label.setStyleSheet("border: none;")
  924. # 第五行:备注(如过长,可自动换行)(核心信息)
  925. remarks = (slip.get('remarks') or "").strip()
  926. if not remarks:
  927. remarks = "-"
  928. remarks_label = QLabel(f"备注: {remarks}")
  929. remarks_label.setFont(QFont("微软雅黑", 11))
  930. remarks_label.setStyleSheet("border: none;")
  931. remarks_label.setWordWrap(True)
  932. # 底部行:主要操作按钮(编辑、打印),一行仅两个按钮,并整体左右居中
  933. btn_layout = QHBoxLayout()
  934. btn_layout.setContentsMargins(0, 0, 0, 0)
  935. # 两个按钮之间留 10px 间距,这样每个按钮实际宽度约为
  936. # (可用总宽度 - 10) / 2,即“各占 1/2 宽度 - 10px(用于间距)”
  937. btn_layout.setSpacing(10)
  938. # 左右各加一个 stretch,使两个按钮整体水平居中
  939. btn_layout.addStretch()
  940. edit_btn = QPushButton("编辑")
  941. # 编辑按钮:字体稍大,尺寸更大,方便点击
  942. edit_btn.setFont(QFont("微软雅黑", 13))
  943. apply_button_style(edit_btn, 'normal')
  944. edit_btn.clicked.connect(lambda checked, sid=slip['id']: self.start_editing_slip(sid))
  945. edit_btn.setEnabled(not slip.get('is_voided'))
  946. preview_btn = QPushButton("打印")
  947. # 打印按钮:与编辑按钮同级别,字体稍大,尺寸更大
  948. preview_btn.setFont(QFont("微软雅黑", 13))
  949. apply_button_style(preview_btn, 'blue')
  950. preview_btn.clicked.connect(lambda checked, sid=slip['id']: self.preview_slip(sid))
  951. # 分别设置按钮的最小尺寸:编辑/打印更大,并允许水平扩展
  952. edit_btn.setMinimumWidth(130)
  953. edit_btn.setMinimumHeight(38)
  954. edit_btn.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
  955. preview_btn.setMinimumWidth(130)
  956. preview_btn.setMinimumHeight(38)
  957. preview_btn.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
  958. # 底部只放主要操作:编辑、打印,一行两个大按钮均分宽度,整体居中
  959. btn_layout.addWidget(edit_btn)
  960. btn_layout.addWidget(preview_btn)
  961. btn_layout.addStretch()
  962. # 判断当天称重,高亮卡片背景(仅调整背景,不改变字体颜色)
  963. is_today_weight = any(
  964. (slip.get(field) or "").startswith(today_str)
  965. for field in ('gross_weight_time', 'tare_weight_time')
  966. )
  967. # 移除当天高亮和作废单背景色
  968. card.setStyleSheet("border: 1px solid #ccc; border-radius: 6px;")
  969. card_layout.addLayout(top_layout)
  970. card_layout.addLayout(middle_layout) # 车牌号 + 产品
  971. card_layout.addLayout(company_layout) # 供货单位 -> 收货单位
  972. card_layout.addWidget(weight_line_label) # 毛重 + 净重 + 本次量
  973. card_layout.addWidget(remarks_label) # 备注
  974. card_layout.addLayout(btn_layout)
  975. card.setLayout(card_layout)
  976. # 记录卡片控件,便于统一调整宽度
  977. if not hasattr(self, "_card_widgets"):
  978. self._card_widgets = []
  979. self._card_widgets.append(card)
  980. # 添加到网格布局:一行多个(由 self.card_columns 控制)
  981. col_count = getattr(self, "card_columns", 3) or 3
  982. row = idx // col_count
  983. col = idx % col_count
  984. self.card_layout.addWidget(card, row, col)
  985. # 刷新完后根据当前宽度调整卡片宽度
  986. self._update_card_widths()
  987. # 显示卡片区域、隐藏表格
  988. self.table.setVisible(False)
  989. self.card_scroll_area.setVisible(True)
  990. def resizeEvent(self, event):
  991. super().resizeEvent(event)
  992. # 仅在表格视图下调整列宽
  993. if getattr(self, "view_mode", "table") == "table":
  994. self._apply_table_column_widths()
  995. else:
  996. # 卡片视图下根据当前宽度调整卡片宽度
  997. self._update_card_widths()
  998. self._update_form_widget_height()
  999. def showEvent(self, event):
  1000. super().showEvent(event)
  1001. if getattr(self, "view_mode", "table") == "table":
  1002. QTimer.singleShot(0, lambda: self._apply_table_column_widths(force=True))
  1003. def _on_section_resized(self, *_):
  1004. # 仅在表格视图下记录用户手动调整列宽
  1005. if getattr(self, "view_mode", "table") != "table":
  1006. return
  1007. if getattr(self, "_is_applying_column_widths", False):
  1008. return
  1009. self._user_resized_columns = True
  1010. def _apply_table_column_widths(self, force: bool = False):
  1011. if not hasattr(self, "table") or not hasattr(self, "column_width_ratios"):
  1012. return
  1013. # 卡片视图下不自动调整表格列宽
  1014. if getattr(self, "view_mode", "table") != "table":
  1015. return
  1016. if getattr(self, "_user_resized_columns", False) and not force:
  1017. return
  1018. viewport_width = self.table.viewport().width()
  1019. if viewport_width <= 0:
  1020. return
  1021. total_ratio = sum(self.column_width_ratios) or 1
  1022. assigned_width = 0
  1023. header = self.table.horizontalHeader()
  1024. self._is_applying_column_widths = True
  1025. header.blockSignals(True)
  1026. try:
  1027. for index, ratio in enumerate(self.column_width_ratios):
  1028. if index == self.table.columnCount() - 1:
  1029. width = viewport_width - assigned_width
  1030. else:
  1031. width = int(viewport_width * ratio / total_ratio)
  1032. assigned_width += width
  1033. self.table.setColumnWidth(index, max(width, 70))
  1034. # 像素级微调:
  1035. # - 日期列宽度在计算结果基础上增加 20 像素
  1036. # - 毛重/皮重列宽度在计算结果基础上各减少 10 像素
  1037. # (三列整体保持总宽度不变)
  1038. # 列索引:0 = 日期, 6 = 毛重(t), 8 = 皮重(t)
  1039. date_col_index = 0
  1040. gross_col_index = 6
  1041. tare_col_index = 8
  1042. # 当前宽度
  1043. date_width = self.table.columnWidth(date_col_index)
  1044. gross_width = self.table.columnWidth(gross_col_index)
  1045. tare_width = self.table.columnWidth(tare_col_index)
  1046. # 目标宽度(注意仍然要遵守最小宽度 70 像素)
  1047. self.table.setColumnWidth(date_col_index, max(date_width + 20, 70))
  1048. self.table.setColumnWidth(gross_col_index, max(gross_width - 10, 70))
  1049. self.table.setColumnWidth(tare_col_index, max(tare_width - 10, 70))
  1050. finally:
  1051. header.blockSignals(False)
  1052. self._is_applying_column_widths = False
  1053. def _update_form_widget_height(self):
  1054. if not hasattr(self, "form_widget") or not self.form_widget:
  1055. return
  1056. hint_height = self.form_widget.sizeHint().height()
  1057. if hint_height > 0:
  1058. self.form_widget.setMaximumHeight(hint_height)
  1059. def _update_card_widths(self):
  1060. """根据当前滚动区域宽度,动态设置卡片宽度:
  1061. 一行 5 个卡片,每个宽度约等于(总宽度 / 5) - 4px(用于卡片间间隔)"""
  1062. # 仅在卡片视图下生效
  1063. if getattr(self, "view_mode", "table") == "table":
  1064. return
  1065. if not hasattr(self, "card_scroll_area") or not hasattr(self, "card_layout"):
  1066. return
  1067. if not hasattr(self, "_card_widgets") or not self._card_widgets:
  1068. return
  1069. viewport = self.card_scroll_area.viewport()
  1070. total_width = viewport.width()
  1071. if total_width <= 0:
  1072. return
  1073. # 计算可用宽度:去掉左右外边距
  1074. margins = self.card_layout.contentsMargins()
  1075. available_width = total_width - margins.left() - margins.right()
  1076. if available_width <= 0:
  1077. return
  1078. col_count = getattr(self, "card_columns", 5) or 5
  1079. # 列间距(卡片间的空隙)
  1080. h_spacing = self.card_layout.horizontalSpacing() or 0
  1081. # 总间隔宽度 = (列数 - 1) * spacing
  1082. total_spacing = (col_count - 1) * h_spacing
  1083. if available_width <= total_spacing:
  1084. return
  1085. # 每个卡片的目标宽度:剩余宽度平均分到 5 列,再略减一点,避免溢出
  1086. card_width = int((available_width - total_spacing) / col_count)
  1087. if card_width <= 0:
  1088. return
  1089. # 过滤掉已经被 Qt 销毁的卡片对象,避免 RuntimeError
  1090. alive_cards = []
  1091. for card in self._card_widgets:
  1092. if card is None:
  1093. continue
  1094. # sip.isdeleted 用来判断底层 C++ 对象是否已经被销毁
  1095. if sip.isdeleted(card):
  1096. continue
  1097. alive_cards.append(card)
  1098. card.setMinimumWidth(card_width)
  1099. card.setMaximumWidth(card_width)
  1100. # 用仅包含存活对象的列表替换原缓存
  1101. self._card_widgets = alive_cards
  1102. def event(self, event):
  1103. screen_change_event = getattr(QEvent, "ScreenChangeInternal", None)
  1104. event_types = (
  1105. QEvent.FontChange,
  1106. QEvent.ApplicationFontChange,
  1107. QEvent.StyleChange,
  1108. )
  1109. if screen_change_event is not None:
  1110. event_types = event_types + (screen_change_event,)
  1111. if event.type() in event_types:
  1112. QTimer.singleShot(0, self._update_form_widget_height)
  1113. return super().event(event)
  1114. def _switch_view_mode(self, mode: str):
  1115. """切换列表展示模式:table / card"""
  1116. if mode == self.view_mode:
  1117. return
  1118. self.view_mode = mode
  1119. # 同步按钮选中状态
  1120. if mode == "table":
  1121. self.table_view_btn.setChecked(True)
  1122. self.card_view_btn.setChecked(False)
  1123. # 重新以表格方式渲染
  1124. self._refresh_table_view()
  1125. else:
  1126. self.table_view_btn.setChecked(False)
  1127. self.card_view_btn.setChecked(True)
  1128. # 重新以卡片方式渲染
  1129. self._refresh_card_view()
  1130. def export_to_excel(self):
  1131. """导出地磅单信息"""
  1132. slips = self.db.get_all_weighing_slips(include_voided=False)
  1133. if not slips:
  1134. QMessageBox.information(self, "提示", "暂无可导出的地磅单数据。")
  1135. return
  1136. default_name = f"地磅单导出_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
  1137. file_path, _ = QFileDialog.getSaveFileName(
  1138. self,
  1139. "导出地磅单记录",
  1140. default_name,
  1141. "Excel Files (*.xlsx)"
  1142. )
  1143. if not file_path:
  1144. return
  1145. if not file_path.lower().endswith(".xlsx"):
  1146. file_path += ".xlsx"
  1147. export_rows = []
  1148. for slip in slips:
  1149. current_quantity_ton = kg_to_tons(slip.get('current_quantity'))
  1150. export_rows.append({
  1151. "地磅单ID": slip.get('id'),
  1152. "计划号": slip.get('plan_no', ''),
  1153. "批次号": slip.get('batch_no', ''),
  1154. "车号": slip.get('vehicle_no', ''),
  1155. "货物名称": slip.get('cargo_name', ''),
  1156. "业务类型": slip.get('business_type', ''),
  1157. "供货单位": slip.get('supplier', ''),
  1158. "收货单位": slip.get('consignee', ''),
  1159. "毛重(t)": self._ton_value_from_kg(slip.get('gross_weight')),
  1160. "毛重时间": slip.get('gross_weight_time', ''),
  1161. "皮重(t)": self._ton_value_from_kg(slip.get('tare_weight')),
  1162. "皮重时间": slip.get('tare_weight_time', ''),
  1163. "扣杂(t)": self._ton_value_from_kg(slip.get('deduction')),
  1164. "净重(t)": self._ton_value_from_kg(slip.get('net_weight')),
  1165. "本次量(t)": round(current_quantity_ton, 3) if current_quantity_ton is not None else "",
  1166. "称重时间": slip.get('created_at', ''),
  1167. "备注": slip.get('remarks', ''),
  1168. "已执行量(kg)": slip.get('executed_quantity', ''),
  1169. "是否作废": "是" if slip.get('is_voided') else "否"
  1170. })
  1171. try:
  1172. df = pd.DataFrame(export_rows)
  1173. df.to_excel(file_path, index=False)
  1174. QMessageBox.information(self, "导出成功", f"已导出 {len(export_rows)} 条地磅单记录。")
  1175. except Exception as e:
  1176. QMessageBox.critical(self, "导出失败", f"导出Excel失败:{str(e)}")
  1177. def validate_form(self) -> Tuple[bool, str]:
  1178. """验证表单数据"""
  1179. # 清除之前的错误样式
  1180. self.clear_error_styles()
  1181. if not self.vehicle_no_input.text().strip():
  1182. self.set_error_style(self.vehicle_no_input)
  1183. return False, "请填写车号"
  1184. if self.cargo_combo.currentIndex() <= 0 or not self.cargo_combo.currentText().strip():
  1185. self.set_error_style(self.cargo_combo)
  1186. return False, "请选择货物名称"
  1187. if not self.business_type_group.checkedButton():
  1188. return False, "请选择业务类型"
  1189. if self.supplier_combo.currentIndex() <= 0 or not self.supplier_combo.currentText().strip():
  1190. self.set_error_style(self.supplier_combo)
  1191. return False, "请选择供货单位"
  1192. if self.consignee_combo.currentIndex() <= 0 or not self.consignee_combo.currentText().strip():
  1193. self.set_error_style(self.consignee_combo)
  1194. return False, "请选择收货单位"
  1195. gross_value = self._get_weight_input_value(self.gross_weight_input)
  1196. tare_value = self._get_weight_input_value(self.tare_weight_input)
  1197. gross_time_text = self._get_datetime_text(self.gross_weight_time)
  1198. tare_time_text = self._get_datetime_text(self.tare_weight_time)
  1199. gross_time_valid = self.gross_weight_time.dateTime().isValid() and bool(gross_time_text)
  1200. tare_time_valid = self.tare_weight_time.dateTime().isValid() and bool(tare_time_text)
  1201. if gross_value is not None and gross_value <= 0:
  1202. self.set_error_style(self.gross_weight_input)
  1203. return False, "毛重必须大于0"
  1204. if tare_value is not None and tare_value <= 0:
  1205. self.set_error_style(self.tare_weight_input)
  1206. return False, "皮重必须大于0"
  1207. if gross_value is not None and not gross_time_valid:
  1208. self.set_error_style(self.gross_weight_time)
  1209. return False, "已填写毛重后必须填写毛重时间"
  1210. if gross_time_valid and gross_value is None:
  1211. self.set_error_style(self.gross_weight_input)
  1212. return False, "填写毛重时间前需要填写毛重"
  1213. if tare_value is not None and not tare_time_valid:
  1214. self.set_error_style(self.tare_weight_time)
  1215. return False, "已填写皮重后必须填写皮重时间"
  1216. if tare_time_valid and tare_value is None:
  1217. self.set_error_style(self.tare_weight_input)
  1218. return False, "填写皮重时间前需要填写皮重"
  1219. if gross_value is not None and tare_value is not None:
  1220. deduction = self._get_deduction_value()
  1221. net_weight = gross_value - tare_value - deduction
  1222. if net_weight <= 0:
  1223. return False, "净重必须大于0,请检查毛重、皮重和扣杂的数值"
  1224. return True, ""
  1225. def set_error_style(self, widget):
  1226. """设置错误样式(红色边框)"""
  1227. widget.setStyleSheet("border: 2px solid red;")
  1228. def clear_error_styles(self):
  1229. """清除所有错误样式"""
  1230. self.vehicle_no_input.setStyleSheet("")
  1231. self.cargo_combo.setStyleSheet("")
  1232. self.supplier_combo.setStyleSheet("")
  1233. self.consignee_combo.setStyleSheet("")
  1234. self.gross_weight_input.setStyleSheet("")
  1235. self.tare_weight_input.setStyleSheet("")
  1236. self.gross_weight_time.setStyleSheet("")
  1237. self.tare_weight_time.setStyleSheet("")
  1238. def save_weighing_slip(self):
  1239. """保存地磅单"""
  1240. # 验证
  1241. valid, error_msg = self.validate_form()
  1242. if not valid:
  1243. QMessageBox.warning(self, "验证失败", error_msg)
  1244. return
  1245. gross_value = self._get_weight_input_value(self.gross_weight_input)
  1246. tare_value = self._get_weight_input_value(self.tare_weight_input)
  1247. deduction_value = self._get_deduction_value()
  1248. gross_weight = gross_value if gross_value is not None else 0
  1249. tare_weight = tare_value if tare_value is not None else 0
  1250. planned_quantity_value = self.planned_quantity_input.value()
  1251. planned_quantity_tons = planned_quantity_value if planned_quantity_value >= 0 else None
  1252. planned_quantity = tons_to_kg(planned_quantity_tons) if planned_quantity_tons is not None else None
  1253. executed_quantity_value = self.executed_quantity_input.value()
  1254. executed_quantity_tons = executed_quantity_value if executed_quantity_value >= 0 else None
  1255. executed_quantity = tons_to_kg(executed_quantity_tons) if executed_quantity_tons is not None else None
  1256. current_quantity_value = self.current_quantity_input.value()
  1257. current_quantity_tons = current_quantity_value if current_quantity_value >= 0 else None
  1258. current_quantity = tons_to_kg(current_quantity_tons) if current_quantity_tons is not None else None
  1259. data = {
  1260. 'vehicle_no': self.vehicle_no_input.text().strip(),
  1261. 'plan_no': self.plan_no_input.text().strip(),
  1262. 'cargo_name': self.cargo_combo.currentText(),
  1263. 'business_type': self.business_type_group.checkedButton().text(),
  1264. 'batch_no': self.batch_no_input.text().strip(),
  1265. 'supplier': self.supplier_combo.currentText(),
  1266. 'consignee': self.consignee_combo.currentText(),
  1267. 'gross_weight': gross_weight,
  1268. 'gross_weight_time': self._get_datetime_str(self.gross_weight_time),
  1269. 'tare_weight': tare_weight,
  1270. 'tare_weight_time': self._get_datetime_str(self.tare_weight_time),
  1271. 'deduction': deduction_value,
  1272. 'planned_quantity': planned_quantity,
  1273. 'executed_quantity': executed_quantity,
  1274. 'current_quantity': current_quantity,
  1275. 'remarks': self.remarks_input.toPlainText().strip(),
  1276. 'purchase_plan_id': self.current_plan['id'] if self.current_plan and self.current_plan.get('id') else None,
  1277. 'inbound_outbound_id': self.current_inbound_id,
  1278. 'weighing_point': self.current_plan.get('weighing_point') if self.current_plan and self.current_plan.get('weighing_point') else '山峡地磅'
  1279. }
  1280. try:
  1281. operation_success = False
  1282. if self.editing_slip_id:
  1283. operation_success = self.db.update_weighing_slip(self.editing_slip_id, data)
  1284. if not operation_success:
  1285. QMessageBox.warning(self, "提示", "未能更新地磅单,请重试。")
  1286. return
  1287. QMessageBox.information(self, "成功", "地磅单更新成功!")
  1288. else:
  1289. self.db.insert_weighing_slip(data)
  1290. operation_success = True
  1291. QMessageBox.information(self, "成功", "地磅单保存成功!")
  1292. if operation_success:
  1293. self.clear_error_styles() # 清除错误样式
  1294. self.clear_form()
  1295. self.refresh_list()
  1296. except ValueError as e:
  1297. QMessageBox.warning(self, "提示", str(e))
  1298. except Exception as e:
  1299. QMessageBox.critical(self, "错误", f"保存失败:{str(e)}")
  1300. def clear_form(self):
  1301. """清空表单"""
  1302. self._is_clearing_form = True
  1303. try:
  1304. self.editing_slip_id = None
  1305. self.save_btn.setText("保存")
  1306. self.vehicle_no_input.clear()
  1307. self.plan_no_input.clear()
  1308. # 清空货物名称、供货单位、收货单位(设置为第一个空选项)
  1309. if self.cargo_combo.count() > 0:
  1310. self.cargo_combo.setCurrentIndex(0)
  1311. if self.supplier_combo.count() > 0:
  1312. self.supplier_combo.setCurrentIndex(0)
  1313. if self.consignee_combo.count() > 0:
  1314. self.consignee_combo.setCurrentIndex(0)
  1315. # 不设置业务类型默认选中
  1316. if self.business_type_group.checkedButton():
  1317. self.business_type_group.setExclusive(False)
  1318. self.business_type_group.checkedButton().setChecked(False)
  1319. self.business_type_group.setExclusive(True)
  1320. self.batch_no_input.clear()
  1321. self.gross_weight_input.setValue(-1)
  1322. # 不设置毛重时间默认值,使用无效日期时间
  1323. self.gross_weight_time.setDateTime(QDateTime())
  1324. if self.gross_weight_time.lineEdit():
  1325. self.gross_weight_time.lineEdit().setText("")
  1326. # 延迟清空,确保显示被正确清空
  1327. QTimer.singleShot(0, lambda: self.gross_weight_time.lineEdit().setText("") if self.gross_weight_time.lineEdit() else None)
  1328. self.tare_weight_input.setValue(-1)
  1329. # 不设置皮重时间默认值,使用无效日期时间
  1330. self.tare_weight_time.setDateTime(QDateTime())
  1331. if self.tare_weight_time.lineEdit():
  1332. self.tare_weight_time.lineEdit().setText("")
  1333. # 延迟清空,确保显示被正确清空
  1334. QTimer.singleShot(0, lambda: self.tare_weight_time.lineEdit().setText("") if self.tare_weight_time.lineEdit() else None)
  1335. self.deduction_input.setValue(-1)
  1336. self.net_weight_label.setText("0.000 t")
  1337. self.planned_quantity_input.setValue(-1)
  1338. self.executed_quantity_input.setValue(-1)
  1339. self.current_quantity_input.setValue(-1)
  1340. self.remarks_input.clear()
  1341. self.clear_plan_binding()
  1342. self.current_inbound_id = None
  1343. finally:
  1344. self._is_clearing_form = False
  1345. def clear_plan_binding(self):
  1346. """清空关联的采购计划"""
  1347. self.current_plan = None
  1348. if hasattr(self, 'plan_binding_label'):
  1349. self.plan_binding_label.setText("未关联")
  1350. self.plan_binding_label.setStyleSheet("")
  1351. def set_source_plan(self, plan: dict):
  1352. """设置当前关联的采购计划"""
  1353. self.current_plan = plan
  1354. if not hasattr(self, 'plan_binding_label'):
  1355. return
  1356. parts = [f"ID {plan.get('id', '')}", plan.get('business_type', '')]
  1357. if plan.get('customer_name'):
  1358. parts.append(plan['customer_name'])
  1359. if plan.get('execution_status'):
  1360. parts.append(plan['execution_status'])
  1361. self.plan_binding_label.setText(" · ".join([p for p in parts if p]))
  1362. status = plan.get('execution_status', '')
  1363. # 移除状态文字颜色
  1364. # 同步已执行量(kg)
  1365. executed_qty = plan.get('executed_quantity')
  1366. executed_qty_tons = kg_to_tons(executed_qty) if executed_qty is not None else None
  1367. if executed_qty_tons is not None and executed_qty_tons >= 0:
  1368. self.executed_quantity_input.setValue(executed_qty_tons)
  1369. else:
  1370. self.executed_quantity_input.setValue(-1)
  1371. def show_detail(self, slip_id: int):
  1372. """显示地磅单详情"""
  1373. slip = self.db.get_weighing_slip_by_id(slip_id)
  1374. if not slip:
  1375. QMessageBox.warning(self, "错误", "未找到该地磅单")
  1376. return
  1377. dialog = DetailDialog(slip, self.db, self)
  1378. dialog.exec_()
  1379. def preview_slip(self, slip_id: int):
  1380. """预览地磅单"""
  1381. slip = self.db.get_weighing_slip_by_id(slip_id)
  1382. if not slip:
  1383. QMessageBox.warning(self, "错误", "未找到该地磅单")
  1384. return
  1385. try:
  1386. self.printer.preview_weighing_slip(
  1387. slip, copies=self.print_copies
  1388. )
  1389. except Exception as e:
  1390. QMessageBox.critical(self, "错误", f"预览失败:{str(e)}")
  1391. def start_editing_slip(self, slip_id: int):
  1392. """进入编辑模式并回显表单"""
  1393. slip = self.db.get_weighing_slip_by_id(slip_id)
  1394. if not slip:
  1395. QMessageBox.warning(self, "错误", "未找到该地磅单")
  1396. return
  1397. if slip.get('is_voided'):
  1398. QMessageBox.warning(self, "提示", "已作废的地磅单不可编辑")
  1399. return
  1400. executed_quantity = slip.get('executed_quantity')
  1401. self.clear_error_styles()
  1402. self._is_clearing_form = True
  1403. try:
  1404. self.editing_slip_id = slip_id
  1405. self.save_btn.setText("更新")
  1406. self.vehicle_no_input.setText(slip.get('vehicle_no', ''))
  1407. plan_no = slip.get('plan_no', '')
  1408. self.plan_no_input.setText(plan_no)
  1409. self.batch_no_input.setText(slip.get('batch_no', ''))
  1410. business_type = slip.get('business_type')
  1411. if business_type == '出库':
  1412. self.business_sale_radio.setChecked(True)
  1413. elif business_type == '入库':
  1414. self.business_purchase_radio.setChecked(True)
  1415. else:
  1416. if self.business_type_group.checkedButton():
  1417. self.business_type_group.setExclusive(False)
  1418. self.business_type_group.checkedButton().setChecked(False)
  1419. self.business_type_group.setExclusive(True)
  1420. self._ensure_combo_value(self.cargo_combo, slip.get('cargo_name', ''))
  1421. self._ensure_combo_value(self.supplier_combo, slip.get('supplier', ''))
  1422. self._ensure_combo_value(self.consignee_combo, slip.get('consignee', ''))
  1423. gross_should_empty = slip.get('gross_weight', 0) <= 0 and not slip.get('gross_weight_time')
  1424. self.gross_weight_input.setValue(slip.get('gross_weight', 0) if not gross_should_empty else -1)
  1425. self._set_datetime_from_str(self.gross_weight_time, slip.get('gross_weight_time', ''))
  1426. tare_should_empty = slip.get('tare_weight', 0) <= 0 and not slip.get('tare_weight_time')
  1427. self.tare_weight_input.setValue(slip.get('tare_weight', 0) if not tare_should_empty else -1)
  1428. self._set_datetime_from_str(self.tare_weight_time, slip.get('tare_weight_time', ''))
  1429. deduction_value = slip.get('deduction')
  1430. self.deduction_input.setValue(deduction_value if deduction_value is not None else -1)
  1431. planned_quantity = slip.get('planned_quantity')
  1432. planned_quantity_tons = kg_to_tons(planned_quantity) if planned_quantity is not None else None
  1433. self.planned_quantity_input.setValue(planned_quantity_tons if planned_quantity_tons is not None else -1)
  1434. executed_quantity_tons = kg_to_tons(executed_quantity) if executed_quantity is not None else None
  1435. self.executed_quantity_input.setValue(executed_quantity_tons if executed_quantity_tons is not None else -1)
  1436. current_quantity = slip.get('current_quantity')
  1437. current_quantity_tons = kg_to_tons(current_quantity) if current_quantity is not None else None
  1438. self.current_quantity_input.setValue(current_quantity_tons if current_quantity_tons is not None else -1)
  1439. self.remarks_input.setPlainText(slip.get('remarks', ''))
  1440. finally:
  1441. self._is_clearing_form = False
  1442. # 设置关联的出入库单ID
  1443. self.current_inbound_id = slip.get('inbound_outbound_id')
  1444. # 优先通过purchase_plan_id查询计划,如果没有则通过计划号查询
  1445. linked_plan = None
  1446. if slip.get('purchase_plan_id'):
  1447. linked_plan = self.db.get_purchase_plan_by_id(slip['purchase_plan_id'])
  1448. if not linked_plan:
  1449. linked_plan = {
  1450. 'id': slip['purchase_plan_id'],
  1451. 'business_type': slip.get('business_type', ''),
  1452. 'customer_name': slip.get('consignee', '') if slip.get('business_type') == '出库' else slip.get('supplier', ''),
  1453. 'execution_status': ''
  1454. }
  1455. elif plan_no:
  1456. # 如果没有purchase_plan_id,通过计划号查询
  1457. linked_plan = self.db.get_purchase_plan_by_plan_no(plan_no)
  1458. if linked_plan:
  1459. self.set_source_plan(linked_plan)
  1460. # 如果通过计划号查询到计划,更新计划量和已执行量
  1461. # 注意:已执行量优先使用计划中的值,如果没有则使用地磅单中的值
  1462. if plan_no and linked_plan:
  1463. planned_quantity_t = linked_plan.get('planned_quantity')
  1464. if planned_quantity_t is not None:
  1465. self.planned_quantity_input.setValue(planned_quantity_t)
  1466. # 已执行量:优先使用计划中的值,如果没有则使用地磅单中的值
  1467. executed_quantity_kg = linked_plan.get('executed_quantity')
  1468. executed_quantity_t = kg_to_tons(executed_quantity_kg) if executed_quantity_kg is not None else None
  1469. if executed_quantity_t is not None:
  1470. self.executed_quantity_input.setValue(executed_quantity_t)
  1471. elif executed_quantity_tons is not None:
  1472. self.executed_quantity_input.setValue(executed_quantity_tons)
  1473. else:
  1474. self.clear_plan_binding()
  1475. # 如果没有关联计划,使用地磅单中的已执行量
  1476. if executed_quantity_tons is not None:
  1477. self.executed_quantity_input.setValue(executed_quantity_tons)
  1478. self.calculate_net_weight()
  1479. def print_slip(self, slip_id: int):
  1480. """打印地磅单"""
  1481. slip = self.db.get_weighing_slip_by_id(slip_id)
  1482. if not slip:
  1483. QMessageBox.warning(self, "错误", "未找到该地磅单")
  1484. return
  1485. try:
  1486. self.printer.print_weighing_slip(
  1487. slip, copies=self.print_copies
  1488. )
  1489. QMessageBox.information(self, "成功", "打印任务已发送")
  1490. except Exception as e:
  1491. QMessageBox.critical(self, "错误", f"打印失败:{str(e)}")
  1492. def void_slip(self, slip_id: int):
  1493. """作废地磅单"""
  1494. msg = QMessageBox()
  1495. msg.setIcon(QMessageBox.Question)
  1496. msg.setWindowTitle("确认")
  1497. msg.setText("确定要作废这条地磅单吗?")
  1498. msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
  1499. msg.setDefaultButton(QMessageBox.No)
  1500. msg.button(QMessageBox.Yes).setText("是")
  1501. msg.button(QMessageBox.No).setText("否")
  1502. reply = msg.exec_()
  1503. if reply == QMessageBox.Yes:
  1504. if self.db.void_weighing_slip(slip_id):
  1505. QMessageBox.information(self, "成功", "地磅单已作废")
  1506. self.refresh_list()
  1507. else:
  1508. QMessageBox.warning(self, "错误", "作废失败")
  1509. def has_unsaved_weight_data(self) -> bool:
  1510. """检查是否有未保存的重量数据(皮重或毛重任何一个有数据)"""
  1511. gross_value = self._get_weight_input_value(self.gross_weight_input)
  1512. tare_value = self._get_weight_input_value(self.tare_weight_input)
  1513. # 如果皮重或毛重任何一个有数据(值大于0),返回True
  1514. return (gross_value is not None and gross_value > 0) or \
  1515. (tare_value is not None and tare_value > 0)
  1516. def on_plan_no_changed(self, text: str):
  1517. """计划号输入变化时,自动查询计划并填充计划量和已执行量"""
  1518. # 如果正在清空表单,不执行查询
  1519. if self._is_clearing_form:
  1520. return
  1521. plan_no = text.strip()
  1522. # 如果计划号为空,清空计划量和已执行量
  1523. if not plan_no:
  1524. self.planned_quantity_input.setValue(-1)
  1525. self.executed_quantity_input.setValue(-1)
  1526. self.clear_plan_binding()
  1527. return
  1528. # 查询计划
  1529. try:
  1530. plan = self.db.get_purchase_plan_by_plan_no(plan_no)
  1531. if plan:
  1532. # 找到计划,填充计划量和已执行量
  1533. planned_quantity_t = plan.get('planned_quantity')
  1534. if planned_quantity_t is not None and planned_quantity_t >= 0:
  1535. self.planned_quantity_input.setValue(planned_quantity_t)
  1536. else:
  1537. self.planned_quantity_input.setValue(-1)
  1538. executed_quantity_kg = plan.get('executed_quantity')
  1539. executed_quantity_t = kg_to_tons(executed_quantity_kg) if executed_quantity_kg is not None else None
  1540. if executed_quantity_t is not None and executed_quantity_t >= 0:
  1541. self.executed_quantity_input.setValue(executed_quantity_t)
  1542. else:
  1543. self.executed_quantity_input.setValue(-1)
  1544. # 设置关联的计划
  1545. self.set_source_plan(plan)
  1546. else:
  1547. # 未找到计划,清空计划量和已执行量
  1548. self.planned_quantity_input.setValue(-1)
  1549. self.executed_quantity_input.setValue(-1)
  1550. self.clear_plan_binding()
  1551. except Exception as e:
  1552. # 查询失败,不影响用户输入
  1553. logger.warning(f"查询计划失败: {str(e)}")
  1554. self.planned_quantity_input.setValue(-1)
  1555. self.executed_quantity_input.setValue(-1)
  1556. self.clear_plan_binding()
  1557. class DetailDialog(QDialog):
  1558. """地磅单详情对话框"""
  1559. def __init__(self, slip: dict, db: Database, parent=None):
  1560. super().__init__(parent)
  1561. self.slip = slip
  1562. self.db = db
  1563. self.printer = Printer()
  1564. self.print_copies = getattr(parent, "print_copies", DEFAULT_PRINT_COPIES)
  1565. self.init_ui()
  1566. def init_ui(self):
  1567. """初始化对话框界面"""
  1568. self.setWindowTitle("地磅单详情")
  1569. self.setMinimumWidth(500)
  1570. layout = QVBoxLayout()
  1571. layout.setSpacing(10)
  1572. layout.setContentsMargins(20, 20, 20, 20)
  1573. # 显示详情信息(只读)
  1574. form_layout = QFormLayout()
  1575. form_layout.setSpacing(10)
  1576. label_font = QFont("微软雅黑", 16)
  1577. gross_t = kg_to_tons(self.slip.get('gross_weight'))
  1578. tare_t = kg_to_tons(self.slip.get('tare_weight'))
  1579. net_t = kg_to_tons(self.slip.get('net_weight'))
  1580. current_t = kg_to_tons(self.slip.get('current_quantity')) if self.slip.get('current_quantity') is not None else None
  1581. planned_t = kg_to_tons(self.slip.get('planned_quantity')) if self.slip.get('planned_quantity') is not None else None
  1582. executed_t = kg_to_tons(self.slip.get('executed_quantity')) if self.slip.get('executed_quantity') is not None else None
  1583. deduction_t = kg_to_tons(self.slip.get('deduction')) if self.slip.get('deduction') is not None else None
  1584. fields = [
  1585. ("车号", self.slip['vehicle_no']),
  1586. ("计划号", self.slip.get('plan_no', '')),
  1587. ("货物名称", self.slip['cargo_name']),
  1588. ("业务类型", self.slip['business_type']),
  1589. ("批号", self.slip.get('batch_no', '')),
  1590. ("供货单位", self.slip['supplier']),
  1591. ("收货单位", self.slip['consignee']),
  1592. ("毛重(t)", f"{gross_t:.3f}" if gross_t is not None else ""),
  1593. ("毛重时间", self.slip['gross_weight_time']),
  1594. ("皮重(t)", f"{tare_t:.3f}" if tare_t is not None else ""),
  1595. ("皮重时间", self.slip['tare_weight_time']),
  1596. ("扣杂(t)", f"{deduction_t:.3f}" if deduction_t is not None else ""),
  1597. ("净重(t)", f"{net_t:.3f}" if net_t is not None else ""),
  1598. ("本次量(t)", f"{current_t:.3f}" if current_t is not None else ""),
  1599. ("计划量(t)", f"{planned_t:.3f}" if planned_t is not None else ""),
  1600. ("已执行量(t)", f"{executed_t:.3f}" if executed_t is not None else ""),
  1601. ("磅点", self.slip.get('weighing_point', '山峡地磅')),
  1602. ("备注", self.slip.get('remarks', ''))
  1603. ]
  1604. for label, value in fields:
  1605. label_widget = QLabel(f"{label}:")
  1606. label_widget.setFont(label_font)
  1607. value_label = QLabel(str(value) if value else "")
  1608. value_label.setFont(QFont("微软雅黑", 15))
  1609. form_layout.addRow(label_widget, value_label)
  1610. layout.addLayout(form_layout)
  1611. # 按钮
  1612. button_layout = QHBoxLayout()
  1613. button_layout.addStretch()
  1614. preview_btn = QPushButton("打印")
  1615. preview_btn.setMinimumHeight(40)
  1616. preview_btn.setMinimumWidth(100)
  1617. preview_btn.setFont(QFont("微软雅黑", 15))
  1618. apply_button_style(preview_btn, 'blue')
  1619. preview_btn.clicked.connect(self.preview_slip)
  1620. close_btn = QPushButton("关闭")
  1621. close_btn.setMinimumHeight(40)
  1622. close_btn.setMinimumWidth(100)
  1623. close_btn.setFont(QFont("微软雅黑", 15))
  1624. apply_button_style(close_btn, 'normal')
  1625. close_btn.clicked.connect(self.accept)
  1626. button_layout.addWidget(preview_btn)
  1627. button_layout.addWidget(close_btn)
  1628. layout.addLayout(button_layout)
  1629. self.setLayout(layout)
  1630. def preview_slip(self):
  1631. """预览地磅单(按钮文本为打印)"""
  1632. try:
  1633. self.printer.preview_weighing_slip(
  1634. self.slip, copies=self.print_copies
  1635. )
  1636. except Exception as e:
  1637. QMessageBox.critical(self, "错误", f"预览失败:{str(e)}")