inbound_outbound_tab.py 158 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617
  1. """
  2. 出入库管理Tab页面
  3. """
  4. from PyQt5.QtWidgets import (
  5. QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QComboBox,
  6. QRadioButton, QButtonGroup, QDateEdit, QTextEdit, QPushButton,
  7. QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox, QDialog,
  8. QFormLayout, QSplitter, QGroupBox, QDoubleSpinBox, QGridLayout,
  9. QFileDialog, QSizePolicy, QApplication, QCheckBox, QScrollArea, QFrame
  10. )
  11. from PyQt5.QtCore import Qt, QDate, QDateTime, QTimer, pyqtSignal, QEvent
  12. from PyQt5.QtGui import QFont, QKeySequence, QBrush, QColor, QMouseEvent, QShowEvent
  13. from datetime import datetime
  14. from typing import Optional, Dict
  15. import logging
  16. import time
  17. import json
  18. from database import Database
  19. from .weighing_tab import EmptyDoubleSpinBox, EmptyDateTimeEdit, kg_to_tons, tons_to_kg
  20. from .button_styles import apply_button_style
  21. from utils.printer import Printer
  22. from utils.serial_reader import SerialReader, list_available_ports, get_reader_for_port
  23. import pandas as pd
  24. import sip
  25. logger = logging.getLogger(__name__)
  26. startup_logger = logging.getLogger('startup')
  27. class MultiSelectDropdown(QPushButton):
  28. """多选下拉框组件"""
  29. selection_changed = pyqtSignal() # 选择改变信号
  30. def __init__(self, options=None, default_selected=None, parent=None):
  31. super().__init__(parent)
  32. self.options = options or []
  33. self.selected_items = set(default_selected or [])
  34. self._setup_ui()
  35. def _setup_ui(self):
  36. """设置UI"""
  37. self.setMinimumWidth(150)
  38. self.setMinimumHeight(30)
  39. self.setFont(QFont("微软雅黑", 13))
  40. self.setStyleSheet("""
  41. QPushButton {
  42. text-align: left;
  43. padding-left: 8px;
  44. border: 1px solid #ccc;
  45. border-radius: 3px;
  46. background-color: white;
  47. }
  48. QPushButton:hover {
  49. border-color: #0078d4;
  50. }
  51. QPushButton:pressed {
  52. background-color: #f3f2f1;
  53. }
  54. """)
  55. self._update_display_text()
  56. # 创建菜单
  57. from PyQt5.QtWidgets import QMenu, QAction
  58. self.menu = QMenu(self)
  59. self.setMenu(self.menu)
  60. # 添加选项
  61. for option in self.options:
  62. action = QAction(option, self.menu, checkable=True)
  63. action.setChecked(option in self.selected_items)
  64. action.triggered.connect(lambda checked, opt=option: self._on_option_toggled(opt, checked))
  65. self.menu.addAction(action)
  66. def _on_option_toggled(self, option, checked):
  67. """选项切换处理"""
  68. if option == "全部":
  69. # 选择"全部"时,选择所有选项
  70. if checked:
  71. self.selected_items = set(self.options)
  72. else:
  73. # 取消选择"全部"时,取消选择所有选项
  74. self.selected_items.clear()
  75. else:
  76. # 选择具体选项时
  77. if checked:
  78. self.selected_items.add(option)
  79. # 如果选择了所有非"全部"选项,自动选择"全部"
  80. non_all_options = [opt for opt in self.options if opt != "全部"]
  81. if all(opt in self.selected_items for opt in non_all_options):
  82. self.selected_items.add("全部")
  83. else:
  84. self.selected_items.discard(option)
  85. # 如果取消选择了某个选项,同时取消选择"全部"
  86. if "全部" in self.selected_items:
  87. self.selected_items.discard("全部")
  88. # 更新菜单项的选中状态
  89. for action in self.menu.actions():
  90. action_opt = action.text()
  91. action.setChecked(action_opt in self.selected_items)
  92. self._update_display_text()
  93. self.selection_changed.emit()
  94. def _update_display_text(self):
  95. """更新显示文本"""
  96. if not self.selected_items:
  97. self.setText("请选择...")
  98. elif len(self.selected_items) == len(self.options):
  99. self.setText("全部")
  100. else:
  101. selected_list = sorted(self.selected_items)
  102. if len(selected_list) <= 2:
  103. self.setText("、".join(selected_list))
  104. else:
  105. self.setText(f"{selected_list[0]}等{len(selected_list)}项")
  106. def get_selected_items(self):
  107. """获取选中的项目"""
  108. return self.selected_items.copy()
  109. def set_selected_items(self, items):
  110. """设置选中的项目"""
  111. self.selected_items = set(items)
  112. # 更新菜单项的选中状态
  113. for action in self.menu.actions():
  114. option = action.text()
  115. action.setChecked(option in self.selected_items)
  116. self._update_display_text()
  117. class EmptyDateEdit(QDateEdit):
  118. """自定义QDateEdit,支持显示为空白"""
  119. def __init__(self, parent=None):
  120. super().__init__(parent)
  121. self._is_empty = True
  122. # 使用当前日期作为内部日期,这样日历弹窗打开时会显示当前月
  123. # 但lineEdit会显示为空,避免当天日期无法选择的问题
  124. self._placeholder_date = QDate.currentDate()
  125. self._suppress_signal_sync = False
  126. self._calendar_was_opened = False # 跟踪日历弹窗是否被打开过
  127. self._apply_placeholder_date()
  128. self._sync_line_edit()
  129. self.dateChanged.connect(self._handle_user_date_changed)
  130. def _apply_placeholder_date(self):
  131. # 使用当前日期作为占位符,这样日历弹窗打开时会显示当前月
  132. # 但用户仍然可以选择当天日期,因为日期会从当前日期变为当前日期
  133. # 我们在_handle_user_date_changed中处理这种情况
  134. self._placeholder_date = QDate.currentDate()
  135. self._suppress_signal_sync = True
  136. try:
  137. super().setDate(self._placeholder_date)
  138. finally:
  139. self._suppress_signal_sync = False
  140. def _sync_line_edit(self):
  141. line_edit = self.lineEdit()
  142. if not line_edit:
  143. return
  144. if self._is_empty:
  145. line_edit.clear()
  146. line_edit.setPlaceholderText("请选择日期")
  147. else:
  148. line_edit.setPlaceholderText("")
  149. line_edit.setText(super().text())
  150. def setDate(self, date: QDate):
  151. if not date.isValid():
  152. self._is_empty = True
  153. self._apply_placeholder_date()
  154. self._sync_line_edit()
  155. return
  156. self._is_empty = False
  157. self._suppress_signal_sync = True
  158. try:
  159. super().setDate(date)
  160. finally:
  161. self._suppress_signal_sync = False
  162. self._sync_line_edit()
  163. def date(self) -> QDate:
  164. if self._is_empty:
  165. return QDate()
  166. return super().date()
  167. def clear(self):
  168. self.setDate(QDate())
  169. def is_empty(self) -> bool:
  170. return self._is_empty
  171. def textFromDateTime(self, date_time: QDateTime) -> str:
  172. if self._is_empty:
  173. return ""
  174. return super().textFromDateTime(date_time)
  175. def _handle_user_date_changed(self, date: QDate):
  176. if self._suppress_signal_sync:
  177. return
  178. if not date.isValid():
  179. return
  180. # 如果当前是空状态,用户选择了日期(包括当前日期),更新状态
  181. if self._is_empty:
  182. # 无论选择什么日期(包括当前日期),都认为用户已选择日期
  183. # 因为用户可能点击了日历中的日期,即使日期没有变化
  184. self._is_empty = False
  185. self._sync_line_edit()
  186. else:
  187. # 如果已经有日期,正常同步显示
  188. self._sync_line_edit()
  189. def mousePressEvent(self, event):
  190. """重写鼠标点击事件,跟踪日历弹窗是否被打开"""
  191. # 检查是否点击了日期按钮
  192. if event.button() == Qt.LeftButton:
  193. button_width = 25
  194. widget_width = self.width()
  195. is_clicking_button = event.x() >= widget_width - button_width
  196. if is_clicking_button:
  197. # 标记日历弹窗将被打开
  198. self._calendar_was_opened = True
  199. # 正常处理事件,由于占位符日期已经是当前日期,日历弹窗会显示当前月
  200. super().mousePressEvent(event)
  201. def focusOutEvent(self, event):
  202. """重写失去焦点事件,在失去焦点时检查用户是否选择了日期"""
  203. # 检查用户是否在日历中点击了日期
  204. current_display_date = super().date()
  205. current_date = QDate.currentDate()
  206. if self._is_empty:
  207. # 如果日历弹窗被打开过,且日期是当前日期
  208. # 说明用户可能点击了当前日期(即使dateChanged信号没有触发)
  209. if self._calendar_was_opened and current_display_date == current_date:
  210. # 用户选择了当前日期,更新状态
  211. self._is_empty = False
  212. self._sync_line_edit()
  213. else:
  214. # 更新占位符日期为当前日期,确保下次打开时显示当前月
  215. if self._placeholder_date != current_date:
  216. self._placeholder_date = current_date
  217. self._apply_placeholder_date()
  218. else:
  219. # 如果已经不是空状态,确保lineEdit正确显示
  220. self._sync_line_edit()
  221. # 重置标志
  222. self._calendar_was_opened = False
  223. super().focusOutEvent(event)
  224. class InboundOutboundTab(QWidget):
  225. """出入库管理Tab"""
  226. def __init__(self, db: Database, main_window=None, current_user: Optional[Dict] = None):
  227. tab_start = time.time()
  228. super().__init__()
  229. self.db = db
  230. self.main_window = main_window
  231. self.current_user = current_user or {}
  232. self._is_admin = self.current_user.get('role') == 'admin'
  233. self.current_plan_id: Optional[int] = None
  234. self.editing_inbound_id: Optional[int] = None
  235. self.search_keyword: str = ""
  236. # 列表筛选选项(保留供 WeighingSlipDialog 等内部逻辑引用)
  237. self.show_pending_inbound: bool = True
  238. self.show_pending_outbound: bool = True
  239. self.show_recent_completed: bool = True
  240. self.show_all_completed: bool = False
  241. self.show_today_only: bool = True
  242. ui_start = time.time()
  243. self.init_ui()
  244. startup_logger.info(f" 界面初始化 (耗时: {time.time() - ui_start:.3f}秒)")
  245. @staticmethod
  246. def _is_completed_status(status: str) -> bool:
  247. """判断出入库状态是否为已完成"""
  248. if not status:
  249. return False
  250. status = status.strip()
  251. # 判断是否为已完成状态:已入库、已出库,或其他以"已"开头的状态
  252. return status.startswith('已')
  253. def init_ui(self):
  254. """初始化界面:仅保留出入库单ID输入框与检索按钮"""
  255. layout = QVBoxLayout()
  256. layout.setSpacing(16)
  257. layout.setContentsMargins(20, 20, 20, 20)
  258. # 标题
  259. title = QLabel("出入库管理")
  260. title.setFont(QFont("微软雅黑", 18, QFont.Bold))
  261. layout.addWidget(title)
  262. # 水平布局:出入库单ID 输入框 + 检索按钮(左右居中)
  263. row = QHBoxLayout()
  264. row.setSpacing(12)
  265. id_label = QLabel("出入库单ID:")
  266. id_label.setFont(QFont("微软雅黑", 14))
  267. self.inbound_id_input = QLineEdit()
  268. self.inbound_id_input.setPlaceholderText("请输入出入库单ID")
  269. self.inbound_id_input.setFont(QFont("微软雅黑", 14))
  270. self.inbound_id_input.setMinimumHeight(40)
  271. self.inbound_id_input.setMinimumWidth(440) # 宽度为原来的两倍(220*2)
  272. self.search_btn = QPushButton("检索")
  273. self.search_btn.setFont(QFont("微软雅黑", 14))
  274. self.search_btn.setMinimumHeight(40)
  275. self.search_btn.setMinimumWidth(100)
  276. apply_button_style(self.search_btn, 'blue')
  277. self.search_btn.clicked.connect(self.on_search_by_inbound_id)
  278. # 扫码枪输入后通常会发送 Enter,按回车自动触发检索
  279. self.inbound_id_input.returnPressed.connect(self.on_search_by_inbound_id)
  280. row.addStretch(1) # 左侧弹性空间,使内容居中
  281. row.addWidget(id_label)
  282. row.addWidget(self.inbound_id_input)
  283. row.addWidget(self.search_btn)
  284. row.addStretch(1) # 右侧弹性空间,使内容居中
  285. layout.addLayout(row)
  286. # 当天出入库单卡片区域:标题 + 刷新按钮
  287. today_row = QHBoxLayout()
  288. today_label = QLabel("当天出入库单")
  289. today_label.setFont(QFont("微软雅黑", 14, QFont.Bold))
  290. today_row.addWidget(today_label)
  291. today_row.addSpacing(16)
  292. self.today_refresh_btn = QPushButton("刷新")
  293. self.today_refresh_btn.setFont(QFont("微软雅黑", 12))
  294. self.today_refresh_btn.setMinimumHeight(32)
  295. self.today_refresh_btn.setMinimumWidth(80)
  296. apply_button_style(self.today_refresh_btn, 'normal')
  297. self.today_refresh_btn.clicked.connect(self.refresh_list)
  298. today_row.addWidget(self.today_refresh_btn)
  299. today_row.addStretch(1)
  300. layout.addLayout(today_row)
  301. # 为使用 _refresh_card_view,需存在 table 与 card 相关控件(table 不加入布局,仅占位)
  302. self.view_mode = "card"
  303. self.card_columns = 5
  304. self._card_widgets = []
  305. self.table = QTableWidget()
  306. self.table.setColumnCount(14)
  307. self.table.setHorizontalHeaderLabels([
  308. "计划号", "批次号", "日期", "往来单位", "业务类型",
  309. "产品", "车牌号", "本次量(t)", "净重(t)", "毛重(t)",
  310. "皮重(t)", "扣杂(t)", "状态", "操作"
  311. ])
  312. self.table.setParent(self)
  313. self.table.setVisible(False)
  314. self.card_scroll_area = QScrollArea()
  315. self.card_scroll_area.setWidgetResizable(True)
  316. self.card_scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
  317. self.card_container = QWidget()
  318. self.card_layout = QGridLayout()
  319. self.card_layout.setContentsMargins(4, 4, 4, 4)
  320. self.card_layout.setHorizontalSpacing(4)
  321. self.card_layout.setVerticalSpacing(10)
  322. self.card_container.setLayout(self.card_layout)
  323. self.card_scroll_area.setWidget(self.card_container)
  324. layout.addWidget(self.card_scroll_area)
  325. self.setLayout(layout)
  326. # 每10秒尝试将焦点拉回「出入库单ID」输入框,便于扫码枪输入(仅在本 Tab 可见且无弹窗时执行)
  327. self._focus_timer = QTimer(self)
  328. self._focus_timer.timeout.connect(self._try_focus_inbound_id_input)
  329. self._focus_timer.start(10000)
  330. # 初始加载当天出入库单卡片
  331. QTimer.singleShot(0, self.refresh_today_cards)
  332. def _try_focus_inbound_id_input(self):
  333. """定时尝试将焦点设回出入库单ID输入框:仅当本 Tab 可见且无模态弹窗时执行,避免打断用户操作。"""
  334. if not self.isVisible():
  335. return
  336. if QApplication.activeModalWidget() is not None:
  337. return
  338. if getattr(self, "inbound_id_input", None):
  339. self.inbound_id_input.setFocus()
  340. def showEvent(self, event: QShowEvent):
  341. """Tab 显示时自动聚焦到出入库单ID输入框(具体聚焦与刷新在下方 showEvent 中统一处理)"""
  342. super().showEvent(event)
  343. def _clear_inbound_id_after_search(self):
  344. """检索后清空出入库单ID输入框"""
  345. if getattr(self, "inbound_id_input", None):
  346. self.inbound_id_input.clear()
  347. def refresh_today_cards(self):
  348. """加载并展示当天出入库单卡片(与旧版卡片内容、样式、按钮及功能一致)"""
  349. if not getattr(self, "card_layout", None):
  350. return
  351. today_str = datetime.now().strftime("%Y-%m-%d")
  352. inbounds = self.db.get_inbound_outbound_by_date(today_str)
  353. # 无当天数据时显示占位提示
  354. if not inbounds:
  355. while self.card_layout.count():
  356. item = self.card_layout.takeAt(0)
  357. w = item.widget()
  358. if w is not None:
  359. w.deleteLater()
  360. self._card_widgets = []
  361. empty_label = QLabel("今日暂无出入库单")
  362. empty_label.setFont(QFont("微软雅黑", 14))
  363. empty_label.setStyleSheet("color: #666;")
  364. empty_label.setAlignment(Qt.AlignCenter)
  365. self.card_layout.addWidget(empty_label, 0, 0)
  366. if getattr(self, "card_scroll_area", None) is not None:
  367. self.card_scroll_area.setVisible(True)
  368. return
  369. inbound_ids = [i.get("id") for i in inbounds if i.get("id")]
  370. slip_summary_map = self.db.get_weighing_slip_summary_by_inbound_ids(inbound_ids) if inbound_ids else {}
  371. def get_sort_key(r):
  372. date_str = str(r.get("date", ""))
  373. try:
  374. date_obj = datetime.strptime(date_str, "%Y-%m-%d")
  375. date_sort_key = -date_obj.timestamp()
  376. except (ValueError, TypeError):
  377. date_sort_key = float("inf")
  378. status = str(r.get("status", "")).strip()
  379. if status == "待入库":
  380. status_priority = 1
  381. elif status == "待出库":
  382. status_priority = 2
  383. elif status.startswith("已"):
  384. status_priority = 3
  385. else:
  386. status_priority = 4
  387. slip_summary = slip_summary_map.get(r.get("id")) if r.get("id") else None
  388. gross_weight_time_str = slip_summary.get("gross_weight_time", "") if slip_summary else ""
  389. try:
  390. if gross_weight_time_str:
  391. gross_time_obj = datetime.strptime(gross_weight_time_str, "%Y-%m-%d %H:%M:%S")
  392. gross_time_sort_key = -gross_time_obj.timestamp()
  393. else:
  394. gross_time_sort_key = float("inf")
  395. except (ValueError, TypeError):
  396. gross_time_sort_key = float("inf")
  397. return (date_sort_key, status_priority, gross_time_sort_key)
  398. inbounds.sort(key=get_sort_key)
  399. self._current_inbounds = inbounds
  400. self._slip_summary_map = slip_summary_map
  401. self._refresh_card_view()
  402. def _show_search_message(self, icon: QMessageBox.Icon, title: str, text: str):
  403. """
  404. 出入库单管理-检索相关提示框:统一设置为加大加粗字体显示
  405. """
  406. box = QMessageBox(self)
  407. box.setIcon(icon)
  408. box.setWindowTitle(title)
  409. box.setText(text)
  410. box.setFont(QFont("微软雅黑", 18, QFont.Bold))
  411. box.exec_()
  412. def on_search_by_inbound_id(self):
  413. """
  414. 根据出入库单ID检索:
  415. - ID不存在 → 提示异常(加大加粗),并显示出入库单ID
  416. - ID存在且日期为以前:有地磅单则弹窗(读毛重/读皮重不可操作),无地磅单则提示异常
  417. - ID存在且日期为未来 → 提示异常
  418. - ID存在且当天:该车牌当天有未完成的地磅单(且非本单)则提示异常,否则弹窗
  419. 未完成地磅单:有毛重没有皮重,或有皮重没有毛重。
  420. 所有异常信息均加大加粗并显示检索的出入库单ID。检索成功后清空输入框。
  421. """
  422. raw = (self.inbound_id_input.text() or "").strip()
  423. display_id = raw if raw else "(未输入)"
  424. if not raw:
  425. self._show_search_message(
  426. QMessageBox.Warning,
  427. "提示",
  428. f"请输入出入库单ID。\n\n当前输入的出入库单ID:{display_id}",
  429. )
  430. return
  431. try:
  432. inbound_id = int(raw)
  433. except ValueError:
  434. self._clear_inbound_id_after_search()
  435. self._show_search_message(
  436. QMessageBox.Warning,
  437. "提示",
  438. f"请输入有效的出入库单ID(数字)。\n\n当前输入的出入库单ID:{display_id}",
  439. )
  440. return
  441. if inbound_id <= 0:
  442. self._clear_inbound_id_after_search()
  443. self._show_search_message(
  444. QMessageBox.Warning,
  445. "提示",
  446. f"请输入有效的出入库单ID。\n\n当前输入的出入库单ID:{display_id}",
  447. )
  448. return
  449. inbound = self.db.get_inbound_outbound_by_id(inbound_id)
  450. if not inbound:
  451. self._clear_inbound_id_after_search()
  452. self._show_search_message(
  453. QMessageBox.Critical,
  454. "错误",
  455. f"该出入库单ID不存在。\n\n当前输入的出入库单ID:{display_id}",
  456. )
  457. return
  458. # 解析出入库单日期,用于判断以前/当天/未来
  459. inbound_date = inbound.get("date")
  460. if inbound_date is not None:
  461. if hasattr(inbound_date, "strftime"):
  462. inbound_date_str = inbound_date.strftime("%Y-%m-%d")
  463. else:
  464. inbound_date_str = str(inbound_date).strip()[:10]
  465. else:
  466. inbound_date_str = ""
  467. today_str = datetime.now().strftime("%Y-%m-%d")
  468. is_past = bool(inbound_date_str and inbound_date_str < today_str)
  469. is_future = bool(inbound_date_str and inbound_date_str > today_str)
  470. is_today = bool(inbound_date_str and inbound_date_str == today_str)
  471. # 日期为未来:提示异常
  472. if is_future:
  473. self._clear_inbound_id_after_search()
  474. self._show_search_message(
  475. QMessageBox.Critical,
  476. "错误",
  477. f"该出入库单日期为未来日期,无法操作。\n\n当前输入的出入库单ID:{display_id}",
  478. )
  479. return
  480. # 日期为以前(历史)
  481. if is_past:
  482. linked_slip = self.db.get_weighing_slip_by_inbound_id(inbound_id, include_voided=False)
  483. if not linked_slip:
  484. self._clear_inbound_id_after_search()
  485. self._show_search_message(
  486. QMessageBox.Critical,
  487. "错误",
  488. f"该历史出入库单未关联任何地磅单,无法查看历史称重记录。\n\n当前输入的出入库单ID:{display_id}",
  489. )
  490. return
  491. # 有地磅单:弹窗,读毛重/读皮重不可操作(在 jump_to_weighing 中通过 set_history_mode 实现)
  492. self._clear_inbound_id_after_search()
  493. self.jump_to_weighing(inbound_id)
  494. return
  495. # 当天:校验车牌号
  496. vehicle_no = (inbound.get("vehicle_no") or "").strip()
  497. if not vehicle_no:
  498. self._clear_inbound_id_after_search()
  499. self._show_search_message(
  500. QMessageBox.Critical,
  501. "错误",
  502. f"该出入库单缺少车牌号信息。\n\n当前输入的出入库单ID:{display_id}",
  503. )
  504. return
  505. # 当天该车牌是否还有未完成的地磅单(有毛重没皮重,或有皮重没毛重);若未完成的是其他出入库单则提示异常
  506. incomplete_slips = self.db.get_today_incomplete_weighing_slips_by_vehicle(vehicle_no)
  507. other_incomplete_ids = []
  508. for slip in incomplete_slips:
  509. slip_inbound_id = slip.get("inbound_outbound_id")
  510. if slip_inbound_id is not None and int(slip_inbound_id) != int(inbound_id):
  511. other_incomplete_ids.append(int(slip_inbound_id))
  512. if other_incomplete_ids:
  513. # 去重并排序,便于用户查看
  514. other_incomplete_ids = sorted(set(other_incomplete_ids))
  515. incomplete_ids_text = "、".join(str(i) for i in other_incomplete_ids)
  516. self._clear_inbound_id_after_search()
  517. self._show_search_message(
  518. QMessageBox.Warning,
  519. "提示",
  520. f"当天该车牌已存在未完成的称重记录,请输入未完成的出入库单的ID。\n\n未完成的出入库单ID:{incomplete_ids_text}\n当前输入的出入库单ID:{display_id}",
  521. )
  522. return
  523. # 通过校验:清空输入框并弹出地磅单弹窗
  524. self._clear_inbound_id_after_search()
  525. self.jump_to_weighing(inbound_id)
  526. def create_form_widget(self) -> QWidget:
  527. """创建出入库单填写表单"""
  528. widget = QWidget()
  529. layout = QVBoxLayout()
  530. layout.setSpacing(8)
  531. layout.setContentsMargins(10, 10, 10, 10)
  532. # 标题
  533. title = QLabel("出入库单填写")
  534. title_font = QFont("微软雅黑", 16, QFont.Bold)
  535. title.setFont(title_font)
  536. layout.addWidget(title)
  537. # 表单区域 - 使用网格布局,一行放4个字段(8列,label+控件各占1列)
  538. form_layout = QGridLayout()
  539. form_layout.setSpacing(12)
  540. form_layout.setColumnStretch(1, 1)
  541. form_layout.setColumnStretch(3, 1)
  542. form_layout.setColumnStretch(5, 1)
  543. form_layout.setColumnStretch(7, 1)
  544. input_height = 40
  545. row = 0
  546. # ========== 必填字段(红色label,放前面) ==========
  547. # 第一行:日期(必填)、往来单位(必填)、业务类型(必填)、计划号(只读)
  548. date_label = QLabel("<span style='color: black;'>日期 *</span>:")
  549. date_label.setFont(QFont("微软雅黑", 16))
  550. date_label.setTextFormat(Qt.RichText)
  551. self.date_input = EmptyDateEdit()
  552. self.date_input.setMinimumHeight(input_height)
  553. self.date_input.setFont(QFont("微软雅黑", 16))
  554. self.date_input.setCalendarPopup(True)
  555. self.date_input.setDisplayFormat("yyyy-MM-dd")
  556. self.date_input.dateChanged.connect(self.on_date_changed)
  557. form_layout.addWidget(date_label, row, 0)
  558. form_layout.addWidget(self.date_input, row, 1)
  559. partner_label = QLabel("<span style='color: black;'>往来单位 *</span>:")
  560. partner_label.setFont(QFont("微软雅黑", 16))
  561. partner_label.setTextFormat(Qt.RichText)
  562. self.partner_combo = QComboBox()
  563. self.partner_combo.setMinimumHeight(input_height)
  564. self.partner_combo.setFont(QFont("微软雅黑", 16))
  565. self.partner_combo.setEditable(False)
  566. form_layout.addWidget(partner_label, row, 2)
  567. form_layout.addWidget(self.partner_combo, row, 3)
  568. business_label = QLabel("<span style='color: black;'>业务类型 *</span>:")
  569. business_label.setFont(QFont("微软雅黑", 16))
  570. business_label.setTextFormat(Qt.RichText)
  571. self.business_type_group = QButtonGroup()
  572. self.business_inbound_radio = QRadioButton("入库")
  573. self.business_outbound_radio = QRadioButton("出库")
  574. self.business_inbound_radio.setFont(QFont("微软雅黑", 16))
  575. self.business_outbound_radio.setFont(QFont("微软雅黑", 16))
  576. # 设置选中时样式(移除颜色)
  577. self.business_inbound_radio.setStyleSheet("")
  578. self.business_outbound_radio.setStyleSheet("")
  579. self.business_type_group.addButton(self.business_inbound_radio, 0)
  580. self.business_type_group.addButton(self.business_outbound_radio, 1)
  581. self.business_inbound_radio.toggled.connect(self.on_business_type_changed)
  582. self.business_outbound_radio.toggled.connect(self.on_business_type_changed)
  583. business_layout = QHBoxLayout()
  584. business_layout.addWidget(self.business_inbound_radio)
  585. business_layout.addWidget(self.business_outbound_radio)
  586. business_layout.addStretch()
  587. business_widget = QWidget()
  588. business_widget.setLayout(business_layout)
  589. form_layout.addWidget(business_label, row, 4)
  590. form_layout.addWidget(business_widget, row, 5)
  591. # ========== 非必填字段(黑色label) ==========
  592. plan_no_label = QLabel("计划号:")
  593. plan_no_label.setFont(QFont("微软雅黑", 16))
  594. self.plan_no_display = QLabel("未关联")
  595. self.plan_no_display.setMinimumHeight(input_height)
  596. self.plan_no_display.setFont(QFont("微软雅黑", 16))
  597. self.plan_no_display.setStyleSheet("padding: 5px; border: 1px solid #ccc;")
  598. form_layout.addWidget(plan_no_label, row, 6)
  599. form_layout.addWidget(self.plan_no_display, row, 7)
  600. row += 1
  601. # 第二行:产品(必填)、本次量(t)(必填)、车牌号(必填)、批次号
  602. product_label = QLabel("<span style='color: black;'>产品 *</span>:")
  603. product_label.setFont(QFont("微软雅黑", 16))
  604. product_label.setTextFormat(Qt.RichText)
  605. self.product_combo = QComboBox()
  606. self.product_combo.setMinimumHeight(input_height)
  607. self.product_combo.setFont(QFont("微软雅黑", 16))
  608. self.product_combo.setEditable(False)
  609. form_layout.addWidget(product_label, row, 0)
  610. form_layout.addWidget(self.product_combo, row, 1)
  611. quantity_label = QLabel("<span style='color: black;'>本次量(t) *</span>:")
  612. quantity_label.setFont(QFont("微软雅黑", 16))
  613. quantity_label.setTextFormat(Qt.RichText)
  614. self.quantity_input = EmptyDoubleSpinBox()
  615. self.quantity_input.setMinimumHeight(input_height)
  616. self.quantity_input.setFont(QFont("微软雅黑", 16))
  617. self.quantity_input.setDecimals(3)
  618. self.quantity_input.setMinimum(-1)
  619. self.quantity_input.setMaximum(999999)
  620. self.quantity_input.setSpecialValueText("")
  621. self.quantity_input.setValue(-1)
  622. form_layout.addWidget(quantity_label, row, 2)
  623. form_layout.addWidget(self.quantity_input, row, 3)
  624. vehicle_label = QLabel("<span style='color: black;'>车牌号 *</span>:")
  625. vehicle_label.setFont(QFont("微软雅黑", 16))
  626. vehicle_label.setTextFormat(Qt.RichText)
  627. self.vehicle_no_input = QLineEdit()
  628. self.vehicle_no_input.setMinimumHeight(input_height)
  629. self.vehicle_no_input.setFont(QFont("微软雅黑", 16))
  630. form_layout.addWidget(vehicle_label, row, 4)
  631. form_layout.addWidget(self.vehicle_no_input, row, 5)
  632. batch_label = QLabel("批次号:")
  633. batch_label.setFont(QFont("微软雅黑", 16))
  634. self.batch_no_input = QLineEdit()
  635. self.batch_no_input.setMinimumHeight(input_height)
  636. self.batch_no_input.setFont(QFont("微软雅黑", 16))
  637. # 批次号输入框失去焦点时,如果为空则自动生成
  638. self.batch_no_input.editingFinished.connect(self.on_batch_no_editing_finished)
  639. form_layout.addWidget(batch_label, row, 6)
  640. form_layout.addWidget(self.batch_no_input, row, 7)
  641. row += 1
  642. # 第三行:状态(只读)、备注(占三个元素的宽度)
  643. status_label = QLabel("状态:")
  644. status_label.setFont(QFont("微软雅黑", 16))
  645. self.status_pending_style = "padding: 5px; border: 1px solid #ccc;"
  646. self.status_completed_style = "padding: 5px; border: 1px solid #ccc;"
  647. self.status_display = QLabel("待入库")
  648. self.status_display.setMinimumHeight(45)
  649. self.status_display.setFixedHeight(45)
  650. self.status_display.setFont(QFont("微软雅黑", 16))
  651. self.status_display.setStyleSheet(self.status_pending_style)
  652. form_layout.addWidget(status_label, row, 0)
  653. form_layout.addWidget(self.status_display, row, 1)
  654. remarks_label = QLabel("备注:")
  655. remarks_label.setFont(QFont("微软雅黑", 16))
  656. self.remarks_input = QTextEdit()
  657. self.remarks_input.setMinimumHeight(45)
  658. self.remarks_input.setFixedHeight(45)
  659. self.remarks_input.setFont(QFont("微软雅黑", 16))
  660. form_layout.addWidget(remarks_label, row, 2)
  661. form_layout.addWidget(self.remarks_input, row, 3, 1, 5)
  662. # 按钮区域
  663. row += 1
  664. button_layout = QHBoxLayout()
  665. button_layout.setContentsMargins(0, 4, 0, 0)
  666. button_layout.setSpacing(12)
  667. button_layout.addStretch()
  668. self.save_btn = QPushButton("保存")
  669. self.save_btn.setMinimumHeight(30)
  670. self.save_btn.setMinimumWidth(110)
  671. self.save_btn.setFont(QFont("微软雅黑", 13, QFont.Bold))
  672. apply_button_style(self.save_btn, 'green')
  673. self.save_btn.clicked.connect(self.save_inbound_outbound)
  674. self.save_btn.setShortcut(QKeySequence("Ctrl+S"))
  675. self.clear_btn = QPushButton("清空")
  676. self.clear_btn.setMinimumHeight(30)
  677. self.clear_btn.setMinimumWidth(110)
  678. self.clear_btn.setFont(QFont("微软雅黑", 13))
  679. apply_button_style(self.clear_btn, 'normal')
  680. self.clear_btn.clicked.connect(self.clear_form)
  681. button_layout.addWidget(self.save_btn)
  682. button_layout.addWidget(self.clear_btn)
  683. button_layout.addStretch()
  684. button_widget = QWidget()
  685. button_widget.setLayout(button_layout)
  686. button_widget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
  687. button_widget.setMaximumHeight(50)
  688. form_layout.addWidget(button_widget, row, 0, 1, 8)
  689. layout.addLayout(form_layout)
  690. # 包装在GroupBox中
  691. group_box = QGroupBox()
  692. group_box.setLayout(layout)
  693. # 隐藏整个“出入库单填写”区域(保持实例存在以免影响其他逻辑)
  694. # 仅设置为不可见并限制最大高度为0,便于后续如需恢复时只需调用 setVisible(True) 并重置高度。
  695. try:
  696. group_box.setVisible(False)
  697. group_box.setMaximumHeight(0)
  698. except Exception:
  699. # 如果运行环境不允许设置(极少见),忽略以保持兼容性
  700. pass
  701. return group_box
  702. def create_list_widget(self) -> QWidget:
  703. """创建出入库单记录列表"""
  704. widget = QWidget()
  705. layout = QVBoxLayout()
  706. layout.setContentsMargins(10, 10, 10, 10)
  707. # 标题和刷新按钮区域
  708. title_layout = QHBoxLayout()
  709. title = QLabel("出入库单记录列表")
  710. title_font = QFont("微软雅黑", 18, QFont.Bold)
  711. title.setFont(title_font)
  712. title_layout.addWidget(title)
  713. title_layout.addStretch()
  714. # 视图切换按钮:列表 / 卡片,默认卡片视图
  715. self.view_mode = "card"
  716. # 隐藏列表视图按钮
  717. # self.table_view_btn = QPushButton("列表视图")
  718. # self.table_view_btn.setCheckable(True)
  719. # self.table_view_btn.setChecked(False)
  720. # self.table_view_btn.setFont(QFont("微软雅黑", 13))
  721. # apply_button_style(self.table_view_btn, 'normal')
  722. self.card_view_btn = QPushButton("卡片视图")
  723. self.card_view_btn.setCheckable(True)
  724. self.card_view_btn.setFont(QFont("微软雅黑", 13))
  725. apply_button_style(self.card_view_btn, 'normal')
  726. # 隐藏列表视图按钮
  727. # self.table_view_btn.clicked.connect(lambda: self._switch_view_mode("table"))
  728. self.card_view_btn.clicked.connect(lambda: self._switch_view_mode("card"))
  729. # title_layout.addWidget(self.table_view_btn)
  730. title_layout.addWidget(self.card_view_btn)
  731. # 筛选多选下拉框(默认选择待入库和待出库)
  732. self.status_filter_dropdown = MultiSelectDropdown(
  733. options=["待入库", "待出库", "全部"],
  734. default_selected=["待入库", "待出库"]
  735. )
  736. # 初始化时设置默认选择
  737. self.status_filter_dropdown.set_selected_items(["待入库", "待出库"])
  738. self.status_filter_dropdown.selection_changed.connect(self.on_filter_changed)
  739. title_layout.addWidget(self.status_filter_dropdown)
  740. title_layout.addSpacing(12)
  741. # 30分钟内的已完成的筛选下拉框(默认选择30分钟内已完成的)
  742. self.recent_completed_dropdown = QComboBox()
  743. self.recent_completed_dropdown.setMinimumWidth(150)
  744. self.recent_completed_dropdown.setFont(QFont("微软雅黑", 13))
  745. self.recent_completed_dropdown.addItems(["30分钟内已完成的", "全部"])
  746. self.recent_completed_dropdown.setCurrentText("30分钟内已完成的")
  747. self.recent_completed_dropdown.currentTextChanged.connect(self.on_filter_changed)
  748. title_layout.addWidget(self.recent_completed_dropdown)
  749. title_layout.addSpacing(12)
  750. # 只看当天单子过滤勾选框(默认勾选)
  751. self.today_only_checkbox = QCheckBox("只看当天")
  752. self.today_only_checkbox.setChecked(True)
  753. self.today_only_checkbox.setFont(QFont("微软雅黑", 13))
  754. self.today_only_checkbox.stateChanged.connect(self.on_today_filter_changed)
  755. title_layout.addWidget(self.today_only_checkbox)
  756. title_layout.addSpacing(12)
  757. self.search_input = QLineEdit()
  758. self.search_input.setPlaceholderText("检索往来单位 / 车牌号 / 产品")
  759. self.search_input.setMinimumHeight(36)
  760. self.search_input.setMinimumWidth(500)
  761. self.search_input.setMaximumWidth(600)
  762. self.search_input.setFont(QFont("微软雅黑", 14))
  763. self.search_input.setClearButtonEnabled(True)
  764. self.search_input.textChanged.connect(self.on_search_text_changed)
  765. title_layout.addWidget(self.search_input)
  766. title_layout.addSpacing(12)
  767. self.export_btn = QPushButton("导出Excel")
  768. self.export_btn.setMinimumHeight(40)
  769. self.export_btn.setMinimumWidth(120)
  770. self.export_btn.setFont(QFont("微软雅黑", 16))
  771. apply_button_style(self.export_btn, 'normal')
  772. self.export_btn.clicked.connect(self.export_to_excel)
  773. title_layout.addWidget(self.export_btn)
  774. self.refresh_btn = QPushButton("刷新")
  775. self.refresh_btn.setMinimumHeight(40)
  776. self.refresh_btn.setMinimumWidth(100)
  777. self.refresh_btn.setFont(QFont("微软雅黑", 16))
  778. apply_button_style(self.refresh_btn, 'normal')
  779. self.refresh_btn.clicked.connect(self.refresh_list)
  780. self.refresh_btn.setShortcut(QKeySequence("F5"))
  781. title_layout.addWidget(self.refresh_btn)
  782. layout.addLayout(title_layout)
  783. # 表格
  784. self.table = QTableWidget()
  785. self.table.setColumnCount(14)
  786. self.table.setHorizontalHeaderLabels([
  787. "计划号", "批次号", "日期", "往来单位", "业务类型",
  788. "产品", "车牌号", "本次量(t)", "净重(t)", "毛重(t)",
  789. "皮重(t)", "扣杂(t)", "状态", "操作"
  790. ])
  791. header = self.table.horizontalHeader()
  792. header.setFont(QFont("微软雅黑", 15, QFont.Bold))
  793. header.setSectionsMovable(False)
  794. header.setStretchLastSection(False)
  795. header.setSectionsClickable(False)
  796. self.column_width_ratios = [
  797. 0.08, 0.08, 0.09, 0.12, 0.08, 0.1, 0.08,
  798. 0.08, 0.07, 0.07, 0.07, 0.05, 0.05, 0.12
  799. ]
  800. self._user_resized_columns = False
  801. self._is_applying_column_widths = False
  802. for i in range(self.table.columnCount()):
  803. header.setSectionResizeMode(i, QHeaderView.Interactive)
  804. header.sectionResized.connect(self._on_section_resized)
  805. self._apply_table_column_widths(force=True)
  806. vertical_header = self.table.verticalHeader()
  807. vertical_header.setDefaultAlignment(Qt.AlignCenter)
  808. vertical_header.setFixedWidth(60)
  809. vertical_header.setSectionResizeMode(QHeaderView.ResizeToContents)
  810. self.table.setFont(QFont("微软雅黑", 15))
  811. self.table.setAlternatingRowColors(True)
  812. self.table.setSelectionBehavior(QTableWidget.SelectRows)
  813. layout.addWidget(self.table)
  814. # 卡片视图:使用 QScrollArea + 容器布局
  815. self.card_scroll_area = QScrollArea()
  816. self.card_scroll_area.setWidgetResizable(True)
  817. self.card_scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
  818. self.card_container = QWidget()
  819. # 卡片区域使用网格布局,一行放多个卡片
  820. self.card_layout = QGridLayout()
  821. # 外边距和间距都设置为 4px,保证多张卡片之间用 4px 作为间隔
  822. self.card_layout.setContentsMargins(4, 4, 4, 4)
  823. self.card_layout.setHorizontalSpacing(4)
  824. self.card_layout.setVerticalSpacing(10)
  825. self.card_container.setLayout(self.card_layout)
  826. # 一行放 5 个卡片
  827. self.card_columns = 5
  828. # 当前卡片控件缓存,用于窗口大小变化时调整宽度
  829. self._card_widgets = []
  830. self.card_scroll_area.setWidget(self.card_container)
  831. # 默认采用卡片视图,表格视图在需要时再显示
  832. self.card_scroll_area.setVisible(True)
  833. layout.addWidget(self.card_scroll_area)
  834. widget.setLayout(layout)
  835. return widget
  836. def refresh_dropdowns(self):
  837. """刷新下拉列表(简化版界面无下拉框,直接返回)"""
  838. if not getattr(self, "partner_combo", None):
  839. return
  840. # 刷新往来单位
  841. self.partner_combo.clear()
  842. self.partner_combo.addItem("")
  843. companies = self.db.get_all_companies()
  844. for company in companies:
  845. self.partner_combo.addItem(company['name'])
  846. self.partner_combo.setCurrentIndex(0)
  847. # 刷新产品
  848. self.product_combo.clear()
  849. self.product_combo.addItem("")
  850. cargos = self.db.get_all_cargos()
  851. for cargo in cargos:
  852. self.product_combo.addItem(cargo['name'])
  853. self.product_combo.setCurrentIndex(0)
  854. def refresh_list(self):
  855. """刷新出入库单记录列表(简化版界面无列表,直接返回)"""
  856. if not getattr(self, "table", None):
  857. return
  858. keyword = getattr(self, "search_keyword", "").strip()
  859. inbounds = self.db.get_all_inbound_outbound(keyword if keyword else None)
  860. # 先获取地磅单摘要,以便在筛选和排序时使用时间信息
  861. inbound_ids = [inbound.get('id') for inbound in inbounds if inbound.get('id')]
  862. slip_summary_map = self.db.get_weighing_slip_summary_by_inbound_ids(inbound_ids)
  863. # 根据勾选框过滤:只看待入库、待出库、已完成的
  864. show_pending_inbound = getattr(self, "show_pending_inbound", True)
  865. show_pending_outbound = getattr(self, "show_pending_outbound", True)
  866. show_recent_completed = getattr(self, "show_recent_completed", True)
  867. show_all_completed = getattr(self, "show_all_completed", True)
  868. # 计算30分钟前的时间
  869. now = datetime.now()
  870. thirty_minutes_ago = now.timestamp() - 30 * 60
  871. filtered_inbounds = []
  872. for inbound in inbounds:
  873. status = str(inbound.get("status", "")).strip()
  874. inbound_id = inbound.get('id')
  875. slip_summary = slip_summary_map.get(inbound_id) if inbound_id else None
  876. # 判断是否应该显示
  877. should_show = False
  878. # 待入库
  879. if status == "待入库" and show_pending_inbound:
  880. should_show = True
  881. # 待出库
  882. elif status == "待出库" and show_pending_outbound:
  883. should_show = True
  884. # 已完成的记录筛选
  885. elif status.startswith("已") and (show_recent_completed or show_all_completed):
  886. if show_all_completed:
  887. # 显示所有已完成的记录
  888. should_show = True
  889. elif show_recent_completed:
  890. # 只显示30分钟内的已完成的记录
  891. # 检查毛重时间或皮重时间,只要有一个在30分钟内就显示
  892. # 如果没有时间戳信息,也显示(可能是刚完成的记录)
  893. gross_weight_time_str = slip_summary.get('gross_weight_time', '') if slip_summary else ''
  894. tare_weight_time_str = slip_summary.get('tare_weight_time', '') if slip_summary else ''
  895. # 如果没有任何时间戳信息,认为是刚完成的记录,显示出来
  896. if not gross_weight_time_str and not tare_weight_time_str:
  897. should_show = True
  898. else:
  899. # 检查毛重时间
  900. if gross_weight_time_str:
  901. try:
  902. gross_time_obj = datetime.strptime(gross_weight_time_str, "%Y-%m-%d %H:%M:%S")
  903. if gross_time_obj.timestamp() >= thirty_minutes_ago:
  904. should_show = True
  905. except (ValueError, TypeError):
  906. pass
  907. # 如果毛重时间不在30分钟内,再检查皮重时间
  908. if not should_show and tare_weight_time_str:
  909. try:
  910. tare_time_obj = datetime.strptime(tare_weight_time_str, "%Y-%m-%d %H:%M:%S")
  911. if tare_time_obj.timestamp() >= thirty_minutes_ago:
  912. should_show = True
  913. except (ValueError, TypeError):
  914. pass
  915. if should_show:
  916. filtered_inbounds.append(inbound)
  917. inbounds = filtered_inbounds
  918. # 根据勾选框过滤:默认只看当天
  919. show_today_only = getattr(self, "show_today_only", True)
  920. if show_today_only:
  921. today_str = datetime.now().strftime("%Y-%m-%d")
  922. inbounds = [
  923. inbound
  924. for inbound in inbounds
  925. if inbound.get("date", "") == today_str
  926. ]
  927. # 多级排序:日期倒序、状态(待入库、待出库、已完成)、毛重时间倒序
  928. def get_sort_key(r):
  929. # 1. 日期(倒序,最新的在前)
  930. date_str = str(r.get("date", ""))
  931. try:
  932. # 将日期字符串转换为datetime对象,然后取负的timestamp实现倒序
  933. date_obj = datetime.strptime(date_str, "%Y-%m-%d")
  934. date_sort_key = -date_obj.timestamp() # 负值实现倒序
  935. except (ValueError, TypeError):
  936. # 如果日期格式不正确,使用空字符串排序(排在最后)
  937. date_sort_key = float('inf') # 无效日期排在最后
  938. # 2. 状态优先级:待入库=1, 待出库=2, 已完成=3
  939. status = str(r.get("status", "")).strip()
  940. if status == "待入库":
  941. status_priority = 1
  942. elif status == "待出库":
  943. status_priority = 2
  944. elif status.startswith("已"): # 已完成状态(已入库、已出库等)
  945. status_priority = 3
  946. else:
  947. status_priority = 4 # 其他状态排在最后
  948. # 3. 毛重时间(倒序,最新的在前)
  949. inbound_id = r.get('id')
  950. slip_summary = slip_summary_map.get(inbound_id) if inbound_id else None
  951. gross_weight_time_str = slip_summary.get('gross_weight_time', '') if slip_summary else ''
  952. try:
  953. if gross_weight_time_str:
  954. # 毛重时间格式:YYYY-MM-DD HH:mm:ss
  955. gross_time_obj = datetime.strptime(gross_weight_time_str, "%Y-%m-%d %H:%M:%S")
  956. gross_time_sort_key = -gross_time_obj.timestamp() # 负值实现倒序
  957. else:
  958. # 如果没有毛重时间,排在最后
  959. gross_time_sort_key = float('inf')
  960. except (ValueError, TypeError):
  961. # 如果毛重时间格式不正确,排在最后
  962. gross_time_sort_key = float('inf')
  963. # 返回排序键:日期倒序、状态正序、毛重时间倒序
  964. return (date_sort_key, status_priority, gross_time_sort_key)
  965. inbounds.sort(key=get_sort_key)
  966. # 缓存当前列表数据,供卡片/表格视图复用
  967. self._current_inbounds = inbounds
  968. self._slip_summary_map = slip_summary_map
  969. # 根据当前视图模式渲染
  970. if getattr(self, "view_mode", "table") == "card":
  971. self._refresh_card_view()
  972. else:
  973. self._refresh_table_view()
  974. def _refresh_table_view(self):
  975. """以表格形式渲染出入库单列表"""
  976. inbounds = getattr(self, "_current_inbounds", [])
  977. slip_summary_map = getattr(self, "_slip_summary_map", {})
  978. self.table.setRowCount(len(inbounds))
  979. # 获取当前日期(格式:yyyy-MM-dd)
  980. today_str = datetime.now().strftime("%Y-%m-%d")
  981. # 移除背景色设置
  982. for i, inbound in enumerate(inbounds):
  983. # 判断是否为当天的单子
  984. is_today = inbound.get('date', '') == today_str
  985. # 计划号
  986. plan_no_item = QTableWidgetItem(inbound.get('plan_no', ''))
  987. # 移除当天高亮背景
  988. self.table.setItem(i, 0, plan_no_item)
  989. # 批次号
  990. batch_no_item = QTableWidgetItem(inbound.get('batch_no', ''))
  991. # 移除当天高亮背景
  992. self.table.setItem(i, 1, batch_no_item)
  993. # 日期
  994. date_item = QTableWidgetItem(inbound['date'])
  995. # 移除当天高亮背景
  996. self.table.setItem(i, 2, date_item)
  997. # 往来单位
  998. partner_item = QTableWidgetItem(inbound['partner_company'])
  999. # 移除当天高亮背景
  1000. self.table.setItem(i, 3, partner_item)
  1001. # 业务类型
  1002. business_item = QTableWidgetItem(inbound['business_type'])
  1003. # 移除当天高亮背景
  1004. self.table.setItem(i, 4, business_item)
  1005. # 产品
  1006. product_item = QTableWidgetItem(inbound['product'])
  1007. # 移除当天高亮背景
  1008. self.table.setItem(i, 5, product_item)
  1009. # 车牌号
  1010. vehicle_item = QTableWidgetItem(inbound['vehicle_no'])
  1011. # 移除当天高亮背景
  1012. self.table.setItem(i, 6, vehicle_item)
  1013. # 本次量(t)
  1014. quantity_item = QTableWidgetItem(f"{inbound['quantity']:.3f}")
  1015. # 移除当天高亮背景
  1016. self.table.setItem(i, 7, quantity_item)
  1017. slip_summary = slip_summary_map.get(inbound.get('id'))
  1018. def _format_slip_weight(field: str) -> str:
  1019. if not slip_summary:
  1020. return ""
  1021. value = slip_summary.get(field)
  1022. if value is None:
  1023. return ""
  1024. tons_value = kg_to_tons(value)
  1025. if tons_value is None:
  1026. return ""
  1027. return f"{tons_value:.3f}"
  1028. # 净重(t)
  1029. net_weight_item = QTableWidgetItem(_format_slip_weight('net_weight'))
  1030. # 移除当天高亮背景
  1031. self.table.setItem(i, 8, net_weight_item)
  1032. # 毛重(t)
  1033. gross_weight_item = QTableWidgetItem(_format_slip_weight('gross_weight'))
  1034. # 移除当天高亮背景
  1035. self.table.setItem(i, 9, gross_weight_item)
  1036. # 皮重(t)
  1037. tare_weight_item = QTableWidgetItem(_format_slip_weight('tare_weight'))
  1038. # 移除当天高亮背景
  1039. self.table.setItem(i, 10, tare_weight_item)
  1040. # 扣杂(t)
  1041. deduction_item = QTableWidgetItem(_format_slip_weight('deduction'))
  1042. # 移除当天高亮背景
  1043. self.table.setItem(i, 11, deduction_item)
  1044. # 状态
  1045. status_text = (inbound.get('status', '') or '').strip()
  1046. status_item = QTableWidgetItem(status_text)
  1047. # 移除状态文字颜色和当天高亮背景
  1048. self.table.setItem(i, 12, status_item)
  1049. # 操作按钮
  1050. btn_widget = QWidget()
  1051. btn_layout = QHBoxLayout()
  1052. btn_layout.setContentsMargins(5, 2, 5, 2)
  1053. is_completed = self._is_completed_status(status_text)
  1054. # 为已完成的行设置淡绿色背景
  1055. if is_completed:
  1056. light_green = QColor(220, 255, 220) # 淡绿色
  1057. brush = QBrush(light_green)
  1058. for col in range(self.table.columnCount()):
  1059. item = self.table.item(i, col)
  1060. if item:
  1061. item.setBackground(brush)
  1062. # 地磅单和打印按钮放在前面
  1063. # 地磅单按钮始终显示(无论是否完成)
  1064. jump_btn = QPushButton("地磅单")
  1065. jump_btn.setFont(QFont("微软雅黑", 14))
  1066. apply_button_style(jump_btn, 'blue')
  1067. jump_btn.clicked.connect(lambda checked, iid=inbound['id']: self.jump_to_weighing(iid))
  1068. btn_layout.addWidget(jump_btn)
  1069. # 如果有地磅单,显示打印按钮(无论是否完成)
  1070. slip_summary = slip_summary_map.get(inbound.get('id'))
  1071. if slip_summary:
  1072. print_btn = QPushButton("打印")
  1073. print_btn.setFont(QFont("微软雅黑", 14))
  1074. apply_button_style(print_btn, 'blue')
  1075. print_btn.clicked.connect(lambda checked, iid=inbound['id']: self.print_weighing_slip(iid))
  1076. btn_layout.addWidget(print_btn)
  1077. # 其他按钮放在后面
  1078. if is_completed:
  1079. view_btn = QPushButton("查看")
  1080. view_btn.setFont(QFont("微软雅黑", 14))
  1081. apply_button_style(view_btn, 'normal')
  1082. view_btn.clicked.connect(lambda checked, iid=inbound['id']: self.view_inbound(iid))
  1083. btn_layout.addWidget(view_btn)
  1084. else:
  1085. edit_btn = QPushButton("编辑")
  1086. edit_btn.setFont(QFont("微软雅黑", 14))
  1087. apply_button_style(edit_btn, 'normal')
  1088. edit_btn.clicked.connect(lambda checked, iid=inbound['id']: self.start_editing_inbound(iid))
  1089. btn_layout.addWidget(edit_btn)
  1090. if self._is_admin:
  1091. delete_btn = QPushButton("删除")
  1092. delete_btn.setFont(QFont("微软雅黑", 14))
  1093. apply_button_style(delete_btn, 'normal')
  1094. delete_btn.clicked.connect(lambda checked, iid=inbound['id']: self.delete_inbound(iid))
  1095. btn_layout.addWidget(delete_btn)
  1096. btn_widget.setLayout(btn_layout)
  1097. self.table.setCellWidget(i, 13, btn_widget)
  1098. self.table.resizeRowsToContents()
  1099. QTimer.singleShot(0, self.table.resizeRowsToContents)
  1100. self._apply_table_column_widths()
  1101. # 只在表格视图下显示表格、隐藏卡片区域
  1102. if hasattr(self, "card_scroll_area"):
  1103. self.table.setVisible(True)
  1104. self.card_scroll_area.setVisible(False)
  1105. def _refresh_card_view(self):
  1106. """以卡片形式渲染出入库单列表"""
  1107. inbounds = getattr(self, "_current_inbounds", [])
  1108. slip_summary_map = getattr(self, "_slip_summary_map", {})
  1109. today_str = datetime.now().strftime("%Y-%m-%d")
  1110. # 清空旧卡片(网格布局)
  1111. while self.card_layout.count():
  1112. item = self.card_layout.takeAt(0)
  1113. w = item.widget()
  1114. if w is not None:
  1115. w.deleteLater()
  1116. # 清空旧的卡片缓存,避免引用到已销毁的 QFrame
  1117. self._card_widgets = []
  1118. def _format_slip_weight(summary: Optional[dict], field: str) -> str:
  1119. if not summary:
  1120. return "-"
  1121. value = summary.get(field)
  1122. if value is None:
  1123. return "-"
  1124. tons_value = kg_to_tons(value)
  1125. if tons_value is None:
  1126. return "-"
  1127. return f"{tons_value:.3f} t"
  1128. for idx, inbound in enumerate(inbounds):
  1129. slip_summary = slip_summary_map.get(inbound.get('id'))
  1130. card = QFrame()
  1131. card.setFrameShape(QFrame.NoFrame)
  1132. card.setFrameShadow(QFrame.Plain)
  1133. # 判断是否已完成
  1134. status_text = (inbound.get("status", "") or "").strip()
  1135. is_completed = self._is_completed_status(status_text)
  1136. # 根据完成状态设置卡片背景色
  1137. if is_completed:
  1138. # 已完成:淡绿色背景
  1139. card.setStyleSheet("border: 1px solid #ccc; border-radius: 6px; background-color: #dcffdc;")
  1140. else:
  1141. # 默认卡片样式:带细边框的白色卡片
  1142. card.setStyleSheet("border: 1px solid #ccc; border-radius: 6px;")
  1143. # 控制卡片高度为固定值,宽度由布局和窗口大小动态控制
  1144. card.setFixedHeight(220)
  1145. card_layout = QVBoxLayout()
  1146. card_layout.setContentsMargins(10, 8, 10, 8)
  1147. card_layout.setSpacing(4)
  1148. # 顶部行:业务类型、产品、本次量
  1149. top_layout = QHBoxLayout()
  1150. top_layout.setContentsMargins(0, 0, 0, 0)
  1151. top_layout.setSpacing(10)
  1152. # 业务类型
  1153. business_type = inbound.get("business_type", "")
  1154. biz_label = QLabel(business_type)
  1155. biz_label.setFont(QFont("微软雅黑", 12, QFont.Bold))
  1156. biz_label.setStyleSheet("border: none;")
  1157. # 产品
  1158. product_label = QLabel(inbound.get("product", "") or "-")
  1159. product_label.setFont(QFont("微软雅黑", 12, QFont.Bold))
  1160. product_label.setStyleSheet("border: none;")
  1161. # 本次量
  1162. quantity = inbound.get("quantity")
  1163. if quantity is not None and quantity > 0:
  1164. quantity_text = f"{quantity:.3f} t"
  1165. else:
  1166. quantity_text = "-"
  1167. quantity_label = QLabel(f"本次: {quantity_text}")
  1168. quantity_label.setFont(QFont("微软雅黑", 12))
  1169. quantity_label.setStyleSheet("border: none;")
  1170. top_layout.addWidget(biz_label)
  1171. top_layout.addWidget(product_label)
  1172. top_layout.addWidget(quantity_label)
  1173. top_layout.addStretch()
  1174. # 顶部右侧显示状态
  1175. status_text = (inbound.get("status", "") or "").strip()
  1176. is_completed = self._is_completed_status(status_text)
  1177. status_top_label = QLabel(status_text or "-")
  1178. status_top_label.setFont(QFont("微软雅黑", 12, QFont.Bold))
  1179. status_top_label.setStyleSheet("border: none;")
  1180. # 移除状态文字颜色
  1181. top_layout.addWidget(status_top_label)
  1182. # 中间行:左边ID+日期 + 右边车牌号
  1183. middle_layout = QHBoxLayout()
  1184. # 左边:出入库单ID + 实际日期
  1185. date_str = inbound.get("date", "") or "-"
  1186. inbound_id = inbound.get("id")
  1187. if inbound_id is not None:
  1188. date_display_text = f"ID: {inbound_id}\n{date_str}"
  1189. else:
  1190. date_display_text = date_str
  1191. date_display_label = QLabel(date_display_text)
  1192. date_display_label.setFont(QFont("微软雅黑", 16, QFont.Bold))
  1193. date_display_label.setStyleSheet("border: none;")
  1194. date_display_label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
  1195. # 重量信息(来自地磅单汇总)- 提前计算用于车牌号前缀
  1196. net_text = _format_slip_weight(slip_summary, "net_weight")
  1197. gross_text = _format_slip_weight(slip_summary, "gross_weight")
  1198. tare_text = _format_slip_weight(slip_summary, "tare_weight")
  1199. # 右边:车牌号(根据毛重和皮重添加前缀)
  1200. vehicle_no = inbound.get("vehicle_no", "") or "-"
  1201. prefix = ""
  1202. # 从原始值判断,确保不为0才算有值
  1203. gross_value = slip_summary.get("gross_weight") if slip_summary else None
  1204. tare_value = slip_summary.get("tare_weight") if slip_summary else None
  1205. has_gross = gross_value is not None and gross_value != 0
  1206. has_tare = tare_value is not None and tare_value != 0
  1207. if has_gross and has_tare:
  1208. prefix = "(毛皮)"
  1209. elif has_gross:
  1210. prefix = "(毛)"
  1211. elif has_tare:
  1212. prefix = "(皮)"
  1213. plate_text = f"{prefix}{vehicle_no}" if prefix else vehicle_no
  1214. plate_label = QLabel(plate_text)
  1215. plate_label.setFont(QFont("微软雅黑", 20, QFont.Bold))
  1216. plate_label.setStyleSheet("border: none;")
  1217. plate_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
  1218. middle_layout.addWidget(date_display_label, stretch=1)
  1219. middle_layout.addWidget(plate_label, stretch=1)
  1220. # 往来单位 - 隐藏公司名称显示
  1221. # partner_layout = QHBoxLayout()
  1222. # partner_text = inbound.get("partner_company", "") or "-"
  1223. # partner_label = QLabel(partner_text)
  1224. # partner_label.setFont(QFont("微软雅黑", 12))
  1225. # partner_label.setStyleSheet("border: none;")
  1226. # partner_layout.addWidget(partner_label)
  1227. # partner_layout.addStretch()
  1228. deduction_text = _format_slip_weight(slip_summary, "deduction")
  1229. weight_line_label = QLabel(
  1230. f"净重: {net_text} 毛重: {gross_text} 皮重: {tare_text}"
  1231. )
  1232. weight_line_label.setFont(QFont("微软雅黑", 12))
  1233. weight_line_label.setStyleSheet("border: none;")
  1234. # 扣杂 / 备注
  1235. remarks = (inbound.get("remarks") or "").strip()
  1236. if not remarks:
  1237. remarks = "-"
  1238. remarks_label = QLabel(f"扣杂: {deduction_text} 备注: {remarks}")
  1239. remarks_label.setFont(QFont("微软雅黑", 11))
  1240. remarks_label.setStyleSheet("border: none;")
  1241. remarks_label.setWordWrap(True)
  1242. # 底部主要操作按钮
  1243. btn_layout = QHBoxLayout()
  1244. btn_layout.setContentsMargins(0, 0, 0, 0)
  1245. btn_layout.setSpacing(10)
  1246. btn_layout.addStretch()
  1247. # 卡片视图不显示「地磅单」按钮
  1248. # 若有地磅单则显示「打印」
  1249. # 如果有地磅单,显示打印按钮(无论是否完成)
  1250. if slip_summary:
  1251. print_btn_main = QPushButton("打印")
  1252. print_font = QFont("微软雅黑", 15)
  1253. print_font.setBold(True)
  1254. print_btn_main.setFont(print_font)
  1255. print_btn_main.setMinimumWidth(90)
  1256. print_btn_main.setMinimumHeight(38)
  1257. print_btn_main.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
  1258. apply_button_style(print_btn_main, 'blue')
  1259. print_btn_main.clicked.connect(lambda checked, iid=inbound["id"]: self.print_weighing_slip(iid))
  1260. btn_layout.addWidget(print_btn_main)
  1261. # 其他按钮放在后面 - 隐藏查看和编辑按钮
  1262. # if is_completed:
  1263. # view_btn_main = QPushButton("查看")
  1264. # view_btn_main.setFont(QFont("微软雅黑", 13))
  1265. # view_btn_main.setMinimumWidth(100)
  1266. # view_btn_main.setMinimumHeight(38)
  1267. # view_btn_main.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
  1268. # apply_button_style(view_btn_main, 'normal')
  1269. # view_btn_main.clicked.connect(lambda checked, iid=inbound["id"]: self.view_inbound(iid))
  1270. # btn_layout.addWidget(view_btn_main)
  1271. # else:
  1272. # edit_btn_main = QPushButton("编辑")
  1273. # edit_btn_main.setFont(QFont("微软雅黑", 13))
  1274. # edit_btn_main.setMinimumWidth(80)
  1275. # edit_btn_main.setMinimumHeight(38)
  1276. # edit_btn_main.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
  1277. # apply_button_style(edit_btn_main, 'normal')
  1278. # edit_btn_main.clicked.connect(lambda checked, iid=inbound["id"]: self.start_editing_inbound(iid))
  1279. # btn_layout.addWidget(edit_btn_main)
  1280. if self._is_admin:
  1281. delete_btn_main = QPushButton("删除")
  1282. delete_btn_main.setFont(QFont("微软雅黑", 13))
  1283. delete_btn_main.setMinimumWidth(80)
  1284. delete_btn_main.setMinimumHeight(38)
  1285. delete_btn_main.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
  1286. apply_button_style(delete_btn_main, 'normal')
  1287. delete_btn_main.clicked.connect(lambda checked, iid=inbound["id"]: self.delete_inbound(iid))
  1288. btn_layout.addWidget(delete_btn_main)
  1289. btn_layout.addStretch()
  1290. # 当天单据高亮卡片背景
  1291. is_today = inbound.get("date", "") == today_str
  1292. # 卡片背景色已在上面根据完成状态设置,这里不再重复设置
  1293. card_layout.addLayout(top_layout)
  1294. card_layout.addLayout(middle_layout)
  1295. # card_layout.addLayout(partner_layout) # 隐藏公司名称显示
  1296. card_layout.addWidget(weight_line_label)
  1297. card_layout.addWidget(remarks_label)
  1298. card_layout.addLayout(btn_layout)
  1299. card.setLayout(card_layout)
  1300. # 记录卡片控件,便于统一调整宽度
  1301. if not hasattr(self, "_card_widgets"):
  1302. self._card_widgets = []
  1303. self._card_widgets.append(card)
  1304. # 添加到网格布局:一行多个(由 self.card_columns 控制)
  1305. col_count = getattr(self, "card_columns", 3) or 3
  1306. row = idx // col_count
  1307. col = idx % col_count
  1308. self.card_layout.addWidget(card, row, col)
  1309. # 刷新完后根据当前宽度调整卡片宽度
  1310. self._update_card_widths()
  1311. # 显示卡片区域、隐藏表格(简化版可能无 table)
  1312. table = getattr(self, "table", None)
  1313. if table is not None:
  1314. table.setVisible(False)
  1315. if getattr(self, "card_scroll_area", None) is not None:
  1316. self.card_scroll_area.setVisible(True)
  1317. def resizeEvent(self, event):
  1318. super().resizeEvent(event)
  1319. # 仅在表格视图下调整列宽
  1320. if getattr(self, "view_mode", "table") == "table":
  1321. self._apply_table_column_widths()
  1322. else:
  1323. # 卡片视图下根据当前宽度调整卡片宽度
  1324. self._update_card_widths()
  1325. self._update_form_widget_height()
  1326. def showEvent(self, event):
  1327. super().showEvent(event)
  1328. if getattr(self, "inbound_id_input", None):
  1329. self.inbound_id_input.setFocus()
  1330. if getattr(self, "card_layout", None):
  1331. # 短延迟刷新,避免首次显示时布局未完成导致卡片不展示
  1332. QTimer.singleShot(80, self.refresh_today_cards)
  1333. if getattr(self, "view_mode", "table") == "table":
  1334. QTimer.singleShot(0, lambda: self._apply_table_column_widths(force=True))
  1335. else:
  1336. QTimer.singleShot(0, self._update_card_widths)
  1337. def _on_section_resized(self, *_):
  1338. if getattr(self, "_is_applying_column_widths", False):
  1339. return
  1340. self._user_resized_columns = True
  1341. def _apply_table_column_widths(self, force: bool = False):
  1342. if not hasattr(self, "table") or not hasattr(self, "column_width_ratios"):
  1343. return
  1344. if getattr(self, "_user_resized_columns", False) and not force:
  1345. return
  1346. viewport_width = self.table.viewport().width()
  1347. if viewport_width <= 0:
  1348. return
  1349. total_ratio = sum(self.column_width_ratios) or 1
  1350. assigned_width = 0
  1351. header = self.table.horizontalHeader()
  1352. self._is_applying_column_widths = True
  1353. header.blockSignals(True)
  1354. try:
  1355. for index, ratio in enumerate(self.column_width_ratios):
  1356. if index == self.table.columnCount() - 1:
  1357. width = viewport_width - assigned_width
  1358. else:
  1359. width = int(viewport_width * ratio / total_ratio)
  1360. assigned_width += width
  1361. self.table.setColumnWidth(index, max(width, 60))
  1362. # 额外像素级调整:日期列宽度不额外加宽,皮重列宽度与毛重列宽度保持一致
  1363. # 列索引:2 = 日期, 9 = 毛重(t), 10 = 皮重(t)
  1364. date_col_index = 2
  1365. gross_col_index = 9
  1366. tare_col_index = 10
  1367. date_width = self.table.columnWidth(date_col_index)
  1368. gross_width = self.table.columnWidth(gross_col_index)
  1369. tare_width = gross_width
  1370. self.table.setColumnWidth(date_col_index, date_width)
  1371. self.table.setColumnWidth(gross_col_index, gross_width)
  1372. self.table.setColumnWidth(tare_col_index, tare_width)
  1373. finally:
  1374. header.blockSignals(False)
  1375. self._is_applying_column_widths = False
  1376. def _switch_view_mode(self, mode: str):
  1377. """切换列表展示模式:table / card"""
  1378. if mode == getattr(self, "view_mode", "table"):
  1379. return
  1380. self.view_mode = mode
  1381. # 同步按钮选中状态
  1382. if mode == "table":
  1383. if hasattr(self, "table_view_btn"):
  1384. self.table_view_btn.setChecked(True)
  1385. if hasattr(self, "card_view_btn"):
  1386. self.card_view_btn.setChecked(False)
  1387. # 重新以表格方式渲染
  1388. self._refresh_table_view()
  1389. else:
  1390. if hasattr(self, "table_view_btn"):
  1391. self.table_view_btn.setChecked(False)
  1392. if hasattr(self, "card_view_btn"):
  1393. self.card_view_btn.setChecked(True)
  1394. # 重新以卡片方式渲染
  1395. self._refresh_card_view()
  1396. def _update_card_widths(self):
  1397. """根据当前滚动区域宽度,动态设置卡片宽度"""
  1398. # 仅在卡片视图下生效
  1399. if getattr(self, "view_mode", "table") == "table":
  1400. return
  1401. if not hasattr(self, "card_scroll_area") or not hasattr(self, "card_layout"):
  1402. return
  1403. if not hasattr(self, "_card_widgets") or not self._card_widgets:
  1404. return
  1405. viewport = self.card_scroll_area.viewport()
  1406. total_width = viewport.width()
  1407. if total_width <= 0:
  1408. return
  1409. # 计算可用宽度:去掉左右外边距
  1410. margins = self.card_layout.contentsMargins()
  1411. available_width = total_width - margins.left() - margins.right()
  1412. if available_width <= 0:
  1413. return
  1414. col_count = getattr(self, "card_columns", 5) or 5
  1415. h_spacing = self.card_layout.horizontalSpacing() or 0
  1416. total_spacing = (col_count - 1) * h_spacing
  1417. if available_width <= total_spacing:
  1418. return
  1419. card_width = int((available_width - total_spacing) / col_count)
  1420. if card_width <= 0:
  1421. return
  1422. alive_cards = []
  1423. for card in self._card_widgets:
  1424. if card is None:
  1425. continue
  1426. if sip.isdeleted(card):
  1427. continue
  1428. alive_cards.append(card)
  1429. card.setMinimumWidth(card_width)
  1430. card.setMaximumWidth(card_width)
  1431. self._card_widgets = alive_cards
  1432. def _update_form_widget_height(self):
  1433. if not hasattr(self, "form_widget") or not self.form_widget:
  1434. return
  1435. hint_height = self.form_widget.sizeHint().height()
  1436. if hint_height > 0:
  1437. self.form_widget.setMaximumHeight(hint_height)
  1438. def event(self, event):
  1439. screen_change_event = getattr(QEvent, "ScreenChangeInternal", None)
  1440. event_types = (
  1441. QEvent.FontChange,
  1442. QEvent.ApplicationFontChange,
  1443. QEvent.StyleChange,
  1444. )
  1445. if screen_change_event is not None:
  1446. event_types = event_types + (screen_change_event,)
  1447. if event.type() in event_types:
  1448. QTimer.singleShot(0, self._update_form_widget_height)
  1449. return super().event(event)
  1450. def export_to_excel(self):
  1451. """导出出入库信息及关联地磅单"""
  1452. inbounds = self.db.get_all_inbound_outbound()
  1453. if not inbounds:
  1454. QMessageBox.information(self, "提示", "暂无可导出的出入库记录。")
  1455. return
  1456. default_name = f"出入库记录导出_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
  1457. file_path, _ = QFileDialog.getSaveFileName(
  1458. self,
  1459. "导出出入库记录",
  1460. default_name,
  1461. "Excel Files (*.xlsx)"
  1462. )
  1463. if not file_path:
  1464. return
  1465. if not file_path.lower().endswith(".xlsx"):
  1466. file_path += ".xlsx"
  1467. export_rows = []
  1468. for inbound in inbounds:
  1469. slips = self.db.get_weighing_slips_by_inbound_id(inbound.get('id'), include_voided=False)
  1470. if not slips:
  1471. export_rows.append(self._build_export_row(inbound, None))
  1472. else:
  1473. for slip in slips:
  1474. export_rows.append(self._build_export_row(inbound, slip))
  1475. try:
  1476. df = pd.DataFrame(export_rows)
  1477. df.to_excel(file_path, index=False)
  1478. QMessageBox.information(self, "导出成功", f"已导出 {len(export_rows)} 条行记录。")
  1479. except Exception as e:
  1480. QMessageBox.critical(self, "导出失败", f"导出Excel失败:{str(e)}")
  1481. def validate_form(self) -> tuple:
  1482. """验证表单数据"""
  1483. if not self._has_selected_date():
  1484. return False, "请选择日期"
  1485. if self.partner_combo.currentIndex() <= 0 or not self.partner_combo.currentText().strip():
  1486. return False, "请选择往来单位"
  1487. if not self.business_type_group.checkedButton():
  1488. return False, "请选择业务类型"
  1489. if self.product_combo.currentIndex() <= 0 or not self.product_combo.currentText().strip():
  1490. return False, "请选择产品"
  1491. quantity_value = self.quantity_input.value()
  1492. if quantity_value <= 0 or quantity_value == -1:
  1493. return False, "本次量必须大于0"
  1494. if not self.vehicle_no_input.text().strip():
  1495. return False, "请填写车牌号"
  1496. return True, ""
  1497. def save_inbound_outbound(self):
  1498. """保存出入库单"""
  1499. # 验证
  1500. valid, error_msg = self.validate_form()
  1501. if not valid:
  1502. QMessageBox.warning(self, "验证失败", error_msg)
  1503. return
  1504. # 获取业务类型
  1505. business_type = self.business_type_group.checkedButton().text()
  1506. # 准备数据
  1507. data = {
  1508. 'date': self.date_input.date().toString("yyyy-MM-dd"),
  1509. 'partner_company': self.partner_combo.currentText(),
  1510. 'business_type': business_type,
  1511. 'product': self.product_combo.currentText(),
  1512. 'quantity': self.quantity_input.value(),
  1513. 'plan_no': self.plan_no_display.text() if self.plan_no_display.text() != "未关联" else '',
  1514. 'batch_no': self.batch_no_input.text().strip(),
  1515. 'vehicle_no': self.vehicle_no_input.text().strip(),
  1516. 'remarks': self.remarks_input.toPlainText().strip(),
  1517. 'purchase_plan_id': self.current_plan_id
  1518. }
  1519. try:
  1520. if self.editing_inbound_id:
  1521. # 更新模式
  1522. if self.db.update_inbound_outbound(self.editing_inbound_id, data):
  1523. QMessageBox.information(self, "成功", "出入库单更新成功!")
  1524. self.clear_form()
  1525. self.refresh_list()
  1526. else:
  1527. QMessageBox.warning(self, "错误", "更新失败")
  1528. else:
  1529. # 新增模式
  1530. self.db.insert_inbound_outbound(data)
  1531. QMessageBox.information(self, "成功", "出入库单保存成功!")
  1532. self.clear_form()
  1533. self.refresh_list()
  1534. except Exception as e:
  1535. QMessageBox.critical(self, "错误", f"保存失败:{str(e)}")
  1536. def clear_form(self):
  1537. """清空表单(简化版界面仅重置ID输入框)"""
  1538. # 旧版界面有完整的出入库表单,这里只需要保证不会因缺少控件报错
  1539. self.editing_inbound_id = None
  1540. self.current_plan_id = None
  1541. # 简化版界面:只存在出入库单ID输入框
  1542. if hasattr(self, "inbound_id_input"):
  1543. self.inbound_id_input.clear()
  1544. # 其余旧表单控件在当前界面不存在,直接返回即可,避免 AttributeError
  1545. return
  1546. def start_editing_inbound(self, inbound_id: int):
  1547. """进入编辑模式并回显表单"""
  1548. inbound = self.db.get_inbound_outbound_by_id(inbound_id)
  1549. if not inbound:
  1550. QMessageBox.warning(self, "错误", "未找到该出入库单")
  1551. return
  1552. if self._is_completed_status(inbound.get('status', '')):
  1553. QMessageBox.information(self, "提示", "已完成的出入库单仅支持查看。")
  1554. self.view_inbound(inbound_id)
  1555. return
  1556. self.editing_inbound_id = inbound_id
  1557. self.save_btn.setText("更新")
  1558. # 填充数据
  1559. self.date_input.setDate(QDate.fromString(inbound['date'], "yyyy-MM-dd"))
  1560. index = self.partner_combo.findText(inbound['partner_company'])
  1561. if index >= 0:
  1562. self.partner_combo.setCurrentIndex(index)
  1563. if inbound['business_type'] == '入库':
  1564. self.business_inbound_radio.setChecked(True)
  1565. elif inbound['business_type'] == '出库':
  1566. self.business_outbound_radio.setChecked(True)
  1567. index = self.product_combo.findText(inbound['product'])
  1568. if index >= 0:
  1569. self.product_combo.setCurrentIndex(index)
  1570. quantity = inbound.get('quantity', 0)
  1571. if quantity and quantity > 0:
  1572. self.quantity_input.setValue(quantity)
  1573. else:
  1574. self.quantity_input.setValue(-1)
  1575. self.vehicle_no_input.setText(inbound.get('vehicle_no', ''))
  1576. self.batch_no_input.setText(inbound.get('batch_no', ''))
  1577. plan_no = inbound.get('plan_no', '')
  1578. if plan_no:
  1579. self.plan_no_display.setText(plan_no)
  1580. else:
  1581. self.plan_no_display.setText("未关联")
  1582. status = inbound.get('status', '')
  1583. self.status_display.setText(status)
  1584. if status.startswith('已'):
  1585. self.status_display.setStyleSheet(self.status_completed_style)
  1586. else:
  1587. self.status_display.setStyleSheet(self.status_pending_style)
  1588. self.remarks_input.setPlainText(inbound.get('remarks', ''))
  1589. self.current_plan_id = inbound.get('purchase_plan_id')
  1590. def delete_inbound(self, inbound_id: int):
  1591. """删除出入库单"""
  1592. if not self._is_admin:
  1593. QMessageBox.warning(self, "权限不足", "仅管理员可执行删除。")
  1594. return
  1595. inbound = self.db.get_inbound_outbound_by_id(inbound_id)
  1596. if not inbound:
  1597. QMessageBox.warning(self, "错误", "未找到该出入库单")
  1598. return
  1599. if self._is_completed_status(inbound.get('status', '')):
  1600. QMessageBox.warning(self, "提示", "已完成的出入库单不可删除。")
  1601. return
  1602. linked_slip = self.db.get_weighing_slip_by_inbound_id(inbound_id, include_voided=False)
  1603. if linked_slip:
  1604. QMessageBox.warning(self, "提示", "该出入库单已关联地磅单,请先作废对应地磅单。")
  1605. return
  1606. msg = QMessageBox()
  1607. msg.setIcon(QMessageBox.Question)
  1608. msg.setWindowTitle("确认")
  1609. msg.setText("确定要删除该出入库单吗?")
  1610. msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
  1611. msg.setDefaultButton(QMessageBox.No)
  1612. msg.button(QMessageBox.Yes).setText("是")
  1613. msg.button(QMessageBox.No).setText("否")
  1614. reply = msg.exec_()
  1615. if reply == QMessageBox.Yes:
  1616. if self.db.delete_inbound_outbound(inbound_id):
  1617. QMessageBox.information(self, "成功", "删除成功!")
  1618. self.refresh_list()
  1619. else:
  1620. QMessageBox.warning(self, "错误", "删除失败")
  1621. def jump_to_weighing(self, inbound_id: int):
  1622. """从出入库单弹出地磅单填写对话框"""
  1623. inbound = self.db.get_inbound_outbound_by_id(inbound_id)
  1624. if not inbound:
  1625. QMessageBox.warning(self, "错误", "未找到该出入库单")
  1626. return
  1627. # 判断是否为当天出入库单
  1628. is_today = False
  1629. inbound_date = inbound.get("date")
  1630. if inbound_date is not None:
  1631. today_str = datetime.now().strftime("%Y-%m-%d")
  1632. if hasattr(inbound_date, "strftime"):
  1633. inbound_date_str = inbound_date.strftime("%Y-%m-%d")
  1634. else:
  1635. inbound_date_str = str(inbound_date).strip()[:10]
  1636. is_today = (inbound_date_str == today_str)
  1637. # 历史出入库单:仅当已有地磅单时才允许打开,并且只读查看
  1638. history_readonly_mode = False
  1639. if not is_today:
  1640. try:
  1641. linked_slip = self.db.get_weighing_slip_by_inbound_id(inbound_id, include_voided=False)
  1642. except Exception:
  1643. linked_slip = None
  1644. if not linked_slip:
  1645. QMessageBox.warning(self, "提示", "该历史出入库单未关联任何地磅单,无法查看历史称重记录。")
  1646. return
  1647. history_readonly_mode = True
  1648. else:
  1649. # 当天已完成的订单:也只读查看,不显示读毛重/读皮重按钮,展示“历史订单不可以修改”
  1650. try:
  1651. linked_slip = self.db.get_weighing_slip_by_inbound_id(inbound_id, include_voided=False)
  1652. except Exception:
  1653. linked_slip = None
  1654. if linked_slip:
  1655. gross_val = linked_slip.get("gross_weight")
  1656. tare_val = linked_slip.get("tare_weight")
  1657. try:
  1658. has_gross = (gross_val is not None and gross_val != "" and float(gross_val) > 0)
  1659. except (TypeError, ValueError):
  1660. has_gross = False
  1661. try:
  1662. has_tare = (tare_val is not None and tare_val != "" and float(tare_val) > 0)
  1663. except (TypeError, ValueError):
  1664. has_tare = False
  1665. if has_gross and has_tare:
  1666. history_readonly_mode = True
  1667. # 1. 校验产品
  1668. product_name = inbound.get('product', '').strip()
  1669. if not product_name:
  1670. QMessageBox.warning(self, "错误", "该出入库单缺少产品信息")
  1671. return
  1672. # 2. 校验往来单位
  1673. partner_name = inbound.get('partner_company', '').strip()
  1674. if not partner_name:
  1675. QMessageBox.warning(self, "错误", "该出入库单缺少往来单位信息")
  1676. return
  1677. # 3. 自动维护主数据
  1678. auto_messages = []
  1679. # 校验并确保产品在货物表中存在
  1680. cargo_status = self.db.ensure_cargo_active(product_name)
  1681. if cargo_status == "created":
  1682. auto_messages.append(f"新增货物:{product_name}")
  1683. elif cargo_status == "restored":
  1684. auto_messages.append(f"恢复货物:{product_name}")
  1685. # 校验并确保往来单位在公司表中存在
  1686. company_status = self.db.ensure_company_active(partner_name)
  1687. if company_status == "created":
  1688. auto_messages.append(f"新增公司:{partner_name}")
  1689. elif company_status == "restored":
  1690. auto_messages.append(f"恢复公司:{partner_name}")
  1691. # 如果有自动维护操作,提示用户
  1692. if auto_messages:
  1693. QMessageBox.information(
  1694. self,
  1695. "提示",
  1696. "已自动维护以下主数据:\n" + "\n".join(auto_messages)
  1697. )
  1698. # 4. 弹出地磅单填写/查看对话框
  1699. dialog = WeighingSlipDialog(inbound, self.db, parent=self, current_user=self.current_user)
  1700. if history_readonly_mode and hasattr(dialog, "set_history_mode"):
  1701. dialog.set_history_mode()
  1702. dialog.exec_()
  1703. # 对话框关闭后刷新列表
  1704. self.refresh_list()
  1705. def view_inbound(self, inbound_id: int):
  1706. """查看出入库单详情"""
  1707. inbound = self.db.get_inbound_outbound_by_id(inbound_id)
  1708. if not inbound:
  1709. QMessageBox.warning(self, "错误", "未找到该出入库单")
  1710. return
  1711. weighing_tab = getattr(self.main_window, 'weighing_tab', None) if self.main_window else None
  1712. dialog = InboundDetailDialog(inbound, self.db, weighing_tab=weighing_tab, parent=self)
  1713. dialog.exec_()
  1714. def generate_batch_no(self):
  1715. """自动生成批次号:PC-YYYYMMDD001格式"""
  1716. if not self._has_selected_date():
  1717. return
  1718. # 获取当前日期
  1719. current_date = self.date_input.date()
  1720. date_str = current_date.toString("yyyy-MM-dd")
  1721. date_part = date_str.replace('-', '')
  1722. # 查询当天最大的批次号序号
  1723. max_sequence = self.db.get_max_batch_no_sequence(date_str)
  1724. # 生成下一个序号
  1725. next_sequence = max_sequence + 1
  1726. # 生成批次号:PC-YYYYMMDD001
  1727. batch_no = f"PC-{date_part}{next_sequence:03d}"
  1728. # 如果批次号输入框为空,则自动填充
  1729. if not self.batch_no_input.text().strip():
  1730. self.batch_no_input.setText(batch_no)
  1731. def on_date_changed(self, date: QDate):
  1732. """日期改变时的处理"""
  1733. # 只有在新增模式下(非编辑模式)且批次号为空时,才自动生成新的批次号
  1734. if not self.editing_inbound_id and not self.batch_no_input.text().strip():
  1735. self.generate_batch_no()
  1736. def on_batch_no_editing_finished(self):
  1737. """批次号输入框失去焦点时的处理"""
  1738. # 只有在新增模式下(非编辑模式)且批次号为空时,才自动生成
  1739. if not self.editing_inbound_id and not self.batch_no_input.text().strip():
  1740. self.generate_batch_no()
  1741. def on_search_text_changed(self, text: str):
  1742. """列表区域模糊检索"""
  1743. self.search_keyword = text.strip()
  1744. self.refresh_list()
  1745. def on_filter_changed(self):
  1746. """筛选条件变化"""
  1747. selected_items = self.status_filter_dropdown.get_selected_items()
  1748. self.show_all = "全部" in selected_items
  1749. self.show_pending_inbound = "待入库" in selected_items or self.show_all
  1750. self.show_pending_outbound = "待出库" in selected_items or self.show_all
  1751. # 30分钟内已完成的筛选
  1752. recent_completed_selection = self.recent_completed_dropdown.currentText()
  1753. self.show_recent_completed = (recent_completed_selection == "30分钟内已完成的")
  1754. self.show_all_completed = (recent_completed_selection == "全部")
  1755. self.refresh_list()
  1756. def on_today_filter_changed(self, state: int):
  1757. """只看当天勾选框变化"""
  1758. self.show_today_only = self.today_only_checkbox.isChecked()
  1759. self.refresh_list()
  1760. def on_business_type_changed(self, checked: bool):
  1761. """业务类型切换时同步状态显示(仅新增模式)"""
  1762. if not checked or self.editing_inbound_id:
  1763. return
  1764. if self.business_inbound_radio.isChecked():
  1765. status_text = "待入库"
  1766. elif self.business_outbound_radio.isChecked():
  1767. status_text = "待出库"
  1768. else:
  1769. return
  1770. self.status_display.setText(status_text)
  1771. self.status_display.setStyleSheet(self.status_pending_style)
  1772. @staticmethod
  1773. def _ton_value_from_kg(value: Optional[float]):
  1774. tons = kg_to_tons(value)
  1775. if tons is None:
  1776. return ""
  1777. return round(tons, 3)
  1778. def _build_export_row(self, inbound: dict, slip: Optional[dict]) -> dict:
  1779. """组装导出行"""
  1780. row = {
  1781. "出入库ID": inbound.get('id'),
  1782. "计划号": inbound.get('plan_no', ''),
  1783. "批次号": inbound.get('batch_no', ''),
  1784. "日期": inbound.get('date', ''),
  1785. "往来单位": inbound.get('partner_company', ''),
  1786. "业务类型": inbound.get('business_type', ''),
  1787. "产品": inbound.get('product', ''),
  1788. "车牌号": inbound.get('vehicle_no', ''),
  1789. "本次量(t)": round(inbound.get('quantity', 0), 3) if inbound.get('quantity') is not None else "",
  1790. "状态": inbound.get('status', ''),
  1791. "备注": inbound.get('remarks', '')
  1792. }
  1793. if slip:
  1794. row.update({
  1795. "地磅单ID": slip.get('id'),
  1796. "地磅单状态": "已作废" if slip.get('is_voided') else "有效",
  1797. "毛重(t)": self._ton_value_from_kg(slip.get('gross_weight')),
  1798. "毛重时间": slip.get('gross_weight_time', ''),
  1799. "皮重(t)": self._ton_value_from_kg(slip.get('tare_weight')),
  1800. "皮重时间": slip.get('tare_weight_time', ''),
  1801. "扣杂(t)": self._ton_value_from_kg(slip.get('deduction')),
  1802. "净重(t)": self._ton_value_from_kg(slip.get('net_weight')),
  1803. "称重时间": slip.get('created_at', ''),
  1804. })
  1805. else:
  1806. row.update({
  1807. "地磅单ID": "",
  1808. "地磅单状态": "",
  1809. "毛重(t)": "",
  1810. "毛重时间": "",
  1811. "皮重(t)": "",
  1812. "皮重时间": "",
  1813. "扣杂(t)": "",
  1814. "净重(t)": "",
  1815. "称重时间": "",
  1816. })
  1817. return row
  1818. def _has_selected_date(self) -> bool:
  1819. if not self.date_input:
  1820. return False
  1821. return not self.date_input.is_empty()
  1822. def _format_date_display(self, date_str: str) -> str:
  1823. """格式化日期显示:今天/明天/后天/大后天 + 实际日期"""
  1824. if not date_str or date_str == "-":
  1825. return "-"
  1826. try:
  1827. from datetime import datetime, timedelta
  1828. # 解析日期字符串
  1829. date_obj = datetime.strptime(date_str, "%Y-%m-%d").date()
  1830. today = datetime.now().date()
  1831. # 计算日期差
  1832. delta = (date_obj - today).days
  1833. # 根据日期差显示不同的文本
  1834. if delta == 0:
  1835. day_text = "今天"
  1836. elif delta == 1:
  1837. day_text = "明天"
  1838. elif delta == 2:
  1839. day_text = "后天"
  1840. else:
  1841. day_text = "大后天"
  1842. # 返回格式:今天/明天/后天/大后天\n实际日期
  1843. return f"{day_text}\n{date_str}"
  1844. except Exception:
  1845. # 如果解析失败,直接返回原日期
  1846. return date_str
  1847. def print_weighing_slip(self, inbound_id: int):
  1848. """打印出入库单关联的地磅单"""
  1849. slip = self.db.get_weighing_slip_by_inbound_id(inbound_id, include_voided=False)
  1850. if not slip:
  1851. QMessageBox.warning(self, "提示", "该出入库单尚未生成地磅单,无法打印。")
  1852. return
  1853. try:
  1854. printer = Printer()
  1855. printer.preview_weighing_slip(slip, copies=1)
  1856. except Exception as e:
  1857. QMessageBox.critical(self, "错误", f"打印失败:{str(e)}")
  1858. class InboundDetailDialog(QDialog):
  1859. """出入库单详情对话框"""
  1860. def __init__(self, inbound: dict, db: Database, weighing_tab=None, parent=None):
  1861. super().__init__(parent)
  1862. self.inbound = inbound
  1863. self.db = db
  1864. self.weighing_tab = weighing_tab
  1865. self.slip = self.db.get_weighing_slip_by_inbound_id(inbound['id'], include_voided=True)
  1866. self.setWindowTitle("出入库单详情")
  1867. self.resize(560, 480)
  1868. self.setStyleSheet("""
  1869. QWidget {
  1870. font-size: 16px;
  1871. font-family: "微软雅黑";
  1872. }
  1873. QGroupBox {
  1874. font-weight: bold;
  1875. }
  1876. """)
  1877. self.init_ui()
  1878. @staticmethod
  1879. def _format_weight_in_tons(kg_value: float, digits: int = 3) -> str:
  1880. if kg_value is None:
  1881. kg_value = 0
  1882. return f"{kg_value / 1000:.{digits}f}"
  1883. def init_ui(self):
  1884. layout = QVBoxLayout()
  1885. form = QFormLayout()
  1886. form.setLabelAlignment(Qt.AlignRight)
  1887. form.setFormAlignment(Qt.AlignTop)
  1888. def _fmt(value, default=""):
  1889. if value is None:
  1890. return default
  1891. if isinstance(value, float):
  1892. return f"{value:.3f}"
  1893. return str(value)
  1894. info_fields = [
  1895. ("状态", self.inbound.get('status', '')),
  1896. ("业务类型", self.inbound.get('business_type', '')),
  1897. ("日期", self.inbound.get('date', '')),
  1898. ("往来单位", self.inbound.get('partner_company', '')),
  1899. ("产品", self.inbound.get('product', '')),
  1900. ("本次量(t)", _fmt(self.inbound.get('quantity'))),
  1901. ("车牌号", self.inbound.get('vehicle_no', '')),
  1902. ("计划号", self.inbound.get('plan_no', '')),
  1903. ("批次号", self.inbound.get('batch_no', '')),
  1904. ]
  1905. for label_text, value in info_fields:
  1906. label = QLabel(str(value) if value else "——")
  1907. label.setWordWrap(True)
  1908. form.addRow(f"{label_text}:", label)
  1909. remarks_label = QLabel(self.inbound.get('remarks', '') or "无")
  1910. remarks_label.setWordWrap(True)
  1911. remarks_label.setStyleSheet("color: black;")
  1912. form.addRow("备注:", remarks_label)
  1913. layout.addLayout(form)
  1914. layout.addWidget(self._build_slip_section())
  1915. btn_layout = QHBoxLayout()
  1916. btn_layout.addStretch()
  1917. close_btn = QPushButton("关闭")
  1918. close_btn.setMinimumWidth(100)
  1919. apply_button_style(close_btn, 'normal')
  1920. close_btn.clicked.connect(self.accept)
  1921. btn_layout.addWidget(close_btn)
  1922. btn_layout.addStretch()
  1923. layout.addLayout(btn_layout)
  1924. self.setLayout(layout)
  1925. def _build_slip_section(self) -> QGroupBox:
  1926. group = QGroupBox("关联地磅单")
  1927. inner_layout = QVBoxLayout()
  1928. if not self.slip:
  1929. inner_layout.addWidget(QLabel("暂无关联地磅单。"))
  1930. else:
  1931. status = "已作废" if self.slip.get('is_voided') else "有效"
  1932. summary = QLabel(
  1933. f"地磅单ID:{self.slip.get('id')} · 状态:{status} · 净重:{self._format_weight_in_tons(self.slip.get('net_weight', 0))} t"
  1934. )
  1935. summary.setStyleSheet("")
  1936. inner_layout.addWidget(summary)
  1937. detail_rows = [
  1938. ("车牌号", self.slip.get('vehicle_no', '')),
  1939. ("毛重(t)", self._format_weight_in_tons(self.slip.get('gross_weight', 0))),
  1940. ("皮重(t)", self._format_weight_in_tons(self.slip.get('tare_weight', 0))),
  1941. ("扣杂(t)", self._format_weight_in_tons(self.slip.get('deduction', 0))),
  1942. ("供应商", self.slip.get('supplier', '')),
  1943. ("收货单位", self.slip.get('consignee', '')),
  1944. ]
  1945. for title, value in detail_rows:
  1946. row_label = QLabel(f"{title}:{value or '——'}")
  1947. row_label.setWordWrap(True)
  1948. inner_layout.addWidget(row_label)
  1949. btn_layout = QHBoxLayout()
  1950. btn_layout.addStretch()
  1951. view_btn = QPushButton("查看地磅单详情")
  1952. apply_button_style(view_btn, 'normal')
  1953. if not self.weighing_tab:
  1954. view_btn.setEnabled(False)
  1955. view_btn.setToolTip("未能获取地磅单页面,无法打开详情。")
  1956. view_btn.clicked.connect(self.open_weighing_detail)
  1957. btn_layout.addWidget(view_btn)
  1958. btn_layout.addStretch()
  1959. inner_layout.addLayout(btn_layout)
  1960. group.setLayout(inner_layout)
  1961. return group
  1962. def open_weighing_detail(self):
  1963. if not self.slip:
  1964. QMessageBox.warning(self, "提示", "暂无地磅单信息。")
  1965. return
  1966. if not self.weighing_tab:
  1967. QMessageBox.warning(self, "提示", "无法打开地磅单详情。")
  1968. return
  1969. self.weighing_tab.show_detail(self.slip['id'])
  1970. class WeighingSlipDialog(QDialog):
  1971. """地磅单填写对话框"""
  1972. instrument_weight_received = pyqtSignal(float, str) # 重量, 类型(gross/tare)
  1973. def __init__(self, inbound: dict, db: Database, parent=None, current_user: Optional[Dict] = None):
  1974. super().__init__(parent)
  1975. self.inbound = inbound
  1976. self.db = db
  1977. self.current_user = current_user or {}
  1978. self.is_admin = self.current_user.get('role') == 'admin'
  1979. self.main_window = getattr(parent, "main_window", None) if parent else None
  1980. self.printer = Printer()
  1981. self.print_copies = 1
  1982. self._is_clearing_form = False
  1983. self.editing_slip_id: Optional[int] = None
  1984. self.existing_slip = None
  1985. # 检查是否已存在地磅单
  1986. try:
  1987. self.existing_slip = self.db.get_weighing_slip_by_inbound_id(inbound['id'], include_voided=False)
  1988. if self.existing_slip:
  1989. self.editing_slip_id = self.existing_slip['id']
  1990. except Exception as e:
  1991. logger.warning(f"查询地磅单关联关系失败: {str(e)}")
  1992. self.setWindowTitle("地磅单填写")
  1993. self.setMinimumSize(1400, 600) # 增加宽度和高度
  1994. self.resize(1400, 700) # 设置初始大小
  1995. # 初始化地磅相关变量
  1996. self.instrument_weight = None
  1997. # 串口读取相关
  1998. self._serial_reader: Optional[SerialReader] = None
  1999. self._pending_read_target: Optional[str] = None # 'gross' or 'tare'
  2000. self.instrument_weight_received.connect(self._on_instrument_weight_received)
  2001. self.init_ui()
  2002. self._setup_field_permissions()
  2003. self.refresh_dropdowns()
  2004. self._prefill_from_inbound()
  2005. # 绑定实时仪表数据显示
  2006. try:
  2007. self._attach_serial_reader()
  2008. except Exception:
  2009. pass
  2010. def set_history_mode(self):
  2011. """
  2012. 历史出入库单查看模式:只允许查看,不允许修改毛重、皮重,也不允许再次读数或保存/清空
  2013. """
  2014. # 历史订单:隐藏读毛重/读皮重按钮,在原区域显示提示文字
  2015. if hasattr(self, "gross_btn_widget"):
  2016. self.gross_btn_widget.hide()
  2017. if hasattr(self, "tare_btn_widget"):
  2018. self.tare_btn_widget.hide()
  2019. if not hasattr(self, "history_readonly_label"):
  2020. self.history_readonly_label = QLabel("历史订单不可以修改")
  2021. self.history_readonly_label.setFont(QFont("微软雅黑", 18, QFont.Bold))
  2022. self.history_readonly_label.setAlignment(Qt.AlignCenter)
  2023. if hasattr(self, "buttons_layout"):
  2024. self.buttons_layout.addWidget(self.history_readonly_label)
  2025. # 毛重、皮重及时间字段设为只读
  2026. if hasattr(self, "gross_weight_input"):
  2027. try:
  2028. self.gross_weight_input.setReadOnly(True)
  2029. except Exception:
  2030. pass
  2031. if hasattr(self, "gross_weight_time"):
  2032. try:
  2033. self.gross_weight_time.setReadOnly(True)
  2034. if self.gross_weight_time.lineEdit():
  2035. self.gross_weight_time.lineEdit().setReadOnly(True)
  2036. except Exception:
  2037. pass
  2038. if hasattr(self, "tare_weight_input"):
  2039. try:
  2040. self.tare_weight_input.setReadOnly(True)
  2041. except Exception:
  2042. pass
  2043. if hasattr(self, "tare_weight_time"):
  2044. try:
  2045. self.tare_weight_time.setReadOnly(True)
  2046. if self.tare_weight_time.lineEdit():
  2047. self.tare_weight_time.lineEdit().setReadOnly(True)
  2048. except Exception:
  2049. pass
  2050. # 禁用保存、清空按钮(始终允许关闭)
  2051. if hasattr(self, "save_btn"):
  2052. self.save_btn.setEnabled(False)
  2053. if hasattr(self, "clear_btn"):
  2054. self.clear_btn.setEnabled(False)
  2055. def _setup_field_permissions(self):
  2056. """根据用户权限设置字段的可编辑性"""
  2057. # admin用户可以编辑毛重、皮重、毛重时间、皮重时间
  2058. # 其他用户只能查看,不能编辑
  2059. can_edit = self.is_admin
  2060. # 设置毛重字段
  2061. if hasattr(self, 'gross_weight_input'):
  2062. self.gross_weight_input.setReadOnly(not can_edit)
  2063. if not can_edit:
  2064. self.gross_weight_input.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
  2065. # 设置毛重时间字段
  2066. if hasattr(self, 'gross_weight_time'):
  2067. self.gross_weight_time.setReadOnly(not can_edit)
  2068. if not can_edit and self.gross_weight_time.lineEdit():
  2069. self.gross_weight_time.lineEdit().setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
  2070. # 设置皮重字段
  2071. if hasattr(self, 'tare_weight_input'):
  2072. self.tare_weight_input.setReadOnly(not can_edit)
  2073. if not can_edit:
  2074. self.tare_weight_input.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
  2075. # 设置皮重时间字段
  2076. if hasattr(self, 'tare_weight_time'):
  2077. self.tare_weight_time.setReadOnly(not can_edit)
  2078. if not can_edit and self.tare_weight_time.lineEdit():
  2079. self.tare_weight_time.lineEdit().setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
  2080. def init_ui(self):
  2081. """初始化界面"""
  2082. layout = QHBoxLayout() # 主布局改为水平布局
  2083. layout.setSpacing(15)
  2084. layout.setContentsMargins(15, 15, 15, 15)
  2085. # 左侧区域 - 仪表数据、读毛重、读皮重
  2086. left_panel = QWidget()
  2087. # 移除固定宽度,让左右各占一半
  2088. left_layout = QVBoxLayout(left_panel)
  2089. left_layout.setSpacing(30)
  2090. left_layout.setContentsMargins(20, 20, 20, 20)
  2091. # 仪表数据显示区域 - 改成黑底白字,大区域
  2092. instrument_label = QLabel("仪表数据")
  2093. instrument_label.setFont(QFont("微软雅黑", 32, QFont.Bold))
  2094. instrument_label.setAlignment(Qt.AlignCenter)
  2095. instrument_label.setStyleSheet("color: black; margin-bottom: 10px;")
  2096. left_layout.addWidget(instrument_label)
  2097. self.instrument_weight_label = QLabel("0.00 kg")
  2098. self.instrument_weight_label.setFont(QFont("微软雅黑", 42, QFont.Bold))
  2099. self.instrument_weight_label.setStyleSheet("""
  2100. QLabel {
  2101. color: white;
  2102. background-color: black;
  2103. border: 3px solid #333;
  2104. border-radius: 15px;
  2105. padding: 25px;
  2106. }
  2107. """)
  2108. self.instrument_weight_label.setMinimumHeight(240) # 高度增加一倍
  2109. self.instrument_weight_label.setAlignment(Qt.AlignCenter)
  2110. left_layout.addWidget(self.instrument_weight_label)
  2111. # 读毛重和读皮重按钮放在一行(按钮下方带提示文字)
  2112. self.buttons_layout = QHBoxLayout()
  2113. self.buttons_layout.setSpacing(30)
  2114. # 读毛重按钮 - 圆形 + 提示(醒目橙色,适合红绿色盲)
  2115. self.read_gross_btn = QPushButton("满车毛重")
  2116. self.read_gross_btn.setFont(QFont("微软雅黑", 22, QFont.Bold))
  2117. self.read_gross_btn.setMinimumHeight(140)
  2118. self.read_gross_btn.setMinimumWidth(140)
  2119. self.read_gross_btn.setMaximumHeight(140)
  2120. self.read_gross_btn.setMaximumWidth(140)
  2121. self.read_gross_btn.setStyleSheet("""
  2122. QPushButton {
  2123. background-color: #FF6B35;
  2124. color: white;
  2125. border: none;
  2126. border-radius: 70px;
  2127. padding: 10px;
  2128. box-shadow: 0 4px 8px rgba(255, 107, 53, 0.4);
  2129. }
  2130. QPushButton:hover {
  2131. background-color: #E55A2B;
  2132. box-shadow: 0 6px 12px rgba(255, 107, 53, 0.6);
  2133. }
  2134. QPushButton:pressed {
  2135. background-color: #CC4F26;
  2136. box-shadow: 0 2px 4px rgba(255, 107, 53, 0.4);
  2137. }
  2138. """)
  2139. self.read_gross_btn.clicked.connect(lambda: self._start_read_from_instrument('gross'))
  2140. self.gross_btn_widget = QWidget()
  2141. gross_btn_layout = QVBoxLayout()
  2142. gross_btn_layout.setContentsMargins(0, 0, 0, 0)
  2143. gross_btn_layout.setSpacing(6)
  2144. gross_btn_layout.addWidget(self.read_gross_btn, alignment=Qt.AlignCenter)
  2145. gross_hint_label = QLabel("满车时点击")
  2146. gross_hint_label.setFont(QFont("微软雅黑", 12))
  2147. gross_hint_label.setAlignment(Qt.AlignCenter)
  2148. gross_btn_layout.addWidget(gross_hint_label)
  2149. self.gross_btn_widget.setLayout(gross_btn_layout)
  2150. self.buttons_layout.addWidget(self.gross_btn_widget)
  2151. # 读皮重按钮 - 圆形 + 提示(醒目紫色,适合红绿色盲)
  2152. self.read_tare_btn = QPushButton("空车皮重")
  2153. self.read_tare_btn.setFont(QFont("微软雅黑", 22, QFont.Bold))
  2154. self.read_tare_btn.setMinimumHeight(140)
  2155. self.read_tare_btn.setMinimumWidth(140)
  2156. self.read_tare_btn.setMaximumHeight(140)
  2157. self.read_tare_btn.setMaximumWidth(140)
  2158. self.read_tare_btn.setStyleSheet("""
  2159. QPushButton {
  2160. background-color: #8B5CF6;
  2161. color: white;
  2162. border: none;
  2163. border-radius: 70px;
  2164. padding: 10px;
  2165. box-shadow: 0 4px 8px rgba(139, 92, 246, 0.4);
  2166. }
  2167. QPushButton:hover {
  2168. background-color: #7C3AED;
  2169. box-shadow: 0 6px 12px rgba(139, 92, 246, 0.6);
  2170. }
  2171. QPushButton:pressed {
  2172. background-color: #6D28D9;
  2173. box-shadow: 0 2px 4px rgba(139, 92, 246, 0.4);
  2174. }
  2175. """)
  2176. self.read_tare_btn.clicked.connect(lambda: self._start_read_from_instrument('tare'))
  2177. self.tare_btn_widget = QWidget()
  2178. tare_btn_layout = QVBoxLayout()
  2179. tare_btn_layout.setContentsMargins(0, 0, 0, 0)
  2180. tare_btn_layout.setSpacing(6)
  2181. tare_btn_layout.addWidget(self.read_tare_btn, alignment=Qt.AlignCenter)
  2182. tare_hint_label = QLabel("空车时点击")
  2183. tare_hint_label.setFont(QFont("微软雅黑", 12))
  2184. tare_hint_label.setAlignment(Qt.AlignCenter)
  2185. tare_btn_layout.addWidget(tare_hint_label)
  2186. self.tare_btn_widget.setLayout(tare_btn_layout)
  2187. self.buttons_layout.addWidget(self.tare_btn_widget)
  2188. left_layout.addLayout(self.buttons_layout)
  2189. left_layout.addStretch()
  2190. layout.addWidget(left_panel, 1) # 左右各占一半
  2191. # 右侧区域 - 所有数据项(带滚动条)
  2192. right_panel = QWidget()
  2193. right_layout = QVBoxLayout(right_panel)
  2194. right_layout.setSpacing(10)
  2195. right_layout.setContentsMargins(10, 10, 10, 10)
  2196. # 标题
  2197. title = QLabel("地磅单填写")
  2198. title_font = QFont("微软雅黑", 14, QFont.Bold)
  2199. title.setFont(title_font)
  2200. title.setAlignment(Qt.AlignCenter)
  2201. right_layout.addWidget(title)
  2202. # 创建滚动区域
  2203. scroll_area = QScrollArea()
  2204. scroll_area.setWidgetResizable(True)
  2205. scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
  2206. # 不显示纵向滚动条
  2207. scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
  2208. # 创建表单
  2209. form_widget = self.create_form_widget()
  2210. scroll_area.setWidget(form_widget)
  2211. right_layout.addWidget(scroll_area)
  2212. # 按钮区域
  2213. button_layout = QHBoxLayout()
  2214. button_layout.addStretch()
  2215. self.save_btn = QPushButton("保存")
  2216. self.save_btn.setMinimumHeight(45)
  2217. self.save_btn.setMinimumWidth(130)
  2218. self.save_btn.setFont(QFont("微软雅黑", 16, QFont.Bold))
  2219. apply_button_style(self.save_btn, 'green')
  2220. self.save_btn.clicked.connect(self.save_weighing_slip)
  2221. self.save_btn.setShortcut(QKeySequence("Ctrl+S"))
  2222. self.clear_btn = QPushButton("清空")
  2223. self.clear_btn.setMinimumHeight(45)
  2224. self.clear_btn.setMinimumWidth(130)
  2225. self.clear_btn.setFont(QFont("微软雅黑", 16))
  2226. apply_button_style(self.clear_btn, 'normal')
  2227. self.clear_btn.clicked.connect(self.clear_form)
  2228. self.clear_btn.setVisible(False) # 出入库管理地磅单弹窗中隐藏清空按钮
  2229. self.print_btn = QPushButton("打印")
  2230. self.print_btn.setMinimumHeight(45)
  2231. self.print_btn.setMinimumWidth(130)
  2232. self.print_btn.setFont(QFont("微软雅黑", 16))
  2233. apply_button_style(self.print_btn, 'blue')
  2234. self.print_btn.clicked.connect(self._dialog_print_weighing_slip)
  2235. close_btn = QPushButton("关闭")
  2236. close_btn.setMinimumHeight(45)
  2237. close_btn.setMinimumWidth(130)
  2238. close_btn.setFont(QFont("微软雅黑", 16))
  2239. apply_button_style(close_btn, 'normal')
  2240. close_btn.clicked.connect(self.accept)
  2241. button_layout.addWidget(self.save_btn)
  2242. button_layout.addWidget(self.print_btn)
  2243. button_layout.addWidget(self.clear_btn)
  2244. button_layout.addWidget(close_btn)
  2245. button_layout.addStretch()
  2246. right_layout.addLayout(button_layout)
  2247. layout.addWidget(right_panel, 1) # 左右各占一半
  2248. self.setLayout(layout)
  2249. def create_form_widget(self) -> QWidget:
  2250. """创建地磅单填写表单"""
  2251. widget = QWidget()
  2252. layout = QVBoxLayout()
  2253. layout.setSpacing(15)
  2254. layout.setContentsMargins(15, 15, 15, 15)
  2255. # 表单区域 - 使用垂直布局,逐行排列
  2256. form_layout = QVBoxLayout()
  2257. form_layout.setSpacing(15)
  2258. # 列表顶部对齐,允许每行宽度填满父容器
  2259. try:
  2260. form_layout.setAlignment(Qt.AlignTop)
  2261. except Exception:
  2262. pass
  2263. # 第一行:车号(必填)
  2264. vehicle_layout = QHBoxLayout()
  2265. vehicle_layout.setSpacing(10)
  2266. vehicle_label = QLabel("<span style='color: black;'>车号 *</span>:")
  2267. vehicle_label.setFont(QFont("微软雅黑", 16))
  2268. vehicle_label.setTextFormat(Qt.RichText)
  2269. vehicle_label.setMinimumWidth(120)
  2270. vehicle_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
  2271. self.vehicle_no_input = QLineEdit()
  2272. self.vehicle_no_input.setMinimumHeight(45)
  2273. self.vehicle_no_input.setFont(QFont("微软雅黑", 16))
  2274. self.vehicle_no_input.setMinimumWidth(0)
  2275. self.vehicle_no_input.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
  2276. self.vehicle_no_input.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
  2277. # 右侧所有字段设为只读(不可编辑)
  2278. try:
  2279. self.vehicle_no_input.setReadOnly(True)
  2280. except Exception:
  2281. pass
  2282. vehicle_layout.addWidget(vehicle_label)
  2283. vehicle_layout.addWidget(self.vehicle_no_input, 1)
  2284. form_layout.addLayout(vehicle_layout)
  2285. # 第二行:货物名称(必填)
  2286. cargo_layout = QHBoxLayout()
  2287. cargo_layout.setSpacing(10)
  2288. cargo_label = QLabel("<span style='color: black;'>货物名称 *</span>:")
  2289. cargo_label.setFont(QFont("微软雅黑", 16))
  2290. cargo_label.setTextFormat(Qt.RichText)
  2291. cargo_label.setMinimumWidth(120)
  2292. cargo_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
  2293. self.cargo_combo = QComboBox()
  2294. self.cargo_combo.setMinimumHeight(45)
  2295. self.cargo_combo.setFont(QFont("微软雅黑", 16))
  2296. self.cargo_combo.setEditable(False)
  2297. self.cargo_combo.setMinimumWidth(0)
  2298. self.cargo_combo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
  2299. try:
  2300. self.cargo_combo.setEnabled(False)
  2301. except Exception:
  2302. pass
  2303. cargo_layout.addWidget(cargo_label)
  2304. cargo_layout.addWidget(self.cargo_combo, 1)
  2305. form_layout.addLayout(cargo_layout)
  2306. # 第三行:业务类型(必填)
  2307. business_layout = QHBoxLayout()
  2308. business_layout.setSpacing(10)
  2309. business_label = QLabel("<span style='color: black;'>业务类型 *</span>:")
  2310. business_label.setFont(QFont("微软雅黑", 16))
  2311. business_label.setTextFormat(Qt.RichText)
  2312. business_label.setMinimumWidth(120)
  2313. business_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
  2314. self.business_type_group = QButtonGroup()
  2315. self.business_sale_radio = QRadioButton("出库")
  2316. self.business_purchase_radio = QRadioButton("入库")
  2317. self.business_sale_radio.setFont(QFont("微软雅黑", 16))
  2318. self.business_purchase_radio.setFont(QFont("微软雅黑", 16))
  2319. self.business_sale_radio.setStyleSheet("")
  2320. self.business_purchase_radio.setStyleSheet("")
  2321. self.business_type_group.addButton(self.business_sale_radio, 0)
  2322. self.business_type_group.addButton(self.business_purchase_radio, 1)
  2323. # 不允许修改业务类型
  2324. try:
  2325. self.business_sale_radio.setEnabled(False)
  2326. self.business_purchase_radio.setEnabled(False)
  2327. except Exception:
  2328. pass
  2329. business_radio_layout = QHBoxLayout()
  2330. business_radio_layout.addWidget(self.business_sale_radio)
  2331. business_radio_layout.addWidget(self.business_purchase_radio)
  2332. business_radio_layout.addStretch()
  2333. business_widget = QWidget()
  2334. business_widget.setLayout(business_radio_layout)
  2335. business_layout.addWidget(business_label)
  2336. business_layout.addWidget(business_widget, 1)
  2337. form_layout.addLayout(business_layout)
  2338. # 第四行:毛重(必填)
  2339. gross_weight_layout = QHBoxLayout()
  2340. gross_weight_layout.setSpacing(10)
  2341. gross_weight_label = QLabel("<span style='color: white;'>毛重(kg) *</span>:")
  2342. gross_weight_label.setFont(QFont("微软雅黑", 16))
  2343. gross_weight_label.setTextFormat(Qt.RichText)
  2344. gross_weight_label.setMinimumWidth(120)
  2345. gross_weight_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
  2346. gross_weight_label.setStyleSheet("""
  2347. QLabel {
  2348. background-color: #1E40AF;
  2349. color: white;
  2350. padding: 4px 0px 4px 8px;
  2351. border: 1px solid #1D4ED8;
  2352. border-radius: 4px;
  2353. }
  2354. """)
  2355. self.gross_weight_input = EmptyDoubleSpinBox()
  2356. self.gross_weight_input.setMinimumHeight(45)
  2357. self.gross_weight_input.setFont(QFont("微软雅黑", 16))
  2358. self.gross_weight_input.setDecimals(2)
  2359. self.gross_weight_input.setMinimum(-1)
  2360. self.gross_weight_input.setMaximum(999999)
  2361. self.gross_weight_input.setSpecialValueText("")
  2362. self.gross_weight_input.setValue(-1)
  2363. self.gross_weight_input.setMinimumWidth(0)
  2364. self.gross_weight_input.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
  2365. self.gross_weight_input.valueChanged.connect(self.on_gross_weight_changed)
  2366. # 毛重删除按钮 - 隐藏
  2367. gross_weight_clear_btn = QPushButton("删除")
  2368. gross_weight_clear_btn.setMinimumHeight(45)
  2369. gross_weight_clear_btn.setFont(QFont("微软雅黑", 12))
  2370. gross_weight_clear_btn.setMaximumWidth(60)
  2371. apply_button_style(gross_weight_clear_btn, 'red')
  2372. gross_weight_clear_btn.clicked.connect(lambda: self.gross_weight_input.setValue(-1))
  2373. gross_weight_clear_btn.hide() # 隐藏删除按钮
  2374. gross_weight_input_layout = QHBoxLayout()
  2375. gross_weight_input_layout.setContentsMargins(0, 0, 0, 0)
  2376. gross_weight_input_layout.setSpacing(5)
  2377. gross_weight_input_layout.addWidget(self.gross_weight_input)
  2378. gross_weight_input_layout.addWidget(gross_weight_clear_btn)
  2379. gross_weight_widget = QWidget()
  2380. gross_weight_widget.setLayout(gross_weight_input_layout)
  2381. gross_weight_layout.addWidget(gross_weight_label)
  2382. gross_weight_layout.addWidget(gross_weight_widget, 1)
  2383. form_layout.addLayout(gross_weight_layout)
  2384. # 第五行:毛重时间(必填)
  2385. gross_time_layout = QHBoxLayout()
  2386. gross_time_layout.setSpacing(10)
  2387. gross_time_label = QLabel("<span style='color: black;'>毛重时间 *</span>:")
  2388. gross_time_label.setFont(QFont("微软雅黑", 16))
  2389. gross_time_label.setTextFormat(Qt.RichText)
  2390. gross_time_label.setMinimumWidth(120)
  2391. gross_time_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
  2392. self.gross_weight_time = EmptyDateTimeEdit()
  2393. self.gross_weight_time.setMinimumHeight(45)
  2394. self.gross_weight_time.setFont(QFont("微软雅黑", 16))
  2395. self.gross_weight_time.setCalendarPopup(True)
  2396. self.gross_weight_time.setDateTime(QDateTime())
  2397. self.gross_weight_time.setDisplayFormat("yyyy-MM-dd HH:mm:ss")
  2398. self.gross_weight_time.setMinimumWidth(0)
  2399. self.gross_weight_time.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
  2400. # 清空显示
  2401. if self.gross_weight_time.lineEdit():
  2402. self.gross_weight_time.lineEdit().setText("")
  2403. QTimer.singleShot(0, lambda: self.gross_weight_time.lineEdit().setText("") if self.gross_weight_time.lineEdit() else None)
  2404. # 毛重时间当前时间按钮 - 隐藏
  2405. gross_time_now_btn = QPushButton("时间")
  2406. gross_time_now_btn.setMinimumHeight(45)
  2407. gross_time_now_btn.setFont(QFont("微软雅黑", 12))
  2408. gross_time_now_btn.setMaximumWidth(80)
  2409. apply_button_style(gross_time_now_btn, 'blue')
  2410. gross_time_now_btn.clicked.connect(lambda: self._set_time_to_now(self.gross_weight_time))
  2411. gross_time_now_btn.hide() # 隐藏时间按钮
  2412. # 将时间框和按钮放在同一个水平布局中
  2413. gross_time_input_layout = QHBoxLayout()
  2414. gross_time_input_layout.setContentsMargins(0, 0, 0, 0)
  2415. gross_time_input_layout.setSpacing(5)
  2416. gross_time_input_layout.addWidget(self.gross_weight_time)
  2417. gross_time_input_layout.addWidget(gross_time_now_btn)
  2418. gross_time_widget = QWidget()
  2419. gross_time_widget.setLayout(gross_time_input_layout)
  2420. gross_time_layout.addWidget(gross_time_label)
  2421. gross_time_layout.addWidget(gross_time_widget, 1)
  2422. form_layout.addLayout(gross_time_layout)
  2423. # 第六行:皮重(必填)
  2424. tare_weight_layout = QHBoxLayout()
  2425. tare_weight_layout.setSpacing(10)
  2426. tare_weight_label = QLabel("<span style='color: white;'>皮重(kg) *</span>:")
  2427. tare_weight_label.setFont(QFont("微软雅黑", 16))
  2428. tare_weight_label.setTextFormat(Qt.RichText)
  2429. tare_weight_label.setMinimumWidth(120)
  2430. tare_weight_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
  2431. tare_weight_label.setStyleSheet("""
  2432. QLabel {
  2433. background-color: #1E40AF;
  2434. color: white;
  2435. padding: 4px 0px 4px 8px;
  2436. border: 1px solid #1D4ED8;
  2437. border-radius: 4px;
  2438. }
  2439. """)
  2440. self.tare_weight_input = EmptyDoubleSpinBox()
  2441. self.tare_weight_input.setMinimumHeight(45)
  2442. self.tare_weight_input.setFont(QFont("微软雅黑", 16))
  2443. self.tare_weight_input.setDecimals(2)
  2444. self.tare_weight_input.setMinimum(-1)
  2445. self.tare_weight_input.setMaximum(999999)
  2446. self.tare_weight_input.setSpecialValueText("")
  2447. self.tare_weight_input.setValue(-1)
  2448. self.tare_weight_input.setMinimumWidth(0)
  2449. self.tare_weight_input.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
  2450. self.tare_weight_input.valueChanged.connect(self.on_tare_weight_changed)
  2451. # 皮重删除按钮 - 隐藏
  2452. tare_weight_clear_btn = QPushButton("删除")
  2453. tare_weight_clear_btn.setMinimumHeight(45)
  2454. tare_weight_clear_btn.setFont(QFont("微软雅黑", 12))
  2455. tare_weight_clear_btn.setMaximumWidth(60)
  2456. apply_button_style(tare_weight_clear_btn, 'red')
  2457. tare_weight_clear_btn.clicked.connect(lambda: self.tare_weight_input.setValue(-1))
  2458. tare_weight_clear_btn.hide() # 隐藏删除按钮
  2459. tare_weight_input_layout = QHBoxLayout()
  2460. tare_weight_input_layout.setContentsMargins(0, 0, 0, 0)
  2461. tare_weight_input_layout.setSpacing(5)
  2462. tare_weight_input_layout.addWidget(self.tare_weight_input)
  2463. tare_weight_input_layout.addWidget(tare_weight_clear_btn)
  2464. tare_weight_widget = QWidget()
  2465. tare_weight_widget.setLayout(tare_weight_input_layout)
  2466. tare_weight_layout.addWidget(tare_weight_label)
  2467. tare_weight_layout.addWidget(tare_weight_widget, 1)
  2468. form_layout.addLayout(tare_weight_layout)
  2469. # 第七行:皮重时间(必填)
  2470. tare_time_layout = QHBoxLayout()
  2471. tare_time_layout.setSpacing(10)
  2472. tare_time_label = QLabel("<span style='color: black;'>皮重时间 *</span>:")
  2473. tare_time_label.setFont(QFont("微软雅黑", 16))
  2474. tare_time_label.setTextFormat(Qt.RichText)
  2475. tare_time_label.setMinimumWidth(120)
  2476. tare_time_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
  2477. self.tare_weight_time = EmptyDateTimeEdit()
  2478. self.tare_weight_time.setMinimumHeight(45)
  2479. self.tare_weight_time.setFont(QFont("微软雅黑", 16))
  2480. self.tare_weight_time.setCalendarPopup(True)
  2481. self.tare_weight_time.setDateTime(QDateTime())
  2482. self.tare_weight_time.setDisplayFormat("yyyy-MM-dd HH:mm:ss")
  2483. self.tare_weight_time.setMinimumWidth(0)
  2484. self.tare_weight_time.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
  2485. # 清空显示
  2486. if self.tare_weight_time.lineEdit():
  2487. self.tare_weight_time.lineEdit().setText("")
  2488. QTimer.singleShot(0, lambda: self.tare_weight_time.lineEdit().setText("") if self.tare_weight_time.lineEdit() else None)
  2489. # 皮重时间当前时间按钮 - 隐藏
  2490. tare_time_now_btn = QPushButton("时间")
  2491. tare_time_now_btn.setMinimumHeight(45)
  2492. tare_time_now_btn.setFont(QFont("微软雅黑", 12))
  2493. tare_time_now_btn.setMaximumWidth(80)
  2494. apply_button_style(tare_time_now_btn, 'blue')
  2495. tare_time_now_btn.clicked.connect(lambda: self._set_time_to_now(self.tare_weight_time))
  2496. tare_time_now_btn.hide() # 隐藏时间按钮
  2497. # 将时间框和按钮放在同一个水平布局中
  2498. tare_time_input_layout = QHBoxLayout()
  2499. tare_time_input_layout.setContentsMargins(0, 0, 0, 0)
  2500. tare_time_input_layout.setSpacing(5)
  2501. tare_time_input_layout.addWidget(self.tare_weight_time)
  2502. tare_time_input_layout.addWidget(tare_time_now_btn)
  2503. tare_time_widget = QWidget()
  2504. tare_time_widget.setLayout(tare_time_input_layout)
  2505. tare_time_layout.addWidget(tare_time_label)
  2506. tare_time_layout.addWidget(tare_time_widget, 1)
  2507. form_layout.addLayout(tare_time_layout)
  2508. # 第八行:扣杂
  2509. deduction_layout = QHBoxLayout()
  2510. deduction_layout.setSpacing(10)
  2511. deduction_label = QLabel("扣杂(kg):")
  2512. deduction_label.setFont(QFont("微软雅黑", 16))
  2513. deduction_label.setMinimumWidth(120)
  2514. deduction_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
  2515. self.deduction_input = EmptyDoubleSpinBox()
  2516. self.deduction_input.setMinimumHeight(45)
  2517. self.deduction_input.setFont(QFont("微软雅黑", 16))
  2518. self.deduction_input.setDecimals(2)
  2519. self.deduction_input.setMinimum(-1)
  2520. self.deduction_input.setMaximum(999999)
  2521. self.deduction_input.setSpecialValueText("")
  2522. self.deduction_input.setValue(-1)
  2523. self.deduction_input.setMinimumWidth(0)
  2524. self.deduction_input.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
  2525. try:
  2526. self.deduction_input.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
  2527. except Exception:
  2528. pass
  2529. try:
  2530. self.deduction_input.setReadOnly(True)
  2531. except Exception:
  2532. pass
  2533. self.deduction_input.valueChanged.connect(self.calculate_net_weight)
  2534. deduction_layout.addWidget(deduction_label)
  2535. deduction_layout.addWidget(self.deduction_input, 1)
  2536. form_layout.addLayout(deduction_layout)
  2537. # 第九行:净重和本次量(一行文本展示)
  2538. weight_info_layout = QHBoxLayout()
  2539. weight_info_layout.setSpacing(10)
  2540. weight_info_label = QLabel("净重:")
  2541. weight_info_label.setFont(QFont("微软雅黑", 16))
  2542. weight_info_label.setMinimumWidth(60)
  2543. weight_info_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
  2544. self.net_weight_display = QLabel("0.000 t")
  2545. self.net_weight_display.setMinimumHeight(45)
  2546. self.net_weight_display.setFont(QFont("微软雅黑", 18, QFont.Bold))
  2547. self.net_weight_display.setStyleSheet("""
  2548. QLabel {
  2549. background-color: #1E40AF;
  2550. color: white;
  2551. padding: 6px 10px;
  2552. border: 2px solid #1D4ED8;
  2553. border-radius: 6px;
  2554. font-weight: bold;
  2555. min-width: 80px;
  2556. }
  2557. """)
  2558. self.net_weight_display.setAlignment(Qt.AlignCenter)
  2559. current_quantity_info_label = QLabel("本次计划量:")
  2560. current_quantity_info_label.setFont(QFont("微软雅黑", 16))
  2561. current_quantity_info_label.setMinimumWidth(70)
  2562. current_quantity_info_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
  2563. self.current_quantity_display = QLabel("0.000 t")
  2564. self.current_quantity_display.setMinimumHeight(45)
  2565. self.current_quantity_display.setFont(QFont("微软雅黑", 18, QFont.Bold))
  2566. self.current_quantity_display.setStyleSheet("""
  2567. QLabel {
  2568. background-color: #EA580C;
  2569. color: white;
  2570. padding: 6px 10px;
  2571. border: 2px solid #DC2626;
  2572. border-radius: 6px;
  2573. font-weight: bold;
  2574. min-width: 80px;
  2575. }
  2576. """)
  2577. self.current_quantity_display.setAlignment(Qt.AlignCenter)
  2578. weight_info_layout.addStretch()
  2579. weight_info_layout.addWidget(weight_info_label)
  2580. weight_info_layout.addWidget(self.net_weight_display)
  2581. weight_info_layout.addWidget(current_quantity_info_label)
  2582. weight_info_layout.addWidget(self.current_quantity_display)
  2583. weight_info_layout.addStretch()
  2584. form_layout.addLayout(weight_info_layout)
  2585. layout.addLayout(form_layout)
  2586. widget.setLayout(layout)
  2587. return widget
  2588. def refresh_dropdowns(self):
  2589. """刷新下拉列表"""
  2590. # 刷新货物名称
  2591. self.cargo_combo.clear()
  2592. self.cargo_combo.addItem("")
  2593. cargos = self.db.get_all_cargos()
  2594. for cargo in cargos:
  2595. self.cargo_combo.addItem(cargo['name'])
  2596. self.cargo_combo.setCurrentIndex(0)
  2597. # 刷新公司名称 - 隐藏供货单位和收货单位字段
  2598. # self.supplier_combo.clear()
  2599. # self.supplier_combo.addItem("")
  2600. # self.consignee_combo.clear()
  2601. # self.consignee_combo.addItem("")
  2602. # companies = self.db.get_all_companies()
  2603. # for company in companies:
  2604. # self.supplier_combo.addItem(company['name'])
  2605. # self.consignee_combo.addItem(company['name'])
  2606. # self.supplier_combo.setCurrentIndex(0)
  2607. # self.consignee_combo.setCurrentIndex(0)
  2608. def _prefill_from_inbound(self):
  2609. """从出入库单预填数据"""
  2610. # 如果已存在地磅单,加载地磅单数据
  2611. if self.existing_slip:
  2612. logger.info(f"加载已存在的地磅单数据,ID: {self.existing_slip.get('id')}")
  2613. logger.debug(f"地磅单数据: gross_weight_time={self.existing_slip.get('gross_weight_time')}, tare_weight_time={self.existing_slip.get('tare_weight_time')}")
  2614. self._load_slip_data(self.existing_slip)
  2615. return
  2616. # 否则从出入库单预填
  2617. self.vehicle_no_input.setText(self.inbound.get('vehicle_no', ''))
  2618. inbound_quantity_ton = self.inbound.get('quantity')
  2619. if inbound_quantity_ton is not None and inbound_quantity_ton > 0:
  2620. self.current_quantity_display.setText(f"{inbound_quantity_ton:.3f} t")
  2621. else:
  2622. self.current_quantity_display.setText("0.000 t")
  2623. # 隐藏字段,从出入库单获取数据用于保存(界面不显示)
  2624. self._hidden_plan_no = self.inbound.get('plan_no', '')
  2625. self._hidden_batch_no = self.inbound.get('batch_no', '')
  2626. # 业务类型
  2627. if self.inbound['business_type'] == '入库':
  2628. self.business_purchase_radio.setChecked(True)
  2629. elif self.inbound['business_type'] == '出库':
  2630. self.business_sale_radio.setChecked(True)
  2631. # 货物名称(产品)
  2632. product_name = self.inbound.get('product', '').strip()
  2633. if product_name:
  2634. index = self.cargo_combo.findText(product_name)
  2635. if index >= 0:
  2636. self.cargo_combo.setCurrentIndex(index)
  2637. # 供货单位和收货单位:根据业务类型设置 - 隐藏字段,跳过设置
  2638. # fixed_company_name = "安庆市山峡化工有限公司"
  2639. # partner_name = self.inbound.get('partner_company', '').strip()
  2640. #
  2641. # if self.inbound['business_type'] == '入库':
  2642. # # 入库:往来单位是供货单位,固定公司是收货单位
  2643. # index = self.supplier_combo.findText(partner_name)
  2644. # if index >= 0:
  2645. # self.supplier_combo.setCurrentIndex(index)
  2646. # index = self.consignee_combo.findText(fixed_company_name)
  2647. # if index >= 0:
  2648. # self.consignee_combo.setCurrentIndex(index)
  2649. # elif self.inbound['business_type'] == '出库':
  2650. # # 出库:固定公司是供货单位,往来单位是收货单位
  2651. # index = self.supplier_combo.findText(fixed_company_name)
  2652. # if index >= 0:
  2653. # self.supplier_combo.setCurrentIndex(index)
  2654. # index = self.consignee_combo.findText(partner_name)
  2655. # if index >= 0:
  2656. # self.consignee_combo.setCurrentIndex(index)
  2657. def _load_slip_data(self, slip: dict):
  2658. """加载地磅单数据到表单"""
  2659. self.vehicle_no_input.setText(slip.get('vehicle_no', ''))
  2660. # 隐藏字段,跳过设置
  2661. # self.plan_no_input.setText(slip.get('plan_no', ''))
  2662. # self.batch_no_input.setText(slip.get('batch_no', ''))
  2663. business_type = slip.get('business_type')
  2664. if business_type == '出库':
  2665. self.business_sale_radio.setChecked(True)
  2666. elif business_type == '入库':
  2667. self.business_purchase_radio.setChecked(True)
  2668. index = self.cargo_combo.findText(slip.get('cargo_name', ''))
  2669. if index >= 0:
  2670. self.cargo_combo.setCurrentIndex(index)
  2671. # 隐藏供货单位和收货单位字段,跳过设置
  2672. # index = self.supplier_combo.findText(slip.get('supplier', ''))
  2673. # if index >= 0:
  2674. # self.supplier_combo.setCurrentIndex(index)
  2675. #
  2676. # index = self.consignee_combo.findText(slip.get('consignee', ''))
  2677. # if index >= 0:
  2678. # self.consignee_combo.setCurrentIndex(index)
  2679. gross_weight = slip.get('gross_weight', 0)
  2680. if gross_weight > 0:
  2681. self.gross_weight_input.setValue(gross_weight)
  2682. else:
  2683. self.gross_weight_input.setValue(-1)
  2684. # 处理毛重时间
  2685. gross_time = slip.get('gross_weight_time', '')
  2686. if gross_time:
  2687. gross_time = str(gross_time).strip()
  2688. if gross_time:
  2689. gross_dt = QDateTime.fromString(gross_time, "yyyy-MM-dd HH:mm:ss")
  2690. if gross_dt.isValid():
  2691. QTimer.singleShot(10, lambda dt=gross_dt: self._set_time_with_display(self.gross_weight_time, dt))
  2692. else:
  2693. # 尝试其他格式
  2694. gross_dt = QDateTime.fromString(gross_time, "yyyy-MM-dd HH:mm")
  2695. if gross_dt.isValid():
  2696. QTimer.singleShot(10, lambda dt=gross_dt: self._set_time_with_display(self.gross_weight_time, dt))
  2697. else:
  2698. QTimer.singleShot(10, lambda: self._clear_time_display(self.gross_weight_time))
  2699. else:
  2700. QTimer.singleShot(10, lambda: self._clear_time_display(self.gross_weight_time))
  2701. else:
  2702. QTimer.singleShot(10, lambda: self._clear_time_display(self.gross_weight_time))
  2703. tare_weight = slip.get('tare_weight', 0)
  2704. if tare_weight > 0:
  2705. self.tare_weight_input.setValue(tare_weight)
  2706. else:
  2707. self.tare_weight_input.setValue(-1)
  2708. # 处理皮重时间
  2709. tare_time = slip.get('tare_weight_time', '')
  2710. if tare_time:
  2711. tare_time = str(tare_time).strip()
  2712. if tare_time:
  2713. tare_dt = QDateTime.fromString(tare_time, "yyyy-MM-dd HH:mm:ss")
  2714. if tare_dt.isValid():
  2715. QTimer.singleShot(11, lambda dt=tare_dt: self._set_time_with_display(self.tare_weight_time, dt))
  2716. else:
  2717. # 尝试其他格式
  2718. tare_dt = QDateTime.fromString(tare_time, "yyyy-MM-dd HH:mm")
  2719. if tare_dt.isValid():
  2720. QTimer.singleShot(11, lambda dt=tare_dt: self._set_time_with_display(self.tare_weight_time, dt))
  2721. else:
  2722. QTimer.singleShot(11, lambda: self._clear_time_display(self.tare_weight_time))
  2723. else:
  2724. QTimer.singleShot(11, lambda: self._clear_time_display(self.tare_weight_time))
  2725. else:
  2726. QTimer.singleShot(11, lambda: self._clear_time_display(self.tare_weight_time))
  2727. deduction_value = slip.get('deduction')
  2728. self.deduction_input.setValue(deduction_value if deduction_value is not None else -1)
  2729. # 隐藏字段,跳过设置
  2730. # planned_quantity = slip.get('planned_quantity')
  2731. # planned_quantity_tons = kg_to_tons(planned_quantity) if planned_quantity is not None else None
  2732. # self.planned_quantity_input.setValue(planned_quantity_tons if planned_quantity_tons is not None else -1)
  2733. # executed_quantity = slip.get('executed_quantity')
  2734. # executed_quantity_tons = kg_to_tons(executed_quantity) if executed_quantity is not None else None
  2735. # self.executed_quantity_input.setValue(executed_quantity_tons if executed_quantity_tons is not None else -1)
  2736. current_quantity = slip.get('current_quantity')
  2737. current_quantity_tons = kg_to_tons(current_quantity) if current_quantity is not None else None
  2738. if current_quantity_tons is not None:
  2739. self.current_quantity_display.setText(f"{current_quantity_tons:.3f} t")
  2740. else:
  2741. self.current_quantity_display.setText("0.000 t")
  2742. # 隐藏字段,跳过设置
  2743. # self.remarks_input.setPlainText(slip.get('remarks', ''))
  2744. self.calculate_net_weight()
  2745. def calculate_net_weight(self):
  2746. """计算净重"""
  2747. gross = self._get_weight_input_value(self.gross_weight_input) or 0
  2748. tare = self._get_weight_input_value(self.tare_weight_input) or 0
  2749. deduction = self._get_deduction_value()
  2750. net = gross - tare - deduction
  2751. net_tons = kg_to_tons(net)
  2752. if net_tons is None:
  2753. net_tons = 0
  2754. self.net_weight_display.setText(f"{net_tons:.3f} t")
  2755. def on_gross_weight_changed(self, value: float):
  2756. """毛重改变时自动更新时间"""
  2757. self.calculate_net_weight()
  2758. self._maybe_update_weight_time(value, self.gross_weight_time)
  2759. def on_tare_weight_changed(self, value: float):
  2760. """皮重改变时自动更新时间"""
  2761. self.calculate_net_weight()
  2762. self._maybe_update_weight_time(value, self.tare_weight_time)
  2763. def _maybe_update_weight_time(self, value: float, time_edit: EmptyDateTimeEdit):
  2764. """根据重量变化自动填充或清空时间"""
  2765. if self._is_clearing_form:
  2766. return
  2767. if value > 0:
  2768. self._set_time_to_now(time_edit)
  2769. elif value < 0:
  2770. self._clear_time_edit(time_edit)
  2771. def _set_time_to_now(self, time_edit: EmptyDateTimeEdit):
  2772. """将指定时间控件设置为当前时间"""
  2773. current_dt = QDateTime.currentDateTime()
  2774. time_edit.setDateTime(current_dt)
  2775. def _clear_time_edit(self, time_edit: EmptyDateTimeEdit):
  2776. """清空时间控件"""
  2777. time_edit.setDateTime(QDateTime())
  2778. def _set_time_with_display(self, time_edit: EmptyDateTimeEdit, dt: QDateTime):
  2779. """设置时间并更新显示"""
  2780. time_edit.setDateTime(dt)
  2781. self._update_time_display(time_edit, dt)
  2782. def _update_time_display(self, time_edit: EmptyDateTimeEdit, dt: QDateTime):
  2783. """更新时间控件的显示"""
  2784. if time_edit.lineEdit() and dt.isValid():
  2785. time_edit.lineEdit().setText(dt.toString("yyyy-MM-dd HH:mm:ss"))
  2786. def _clear_time_display(self, time_edit: EmptyDateTimeEdit):
  2787. """清空时间控件的显示"""
  2788. time_edit.setDateTime(QDateTime())
  2789. if time_edit.lineEdit():
  2790. time_edit.lineEdit().setText("")
  2791. def _get_weight_input_value(self, spinbox: EmptyDoubleSpinBox) -> Optional[float]:
  2792. """获取重量输入的实际值,未填则返回None"""
  2793. value = spinbox.value()
  2794. return value if value >= 0 else None
  2795. def _get_deduction_value(self) -> float:
  2796. """获取扣杂值,未填返回0"""
  2797. value = self.deduction_input.value()
  2798. return value if value >= 0 else 0
  2799. def _get_datetime_str(self, time_edit: EmptyDateTimeEdit) -> str:
  2800. """将时间控件转换为字符串"""
  2801. if time_edit.dateTime().isValid():
  2802. line_edit = time_edit.lineEdit()
  2803. if line_edit and line_edit.text().strip():
  2804. return time_edit.dateTime().toString("yyyy-MM-dd HH:mm:ss")
  2805. return ""
  2806. def validate_form(self) -> tuple:
  2807. """验证表单数据"""
  2808. if not self.vehicle_no_input.text().strip():
  2809. return False, "请填写车号"
  2810. if self.cargo_combo.currentIndex() <= 0 or not self.cargo_combo.currentText().strip():
  2811. return False, "请选择货物名称"
  2812. if not self.business_type_group.checkedButton():
  2813. return False, "请选择业务类型"
  2814. # 隐藏供货单位和收货单位字段,跳过验证
  2815. # if self.supplier_combo.currentIndex() <= 0 or not self.supplier_combo.currentText().strip():
  2816. # return False, "请选择供货单位"
  2817. #
  2818. # if self.consignee_combo.currentIndex() <= 0 or not self.consignee_combo.currentText().strip():
  2819. # return False, "请选择收货单位"
  2820. gross_value = self._get_weight_input_value(self.gross_weight_input)
  2821. tare_value = self._get_weight_input_value(self.tare_weight_input)
  2822. gross_time_text = self._get_datetime_str(self.gross_weight_time)
  2823. tare_time_text = self._get_datetime_str(self.tare_weight_time)
  2824. # 移除毛重和皮重必须大于0的校验,允许保存任意值
  2825. # if gross_value is not None and gross_value <= 0:
  2826. # return False, "毛重必须大于0"
  2827. # if tare_value is not None and tare_value <= 0:
  2828. # return False, "皮重必须大于0"
  2829. # 移除毛重、皮重、毛重时间、皮重时间之间的关联校验,允许独立删除
  2830. # if gross_value is not None and not gross_time_text:
  2831. # return False, "已填写毛重后必须填写毛重时间"
  2832. # if gross_time_text and gross_value is None:
  2833. # return False, "填写毛重时间前需要填写毛重"
  2834. #
  2835. # if tare_value is not None and not tare_time_text:
  2836. # return False, "已填写皮重后必须填写皮重时间"
  2837. # if tare_time_text and tare_value is None:
  2838. # return False, "填写皮重时间前需要填写皮重"
  2839. if gross_value is not None and tare_value is not None:
  2840. deduction = self._get_deduction_value()
  2841. net_weight = gross_value - tare_value - deduction
  2842. if net_weight <= 0:
  2843. return False, "净重必须大于0,请检查毛重、皮重和扣杂的数值"
  2844. return True, ""
  2845. def save_weighing_slip(self):
  2846. """保存地磅单"""
  2847. valid, error_msg = self.validate_form()
  2848. if not valid:
  2849. QMessageBox.warning(self, "验证失败", error_msg)
  2850. return
  2851. gross_value = self._get_weight_input_value(self.gross_weight_input)
  2852. tare_value = self._get_weight_input_value(self.tare_weight_input)
  2853. deduction_value = self._get_deduction_value()
  2854. gross_weight = gross_value if gross_value is not None else 0
  2855. tare_weight = tare_value if tare_value is not None else 0
  2856. # 隐藏字段,使用默认值
  2857. # planned_quantity_value = self.planned_quantity_input.value()
  2858. # planned_quantity_tons = planned_quantity_value if planned_quantity_value >= 0 else None
  2859. planned_quantity = None # tons_to_kg(planned_quantity_tons) if planned_quantity_tons is not None else None
  2860. # executed_quantity_value = self.executed_quantity_input.value()
  2861. # executed_quantity_tons = executed_quantity_value if executed_quantity_value >= 0 else None
  2862. executed_quantity = None # tons_to_kg(executed_quantity_tons) if executed_quantity_tons is not None else None
  2863. # 从标签文本中解析本次量数值
  2864. current_quantity_text = self.current_quantity_display.text().replace(' t', '')
  2865. try:
  2866. current_quantity_tons = float(current_quantity_text) if current_quantity_text != '0.000' else None
  2867. except ValueError:
  2868. current_quantity_tons = None
  2869. current_quantity = tons_to_kg(current_quantity_tons) if current_quantity_tons is not None else None
  2870. # 对于隐藏的字段,如果是编辑现有地磅单,保持原有值;如果是新增,从出入库单获取值
  2871. if self.existing_slip:
  2872. # 编辑模式:保持数据库中的现有值
  2873. plan_no_value = self.existing_slip.get('plan_no', '')
  2874. batch_no_value = self.existing_slip.get('batch_no', '')
  2875. supplier_value = self.existing_slip.get('supplier', '')
  2876. consignee_value = self.existing_slip.get('consignee', '')
  2877. remarks_value = self.existing_slip.get('remarks', '')
  2878. else:
  2879. # 新增模式:从出入库单获取值
  2880. plan_no_value = getattr(self, '_hidden_plan_no', '')
  2881. batch_no_value = getattr(self, '_hidden_batch_no', '')
  2882. # 根据业务类型设置供货单位和收货单位
  2883. if self.inbound['business_type'] == '入库':
  2884. supplier_value = self.inbound.get('partner_company', '')
  2885. consignee_value = '安庆市山峡化工有限公司'
  2886. else: # 出库
  2887. supplier_value = '安庆市山峡化工有限公司'
  2888. consignee_value = self.inbound.get('partner_company', '')
  2889. remarks_value = ''
  2890. data = {
  2891. 'vehicle_no': self.vehicle_no_input.text().strip(),
  2892. 'plan_no': plan_no_value,
  2893. 'cargo_name': self.cargo_combo.currentText(),
  2894. 'business_type': self.business_type_group.checkedButton().text(),
  2895. 'batch_no': batch_no_value,
  2896. 'supplier': supplier_value,
  2897. 'consignee': consignee_value,
  2898. 'gross_weight': gross_weight,
  2899. 'gross_weight_time': self._get_datetime_str(self.gross_weight_time),
  2900. 'tare_weight': tare_weight,
  2901. 'tare_weight_time': self._get_datetime_str(self.tare_weight_time),
  2902. 'deduction': deduction_value,
  2903. 'planned_quantity': planned_quantity,
  2904. 'executed_quantity': executed_quantity,
  2905. 'current_quantity': current_quantity,
  2906. 'remarks': remarks_value,
  2907. 'inbound_outbound_id': self.inbound['id'],
  2908. 'weighing_point': '山峡地磅'
  2909. }
  2910. try:
  2911. if self.editing_slip_id:
  2912. if self.db.update_weighing_slip(self.editing_slip_id, data):
  2913. QMessageBox.information(self, "成功", "地磅单更新成功!")
  2914. # 毛重和皮重都有时,保存成功后自动打印
  2915. if gross_weight > 0 and tare_weight > 0:
  2916. try:
  2917. self.printer.direct_print_weighing_slip(
  2918. self.db.get_weighing_slip_by_id(self.editing_slip_id),
  2919. copies=1
  2920. )
  2921. QMessageBox.information(self, "成功", "地磅单已自动打印!")
  2922. except Exception as e:
  2923. QMessageBox.warning(self, "打印失败", f"地磅单更新成功,但自动打印失败:{str(e)}")
  2924. self.accept()
  2925. else:
  2926. QMessageBox.warning(self, "错误", "更新失败")
  2927. else:
  2928. slip_id = self.db.insert_weighing_slip(data)
  2929. QMessageBox.information(self, "成功", "地磅单保存成功!")
  2930. # 如果皮重和毛重都大于0,自动打印地磅单
  2931. if gross_weight > 0 and tare_weight > 0:
  2932. try:
  2933. self.printer.direct_print_weighing_slip(
  2934. self.db.get_weighing_slip_by_id(slip_id),
  2935. copies=1
  2936. )
  2937. QMessageBox.information(self, "成功", "地磅单已自动打印!")
  2938. except Exception as e:
  2939. QMessageBox.warning(self, "打印失败", f"地磅单保存成功,但自动打印失败:{str(e)}")
  2940. self.accept()
  2941. except Exception as e:
  2942. QMessageBox.critical(self, "错误", f"保存失败:{str(e)}")
  2943. def _dialog_print_weighing_slip(self):
  2944. """打印出入库单关联的地磅单(与列表中的打印功能一致:打开打印预览)"""
  2945. slip = self.db.get_weighing_slip_by_inbound_id(self.inbound['id'], include_voided=False)
  2946. if not slip:
  2947. QMessageBox.warning(self, "提示", "该出入库单尚未生成地磅单,无法打印。")
  2948. return
  2949. try:
  2950. self.printer.preview_weighing_slip(slip, copies=1)
  2951. except Exception as e:
  2952. QMessageBox.critical(self, "错误", f"打印失败:{str(e)}")
  2953. def clear_form(self):
  2954. """清空表单"""
  2955. self._is_clearing_form = True
  2956. try:
  2957. self.vehicle_no_input.clear()
  2958. # 隐藏字段,跳过清空
  2959. # self.plan_no_input.clear()
  2960. if self.cargo_combo.count() > 0:
  2961. self.cargo_combo.setCurrentIndex(0)
  2962. # 隐藏供货单位和收货单位字段,跳过清空
  2963. # if self.supplier_combo.count() > 0:
  2964. # self.supplier_combo.setCurrentIndex(0)
  2965. # if self.consignee_combo.count() > 0:
  2966. # self.consignee_combo.setCurrentIndex(0)
  2967. if self.business_type_group.checkedButton():
  2968. self.business_type_group.setExclusive(False)
  2969. self.business_type_group.checkedButton().setChecked(False)
  2970. self.business_type_group.setExclusive(True)
  2971. # 隐藏字段,跳过清空
  2972. # self.batch_no_input.clear()
  2973. self.gross_weight_input.setValue(-1)
  2974. self.gross_weight_time.setDateTime(QDateTime())
  2975. if self.gross_weight_time.lineEdit():
  2976. self.gross_weight_time.lineEdit().setText("")
  2977. QTimer.singleShot(0, lambda: self.gross_weight_time.lineEdit().setText("") if self.gross_weight_time.lineEdit() else None)
  2978. self.tare_weight_input.setValue(-1)
  2979. self.tare_weight_time.setDateTime(QDateTime())
  2980. if self.tare_weight_time.lineEdit():
  2981. self.tare_weight_time.lineEdit().setText("")
  2982. QTimer.singleShot(0, lambda: self.tare_weight_time.lineEdit().setText("") if self.tare_weight_time.lineEdit() else None)
  2983. self.deduction_input.setValue(-1)
  2984. self.net_weight_display.setText("0.000 t")
  2985. # 隐藏字段,跳过清空
  2986. # self.planned_quantity_input.setValue(-1)
  2987. # self.executed_quantity_input.setValue(-1)
  2988. self.current_quantity_display.setText("0.000 t")
  2989. # self.remarks_input.clear()
  2990. finally:
  2991. self._is_clearing_form = False
  2992. def _attach_serial_reader(self):
  2993. """附加到串口读取器以接收实时重量更新"""
  2994. sr = None
  2995. try:
  2996. if getattr(self, "main_window", None) and getattr(self.main_window, "yaohua_weighing_tab", None):
  2997. sr = self.main_window.yaohua_weighing_tab.serial_reader
  2998. except Exception:
  2999. sr = None
  3000. if sr is None:
  3001. # 尝试根据配置创建并启动
  3002. cfg = self._load_scale_config()
  3003. if not cfg:
  3004. return
  3005. parity_map = {'无校验': 'N', '偶校验': 'E', '奇校验': 'O'}
  3006. sr = get_reader_for_port(
  3007. cfg.get("port"),
  3008. baudrate=int(cfg.get("baudrate", 9600)),
  3009. bytesize=int(cfg.get("bytesize", 8)),
  3010. parity=parity_map.get(cfg.get("parity", "无校验"), 'N'),
  3011. stopbits=int(cfg.get("stopbits", 1))
  3012. )
  3013. # 将其设置到主窗口的yaohua tab,供其他界面复用
  3014. try:
  3015. if getattr(self, "main_window", None) and getattr(self.main_window, "yaohua_weighing_tab", None):
  3016. self.main_window.yaohua_weighing_tab.serial_reader = sr
  3017. except Exception:
  3018. pass
  3019. # 连接信号
  3020. try:
  3021. # 若已连接则直接订阅信号,否则尝试连接后订阅
  3022. if not sr.is_connected():
  3023. try:
  3024. sr.connect()
  3025. except Exception:
  3026. pass
  3027. # 启动后台读取以保证持续接收
  3028. if not getattr(sr, "is_running", False):
  3029. try:
  3030. sr.start_reading()
  3031. except Exception:
  3032. pass
  3033. # 断开旧连接(如果有)
  3034. if getattr(self, "_serial_reader", None) is not None and getattr(self, "_serial_reader", "dummy") != sr:
  3035. try:
  3036. old = self._serial_reader
  3037. old.weight_received.disconnect(self._on_realtime_weight)
  3038. except Exception:
  3039. pass
  3040. self._serial_reader = sr
  3041. # 订阅实时重量更新
  3042. sr.weight_received.connect(self._on_realtime_weight)
  3043. # 订阅连接状态改变以更新显示
  3044. try:
  3045. sr.connection_status_changed.connect(self._on_connection_status_changed)
  3046. except Exception:
  3047. pass
  3048. except Exception:
  3049. logger.exception("附加串口读取器失败")
  3050. def _on_realtime_weight(self, weight: float):
  3051. """来自串口读取器的实时重量更新(主线程)"""
  3052. try:
  3053. self.instrument_weight = weight
  3054. # 若为None或NaN则显示未连接
  3055. if weight is None or (isinstance(weight, float) and weight != weight):
  3056. self.instrument_weight_label.setText("—")
  3057. else:
  3058. self.instrument_weight_label.setText(f"{weight:.2f} kg")
  3059. except Exception:
  3060. logger.exception("处理实时重量更新失败")
  3061. def _on_connection_status_changed(self, connected: bool):
  3062. """串口连接状态改变"""
  3063. try:
  3064. if not connected:
  3065. self.instrument_weight_label.setText("未连接")
  3066. self.instrument_weight = None
  3067. except Exception:
  3068. logger.exception("处理连接状态改变失败")
  3069. def _start_read_from_instrument(self, target: str):
  3070. """在后台线程读取一次仪表数据,target='gross'|'tare'"""
  3071. # 确保只有一个并发读取
  3072. if getattr(self, "_reading_thread", None) and self._reading_thread.is_alive():
  3073. QMessageBox.information(self, "提示", "正在读取,请稍候...")
  3074. return
  3075. # 如果已有实时读取的最新值,优先使用该值,避免再次同步读取超时问题
  3076. try:
  3077. if getattr(self, "instrument_weight", None) is not None:
  3078. # 直接触发槽函数,主线程安全
  3079. self.instrument_weight_received.emit(self.instrument_weight, target)
  3080. return
  3081. except Exception:
  3082. pass
  3083. # 尝试从主窗口的耀华tab复用串口读取器
  3084. serial_reader = None
  3085. # 优先复用主窗口 yaohua_weighing_tab 的 serial_reader(更可靠)
  3086. try:
  3087. if getattr(self, "main_window", None) and getattr(self.main_window, "yaohua_weighing_tab", None):
  3088. serial_reader = self.main_window.yaohua_weighing_tab.serial_reader
  3089. except Exception:
  3090. serial_reader = None
  3091. # 其次尝试通过父控件查找(兼容不同创建方式)
  3092. if serial_reader is None:
  3093. try:
  3094. parent_widget = self.parent() # 通常是 InboundOutboundTab
  3095. if parent_widget and hasattr(parent_widget, "main_window") and getattr(parent_widget.main_window, "yaohua_weighing_tab", None):
  3096. serial_reader = parent_widget.main_window.yaohua_weighing_tab.serial_reader
  3097. except Exception:
  3098. serial_reader = None
  3099. # 如果没有复用到读取器,尝试新建一个(仅在主界面无可复用读取器时创建)
  3100. if serial_reader is None:
  3101. # 如果主窗口存在且 yaohua tab 已创建但尚无 serial_reader,则根据配置创建单例读取器并附加到主窗口以供复用
  3102. try:
  3103. cfg = self._load_scale_config()
  3104. if cfg and cfg.get("port"):
  3105. parity_map = {'无校验': 'N', '偶校验': 'E', '奇校验': 'O'}
  3106. serial_reader = get_reader_for_port(
  3107. cfg.get("port"),
  3108. baudrate=int(cfg.get("baudrate", 9600)),
  3109. bytesize=int(cfg.get("bytesize", 8)),
  3110. parity=parity_map.get(cfg.get("parity", "无校验"), 'N'),
  3111. stopbits=int(cfg.get("stopbits", 1))
  3112. )
  3113. else:
  3114. # 创建未注册的临时实例
  3115. serial_reader = get_reader_for_port('')
  3116. if getattr(self, "main_window", None) and getattr(self.main_window, "yaohua_weighing_tab", None):
  3117. if getattr(self.main_window.yaohua_weighing_tab, "serial_reader", None) is None:
  3118. self.main_window.yaohua_weighing_tab.serial_reader = serial_reader
  3119. else:
  3120. serial_reader = self.main_window.yaohua_weighing_tab.serial_reader
  3121. except Exception:
  3122. serial_reader = None
  3123. self._serial_reader = serial_reader
  3124. self._pending_read_target = target
  3125. # 在后台线程执行同步读取,避免阻塞UI
  3126. def _worker():
  3127. try:
  3128. weight = None
  3129. # 优先使用已经连接的读取器
  3130. if getattr(serial_reader, "is_connected", lambda: False)() and getattr(serial_reader, "is_running", False):
  3131. weight = serial_reader.read_weight_once(timeout=3.0)
  3132. else:
  3133. # 尝试连接并读取一次
  3134. try:
  3135. serial_reader.connect()
  3136. except Exception:
  3137. pass
  3138. weight = serial_reader.read_weight_once(timeout=3.0)
  3139. if weight is not None:
  3140. # 通过 Qt 信号回到主线程
  3141. self.instrument_weight_received.emit(weight, target)
  3142. else:
  3143. # 发出一个特殊值为None通过信号用以提示读取失败
  3144. self.instrument_weight_received.emit(float("nan"), target)
  3145. except Exception as e:
  3146. # 更详细记录异常,方便排查端口被占用等问题
  3147. logger.exception("读取仪表失败")
  3148. try:
  3149. self.instrument_weight_received.emit(float("nan"), target)
  3150. except Exception:
  3151. pass
  3152. import threading
  3153. self._reading_thread = threading.Thread(target=_worker, daemon=True)
  3154. self._reading_thread.start()
  3155. def _on_instrument_weight_received(self, weight: float, target: str):
  3156. """收到仪表重量后的槽函数(在主线程中执行)"""
  3157. # weight为nan表示读取失败
  3158. if weight != weight: # NaN 检测
  3159. QMessageBox.warning(self, "读取失败", "未能从仪表读取到有效数据,请检查连接和参数。")
  3160. return
  3161. # 显示到界面
  3162. self.instrument_weight = weight
  3163. try:
  3164. self.instrument_weight_label.setText(".2f")
  3165. except Exception:
  3166. self.instrument_weight_label.setText(str(weight))
  3167. # 根据目标将值填入对应控件并更新时间
  3168. now = QDateTime.currentDateTime()
  3169. if target == 'gross':
  3170. # 仪表读到的通常是kg单位,UI中的输入控件也使用kg
  3171. try:
  3172. self.gross_weight_input.setValue(float(f"{weight:.2f}"))
  3173. self._set_time_to_now(self.gross_weight_time)
  3174. except Exception:
  3175. pass
  3176. elif target == 'tare':
  3177. try:
  3178. self.tare_weight_input.setValue(float(f"{weight:.2f}"))
  3179. self._set_time_to_now(self.tare_weight_time)
  3180. except Exception:
  3181. pass
  3182. def _load_scale_config(self) -> Optional[Dict]:
  3183. """从 scale_config.json 加载地磅配置"""
  3184. try:
  3185. import os
  3186. from database import get_base_path
  3187. cfg_path = os.path.join(get_base_path(), "scale_config.json")
  3188. if not os.path.exists(cfg_path):
  3189. return None
  3190. with open(cfg_path, "r", encoding="utf-8") as f:
  3191. cfg = json.load(f)
  3192. return cfg
  3193. except Exception as e:
  3194. logger.exception("加载地磅配置失败")
  3195. return None