| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617 |
- """
- 出入库管理Tab页面
- """
- from PyQt5.QtWidgets import (
- QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QComboBox,
- QRadioButton, QButtonGroup, QDateEdit, QTextEdit, QPushButton,
- QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox, QDialog,
- QFormLayout, QSplitter, QGroupBox, QDoubleSpinBox, QGridLayout,
- QFileDialog, QSizePolicy, QApplication, QCheckBox, QScrollArea, QFrame
- )
- from PyQt5.QtCore import Qt, QDate, QDateTime, QTimer, pyqtSignal, QEvent
- from PyQt5.QtGui import QFont, QKeySequence, QBrush, QColor, QMouseEvent, QShowEvent
- from datetime import datetime
- from typing import Optional, Dict
- import logging
- import time
- import json
- from database import Database
- from .weighing_tab import EmptyDoubleSpinBox, EmptyDateTimeEdit, kg_to_tons, tons_to_kg
- from .button_styles import apply_button_style
- from utils.printer import Printer
- from utils.serial_reader import SerialReader, list_available_ports, get_reader_for_port
- import pandas as pd
- import sip
- logger = logging.getLogger(__name__)
- startup_logger = logging.getLogger('startup')
- class MultiSelectDropdown(QPushButton):
- """多选下拉框组件"""
- selection_changed = pyqtSignal() # 选择改变信号
- def __init__(self, options=None, default_selected=None, parent=None):
- super().__init__(parent)
- self.options = options or []
- self.selected_items = set(default_selected or [])
- self._setup_ui()
- def _setup_ui(self):
- """设置UI"""
- self.setMinimumWidth(150)
- self.setMinimumHeight(30)
- self.setFont(QFont("微软雅黑", 13))
- self.setStyleSheet("""
- QPushButton {
- text-align: left;
- padding-left: 8px;
- border: 1px solid #ccc;
- border-radius: 3px;
- background-color: white;
- }
- QPushButton:hover {
- border-color: #0078d4;
- }
- QPushButton:pressed {
- background-color: #f3f2f1;
- }
- """)
- self._update_display_text()
- # 创建菜单
- from PyQt5.QtWidgets import QMenu, QAction
- self.menu = QMenu(self)
- self.setMenu(self.menu)
- # 添加选项
- for option in self.options:
- action = QAction(option, self.menu, checkable=True)
- action.setChecked(option in self.selected_items)
- action.triggered.connect(lambda checked, opt=option: self._on_option_toggled(opt, checked))
- self.menu.addAction(action)
- def _on_option_toggled(self, option, checked):
- """选项切换处理"""
- if option == "全部":
- # 选择"全部"时,选择所有选项
- if checked:
- self.selected_items = set(self.options)
- else:
- # 取消选择"全部"时,取消选择所有选项
- self.selected_items.clear()
- else:
- # 选择具体选项时
- if checked:
- self.selected_items.add(option)
- # 如果选择了所有非"全部"选项,自动选择"全部"
- non_all_options = [opt for opt in self.options if opt != "全部"]
- if all(opt in self.selected_items for opt in non_all_options):
- self.selected_items.add("全部")
- else:
- self.selected_items.discard(option)
- # 如果取消选择了某个选项,同时取消选择"全部"
- if "全部" in self.selected_items:
- self.selected_items.discard("全部")
- # 更新菜单项的选中状态
- for action in self.menu.actions():
- action_opt = action.text()
- action.setChecked(action_opt in self.selected_items)
- self._update_display_text()
- self.selection_changed.emit()
- def _update_display_text(self):
- """更新显示文本"""
- if not self.selected_items:
- self.setText("请选择...")
- elif len(self.selected_items) == len(self.options):
- self.setText("全部")
- else:
- selected_list = sorted(self.selected_items)
- if len(selected_list) <= 2:
- self.setText("、".join(selected_list))
- else:
- self.setText(f"{selected_list[0]}等{len(selected_list)}项")
- def get_selected_items(self):
- """获取选中的项目"""
- return self.selected_items.copy()
- def set_selected_items(self, items):
- """设置选中的项目"""
- self.selected_items = set(items)
- # 更新菜单项的选中状态
- for action in self.menu.actions():
- option = action.text()
- action.setChecked(option in self.selected_items)
- self._update_display_text()
- class EmptyDateEdit(QDateEdit):
- """自定义QDateEdit,支持显示为空白"""
- def __init__(self, parent=None):
- super().__init__(parent)
- self._is_empty = True
- # 使用当前日期作为内部日期,这样日历弹窗打开时会显示当前月
- # 但lineEdit会显示为空,避免当天日期无法选择的问题
- self._placeholder_date = QDate.currentDate()
- self._suppress_signal_sync = False
- self._calendar_was_opened = False # 跟踪日历弹窗是否被打开过
- self._apply_placeholder_date()
- self._sync_line_edit()
- self.dateChanged.connect(self._handle_user_date_changed)
- def _apply_placeholder_date(self):
- # 使用当前日期作为占位符,这样日历弹窗打开时会显示当前月
- # 但用户仍然可以选择当天日期,因为日期会从当前日期变为当前日期
- # 我们在_handle_user_date_changed中处理这种情况
- self._placeholder_date = QDate.currentDate()
- self._suppress_signal_sync = True
- try:
- super().setDate(self._placeholder_date)
- finally:
- self._suppress_signal_sync = False
- def _sync_line_edit(self):
- line_edit = self.lineEdit()
- if not line_edit:
- return
- if self._is_empty:
- line_edit.clear()
- line_edit.setPlaceholderText("请选择日期")
- else:
- line_edit.setPlaceholderText("")
- line_edit.setText(super().text())
- def setDate(self, date: QDate):
- if not date.isValid():
- self._is_empty = True
- self._apply_placeholder_date()
- self._sync_line_edit()
- return
- self._is_empty = False
- self._suppress_signal_sync = True
- try:
- super().setDate(date)
- finally:
- self._suppress_signal_sync = False
- self._sync_line_edit()
- def date(self) -> QDate:
- if self._is_empty:
- return QDate()
- return super().date()
- def clear(self):
- self.setDate(QDate())
- def is_empty(self) -> bool:
- return self._is_empty
- def textFromDateTime(self, date_time: QDateTime) -> str:
- if self._is_empty:
- return ""
- return super().textFromDateTime(date_time)
- def _handle_user_date_changed(self, date: QDate):
- if self._suppress_signal_sync:
- return
- if not date.isValid():
- return
- # 如果当前是空状态,用户选择了日期(包括当前日期),更新状态
- if self._is_empty:
- # 无论选择什么日期(包括当前日期),都认为用户已选择日期
- # 因为用户可能点击了日历中的日期,即使日期没有变化
- self._is_empty = False
- self._sync_line_edit()
- else:
- # 如果已经有日期,正常同步显示
- self._sync_line_edit()
-
- def mousePressEvent(self, event):
- """重写鼠标点击事件,跟踪日历弹窗是否被打开"""
- # 检查是否点击了日期按钮
- if event.button() == Qt.LeftButton:
- button_width = 25
- widget_width = self.width()
- is_clicking_button = event.x() >= widget_width - button_width
-
- if is_clicking_button:
- # 标记日历弹窗将被打开
- self._calendar_was_opened = True
-
- # 正常处理事件,由于占位符日期已经是当前日期,日历弹窗会显示当前月
- super().mousePressEvent(event)
-
- def focusOutEvent(self, event):
- """重写失去焦点事件,在失去焦点时检查用户是否选择了日期"""
- # 检查用户是否在日历中点击了日期
- current_display_date = super().date()
- current_date = QDate.currentDate()
-
- if self._is_empty:
- # 如果日历弹窗被打开过,且日期是当前日期
- # 说明用户可能点击了当前日期(即使dateChanged信号没有触发)
- if self._calendar_was_opened and current_display_date == current_date:
- # 用户选择了当前日期,更新状态
- self._is_empty = False
- self._sync_line_edit()
- else:
- # 更新占位符日期为当前日期,确保下次打开时显示当前月
- if self._placeholder_date != current_date:
- self._placeholder_date = current_date
- self._apply_placeholder_date()
- else:
- # 如果已经不是空状态,确保lineEdit正确显示
- self._sync_line_edit()
-
- # 重置标志
- self._calendar_was_opened = False
- super().focusOutEvent(event)
- class InboundOutboundTab(QWidget):
- """出入库管理Tab"""
-
- def __init__(self, db: Database, main_window=None, current_user: Optional[Dict] = None):
- tab_start = time.time()
- super().__init__()
- self.db = db
- self.main_window = main_window
- self.current_user = current_user or {}
- self._is_admin = self.current_user.get('role') == 'admin'
- self.current_plan_id: Optional[int] = None
- self.editing_inbound_id: Optional[int] = None
- self.search_keyword: str = ""
- # 列表筛选选项(保留供 WeighingSlipDialog 等内部逻辑引用)
- self.show_pending_inbound: bool = True
- self.show_pending_outbound: bool = True
- self.show_recent_completed: bool = True
- self.show_all_completed: bool = False
- self.show_today_only: bool = True
-
- ui_start = time.time()
- self.init_ui()
- startup_logger.info(f" 界面初始化 (耗时: {time.time() - ui_start:.3f}秒)")
- @staticmethod
- def _is_completed_status(status: str) -> bool:
- """判断出入库状态是否为已完成"""
- if not status:
- return False
- status = status.strip()
- # 判断是否为已完成状态:已入库、已出库,或其他以"已"开头的状态
- return status.startswith('已')
-
- def init_ui(self):
- """初始化界面:仅保留出入库单ID输入框与检索按钮"""
- layout = QVBoxLayout()
- layout.setSpacing(16)
- layout.setContentsMargins(20, 20, 20, 20)
- # 标题
- title = QLabel("出入库管理")
- title.setFont(QFont("微软雅黑", 18, QFont.Bold))
- layout.addWidget(title)
- # 水平布局:出入库单ID 输入框 + 检索按钮(左右居中)
- row = QHBoxLayout()
- row.setSpacing(12)
- id_label = QLabel("出入库单ID:")
- id_label.setFont(QFont("微软雅黑", 14))
- self.inbound_id_input = QLineEdit()
- self.inbound_id_input.setPlaceholderText("请输入出入库单ID")
- self.inbound_id_input.setFont(QFont("微软雅黑", 14))
- self.inbound_id_input.setMinimumHeight(40)
- self.inbound_id_input.setMinimumWidth(440) # 宽度为原来的两倍(220*2)
- self.search_btn = QPushButton("检索")
- self.search_btn.setFont(QFont("微软雅黑", 14))
- self.search_btn.setMinimumHeight(40)
- self.search_btn.setMinimumWidth(100)
- apply_button_style(self.search_btn, 'blue')
- self.search_btn.clicked.connect(self.on_search_by_inbound_id)
- # 扫码枪输入后通常会发送 Enter,按回车自动触发检索
- self.inbound_id_input.returnPressed.connect(self.on_search_by_inbound_id)
- row.addStretch(1) # 左侧弹性空间,使内容居中
- row.addWidget(id_label)
- row.addWidget(self.inbound_id_input)
- row.addWidget(self.search_btn)
- row.addStretch(1) # 右侧弹性空间,使内容居中
- layout.addLayout(row)
- # 当天出入库单卡片区域:标题 + 刷新按钮
- today_row = QHBoxLayout()
- today_label = QLabel("当天出入库单")
- today_label.setFont(QFont("微软雅黑", 14, QFont.Bold))
- today_row.addWidget(today_label)
- today_row.addSpacing(16)
- self.today_refresh_btn = QPushButton("刷新")
- self.today_refresh_btn.setFont(QFont("微软雅黑", 12))
- self.today_refresh_btn.setMinimumHeight(32)
- self.today_refresh_btn.setMinimumWidth(80)
- apply_button_style(self.today_refresh_btn, 'normal')
- self.today_refresh_btn.clicked.connect(self.refresh_list)
- today_row.addWidget(self.today_refresh_btn)
- today_row.addStretch(1)
- layout.addLayout(today_row)
- # 为使用 _refresh_card_view,需存在 table 与 card 相关控件(table 不加入布局,仅占位)
- self.view_mode = "card"
- self.card_columns = 5
- self._card_widgets = []
- self.table = QTableWidget()
- self.table.setColumnCount(14)
- self.table.setHorizontalHeaderLabels([
- "计划号", "批次号", "日期", "往来单位", "业务类型",
- "产品", "车牌号", "本次量(t)", "净重(t)", "毛重(t)",
- "皮重(t)", "扣杂(t)", "状态", "操作"
- ])
- self.table.setParent(self)
- self.table.setVisible(False)
- self.card_scroll_area = QScrollArea()
- self.card_scroll_area.setWidgetResizable(True)
- self.card_scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
- self.card_container = QWidget()
- self.card_layout = QGridLayout()
- self.card_layout.setContentsMargins(4, 4, 4, 4)
- self.card_layout.setHorizontalSpacing(4)
- self.card_layout.setVerticalSpacing(10)
- self.card_container.setLayout(self.card_layout)
- self.card_scroll_area.setWidget(self.card_container)
- layout.addWidget(self.card_scroll_area)
- self.setLayout(layout)
- # 每10秒尝试将焦点拉回「出入库单ID」输入框,便于扫码枪输入(仅在本 Tab 可见且无弹窗时执行)
- self._focus_timer = QTimer(self)
- self._focus_timer.timeout.connect(self._try_focus_inbound_id_input)
- self._focus_timer.start(10000)
- # 初始加载当天出入库单卡片
- QTimer.singleShot(0, self.refresh_today_cards)
- def _try_focus_inbound_id_input(self):
- """定时尝试将焦点设回出入库单ID输入框:仅当本 Tab 可见且无模态弹窗时执行,避免打断用户操作。"""
- if not self.isVisible():
- return
- if QApplication.activeModalWidget() is not None:
- return
- if getattr(self, "inbound_id_input", None):
- self.inbound_id_input.setFocus()
- def showEvent(self, event: QShowEvent):
- """Tab 显示时自动聚焦到出入库单ID输入框(具体聚焦与刷新在下方 showEvent 中统一处理)"""
- super().showEvent(event)
- def _clear_inbound_id_after_search(self):
- """检索后清空出入库单ID输入框"""
- if getattr(self, "inbound_id_input", None):
- self.inbound_id_input.clear()
- def refresh_today_cards(self):
- """加载并展示当天出入库单卡片(与旧版卡片内容、样式、按钮及功能一致)"""
- if not getattr(self, "card_layout", None):
- return
- today_str = datetime.now().strftime("%Y-%m-%d")
- inbounds = self.db.get_inbound_outbound_by_date(today_str)
- # 无当天数据时显示占位提示
- if not inbounds:
- while self.card_layout.count():
- item = self.card_layout.takeAt(0)
- w = item.widget()
- if w is not None:
- w.deleteLater()
- self._card_widgets = []
- empty_label = QLabel("今日暂无出入库单")
- empty_label.setFont(QFont("微软雅黑", 14))
- empty_label.setStyleSheet("color: #666;")
- empty_label.setAlignment(Qt.AlignCenter)
- self.card_layout.addWidget(empty_label, 0, 0)
- if getattr(self, "card_scroll_area", None) is not None:
- self.card_scroll_area.setVisible(True)
- return
- inbound_ids = [i.get("id") for i in inbounds if i.get("id")]
- slip_summary_map = self.db.get_weighing_slip_summary_by_inbound_ids(inbound_ids) if inbound_ids else {}
- def get_sort_key(r):
- date_str = str(r.get("date", ""))
- try:
- date_obj = datetime.strptime(date_str, "%Y-%m-%d")
- date_sort_key = -date_obj.timestamp()
- except (ValueError, TypeError):
- date_sort_key = float("inf")
- status = str(r.get("status", "")).strip()
- if status == "待入库":
- status_priority = 1
- elif status == "待出库":
- status_priority = 2
- elif status.startswith("已"):
- status_priority = 3
- else:
- status_priority = 4
- slip_summary = slip_summary_map.get(r.get("id")) if r.get("id") else None
- gross_weight_time_str = slip_summary.get("gross_weight_time", "") if slip_summary else ""
- try:
- if gross_weight_time_str:
- gross_time_obj = datetime.strptime(gross_weight_time_str, "%Y-%m-%d %H:%M:%S")
- gross_time_sort_key = -gross_time_obj.timestamp()
- else:
- gross_time_sort_key = float("inf")
- except (ValueError, TypeError):
- gross_time_sort_key = float("inf")
- return (date_sort_key, status_priority, gross_time_sort_key)
- inbounds.sort(key=get_sort_key)
- self._current_inbounds = inbounds
- self._slip_summary_map = slip_summary_map
- self._refresh_card_view()
- def _show_search_message(self, icon: QMessageBox.Icon, title: str, text: str):
- """
- 出入库单管理-检索相关提示框:统一设置为加大加粗字体显示
- """
- box = QMessageBox(self)
- box.setIcon(icon)
- box.setWindowTitle(title)
- box.setText(text)
- box.setFont(QFont("微软雅黑", 18, QFont.Bold))
- box.exec_()
- def on_search_by_inbound_id(self):
- """
- 根据出入库单ID检索:
- - ID不存在 → 提示异常(加大加粗),并显示出入库单ID
- - ID存在且日期为以前:有地磅单则弹窗(读毛重/读皮重不可操作),无地磅单则提示异常
- - ID存在且日期为未来 → 提示异常
- - ID存在且当天:该车牌当天有未完成的地磅单(且非本单)则提示异常,否则弹窗
- 未完成地磅单:有毛重没有皮重,或有皮重没有毛重。
- 所有异常信息均加大加粗并显示检索的出入库单ID。检索成功后清空输入框。
- """
- raw = (self.inbound_id_input.text() or "").strip()
- display_id = raw if raw else "(未输入)"
- if not raw:
- self._show_search_message(
- QMessageBox.Warning,
- "提示",
- f"请输入出入库单ID。\n\n当前输入的出入库单ID:{display_id}",
- )
- return
- try:
- inbound_id = int(raw)
- except ValueError:
- self._clear_inbound_id_after_search()
- self._show_search_message(
- QMessageBox.Warning,
- "提示",
- f"请输入有效的出入库单ID(数字)。\n\n当前输入的出入库单ID:{display_id}",
- )
- return
- if inbound_id <= 0:
- self._clear_inbound_id_after_search()
- self._show_search_message(
- QMessageBox.Warning,
- "提示",
- f"请输入有效的出入库单ID。\n\n当前输入的出入库单ID:{display_id}",
- )
- return
- inbound = self.db.get_inbound_outbound_by_id(inbound_id)
- if not inbound:
- self._clear_inbound_id_after_search()
- self._show_search_message(
- QMessageBox.Critical,
- "错误",
- f"该出入库单ID不存在。\n\n当前输入的出入库单ID:{display_id}",
- )
- return
- # 解析出入库单日期,用于判断以前/当天/未来
- inbound_date = inbound.get("date")
- if inbound_date is not None:
- if hasattr(inbound_date, "strftime"):
- inbound_date_str = inbound_date.strftime("%Y-%m-%d")
- else:
- inbound_date_str = str(inbound_date).strip()[:10]
- else:
- inbound_date_str = ""
- today_str = datetime.now().strftime("%Y-%m-%d")
- is_past = bool(inbound_date_str and inbound_date_str < today_str)
- is_future = bool(inbound_date_str and inbound_date_str > today_str)
- is_today = bool(inbound_date_str and inbound_date_str == today_str)
- # 日期为未来:提示异常
- if is_future:
- self._clear_inbound_id_after_search()
- self._show_search_message(
- QMessageBox.Critical,
- "错误",
- f"该出入库单日期为未来日期,无法操作。\n\n当前输入的出入库单ID:{display_id}",
- )
- return
- # 日期为以前(历史)
- if is_past:
- linked_slip = self.db.get_weighing_slip_by_inbound_id(inbound_id, include_voided=False)
- if not linked_slip:
- self._clear_inbound_id_after_search()
- self._show_search_message(
- QMessageBox.Critical,
- "错误",
- f"该历史出入库单未关联任何地磅单,无法查看历史称重记录。\n\n当前输入的出入库单ID:{display_id}",
- )
- return
- # 有地磅单:弹窗,读毛重/读皮重不可操作(在 jump_to_weighing 中通过 set_history_mode 实现)
- self._clear_inbound_id_after_search()
- self.jump_to_weighing(inbound_id)
- return
- # 当天:校验车牌号
- vehicle_no = (inbound.get("vehicle_no") or "").strip()
- if not vehicle_no:
- self._clear_inbound_id_after_search()
- self._show_search_message(
- QMessageBox.Critical,
- "错误",
- f"该出入库单缺少车牌号信息。\n\n当前输入的出入库单ID:{display_id}",
- )
- return
- # 当天该车牌是否还有未完成的地磅单(有毛重没皮重,或有皮重没毛重);若未完成的是其他出入库单则提示异常
- incomplete_slips = self.db.get_today_incomplete_weighing_slips_by_vehicle(vehicle_no)
- other_incomplete_ids = []
- for slip in incomplete_slips:
- slip_inbound_id = slip.get("inbound_outbound_id")
- if slip_inbound_id is not None and int(slip_inbound_id) != int(inbound_id):
- other_incomplete_ids.append(int(slip_inbound_id))
- if other_incomplete_ids:
- # 去重并排序,便于用户查看
- other_incomplete_ids = sorted(set(other_incomplete_ids))
- incomplete_ids_text = "、".join(str(i) for i in other_incomplete_ids)
- self._clear_inbound_id_after_search()
- self._show_search_message(
- QMessageBox.Warning,
- "提示",
- f"当天该车牌已存在未完成的称重记录,请输入未完成的出入库单的ID。\n\n未完成的出入库单ID:{incomplete_ids_text}\n当前输入的出入库单ID:{display_id}",
- )
- return
- # 通过校验:清空输入框并弹出地磅单弹窗
- self._clear_inbound_id_after_search()
- self.jump_to_weighing(inbound_id)
- def create_form_widget(self) -> QWidget:
- """创建出入库单填写表单"""
- widget = QWidget()
- layout = QVBoxLayout()
- layout.setSpacing(8)
- layout.setContentsMargins(10, 10, 10, 10)
-
- # 标题
- title = QLabel("出入库单填写")
- title_font = QFont("微软雅黑", 16, QFont.Bold)
- title.setFont(title_font)
- layout.addWidget(title)
-
- # 表单区域 - 使用网格布局,一行放4个字段(8列,label+控件各占1列)
- form_layout = QGridLayout()
- form_layout.setSpacing(12)
- form_layout.setColumnStretch(1, 1)
- form_layout.setColumnStretch(3, 1)
- form_layout.setColumnStretch(5, 1)
- form_layout.setColumnStretch(7, 1)
- input_height = 40
-
- row = 0
-
- # ========== 必填字段(红色label,放前面) ==========
-
- # 第一行:日期(必填)、往来单位(必填)、业务类型(必填)、计划号(只读)
- date_label = QLabel("<span style='color: black;'>日期 *</span>:")
- date_label.setFont(QFont("微软雅黑", 16))
- date_label.setTextFormat(Qt.RichText)
- self.date_input = EmptyDateEdit()
- self.date_input.setMinimumHeight(input_height)
- self.date_input.setFont(QFont("微软雅黑", 16))
- self.date_input.setCalendarPopup(True)
- self.date_input.setDisplayFormat("yyyy-MM-dd")
- self.date_input.dateChanged.connect(self.on_date_changed)
- form_layout.addWidget(date_label, row, 0)
- form_layout.addWidget(self.date_input, row, 1)
-
- partner_label = QLabel("<span style='color: black;'>往来单位 *</span>:")
- partner_label.setFont(QFont("微软雅黑", 16))
- partner_label.setTextFormat(Qt.RichText)
- self.partner_combo = QComboBox()
- self.partner_combo.setMinimumHeight(input_height)
- self.partner_combo.setFont(QFont("微软雅黑", 16))
- self.partner_combo.setEditable(False)
- form_layout.addWidget(partner_label, row, 2)
- form_layout.addWidget(self.partner_combo, row, 3)
-
- business_label = QLabel("<span style='color: black;'>业务类型 *</span>:")
- business_label.setFont(QFont("微软雅黑", 16))
- business_label.setTextFormat(Qt.RichText)
- self.business_type_group = QButtonGroup()
- self.business_inbound_radio = QRadioButton("入库")
- self.business_outbound_radio = QRadioButton("出库")
- self.business_inbound_radio.setFont(QFont("微软雅黑", 16))
- self.business_outbound_radio.setFont(QFont("微软雅黑", 16))
- # 设置选中时样式(移除颜色)
- self.business_inbound_radio.setStyleSheet("")
- self.business_outbound_radio.setStyleSheet("")
- self.business_type_group.addButton(self.business_inbound_radio, 0)
- self.business_type_group.addButton(self.business_outbound_radio, 1)
- self.business_inbound_radio.toggled.connect(self.on_business_type_changed)
- self.business_outbound_radio.toggled.connect(self.on_business_type_changed)
- business_layout = QHBoxLayout()
- business_layout.addWidget(self.business_inbound_radio)
- business_layout.addWidget(self.business_outbound_radio)
- business_layout.addStretch()
- business_widget = QWidget()
- business_widget.setLayout(business_layout)
- form_layout.addWidget(business_label, row, 4)
- form_layout.addWidget(business_widget, row, 5)
-
- # ========== 非必填字段(黑色label) ==========
-
- plan_no_label = QLabel("计划号:")
- plan_no_label.setFont(QFont("微软雅黑", 16))
- self.plan_no_display = QLabel("未关联")
- self.plan_no_display.setMinimumHeight(input_height)
- self.plan_no_display.setFont(QFont("微软雅黑", 16))
- self.plan_no_display.setStyleSheet("padding: 5px; border: 1px solid #ccc;")
- form_layout.addWidget(plan_no_label, row, 6)
- form_layout.addWidget(self.plan_no_display, row, 7)
-
- row += 1
-
- # 第二行:产品(必填)、本次量(t)(必填)、车牌号(必填)、批次号
- product_label = QLabel("<span style='color: black;'>产品 *</span>:")
- product_label.setFont(QFont("微软雅黑", 16))
- product_label.setTextFormat(Qt.RichText)
- self.product_combo = QComboBox()
- self.product_combo.setMinimumHeight(input_height)
- self.product_combo.setFont(QFont("微软雅黑", 16))
- self.product_combo.setEditable(False)
- form_layout.addWidget(product_label, row, 0)
- form_layout.addWidget(self.product_combo, row, 1)
-
- quantity_label = QLabel("<span style='color: black;'>本次量(t) *</span>:")
- quantity_label.setFont(QFont("微软雅黑", 16))
- quantity_label.setTextFormat(Qt.RichText)
- self.quantity_input = EmptyDoubleSpinBox()
- self.quantity_input.setMinimumHeight(input_height)
- self.quantity_input.setFont(QFont("微软雅黑", 16))
- self.quantity_input.setDecimals(3)
- self.quantity_input.setMinimum(-1)
- self.quantity_input.setMaximum(999999)
- self.quantity_input.setSpecialValueText("")
- self.quantity_input.setValue(-1)
- form_layout.addWidget(quantity_label, row, 2)
- form_layout.addWidget(self.quantity_input, row, 3)
-
- vehicle_label = QLabel("<span style='color: black;'>车牌号 *</span>:")
- vehicle_label.setFont(QFont("微软雅黑", 16))
- vehicle_label.setTextFormat(Qt.RichText)
- self.vehicle_no_input = QLineEdit()
- self.vehicle_no_input.setMinimumHeight(input_height)
- self.vehicle_no_input.setFont(QFont("微软雅黑", 16))
- form_layout.addWidget(vehicle_label, row, 4)
- form_layout.addWidget(self.vehicle_no_input, row, 5)
-
- batch_label = QLabel("批次号:")
- batch_label.setFont(QFont("微软雅黑", 16))
- self.batch_no_input = QLineEdit()
- self.batch_no_input.setMinimumHeight(input_height)
- self.batch_no_input.setFont(QFont("微软雅黑", 16))
- # 批次号输入框失去焦点时,如果为空则自动生成
- self.batch_no_input.editingFinished.connect(self.on_batch_no_editing_finished)
- form_layout.addWidget(batch_label, row, 6)
- form_layout.addWidget(self.batch_no_input, row, 7)
-
- row += 1
-
- # 第三行:状态(只读)、备注(占三个元素的宽度)
- status_label = QLabel("状态:")
- status_label.setFont(QFont("微软雅黑", 16))
- self.status_pending_style = "padding: 5px; border: 1px solid #ccc;"
- self.status_completed_style = "padding: 5px; border: 1px solid #ccc;"
- self.status_display = QLabel("待入库")
- self.status_display.setMinimumHeight(45)
- self.status_display.setFixedHeight(45)
- self.status_display.setFont(QFont("微软雅黑", 16))
- self.status_display.setStyleSheet(self.status_pending_style)
- form_layout.addWidget(status_label, row, 0)
- form_layout.addWidget(self.status_display, row, 1)
-
- remarks_label = QLabel("备注:")
- remarks_label.setFont(QFont("微软雅黑", 16))
- self.remarks_input = QTextEdit()
- self.remarks_input.setMinimumHeight(45)
- self.remarks_input.setFixedHeight(45)
- self.remarks_input.setFont(QFont("微软雅黑", 16))
- form_layout.addWidget(remarks_label, row, 2)
- form_layout.addWidget(self.remarks_input, row, 3, 1, 5)
-
- # 按钮区域
- row += 1
- button_layout = QHBoxLayout()
- button_layout.setContentsMargins(0, 4, 0, 0)
- button_layout.setSpacing(12)
- button_layout.addStretch()
-
- self.save_btn = QPushButton("保存")
- self.save_btn.setMinimumHeight(30)
- self.save_btn.setMinimumWidth(110)
- self.save_btn.setFont(QFont("微软雅黑", 13, QFont.Bold))
- apply_button_style(self.save_btn, 'green')
- self.save_btn.clicked.connect(self.save_inbound_outbound)
- self.save_btn.setShortcut(QKeySequence("Ctrl+S"))
-
- self.clear_btn = QPushButton("清空")
- self.clear_btn.setMinimumHeight(30)
- self.clear_btn.setMinimumWidth(110)
- self.clear_btn.setFont(QFont("微软雅黑", 13))
- apply_button_style(self.clear_btn, 'normal')
- self.clear_btn.clicked.connect(self.clear_form)
-
- button_layout.addWidget(self.save_btn)
- button_layout.addWidget(self.clear_btn)
- button_layout.addStretch()
-
- button_widget = QWidget()
- button_widget.setLayout(button_layout)
- button_widget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
- button_widget.setMaximumHeight(50)
- form_layout.addWidget(button_widget, row, 0, 1, 8)
-
- layout.addLayout(form_layout)
-
- # 包装在GroupBox中
- group_box = QGroupBox()
- group_box.setLayout(layout)
- # 隐藏整个“出入库单填写”区域(保持实例存在以免影响其他逻辑)
- # 仅设置为不可见并限制最大高度为0,便于后续如需恢复时只需调用 setVisible(True) 并重置高度。
- try:
- group_box.setVisible(False)
- group_box.setMaximumHeight(0)
- except Exception:
- # 如果运行环境不允许设置(极少见),忽略以保持兼容性
- pass
-
- return group_box
-
- def create_list_widget(self) -> QWidget:
- """创建出入库单记录列表"""
- widget = QWidget()
- layout = QVBoxLayout()
- layout.setContentsMargins(10, 10, 10, 10)
-
- # 标题和刷新按钮区域
- title_layout = QHBoxLayout()
- title = QLabel("出入库单记录列表")
- title_font = QFont("微软雅黑", 18, QFont.Bold)
- title.setFont(title_font)
- title_layout.addWidget(title)
- title_layout.addStretch()
- # 视图切换按钮:列表 / 卡片,默认卡片视图
- self.view_mode = "card"
- # 隐藏列表视图按钮
- # self.table_view_btn = QPushButton("列表视图")
- # self.table_view_btn.setCheckable(True)
- # self.table_view_btn.setChecked(False)
- # self.table_view_btn.setFont(QFont("微软雅黑", 13))
- # apply_button_style(self.table_view_btn, 'normal')
- self.card_view_btn = QPushButton("卡片视图")
- self.card_view_btn.setCheckable(True)
- self.card_view_btn.setFont(QFont("微软雅黑", 13))
- apply_button_style(self.card_view_btn, 'normal')
- # 隐藏列表视图按钮
- # self.table_view_btn.clicked.connect(lambda: self._switch_view_mode("table"))
- self.card_view_btn.clicked.connect(lambda: self._switch_view_mode("card"))
- # title_layout.addWidget(self.table_view_btn)
- title_layout.addWidget(self.card_view_btn)
-
- # 筛选多选下拉框(默认选择待入库和待出库)
- self.status_filter_dropdown = MultiSelectDropdown(
- options=["待入库", "待出库", "全部"],
- default_selected=["待入库", "待出库"]
- )
- # 初始化时设置默认选择
- self.status_filter_dropdown.set_selected_items(["待入库", "待出库"])
- self.status_filter_dropdown.selection_changed.connect(self.on_filter_changed)
- title_layout.addWidget(self.status_filter_dropdown)
- title_layout.addSpacing(12)
- # 30分钟内的已完成的筛选下拉框(默认选择30分钟内已完成的)
- self.recent_completed_dropdown = QComboBox()
- self.recent_completed_dropdown.setMinimumWidth(150)
- self.recent_completed_dropdown.setFont(QFont("微软雅黑", 13))
- self.recent_completed_dropdown.addItems(["30分钟内已完成的", "全部"])
- self.recent_completed_dropdown.setCurrentText("30分钟内已完成的")
- self.recent_completed_dropdown.currentTextChanged.connect(self.on_filter_changed)
- title_layout.addWidget(self.recent_completed_dropdown)
- title_layout.addSpacing(12)
-
- # 只看当天单子过滤勾选框(默认勾选)
- self.today_only_checkbox = QCheckBox("只看当天")
- self.today_only_checkbox.setChecked(True)
- self.today_only_checkbox.setFont(QFont("微软雅黑", 13))
- self.today_only_checkbox.stateChanged.connect(self.on_today_filter_changed)
- title_layout.addWidget(self.today_only_checkbox)
- title_layout.addSpacing(12)
- self.search_input = QLineEdit()
- self.search_input.setPlaceholderText("检索往来单位 / 车牌号 / 产品")
- self.search_input.setMinimumHeight(36)
- self.search_input.setMinimumWidth(500)
- self.search_input.setMaximumWidth(600)
- self.search_input.setFont(QFont("微软雅黑", 14))
- self.search_input.setClearButtonEnabled(True)
- self.search_input.textChanged.connect(self.on_search_text_changed)
- title_layout.addWidget(self.search_input)
- title_layout.addSpacing(12)
-
- self.export_btn = QPushButton("导出Excel")
- self.export_btn.setMinimumHeight(40)
- self.export_btn.setMinimumWidth(120)
- self.export_btn.setFont(QFont("微软雅黑", 16))
- apply_button_style(self.export_btn, 'normal')
- self.export_btn.clicked.connect(self.export_to_excel)
- title_layout.addWidget(self.export_btn)
-
- self.refresh_btn = QPushButton("刷新")
- self.refresh_btn.setMinimumHeight(40)
- self.refresh_btn.setMinimumWidth(100)
- self.refresh_btn.setFont(QFont("微软雅黑", 16))
- apply_button_style(self.refresh_btn, 'normal')
- self.refresh_btn.clicked.connect(self.refresh_list)
- self.refresh_btn.setShortcut(QKeySequence("F5"))
- title_layout.addWidget(self.refresh_btn)
-
- layout.addLayout(title_layout)
-
- # 表格
- self.table = QTableWidget()
- self.table.setColumnCount(14)
- self.table.setHorizontalHeaderLabels([
- "计划号", "批次号", "日期", "往来单位", "业务类型",
- "产品", "车牌号", "本次量(t)", "净重(t)", "毛重(t)",
- "皮重(t)", "扣杂(t)", "状态", "操作"
- ])
- header = self.table.horizontalHeader()
- header.setFont(QFont("微软雅黑", 15, QFont.Bold))
- header.setSectionsMovable(False)
- header.setStretchLastSection(False)
- header.setSectionsClickable(False)
- self.column_width_ratios = [
- 0.08, 0.08, 0.09, 0.12, 0.08, 0.1, 0.08,
- 0.08, 0.07, 0.07, 0.07, 0.05, 0.05, 0.12
- ]
- self._user_resized_columns = False
- self._is_applying_column_widths = False
- for i in range(self.table.columnCount()):
- header.setSectionResizeMode(i, QHeaderView.Interactive)
- header.sectionResized.connect(self._on_section_resized)
- self._apply_table_column_widths(force=True)
- vertical_header = self.table.verticalHeader()
- vertical_header.setDefaultAlignment(Qt.AlignCenter)
- vertical_header.setFixedWidth(60)
- vertical_header.setSectionResizeMode(QHeaderView.ResizeToContents)
- self.table.setFont(QFont("微软雅黑", 15))
- self.table.setAlternatingRowColors(True)
- self.table.setSelectionBehavior(QTableWidget.SelectRows)
-
- layout.addWidget(self.table)
- # 卡片视图:使用 QScrollArea + 容器布局
- self.card_scroll_area = QScrollArea()
- self.card_scroll_area.setWidgetResizable(True)
- self.card_scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
- self.card_container = QWidget()
- # 卡片区域使用网格布局,一行放多个卡片
- self.card_layout = QGridLayout()
- # 外边距和间距都设置为 4px,保证多张卡片之间用 4px 作为间隔
- self.card_layout.setContentsMargins(4, 4, 4, 4)
- self.card_layout.setHorizontalSpacing(4)
- self.card_layout.setVerticalSpacing(10)
- self.card_container.setLayout(self.card_layout)
- # 一行放 5 个卡片
- self.card_columns = 5
- # 当前卡片控件缓存,用于窗口大小变化时调整宽度
- self._card_widgets = []
- self.card_scroll_area.setWidget(self.card_container)
- # 默认采用卡片视图,表格视图在需要时再显示
- self.card_scroll_area.setVisible(True)
- layout.addWidget(self.card_scroll_area)
-
- widget.setLayout(layout)
- return widget
-
- def refresh_dropdowns(self):
- """刷新下拉列表(简化版界面无下拉框,直接返回)"""
- if not getattr(self, "partner_combo", None):
- return
- # 刷新往来单位
- self.partner_combo.clear()
- self.partner_combo.addItem("")
- companies = self.db.get_all_companies()
- for company in companies:
- self.partner_combo.addItem(company['name'])
- self.partner_combo.setCurrentIndex(0)
-
- # 刷新产品
- self.product_combo.clear()
- self.product_combo.addItem("")
- cargos = self.db.get_all_cargos()
- for cargo in cargos:
- self.product_combo.addItem(cargo['name'])
- self.product_combo.setCurrentIndex(0)
-
- def refresh_list(self):
- """刷新出入库单记录列表(简化版界面无列表,直接返回)"""
- if not getattr(self, "table", None):
- return
- keyword = getattr(self, "search_keyword", "").strip()
- inbounds = self.db.get_all_inbound_outbound(keyword if keyword else None)
- # 先获取地磅单摘要,以便在筛选和排序时使用时间信息
- inbound_ids = [inbound.get('id') for inbound in inbounds if inbound.get('id')]
- slip_summary_map = self.db.get_weighing_slip_summary_by_inbound_ids(inbound_ids)
- # 根据勾选框过滤:只看待入库、待出库、已完成的
- show_pending_inbound = getattr(self, "show_pending_inbound", True)
- show_pending_outbound = getattr(self, "show_pending_outbound", True)
- show_recent_completed = getattr(self, "show_recent_completed", True)
- show_all_completed = getattr(self, "show_all_completed", True)
-
- # 计算30分钟前的时间
- now = datetime.now()
- thirty_minutes_ago = now.timestamp() - 30 * 60
-
- filtered_inbounds = []
- for inbound in inbounds:
- status = str(inbound.get("status", "")).strip()
- inbound_id = inbound.get('id')
- slip_summary = slip_summary_map.get(inbound_id) if inbound_id else None
-
- # 判断是否应该显示
- should_show = False
-
- # 待入库
- if status == "待入库" and show_pending_inbound:
- should_show = True
- # 待出库
- elif status == "待出库" and show_pending_outbound:
- should_show = True
- # 已完成的记录筛选
- elif status.startswith("已") and (show_recent_completed or show_all_completed):
- if show_all_completed:
- # 显示所有已完成的记录
- should_show = True
- elif show_recent_completed:
- # 只显示30分钟内的已完成的记录
- # 检查毛重时间或皮重时间,只要有一个在30分钟内就显示
- # 如果没有时间戳信息,也显示(可能是刚完成的记录)
- gross_weight_time_str = slip_summary.get('gross_weight_time', '') if slip_summary else ''
- tare_weight_time_str = slip_summary.get('tare_weight_time', '') if slip_summary else ''
- # 如果没有任何时间戳信息,认为是刚完成的记录,显示出来
- if not gross_weight_time_str and not tare_weight_time_str:
- should_show = True
- else:
- # 检查毛重时间
- if gross_weight_time_str:
- try:
- gross_time_obj = datetime.strptime(gross_weight_time_str, "%Y-%m-%d %H:%M:%S")
- if gross_time_obj.timestamp() >= thirty_minutes_ago:
- should_show = True
- except (ValueError, TypeError):
- pass
- # 如果毛重时间不在30分钟内,再检查皮重时间
- if not should_show and tare_weight_time_str:
- try:
- tare_time_obj = datetime.strptime(tare_weight_time_str, "%Y-%m-%d %H:%M:%S")
- if tare_time_obj.timestamp() >= thirty_minutes_ago:
- should_show = True
- except (ValueError, TypeError):
- pass
-
- if should_show:
- filtered_inbounds.append(inbound)
-
- inbounds = filtered_inbounds
-
- # 根据勾选框过滤:默认只看当天
- show_today_only = getattr(self, "show_today_only", True)
- if show_today_only:
- today_str = datetime.now().strftime("%Y-%m-%d")
- inbounds = [
- inbound
- for inbound in inbounds
- if inbound.get("date", "") == today_str
- ]
- # 多级排序:日期倒序、状态(待入库、待出库、已完成)、毛重时间倒序
- def get_sort_key(r):
- # 1. 日期(倒序,最新的在前)
- date_str = str(r.get("date", ""))
- try:
- # 将日期字符串转换为datetime对象,然后取负的timestamp实现倒序
- date_obj = datetime.strptime(date_str, "%Y-%m-%d")
- date_sort_key = -date_obj.timestamp() # 负值实现倒序
- except (ValueError, TypeError):
- # 如果日期格式不正确,使用空字符串排序(排在最后)
- date_sort_key = float('inf') # 无效日期排在最后
-
- # 2. 状态优先级:待入库=1, 待出库=2, 已完成=3
- status = str(r.get("status", "")).strip()
- if status == "待入库":
- status_priority = 1
- elif status == "待出库":
- status_priority = 2
- elif status.startswith("已"): # 已完成状态(已入库、已出库等)
- status_priority = 3
- else:
- status_priority = 4 # 其他状态排在最后
-
- # 3. 毛重时间(倒序,最新的在前)
- inbound_id = r.get('id')
- slip_summary = slip_summary_map.get(inbound_id) if inbound_id else None
- gross_weight_time_str = slip_summary.get('gross_weight_time', '') if slip_summary else ''
-
- try:
- if gross_weight_time_str:
- # 毛重时间格式:YYYY-MM-DD HH:mm:ss
- gross_time_obj = datetime.strptime(gross_weight_time_str, "%Y-%m-%d %H:%M:%S")
- gross_time_sort_key = -gross_time_obj.timestamp() # 负值实现倒序
- else:
- # 如果没有毛重时间,排在最后
- gross_time_sort_key = float('inf')
- except (ValueError, TypeError):
- # 如果毛重时间格式不正确,排在最后
- gross_time_sort_key = float('inf')
-
- # 返回排序键:日期倒序、状态正序、毛重时间倒序
- return (date_sort_key, status_priority, gross_time_sort_key)
-
- inbounds.sort(key=get_sort_key)
- # 缓存当前列表数据,供卡片/表格视图复用
- self._current_inbounds = inbounds
- self._slip_summary_map = slip_summary_map
- # 根据当前视图模式渲染
- if getattr(self, "view_mode", "table") == "card":
- self._refresh_card_view()
- else:
- self._refresh_table_view()
- def _refresh_table_view(self):
- """以表格形式渲染出入库单列表"""
- inbounds = getattr(self, "_current_inbounds", [])
- slip_summary_map = getattr(self, "_slip_summary_map", {})
- self.table.setRowCount(len(inbounds))
-
- # 获取当前日期(格式:yyyy-MM-dd)
- today_str = datetime.now().strftime("%Y-%m-%d")
- # 移除背景色设置
-
- for i, inbound in enumerate(inbounds):
- # 判断是否为当天的单子
- is_today = inbound.get('date', '') == today_str
-
- # 计划号
- plan_no_item = QTableWidgetItem(inbound.get('plan_no', ''))
- # 移除当天高亮背景
- self.table.setItem(i, 0, plan_no_item)
-
- # 批次号
- batch_no_item = QTableWidgetItem(inbound.get('batch_no', ''))
- # 移除当天高亮背景
- self.table.setItem(i, 1, batch_no_item)
-
- # 日期
- date_item = QTableWidgetItem(inbound['date'])
- # 移除当天高亮背景
- self.table.setItem(i, 2, date_item)
-
- # 往来单位
- partner_item = QTableWidgetItem(inbound['partner_company'])
- # 移除当天高亮背景
- self.table.setItem(i, 3, partner_item)
-
- # 业务类型
- business_item = QTableWidgetItem(inbound['business_type'])
- # 移除当天高亮背景
- self.table.setItem(i, 4, business_item)
-
- # 产品
- product_item = QTableWidgetItem(inbound['product'])
- # 移除当天高亮背景
- self.table.setItem(i, 5, product_item)
-
- # 车牌号
- vehicle_item = QTableWidgetItem(inbound['vehicle_no'])
- # 移除当天高亮背景
- self.table.setItem(i, 6, vehicle_item)
-
- # 本次量(t)
- quantity_item = QTableWidgetItem(f"{inbound['quantity']:.3f}")
- # 移除当天高亮背景
- self.table.setItem(i, 7, quantity_item)
- slip_summary = slip_summary_map.get(inbound.get('id'))
- def _format_slip_weight(field: str) -> str:
- if not slip_summary:
- return ""
- value = slip_summary.get(field)
- if value is None:
- return ""
- tons_value = kg_to_tons(value)
- if tons_value is None:
- return ""
- return f"{tons_value:.3f}"
- # 净重(t)
- net_weight_item = QTableWidgetItem(_format_slip_weight('net_weight'))
- # 移除当天高亮背景
- self.table.setItem(i, 8, net_weight_item)
-
- # 毛重(t)
- gross_weight_item = QTableWidgetItem(_format_slip_weight('gross_weight'))
- # 移除当天高亮背景
- self.table.setItem(i, 9, gross_weight_item)
-
- # 皮重(t)
- tare_weight_item = QTableWidgetItem(_format_slip_weight('tare_weight'))
- # 移除当天高亮背景
- self.table.setItem(i, 10, tare_weight_item)
-
- # 扣杂(t)
- deduction_item = QTableWidgetItem(_format_slip_weight('deduction'))
- # 移除当天高亮背景
- self.table.setItem(i, 11, deduction_item)
-
- # 状态
- status_text = (inbound.get('status', '') or '').strip()
- status_item = QTableWidgetItem(status_text)
- # 移除状态文字颜色和当天高亮背景
- self.table.setItem(i, 12, status_item)
-
- # 操作按钮
- btn_widget = QWidget()
- btn_layout = QHBoxLayout()
- btn_layout.setContentsMargins(5, 2, 5, 2)
- is_completed = self._is_completed_status(status_text)
-
- # 为已完成的行设置淡绿色背景
- if is_completed:
- light_green = QColor(220, 255, 220) # 淡绿色
- brush = QBrush(light_green)
- for col in range(self.table.columnCount()):
- item = self.table.item(i, col)
- if item:
- item.setBackground(brush)
- # 地磅单和打印按钮放在前面
- # 地磅单按钮始终显示(无论是否完成)
- jump_btn = QPushButton("地磅单")
- jump_btn.setFont(QFont("微软雅黑", 14))
- apply_button_style(jump_btn, 'blue')
- jump_btn.clicked.connect(lambda checked, iid=inbound['id']: self.jump_to_weighing(iid))
- btn_layout.addWidget(jump_btn)
-
- # 如果有地磅单,显示打印按钮(无论是否完成)
- slip_summary = slip_summary_map.get(inbound.get('id'))
- if slip_summary:
- print_btn = QPushButton("打印")
- print_btn.setFont(QFont("微软雅黑", 14))
- apply_button_style(print_btn, 'blue')
- print_btn.clicked.connect(lambda checked, iid=inbound['id']: self.print_weighing_slip(iid))
- btn_layout.addWidget(print_btn)
-
- # 其他按钮放在后面
- if is_completed:
- view_btn = QPushButton("查看")
- view_btn.setFont(QFont("微软雅黑", 14))
- apply_button_style(view_btn, 'normal')
- view_btn.clicked.connect(lambda checked, iid=inbound['id']: self.view_inbound(iid))
- btn_layout.addWidget(view_btn)
- else:
- edit_btn = QPushButton("编辑")
- edit_btn.setFont(QFont("微软雅黑", 14))
- apply_button_style(edit_btn, 'normal')
- edit_btn.clicked.connect(lambda checked, iid=inbound['id']: self.start_editing_inbound(iid))
- btn_layout.addWidget(edit_btn)
-
- if self._is_admin:
- delete_btn = QPushButton("删除")
- delete_btn.setFont(QFont("微软雅黑", 14))
- apply_button_style(delete_btn, 'normal')
- delete_btn.clicked.connect(lambda checked, iid=inbound['id']: self.delete_inbound(iid))
- btn_layout.addWidget(delete_btn)
- btn_widget.setLayout(btn_layout)
-
- self.table.setCellWidget(i, 13, btn_widget)
-
- self.table.resizeRowsToContents()
- QTimer.singleShot(0, self.table.resizeRowsToContents)
- self._apply_table_column_widths()
- # 只在表格视图下显示表格、隐藏卡片区域
- if hasattr(self, "card_scroll_area"):
- self.table.setVisible(True)
- self.card_scroll_area.setVisible(False)
- def _refresh_card_view(self):
- """以卡片形式渲染出入库单列表"""
- inbounds = getattr(self, "_current_inbounds", [])
- slip_summary_map = getattr(self, "_slip_summary_map", {})
- today_str = datetime.now().strftime("%Y-%m-%d")
- # 清空旧卡片(网格布局)
- while self.card_layout.count():
- item = self.card_layout.takeAt(0)
- w = item.widget()
- if w is not None:
- w.deleteLater()
- # 清空旧的卡片缓存,避免引用到已销毁的 QFrame
- self._card_widgets = []
- def _format_slip_weight(summary: Optional[dict], field: str) -> str:
- if not summary:
- return "-"
- value = summary.get(field)
- if value is None:
- return "-"
- tons_value = kg_to_tons(value)
- if tons_value is None:
- return "-"
- return f"{tons_value:.3f} t"
- for idx, inbound in enumerate(inbounds):
- slip_summary = slip_summary_map.get(inbound.get('id'))
- card = QFrame()
- card.setFrameShape(QFrame.NoFrame)
- card.setFrameShadow(QFrame.Plain)
-
- # 判断是否已完成
- status_text = (inbound.get("status", "") or "").strip()
- is_completed = self._is_completed_status(status_text)
-
- # 根据完成状态设置卡片背景色
- if is_completed:
- # 已完成:淡绿色背景
- card.setStyleSheet("border: 1px solid #ccc; border-radius: 6px; background-color: #dcffdc;")
- else:
- # 默认卡片样式:带细边框的白色卡片
- card.setStyleSheet("border: 1px solid #ccc; border-radius: 6px;")
- # 控制卡片高度为固定值,宽度由布局和窗口大小动态控制
- card.setFixedHeight(220)
- card_layout = QVBoxLayout()
- card_layout.setContentsMargins(10, 8, 10, 8)
- card_layout.setSpacing(4)
- # 顶部行:业务类型、产品、本次量
- top_layout = QHBoxLayout()
- top_layout.setContentsMargins(0, 0, 0, 0)
- top_layout.setSpacing(10)
- # 业务类型
- business_type = inbound.get("business_type", "")
- biz_label = QLabel(business_type)
- biz_label.setFont(QFont("微软雅黑", 12, QFont.Bold))
- biz_label.setStyleSheet("border: none;")
- # 产品
- product_label = QLabel(inbound.get("product", "") or "-")
- product_label.setFont(QFont("微软雅黑", 12, QFont.Bold))
- product_label.setStyleSheet("border: none;")
- # 本次量
- quantity = inbound.get("quantity")
- if quantity is not None and quantity > 0:
- quantity_text = f"{quantity:.3f} t"
- else:
- quantity_text = "-"
- quantity_label = QLabel(f"本次: {quantity_text}")
- quantity_label.setFont(QFont("微软雅黑", 12))
- quantity_label.setStyleSheet("border: none;")
- top_layout.addWidget(biz_label)
- top_layout.addWidget(product_label)
- top_layout.addWidget(quantity_label)
- top_layout.addStretch()
- # 顶部右侧显示状态
- status_text = (inbound.get("status", "") or "").strip()
- is_completed = self._is_completed_status(status_text)
- status_top_label = QLabel(status_text or "-")
- status_top_label.setFont(QFont("微软雅黑", 12, QFont.Bold))
- status_top_label.setStyleSheet("border: none;")
- # 移除状态文字颜色
- top_layout.addWidget(status_top_label)
- # 中间行:左边ID+日期 + 右边车牌号
- middle_layout = QHBoxLayout()
-
- # 左边:出入库单ID + 实际日期
- date_str = inbound.get("date", "") or "-"
- inbound_id = inbound.get("id")
- if inbound_id is not None:
- date_display_text = f"ID: {inbound_id}\n{date_str}"
- else:
- date_display_text = date_str
- date_display_label = QLabel(date_display_text)
- date_display_label.setFont(QFont("微软雅黑", 16, QFont.Bold))
- date_display_label.setStyleSheet("border: none;")
- date_display_label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
-
- # 重量信息(来自地磅单汇总)- 提前计算用于车牌号前缀
- net_text = _format_slip_weight(slip_summary, "net_weight")
- gross_text = _format_slip_weight(slip_summary, "gross_weight")
- tare_text = _format_slip_weight(slip_summary, "tare_weight")
-
- # 右边:车牌号(根据毛重和皮重添加前缀)
- vehicle_no = inbound.get("vehicle_no", "") or "-"
- prefix = ""
- # 从原始值判断,确保不为0才算有值
- gross_value = slip_summary.get("gross_weight") if slip_summary else None
- tare_value = slip_summary.get("tare_weight") if slip_summary else None
- has_gross = gross_value is not None and gross_value != 0
- has_tare = tare_value is not None and tare_value != 0
- if has_gross and has_tare:
- prefix = "(毛皮)"
- elif has_gross:
- prefix = "(毛)"
- elif has_tare:
- prefix = "(皮)"
-
- plate_text = f"{prefix}{vehicle_no}" if prefix else vehicle_no
- plate_label = QLabel(plate_text)
- plate_label.setFont(QFont("微软雅黑", 20, QFont.Bold))
- plate_label.setStyleSheet("border: none;")
- plate_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
- middle_layout.addWidget(date_display_label, stretch=1)
- middle_layout.addWidget(plate_label, stretch=1)
- # 往来单位 - 隐藏公司名称显示
- # partner_layout = QHBoxLayout()
- # partner_text = inbound.get("partner_company", "") or "-"
- # partner_label = QLabel(partner_text)
- # partner_label.setFont(QFont("微软雅黑", 12))
- # partner_label.setStyleSheet("border: none;")
- # partner_layout.addWidget(partner_label)
- # partner_layout.addStretch()
- deduction_text = _format_slip_weight(slip_summary, "deduction")
- weight_line_label = QLabel(
- f"净重: {net_text} 毛重: {gross_text} 皮重: {tare_text}"
- )
- weight_line_label.setFont(QFont("微软雅黑", 12))
- weight_line_label.setStyleSheet("border: none;")
- # 扣杂 / 备注
- remarks = (inbound.get("remarks") or "").strip()
- if not remarks:
- remarks = "-"
- remarks_label = QLabel(f"扣杂: {deduction_text} 备注: {remarks}")
- remarks_label.setFont(QFont("微软雅黑", 11))
- remarks_label.setStyleSheet("border: none;")
- remarks_label.setWordWrap(True)
- # 底部主要操作按钮
- btn_layout = QHBoxLayout()
- btn_layout.setContentsMargins(0, 0, 0, 0)
- btn_layout.setSpacing(10)
- btn_layout.addStretch()
- # 卡片视图不显示「地磅单」按钮
- # 若有地磅单则显示「打印」
- # 如果有地磅单,显示打印按钮(无论是否完成)
- if slip_summary:
- print_btn_main = QPushButton("打印")
- print_font = QFont("微软雅黑", 15)
- print_font.setBold(True)
- print_btn_main.setFont(print_font)
- print_btn_main.setMinimumWidth(90)
- print_btn_main.setMinimumHeight(38)
- print_btn_main.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
- apply_button_style(print_btn_main, 'blue')
- print_btn_main.clicked.connect(lambda checked, iid=inbound["id"]: self.print_weighing_slip(iid))
- btn_layout.addWidget(print_btn_main)
-
- # 其他按钮放在后面 - 隐藏查看和编辑按钮
- # if is_completed:
- # view_btn_main = QPushButton("查看")
- # view_btn_main.setFont(QFont("微软雅黑", 13))
- # view_btn_main.setMinimumWidth(100)
- # view_btn_main.setMinimumHeight(38)
- # view_btn_main.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
- # apply_button_style(view_btn_main, 'normal')
- # view_btn_main.clicked.connect(lambda checked, iid=inbound["id"]: self.view_inbound(iid))
- # btn_layout.addWidget(view_btn_main)
- # else:
- # edit_btn_main = QPushButton("编辑")
- # edit_btn_main.setFont(QFont("微软雅黑", 13))
- # edit_btn_main.setMinimumWidth(80)
- # edit_btn_main.setMinimumHeight(38)
- # edit_btn_main.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
- # apply_button_style(edit_btn_main, 'normal')
- # edit_btn_main.clicked.connect(lambda checked, iid=inbound["id"]: self.start_editing_inbound(iid))
- # btn_layout.addWidget(edit_btn_main)
- if self._is_admin:
- delete_btn_main = QPushButton("删除")
- delete_btn_main.setFont(QFont("微软雅黑", 13))
- delete_btn_main.setMinimumWidth(80)
- delete_btn_main.setMinimumHeight(38)
- delete_btn_main.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
- apply_button_style(delete_btn_main, 'normal')
- delete_btn_main.clicked.connect(lambda checked, iid=inbound["id"]: self.delete_inbound(iid))
- btn_layout.addWidget(delete_btn_main)
- btn_layout.addStretch()
- # 当天单据高亮卡片背景
- is_today = inbound.get("date", "") == today_str
- # 卡片背景色已在上面根据完成状态设置,这里不再重复设置
- card_layout.addLayout(top_layout)
- card_layout.addLayout(middle_layout)
- # card_layout.addLayout(partner_layout) # 隐藏公司名称显示
- card_layout.addWidget(weight_line_label)
- card_layout.addWidget(remarks_label)
- card_layout.addLayout(btn_layout)
- card.setLayout(card_layout)
- # 记录卡片控件,便于统一调整宽度
- if not hasattr(self, "_card_widgets"):
- self._card_widgets = []
- self._card_widgets.append(card)
- # 添加到网格布局:一行多个(由 self.card_columns 控制)
- col_count = getattr(self, "card_columns", 3) or 3
- row = idx // col_count
- col = idx % col_count
- self.card_layout.addWidget(card, row, col)
- # 刷新完后根据当前宽度调整卡片宽度
- self._update_card_widths()
- # 显示卡片区域、隐藏表格(简化版可能无 table)
- table = getattr(self, "table", None)
- if table is not None:
- table.setVisible(False)
- if getattr(self, "card_scroll_area", None) is not None:
- self.card_scroll_area.setVisible(True)
- def resizeEvent(self, event):
- super().resizeEvent(event)
- # 仅在表格视图下调整列宽
- if getattr(self, "view_mode", "table") == "table":
- self._apply_table_column_widths()
- else:
- # 卡片视图下根据当前宽度调整卡片宽度
- self._update_card_widths()
- self._update_form_widget_height()
-
- def showEvent(self, event):
- super().showEvent(event)
- if getattr(self, "inbound_id_input", None):
- self.inbound_id_input.setFocus()
- if getattr(self, "card_layout", None):
- # 短延迟刷新,避免首次显示时布局未完成导致卡片不展示
- QTimer.singleShot(80, self.refresh_today_cards)
- if getattr(self, "view_mode", "table") == "table":
- QTimer.singleShot(0, lambda: self._apply_table_column_widths(force=True))
- else:
- QTimer.singleShot(0, self._update_card_widths)
- def _on_section_resized(self, *_):
- if getattr(self, "_is_applying_column_widths", False):
- return
- self._user_resized_columns = True
- def _apply_table_column_widths(self, force: bool = False):
- if not hasattr(self, "table") or not hasattr(self, "column_width_ratios"):
- return
- if getattr(self, "_user_resized_columns", False) and not force:
- return
- viewport_width = self.table.viewport().width()
- if viewport_width <= 0:
- return
- total_ratio = sum(self.column_width_ratios) or 1
- assigned_width = 0
- header = self.table.horizontalHeader()
- self._is_applying_column_widths = True
- header.blockSignals(True)
- try:
- for index, ratio in enumerate(self.column_width_ratios):
- if index == self.table.columnCount() - 1:
- width = viewport_width - assigned_width
- else:
- width = int(viewport_width * ratio / total_ratio)
- assigned_width += width
- self.table.setColumnWidth(index, max(width, 60))
- # 额外像素级调整:日期列宽度不额外加宽,皮重列宽度与毛重列宽度保持一致
- # 列索引:2 = 日期, 9 = 毛重(t), 10 = 皮重(t)
- date_col_index = 2
- gross_col_index = 9
- tare_col_index = 10
- date_width = self.table.columnWidth(date_col_index)
- gross_width = self.table.columnWidth(gross_col_index)
- tare_width = gross_width
- self.table.setColumnWidth(date_col_index, date_width)
- self.table.setColumnWidth(gross_col_index, gross_width)
- self.table.setColumnWidth(tare_col_index, tare_width)
- finally:
- header.blockSignals(False)
- self._is_applying_column_widths = False
- def _switch_view_mode(self, mode: str):
- """切换列表展示模式:table / card"""
- if mode == getattr(self, "view_mode", "table"):
- return
- self.view_mode = mode
- # 同步按钮选中状态
- if mode == "table":
- if hasattr(self, "table_view_btn"):
- self.table_view_btn.setChecked(True)
- if hasattr(self, "card_view_btn"):
- self.card_view_btn.setChecked(False)
- # 重新以表格方式渲染
- self._refresh_table_view()
- else:
- if hasattr(self, "table_view_btn"):
- self.table_view_btn.setChecked(False)
- if hasattr(self, "card_view_btn"):
- self.card_view_btn.setChecked(True)
- # 重新以卡片方式渲染
- self._refresh_card_view()
- def _update_card_widths(self):
- """根据当前滚动区域宽度,动态设置卡片宽度"""
- # 仅在卡片视图下生效
- if getattr(self, "view_mode", "table") == "table":
- return
- if not hasattr(self, "card_scroll_area") or not hasattr(self, "card_layout"):
- return
- if not hasattr(self, "_card_widgets") or not self._card_widgets:
- return
- viewport = self.card_scroll_area.viewport()
- total_width = viewport.width()
- if total_width <= 0:
- return
- # 计算可用宽度:去掉左右外边距
- margins = self.card_layout.contentsMargins()
- available_width = total_width - margins.left() - margins.right()
- if available_width <= 0:
- return
- col_count = getattr(self, "card_columns", 5) or 5
- h_spacing = self.card_layout.horizontalSpacing() or 0
- total_spacing = (col_count - 1) * h_spacing
- if available_width <= total_spacing:
- return
- card_width = int((available_width - total_spacing) / col_count)
- if card_width <= 0:
- return
- alive_cards = []
- for card in self._card_widgets:
- if card is None:
- continue
- if sip.isdeleted(card):
- continue
- alive_cards.append(card)
- card.setMinimumWidth(card_width)
- card.setMaximumWidth(card_width)
- self._card_widgets = alive_cards
- def _update_form_widget_height(self):
- if not hasattr(self, "form_widget") or not self.form_widget:
- return
- hint_height = self.form_widget.sizeHint().height()
- if hint_height > 0:
- self.form_widget.setMaximumHeight(hint_height)
- def event(self, event):
- screen_change_event = getattr(QEvent, "ScreenChangeInternal", None)
- event_types = (
- QEvent.FontChange,
- QEvent.ApplicationFontChange,
- QEvent.StyleChange,
- )
- if screen_change_event is not None:
- event_types = event_types + (screen_change_event,)
- if event.type() in event_types:
- QTimer.singleShot(0, self._update_form_widget_height)
- return super().event(event)
-
- def export_to_excel(self):
- """导出出入库信息及关联地磅单"""
- inbounds = self.db.get_all_inbound_outbound()
- if not inbounds:
- QMessageBox.information(self, "提示", "暂无可导出的出入库记录。")
- return
-
- default_name = f"出入库记录导出_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
- file_path, _ = QFileDialog.getSaveFileName(
- self,
- "导出出入库记录",
- default_name,
- "Excel Files (*.xlsx)"
- )
- if not file_path:
- return
- if not file_path.lower().endswith(".xlsx"):
- file_path += ".xlsx"
-
- export_rows = []
- for inbound in inbounds:
- slips = self.db.get_weighing_slips_by_inbound_id(inbound.get('id'), include_voided=False)
- if not slips:
- export_rows.append(self._build_export_row(inbound, None))
- else:
- for slip in slips:
- export_rows.append(self._build_export_row(inbound, slip))
-
- try:
- df = pd.DataFrame(export_rows)
- df.to_excel(file_path, index=False)
- QMessageBox.information(self, "导出成功", f"已导出 {len(export_rows)} 条行记录。")
- except Exception as e:
- QMessageBox.critical(self, "导出失败", f"导出Excel失败:{str(e)}")
-
- def validate_form(self) -> tuple:
- """验证表单数据"""
- if not self._has_selected_date():
- return False, "请选择日期"
-
- if self.partner_combo.currentIndex() <= 0 or not self.partner_combo.currentText().strip():
- return False, "请选择往来单位"
-
- if not self.business_type_group.checkedButton():
- return False, "请选择业务类型"
-
- if self.product_combo.currentIndex() <= 0 or not self.product_combo.currentText().strip():
- return False, "请选择产品"
-
- quantity_value = self.quantity_input.value()
- if quantity_value <= 0 or quantity_value == -1:
- return False, "本次量必须大于0"
-
- if not self.vehicle_no_input.text().strip():
- return False, "请填写车牌号"
-
- return True, ""
-
- def save_inbound_outbound(self):
- """保存出入库单"""
- # 验证
- valid, error_msg = self.validate_form()
- if not valid:
- QMessageBox.warning(self, "验证失败", error_msg)
- return
-
- # 获取业务类型
- business_type = self.business_type_group.checkedButton().text()
-
- # 准备数据
- data = {
- 'date': self.date_input.date().toString("yyyy-MM-dd"),
- 'partner_company': self.partner_combo.currentText(),
- 'business_type': business_type,
- 'product': self.product_combo.currentText(),
- 'quantity': self.quantity_input.value(),
- 'plan_no': self.plan_no_display.text() if self.plan_no_display.text() != "未关联" else '',
- 'batch_no': self.batch_no_input.text().strip(),
- 'vehicle_no': self.vehicle_no_input.text().strip(),
- 'remarks': self.remarks_input.toPlainText().strip(),
- 'purchase_plan_id': self.current_plan_id
- }
-
- try:
- if self.editing_inbound_id:
- # 更新模式
- if self.db.update_inbound_outbound(self.editing_inbound_id, data):
- QMessageBox.information(self, "成功", "出入库单更新成功!")
- self.clear_form()
- self.refresh_list()
- else:
- QMessageBox.warning(self, "错误", "更新失败")
- else:
- # 新增模式
- self.db.insert_inbound_outbound(data)
- QMessageBox.information(self, "成功", "出入库单保存成功!")
- self.clear_form()
- self.refresh_list()
- except Exception as e:
- QMessageBox.critical(self, "错误", f"保存失败:{str(e)}")
-
- def clear_form(self):
- """清空表单(简化版界面仅重置ID输入框)"""
- # 旧版界面有完整的出入库表单,这里只需要保证不会因缺少控件报错
- self.editing_inbound_id = None
- self.current_plan_id = None
- # 简化版界面:只存在出入库单ID输入框
- if hasattr(self, "inbound_id_input"):
- self.inbound_id_input.clear()
- # 其余旧表单控件在当前界面不存在,直接返回即可,避免 AttributeError
- return
-
- def start_editing_inbound(self, inbound_id: int):
- """进入编辑模式并回显表单"""
- inbound = self.db.get_inbound_outbound_by_id(inbound_id)
- if not inbound:
- QMessageBox.warning(self, "错误", "未找到该出入库单")
- return
- if self._is_completed_status(inbound.get('status', '')):
- QMessageBox.information(self, "提示", "已完成的出入库单仅支持查看。")
- self.view_inbound(inbound_id)
- return
-
- self.editing_inbound_id = inbound_id
- self.save_btn.setText("更新")
-
- # 填充数据
- self.date_input.setDate(QDate.fromString(inbound['date'], "yyyy-MM-dd"))
-
- index = self.partner_combo.findText(inbound['partner_company'])
- if index >= 0:
- self.partner_combo.setCurrentIndex(index)
-
- if inbound['business_type'] == '入库':
- self.business_inbound_radio.setChecked(True)
- elif inbound['business_type'] == '出库':
- self.business_outbound_radio.setChecked(True)
-
- index = self.product_combo.findText(inbound['product'])
- if index >= 0:
- self.product_combo.setCurrentIndex(index)
-
- quantity = inbound.get('quantity', 0)
- if quantity and quantity > 0:
- self.quantity_input.setValue(quantity)
- else:
- self.quantity_input.setValue(-1)
- self.vehicle_no_input.setText(inbound.get('vehicle_no', ''))
- self.batch_no_input.setText(inbound.get('batch_no', ''))
-
- plan_no = inbound.get('plan_no', '')
- if plan_no:
- self.plan_no_display.setText(plan_no)
- else:
- self.plan_no_display.setText("未关联")
-
- status = inbound.get('status', '')
- self.status_display.setText(status)
- if status.startswith('已'):
- self.status_display.setStyleSheet(self.status_completed_style)
- else:
- self.status_display.setStyleSheet(self.status_pending_style)
-
- self.remarks_input.setPlainText(inbound.get('remarks', ''))
- self.current_plan_id = inbound.get('purchase_plan_id')
-
- def delete_inbound(self, inbound_id: int):
- """删除出入库单"""
- if not self._is_admin:
- QMessageBox.warning(self, "权限不足", "仅管理员可执行删除。")
- return
- inbound = self.db.get_inbound_outbound_by_id(inbound_id)
- if not inbound:
- QMessageBox.warning(self, "错误", "未找到该出入库单")
- return
- if self._is_completed_status(inbound.get('status', '')):
- QMessageBox.warning(self, "提示", "已完成的出入库单不可删除。")
- return
- linked_slip = self.db.get_weighing_slip_by_inbound_id(inbound_id, include_voided=False)
- if linked_slip:
- QMessageBox.warning(self, "提示", "该出入库单已关联地磅单,请先作废对应地磅单。")
- return
- msg = QMessageBox()
- msg.setIcon(QMessageBox.Question)
- msg.setWindowTitle("确认")
- msg.setText("确定要删除该出入库单吗?")
- msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
- msg.setDefaultButton(QMessageBox.No)
- msg.button(QMessageBox.Yes).setText("是")
- msg.button(QMessageBox.No).setText("否")
- reply = msg.exec_()
-
- if reply == QMessageBox.Yes:
- if self.db.delete_inbound_outbound(inbound_id):
- QMessageBox.information(self, "成功", "删除成功!")
- self.refresh_list()
- else:
- QMessageBox.warning(self, "错误", "删除失败")
-
- def jump_to_weighing(self, inbound_id: int):
- """从出入库单弹出地磅单填写对话框"""
- inbound = self.db.get_inbound_outbound_by_id(inbound_id)
- if not inbound:
- QMessageBox.warning(self, "错误", "未找到该出入库单")
- return
- # 判断是否为当天出入库单
- is_today = False
- inbound_date = inbound.get("date")
- if inbound_date is not None:
- today_str = datetime.now().strftime("%Y-%m-%d")
- if hasattr(inbound_date, "strftime"):
- inbound_date_str = inbound_date.strftime("%Y-%m-%d")
- else:
- inbound_date_str = str(inbound_date).strip()[:10]
- is_today = (inbound_date_str == today_str)
- # 历史出入库单:仅当已有地磅单时才允许打开,并且只读查看
- history_readonly_mode = False
- if not is_today:
- try:
- linked_slip = self.db.get_weighing_slip_by_inbound_id(inbound_id, include_voided=False)
- except Exception:
- linked_slip = None
- if not linked_slip:
- QMessageBox.warning(self, "提示", "该历史出入库单未关联任何地磅单,无法查看历史称重记录。")
- return
- history_readonly_mode = True
- else:
- # 当天已完成的订单:也只读查看,不显示读毛重/读皮重按钮,展示“历史订单不可以修改”
- try:
- linked_slip = self.db.get_weighing_slip_by_inbound_id(inbound_id, include_voided=False)
- except Exception:
- linked_slip = None
- if linked_slip:
- gross_val = linked_slip.get("gross_weight")
- tare_val = linked_slip.get("tare_weight")
- try:
- has_gross = (gross_val is not None and gross_val != "" and float(gross_val) > 0)
- except (TypeError, ValueError):
- has_gross = False
- try:
- has_tare = (tare_val is not None and tare_val != "" and float(tare_val) > 0)
- except (TypeError, ValueError):
- has_tare = False
- if has_gross and has_tare:
- history_readonly_mode = True
-
- # 1. 校验产品
- product_name = inbound.get('product', '').strip()
- if not product_name:
- QMessageBox.warning(self, "错误", "该出入库单缺少产品信息")
- return
-
- # 2. 校验往来单位
- partner_name = inbound.get('partner_company', '').strip()
- if not partner_name:
- QMessageBox.warning(self, "错误", "该出入库单缺少往来单位信息")
- return
-
- # 3. 自动维护主数据
- auto_messages = []
-
- # 校验并确保产品在货物表中存在
- cargo_status = self.db.ensure_cargo_active(product_name)
- if cargo_status == "created":
- auto_messages.append(f"新增货物:{product_name}")
- elif cargo_status == "restored":
- auto_messages.append(f"恢复货物:{product_name}")
-
- # 校验并确保往来单位在公司表中存在
- company_status = self.db.ensure_company_active(partner_name)
- if company_status == "created":
- auto_messages.append(f"新增公司:{partner_name}")
- elif company_status == "restored":
- auto_messages.append(f"恢复公司:{partner_name}")
-
- # 如果有自动维护操作,提示用户
- if auto_messages:
- QMessageBox.information(
- self,
- "提示",
- "已自动维护以下主数据:\n" + "\n".join(auto_messages)
- )
-
- # 4. 弹出地磅单填写/查看对话框
- dialog = WeighingSlipDialog(inbound, self.db, parent=self, current_user=self.current_user)
- if history_readonly_mode and hasattr(dialog, "set_history_mode"):
- dialog.set_history_mode()
- dialog.exec_()
-
- # 对话框关闭后刷新列表
- self.refresh_list()
- def view_inbound(self, inbound_id: int):
- """查看出入库单详情"""
- inbound = self.db.get_inbound_outbound_by_id(inbound_id)
- if not inbound:
- QMessageBox.warning(self, "错误", "未找到该出入库单")
- return
- weighing_tab = getattr(self.main_window, 'weighing_tab', None) if self.main_window else None
- dialog = InboundDetailDialog(inbound, self.db, weighing_tab=weighing_tab, parent=self)
- dialog.exec_()
-
- def generate_batch_no(self):
- """自动生成批次号:PC-YYYYMMDD001格式"""
- if not self._has_selected_date():
- return
- # 获取当前日期
- current_date = self.date_input.date()
- date_str = current_date.toString("yyyy-MM-dd")
- date_part = date_str.replace('-', '')
-
- # 查询当天最大的批次号序号
- max_sequence = self.db.get_max_batch_no_sequence(date_str)
-
- # 生成下一个序号
- next_sequence = max_sequence + 1
-
- # 生成批次号:PC-YYYYMMDD001
- batch_no = f"PC-{date_part}{next_sequence:03d}"
-
- # 如果批次号输入框为空,则自动填充
- if not self.batch_no_input.text().strip():
- self.batch_no_input.setText(batch_no)
-
- def on_date_changed(self, date: QDate):
- """日期改变时的处理"""
- # 只有在新增模式下(非编辑模式)且批次号为空时,才自动生成新的批次号
- if not self.editing_inbound_id and not self.batch_no_input.text().strip():
- self.generate_batch_no()
-
- def on_batch_no_editing_finished(self):
- """批次号输入框失去焦点时的处理"""
- # 只有在新增模式下(非编辑模式)且批次号为空时,才自动生成
- if not self.editing_inbound_id and not self.batch_no_input.text().strip():
- self.generate_batch_no()
- def on_search_text_changed(self, text: str):
- """列表区域模糊检索"""
- self.search_keyword = text.strip()
- self.refresh_list()
- def on_filter_changed(self):
- """筛选条件变化"""
- selected_items = self.status_filter_dropdown.get_selected_items()
- self.show_all = "全部" in selected_items
- self.show_pending_inbound = "待入库" in selected_items or self.show_all
- self.show_pending_outbound = "待出库" in selected_items or self.show_all
- # 30分钟内已完成的筛选
- recent_completed_selection = self.recent_completed_dropdown.currentText()
- self.show_recent_completed = (recent_completed_selection == "30分钟内已完成的")
- self.show_all_completed = (recent_completed_selection == "全部")
- self.refresh_list()
-
- def on_today_filter_changed(self, state: int):
- """只看当天勾选框变化"""
- self.show_today_only = self.today_only_checkbox.isChecked()
- self.refresh_list()
- def on_business_type_changed(self, checked: bool):
- """业务类型切换时同步状态显示(仅新增模式)"""
- if not checked or self.editing_inbound_id:
- return
- if self.business_inbound_radio.isChecked():
- status_text = "待入库"
- elif self.business_outbound_radio.isChecked():
- status_text = "待出库"
- else:
- return
- self.status_display.setText(status_text)
- self.status_display.setStyleSheet(self.status_pending_style)
-
- @staticmethod
- def _ton_value_from_kg(value: Optional[float]):
- tons = kg_to_tons(value)
- if tons is None:
- return ""
- return round(tons, 3)
-
- def _build_export_row(self, inbound: dict, slip: Optional[dict]) -> dict:
- """组装导出行"""
- row = {
- "出入库ID": inbound.get('id'),
- "计划号": inbound.get('plan_no', ''),
- "批次号": inbound.get('batch_no', ''),
- "日期": inbound.get('date', ''),
- "往来单位": inbound.get('partner_company', ''),
- "业务类型": inbound.get('business_type', ''),
- "产品": inbound.get('product', ''),
- "车牌号": inbound.get('vehicle_no', ''),
- "本次量(t)": round(inbound.get('quantity', 0), 3) if inbound.get('quantity') is not None else "",
- "状态": inbound.get('status', ''),
- "备注": inbound.get('remarks', '')
- }
-
- if slip:
- row.update({
- "地磅单ID": slip.get('id'),
- "地磅单状态": "已作废" if slip.get('is_voided') else "有效",
- "毛重(t)": self._ton_value_from_kg(slip.get('gross_weight')),
- "毛重时间": slip.get('gross_weight_time', ''),
- "皮重(t)": self._ton_value_from_kg(slip.get('tare_weight')),
- "皮重时间": slip.get('tare_weight_time', ''),
- "扣杂(t)": self._ton_value_from_kg(slip.get('deduction')),
- "净重(t)": self._ton_value_from_kg(slip.get('net_weight')),
- "称重时间": slip.get('created_at', ''),
- })
- else:
- row.update({
- "地磅单ID": "",
- "地磅单状态": "",
- "毛重(t)": "",
- "毛重时间": "",
- "皮重(t)": "",
- "皮重时间": "",
- "扣杂(t)": "",
- "净重(t)": "",
- "称重时间": "",
- })
- return row
- def _has_selected_date(self) -> bool:
- if not self.date_input:
- return False
- return not self.date_input.is_empty()
-
- def _format_date_display(self, date_str: str) -> str:
- """格式化日期显示:今天/明天/后天/大后天 + 实际日期"""
- if not date_str or date_str == "-":
- return "-"
-
- try:
- from datetime import datetime, timedelta
- # 解析日期字符串
- date_obj = datetime.strptime(date_str, "%Y-%m-%d").date()
- today = datetime.now().date()
-
- # 计算日期差
- delta = (date_obj - today).days
-
- # 根据日期差显示不同的文本
- if delta == 0:
- day_text = "今天"
- elif delta == 1:
- day_text = "明天"
- elif delta == 2:
- day_text = "后天"
- else:
- day_text = "大后天"
-
- # 返回格式:今天/明天/后天/大后天\n实际日期
- return f"{day_text}\n{date_str}"
- except Exception:
- # 如果解析失败,直接返回原日期
- return date_str
-
- def print_weighing_slip(self, inbound_id: int):
- """打印出入库单关联的地磅单"""
- slip = self.db.get_weighing_slip_by_inbound_id(inbound_id, include_voided=False)
- if not slip:
- QMessageBox.warning(self, "提示", "该出入库单尚未生成地磅单,无法打印。")
- return
-
- try:
- printer = Printer()
- printer.preview_weighing_slip(slip, copies=1)
- except Exception as e:
- QMessageBox.critical(self, "错误", f"打印失败:{str(e)}")
- class InboundDetailDialog(QDialog):
- """出入库单详情对话框"""
- def __init__(self, inbound: dict, db: Database, weighing_tab=None, parent=None):
- super().__init__(parent)
- self.inbound = inbound
- self.db = db
- self.weighing_tab = weighing_tab
- self.slip = self.db.get_weighing_slip_by_inbound_id(inbound['id'], include_voided=True)
- self.setWindowTitle("出入库单详情")
- self.resize(560, 480)
- self.setStyleSheet("""
- QWidget {
- font-size: 16px;
- font-family: "微软雅黑";
- }
- QGroupBox {
- font-weight: bold;
- }
- """)
- self.init_ui()
- @staticmethod
- def _format_weight_in_tons(kg_value: float, digits: int = 3) -> str:
- if kg_value is None:
- kg_value = 0
- return f"{kg_value / 1000:.{digits}f}"
- def init_ui(self):
- layout = QVBoxLayout()
- form = QFormLayout()
- form.setLabelAlignment(Qt.AlignRight)
- form.setFormAlignment(Qt.AlignTop)
- def _fmt(value, default=""):
- if value is None:
- return default
- if isinstance(value, float):
- return f"{value:.3f}"
- return str(value)
- info_fields = [
- ("状态", self.inbound.get('status', '')),
- ("业务类型", self.inbound.get('business_type', '')),
- ("日期", self.inbound.get('date', '')),
- ("往来单位", self.inbound.get('partner_company', '')),
- ("产品", self.inbound.get('product', '')),
- ("本次量(t)", _fmt(self.inbound.get('quantity'))),
- ("车牌号", self.inbound.get('vehicle_no', '')),
- ("计划号", self.inbound.get('plan_no', '')),
- ("批次号", self.inbound.get('batch_no', '')),
- ]
- for label_text, value in info_fields:
- label = QLabel(str(value) if value else "——")
- label.setWordWrap(True)
- form.addRow(f"{label_text}:", label)
- remarks_label = QLabel(self.inbound.get('remarks', '') or "无")
- remarks_label.setWordWrap(True)
- remarks_label.setStyleSheet("color: black;")
- form.addRow("备注:", remarks_label)
- layout.addLayout(form)
- layout.addWidget(self._build_slip_section())
- btn_layout = QHBoxLayout()
- btn_layout.addStretch()
- close_btn = QPushButton("关闭")
- close_btn.setMinimumWidth(100)
- apply_button_style(close_btn, 'normal')
- close_btn.clicked.connect(self.accept)
- btn_layout.addWidget(close_btn)
- btn_layout.addStretch()
- layout.addLayout(btn_layout)
- self.setLayout(layout)
- def _build_slip_section(self) -> QGroupBox:
- group = QGroupBox("关联地磅单")
- inner_layout = QVBoxLayout()
- if not self.slip:
- inner_layout.addWidget(QLabel("暂无关联地磅单。"))
- else:
- status = "已作废" if self.slip.get('is_voided') else "有效"
- summary = QLabel(
- f"地磅单ID:{self.slip.get('id')} · 状态:{status} · 净重:{self._format_weight_in_tons(self.slip.get('net_weight', 0))} t"
- )
- summary.setStyleSheet("")
- inner_layout.addWidget(summary)
- detail_rows = [
- ("车牌号", self.slip.get('vehicle_no', '')),
- ("毛重(t)", self._format_weight_in_tons(self.slip.get('gross_weight', 0))),
- ("皮重(t)", self._format_weight_in_tons(self.slip.get('tare_weight', 0))),
- ("扣杂(t)", self._format_weight_in_tons(self.slip.get('deduction', 0))),
- ("供应商", self.slip.get('supplier', '')),
- ("收货单位", self.slip.get('consignee', '')),
- ]
- for title, value in detail_rows:
- row_label = QLabel(f"{title}:{value or '——'}")
- row_label.setWordWrap(True)
- inner_layout.addWidget(row_label)
- btn_layout = QHBoxLayout()
- btn_layout.addStretch()
- view_btn = QPushButton("查看地磅单详情")
- apply_button_style(view_btn, 'normal')
- if not self.weighing_tab:
- view_btn.setEnabled(False)
- view_btn.setToolTip("未能获取地磅单页面,无法打开详情。")
- view_btn.clicked.connect(self.open_weighing_detail)
- btn_layout.addWidget(view_btn)
- btn_layout.addStretch()
- inner_layout.addLayout(btn_layout)
- group.setLayout(inner_layout)
- return group
- def open_weighing_detail(self):
- if not self.slip:
- QMessageBox.warning(self, "提示", "暂无地磅单信息。")
- return
- if not self.weighing_tab:
- QMessageBox.warning(self, "提示", "无法打开地磅单详情。")
- return
- self.weighing_tab.show_detail(self.slip['id'])
- class WeighingSlipDialog(QDialog):
- """地磅单填写对话框"""
- instrument_weight_received = pyqtSignal(float, str) # 重量, 类型(gross/tare)
-
- def __init__(self, inbound: dict, db: Database, parent=None, current_user: Optional[Dict] = None):
- super().__init__(parent)
- self.inbound = inbound
- self.db = db
- self.current_user = current_user or {}
- self.is_admin = self.current_user.get('role') == 'admin'
- self.main_window = getattr(parent, "main_window", None) if parent else None
- self.printer = Printer()
- self.print_copies = 1
- self._is_clearing_form = False
- self.editing_slip_id: Optional[int] = None
- self.existing_slip = None
-
- # 检查是否已存在地磅单
- try:
- self.existing_slip = self.db.get_weighing_slip_by_inbound_id(inbound['id'], include_voided=False)
- if self.existing_slip:
- self.editing_slip_id = self.existing_slip['id']
- except Exception as e:
- logger.warning(f"查询地磅单关联关系失败: {str(e)}")
-
- self.setWindowTitle("地磅单填写")
- self.setMinimumSize(1400, 600) # 增加宽度和高度
- self.resize(1400, 700) # 设置初始大小
- # 初始化地磅相关变量
- self.instrument_weight = None
- # 串口读取相关
- self._serial_reader: Optional[SerialReader] = None
- self._pending_read_target: Optional[str] = None # 'gross' or 'tare'
- self.instrument_weight_received.connect(self._on_instrument_weight_received)
- self.init_ui()
- self._setup_field_permissions()
- self.refresh_dropdowns()
- self._prefill_from_inbound()
- # 绑定实时仪表数据显示
- try:
- self._attach_serial_reader()
- except Exception:
- pass
- def set_history_mode(self):
- """
- 历史出入库单查看模式:只允许查看,不允许修改毛重、皮重,也不允许再次读数或保存/清空
- """
- # 历史订单:隐藏读毛重/读皮重按钮,在原区域显示提示文字
- if hasattr(self, "gross_btn_widget"):
- self.gross_btn_widget.hide()
- if hasattr(self, "tare_btn_widget"):
- self.tare_btn_widget.hide()
- if not hasattr(self, "history_readonly_label"):
- self.history_readonly_label = QLabel("历史订单不可以修改")
- self.history_readonly_label.setFont(QFont("微软雅黑", 18, QFont.Bold))
- self.history_readonly_label.setAlignment(Qt.AlignCenter)
- if hasattr(self, "buttons_layout"):
- self.buttons_layout.addWidget(self.history_readonly_label)
- # 毛重、皮重及时间字段设为只读
- if hasattr(self, "gross_weight_input"):
- try:
- self.gross_weight_input.setReadOnly(True)
- except Exception:
- pass
- if hasattr(self, "gross_weight_time"):
- try:
- self.gross_weight_time.setReadOnly(True)
- if self.gross_weight_time.lineEdit():
- self.gross_weight_time.lineEdit().setReadOnly(True)
- except Exception:
- pass
- if hasattr(self, "tare_weight_input"):
- try:
- self.tare_weight_input.setReadOnly(True)
- except Exception:
- pass
- if hasattr(self, "tare_weight_time"):
- try:
- self.tare_weight_time.setReadOnly(True)
- if self.tare_weight_time.lineEdit():
- self.tare_weight_time.lineEdit().setReadOnly(True)
- except Exception:
- pass
- # 禁用保存、清空按钮(始终允许关闭)
- if hasattr(self, "save_btn"):
- self.save_btn.setEnabled(False)
- if hasattr(self, "clear_btn"):
- self.clear_btn.setEnabled(False)
- def _setup_field_permissions(self):
- """根据用户权限设置字段的可编辑性"""
- # admin用户可以编辑毛重、皮重、毛重时间、皮重时间
- # 其他用户只能查看,不能编辑
- can_edit = self.is_admin
- # 设置毛重字段
- if hasattr(self, 'gross_weight_input'):
- self.gross_weight_input.setReadOnly(not can_edit)
- if not can_edit:
- self.gross_weight_input.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
- # 设置毛重时间字段
- if hasattr(self, 'gross_weight_time'):
- self.gross_weight_time.setReadOnly(not can_edit)
- if not can_edit and self.gross_weight_time.lineEdit():
- self.gross_weight_time.lineEdit().setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
- # 设置皮重字段
- if hasattr(self, 'tare_weight_input'):
- self.tare_weight_input.setReadOnly(not can_edit)
- if not can_edit:
- self.tare_weight_input.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
- # 设置皮重时间字段
- if hasattr(self, 'tare_weight_time'):
- self.tare_weight_time.setReadOnly(not can_edit)
- if not can_edit and self.tare_weight_time.lineEdit():
- self.tare_weight_time.lineEdit().setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
- def init_ui(self):
- """初始化界面"""
- layout = QHBoxLayout() # 主布局改为水平布局
- layout.setSpacing(15)
- layout.setContentsMargins(15, 15, 15, 15)
- # 左侧区域 - 仪表数据、读毛重、读皮重
- left_panel = QWidget()
- # 移除固定宽度,让左右各占一半
- left_layout = QVBoxLayout(left_panel)
- left_layout.setSpacing(30)
- left_layout.setContentsMargins(20, 20, 20, 20)
- # 仪表数据显示区域 - 改成黑底白字,大区域
- instrument_label = QLabel("仪表数据")
- instrument_label.setFont(QFont("微软雅黑", 32, QFont.Bold))
- instrument_label.setAlignment(Qt.AlignCenter)
- instrument_label.setStyleSheet("color: black; margin-bottom: 10px;")
- left_layout.addWidget(instrument_label)
- self.instrument_weight_label = QLabel("0.00 kg")
- self.instrument_weight_label.setFont(QFont("微软雅黑", 42, QFont.Bold))
- self.instrument_weight_label.setStyleSheet("""
- QLabel {
- color: white;
- background-color: black;
- border: 3px solid #333;
- border-radius: 15px;
- padding: 25px;
- }
- """)
- self.instrument_weight_label.setMinimumHeight(240) # 高度增加一倍
- self.instrument_weight_label.setAlignment(Qt.AlignCenter)
- left_layout.addWidget(self.instrument_weight_label)
- # 读毛重和读皮重按钮放在一行(按钮下方带提示文字)
- self.buttons_layout = QHBoxLayout()
- self.buttons_layout.setSpacing(30)
- # 读毛重按钮 - 圆形 + 提示(醒目橙色,适合红绿色盲)
- self.read_gross_btn = QPushButton("满车毛重")
- self.read_gross_btn.setFont(QFont("微软雅黑", 22, QFont.Bold))
- self.read_gross_btn.setMinimumHeight(140)
- self.read_gross_btn.setMinimumWidth(140)
- self.read_gross_btn.setMaximumHeight(140)
- self.read_gross_btn.setMaximumWidth(140)
- self.read_gross_btn.setStyleSheet("""
- QPushButton {
- background-color: #FF6B35;
- color: white;
- border: none;
- border-radius: 70px;
- padding: 10px;
- box-shadow: 0 4px 8px rgba(255, 107, 53, 0.4);
- }
- QPushButton:hover {
- background-color: #E55A2B;
- box-shadow: 0 6px 12px rgba(255, 107, 53, 0.6);
- }
- QPushButton:pressed {
- background-color: #CC4F26;
- box-shadow: 0 2px 4px rgba(255, 107, 53, 0.4);
- }
- """)
- self.read_gross_btn.clicked.connect(lambda: self._start_read_from_instrument('gross'))
- self.gross_btn_widget = QWidget()
- gross_btn_layout = QVBoxLayout()
- gross_btn_layout.setContentsMargins(0, 0, 0, 0)
- gross_btn_layout.setSpacing(6)
- gross_btn_layout.addWidget(self.read_gross_btn, alignment=Qt.AlignCenter)
- gross_hint_label = QLabel("满车时点击")
- gross_hint_label.setFont(QFont("微软雅黑", 12))
- gross_hint_label.setAlignment(Qt.AlignCenter)
- gross_btn_layout.addWidget(gross_hint_label)
- self.gross_btn_widget.setLayout(gross_btn_layout)
- self.buttons_layout.addWidget(self.gross_btn_widget)
- # 读皮重按钮 - 圆形 + 提示(醒目紫色,适合红绿色盲)
- self.read_tare_btn = QPushButton("空车皮重")
- self.read_tare_btn.setFont(QFont("微软雅黑", 22, QFont.Bold))
- self.read_tare_btn.setMinimumHeight(140)
- self.read_tare_btn.setMinimumWidth(140)
- self.read_tare_btn.setMaximumHeight(140)
- self.read_tare_btn.setMaximumWidth(140)
- self.read_tare_btn.setStyleSheet("""
- QPushButton {
- background-color: #8B5CF6;
- color: white;
- border: none;
- border-radius: 70px;
- padding: 10px;
- box-shadow: 0 4px 8px rgba(139, 92, 246, 0.4);
- }
- QPushButton:hover {
- background-color: #7C3AED;
- box-shadow: 0 6px 12px rgba(139, 92, 246, 0.6);
- }
- QPushButton:pressed {
- background-color: #6D28D9;
- box-shadow: 0 2px 4px rgba(139, 92, 246, 0.4);
- }
- """)
- self.read_tare_btn.clicked.connect(lambda: self._start_read_from_instrument('tare'))
- self.tare_btn_widget = QWidget()
- tare_btn_layout = QVBoxLayout()
- tare_btn_layout.setContentsMargins(0, 0, 0, 0)
- tare_btn_layout.setSpacing(6)
- tare_btn_layout.addWidget(self.read_tare_btn, alignment=Qt.AlignCenter)
- tare_hint_label = QLabel("空车时点击")
- tare_hint_label.setFont(QFont("微软雅黑", 12))
- tare_hint_label.setAlignment(Qt.AlignCenter)
- tare_btn_layout.addWidget(tare_hint_label)
- self.tare_btn_widget.setLayout(tare_btn_layout)
- self.buttons_layout.addWidget(self.tare_btn_widget)
- left_layout.addLayout(self.buttons_layout)
- left_layout.addStretch()
- layout.addWidget(left_panel, 1) # 左右各占一半
- # 右侧区域 - 所有数据项(带滚动条)
- right_panel = QWidget()
- right_layout = QVBoxLayout(right_panel)
- right_layout.setSpacing(10)
- right_layout.setContentsMargins(10, 10, 10, 10)
- # 标题
- title = QLabel("地磅单填写")
- title_font = QFont("微软雅黑", 14, QFont.Bold)
- title.setFont(title_font)
- title.setAlignment(Qt.AlignCenter)
- right_layout.addWidget(title)
- # 创建滚动区域
- scroll_area = QScrollArea()
- scroll_area.setWidgetResizable(True)
- scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
- # 不显示纵向滚动条
- scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
- # 创建表单
- form_widget = self.create_form_widget()
- scroll_area.setWidget(form_widget)
- right_layout.addWidget(scroll_area)
- # 按钮区域
- button_layout = QHBoxLayout()
- button_layout.addStretch()
- self.save_btn = QPushButton("保存")
- self.save_btn.setMinimumHeight(45)
- self.save_btn.setMinimumWidth(130)
- self.save_btn.setFont(QFont("微软雅黑", 16, QFont.Bold))
- apply_button_style(self.save_btn, 'green')
- self.save_btn.clicked.connect(self.save_weighing_slip)
- self.save_btn.setShortcut(QKeySequence("Ctrl+S"))
- self.clear_btn = QPushButton("清空")
- self.clear_btn.setMinimumHeight(45)
- self.clear_btn.setMinimumWidth(130)
- self.clear_btn.setFont(QFont("微软雅黑", 16))
- apply_button_style(self.clear_btn, 'normal')
- self.clear_btn.clicked.connect(self.clear_form)
- self.clear_btn.setVisible(False) # 出入库管理地磅单弹窗中隐藏清空按钮
- self.print_btn = QPushButton("打印")
- self.print_btn.setMinimumHeight(45)
- self.print_btn.setMinimumWidth(130)
- self.print_btn.setFont(QFont("微软雅黑", 16))
- apply_button_style(self.print_btn, 'blue')
- self.print_btn.clicked.connect(self._dialog_print_weighing_slip)
- close_btn = QPushButton("关闭")
- close_btn.setMinimumHeight(45)
- close_btn.setMinimumWidth(130)
- close_btn.setFont(QFont("微软雅黑", 16))
- apply_button_style(close_btn, 'normal')
- close_btn.clicked.connect(self.accept)
- button_layout.addWidget(self.save_btn)
- button_layout.addWidget(self.print_btn)
- button_layout.addWidget(self.clear_btn)
- button_layout.addWidget(close_btn)
- button_layout.addStretch()
- right_layout.addLayout(button_layout)
- layout.addWidget(right_panel, 1) # 左右各占一半
- self.setLayout(layout)
-
- def create_form_widget(self) -> QWidget:
- """创建地磅单填写表单"""
- widget = QWidget()
- layout = QVBoxLayout()
- layout.setSpacing(15)
- layout.setContentsMargins(15, 15, 15, 15)
- # 表单区域 - 使用垂直布局,逐行排列
- form_layout = QVBoxLayout()
- form_layout.setSpacing(15)
- # 列表顶部对齐,允许每行宽度填满父容器
- try:
- form_layout.setAlignment(Qt.AlignTop)
- except Exception:
- pass
- # 第一行:车号(必填)
- vehicle_layout = QHBoxLayout()
- vehicle_layout.setSpacing(10)
- vehicle_label = QLabel("<span style='color: black;'>车号 *</span>:")
- vehicle_label.setFont(QFont("微软雅黑", 16))
- vehicle_label.setTextFormat(Qt.RichText)
- vehicle_label.setMinimumWidth(120)
- vehicle_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
- self.vehicle_no_input = QLineEdit()
- self.vehicle_no_input.setMinimumHeight(45)
- self.vehicle_no_input.setFont(QFont("微软雅黑", 16))
- self.vehicle_no_input.setMinimumWidth(0)
- self.vehicle_no_input.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
- self.vehicle_no_input.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
- # 右侧所有字段设为只读(不可编辑)
- try:
- self.vehicle_no_input.setReadOnly(True)
- except Exception:
- pass
- vehicle_layout.addWidget(vehicle_label)
- vehicle_layout.addWidget(self.vehicle_no_input, 1)
- form_layout.addLayout(vehicle_layout)
- # 第二行:货物名称(必填)
- cargo_layout = QHBoxLayout()
- cargo_layout.setSpacing(10)
- cargo_label = QLabel("<span style='color: black;'>货物名称 *</span>:")
- cargo_label.setFont(QFont("微软雅黑", 16))
- cargo_label.setTextFormat(Qt.RichText)
- cargo_label.setMinimumWidth(120)
- cargo_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
- self.cargo_combo = QComboBox()
- self.cargo_combo.setMinimumHeight(45)
- self.cargo_combo.setFont(QFont("微软雅黑", 16))
- self.cargo_combo.setEditable(False)
- self.cargo_combo.setMinimumWidth(0)
- self.cargo_combo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
- try:
- self.cargo_combo.setEnabled(False)
- except Exception:
- pass
- cargo_layout.addWidget(cargo_label)
- cargo_layout.addWidget(self.cargo_combo, 1)
- form_layout.addLayout(cargo_layout)
- # 第三行:业务类型(必填)
- business_layout = QHBoxLayout()
- business_layout.setSpacing(10)
- business_label = QLabel("<span style='color: black;'>业务类型 *</span>:")
- business_label.setFont(QFont("微软雅黑", 16))
- business_label.setTextFormat(Qt.RichText)
- business_label.setMinimumWidth(120)
- business_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
- self.business_type_group = QButtonGroup()
- self.business_sale_radio = QRadioButton("出库")
- self.business_purchase_radio = QRadioButton("入库")
- self.business_sale_radio.setFont(QFont("微软雅黑", 16))
- self.business_purchase_radio.setFont(QFont("微软雅黑", 16))
- self.business_sale_radio.setStyleSheet("")
- self.business_purchase_radio.setStyleSheet("")
- self.business_type_group.addButton(self.business_sale_radio, 0)
- self.business_type_group.addButton(self.business_purchase_radio, 1)
- # 不允许修改业务类型
- try:
- self.business_sale_radio.setEnabled(False)
- self.business_purchase_radio.setEnabled(False)
- except Exception:
- pass
- business_radio_layout = QHBoxLayout()
- business_radio_layout.addWidget(self.business_sale_radio)
- business_radio_layout.addWidget(self.business_purchase_radio)
- business_radio_layout.addStretch()
- business_widget = QWidget()
- business_widget.setLayout(business_radio_layout)
- business_layout.addWidget(business_label)
- business_layout.addWidget(business_widget, 1)
- form_layout.addLayout(business_layout)
- # 第四行:毛重(必填)
- gross_weight_layout = QHBoxLayout()
- gross_weight_layout.setSpacing(10)
- gross_weight_label = QLabel("<span style='color: white;'>毛重(kg) *</span>:")
- gross_weight_label.setFont(QFont("微软雅黑", 16))
- gross_weight_label.setTextFormat(Qt.RichText)
- gross_weight_label.setMinimumWidth(120)
- gross_weight_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
- gross_weight_label.setStyleSheet("""
- QLabel {
- background-color: #1E40AF;
- color: white;
- padding: 4px 0px 4px 8px;
- border: 1px solid #1D4ED8;
- border-radius: 4px;
- }
- """)
- self.gross_weight_input = EmptyDoubleSpinBox()
- self.gross_weight_input.setMinimumHeight(45)
- self.gross_weight_input.setFont(QFont("微软雅黑", 16))
- self.gross_weight_input.setDecimals(2)
- self.gross_weight_input.setMinimum(-1)
- self.gross_weight_input.setMaximum(999999)
- self.gross_weight_input.setSpecialValueText("")
- self.gross_weight_input.setValue(-1)
- self.gross_weight_input.setMinimumWidth(0)
- self.gross_weight_input.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
- self.gross_weight_input.valueChanged.connect(self.on_gross_weight_changed)
- # 毛重删除按钮 - 隐藏
- gross_weight_clear_btn = QPushButton("删除")
- gross_weight_clear_btn.setMinimumHeight(45)
- gross_weight_clear_btn.setFont(QFont("微软雅黑", 12))
- gross_weight_clear_btn.setMaximumWidth(60)
- apply_button_style(gross_weight_clear_btn, 'red')
- gross_weight_clear_btn.clicked.connect(lambda: self.gross_weight_input.setValue(-1))
- gross_weight_clear_btn.hide() # 隐藏删除按钮
- gross_weight_input_layout = QHBoxLayout()
- gross_weight_input_layout.setContentsMargins(0, 0, 0, 0)
- gross_weight_input_layout.setSpacing(5)
- gross_weight_input_layout.addWidget(self.gross_weight_input)
- gross_weight_input_layout.addWidget(gross_weight_clear_btn)
- gross_weight_widget = QWidget()
- gross_weight_widget.setLayout(gross_weight_input_layout)
- gross_weight_layout.addWidget(gross_weight_label)
- gross_weight_layout.addWidget(gross_weight_widget, 1)
- form_layout.addLayout(gross_weight_layout)
- # 第五行:毛重时间(必填)
- gross_time_layout = QHBoxLayout()
- gross_time_layout.setSpacing(10)
- gross_time_label = QLabel("<span style='color: black;'>毛重时间 *</span>:")
- gross_time_label.setFont(QFont("微软雅黑", 16))
- gross_time_label.setTextFormat(Qt.RichText)
- gross_time_label.setMinimumWidth(120)
- gross_time_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
- self.gross_weight_time = EmptyDateTimeEdit()
- self.gross_weight_time.setMinimumHeight(45)
- self.gross_weight_time.setFont(QFont("微软雅黑", 16))
- self.gross_weight_time.setCalendarPopup(True)
- self.gross_weight_time.setDateTime(QDateTime())
- self.gross_weight_time.setDisplayFormat("yyyy-MM-dd HH:mm:ss")
- self.gross_weight_time.setMinimumWidth(0)
- self.gross_weight_time.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
- # 清空显示
- if self.gross_weight_time.lineEdit():
- self.gross_weight_time.lineEdit().setText("")
- QTimer.singleShot(0, lambda: self.gross_weight_time.lineEdit().setText("") if self.gross_weight_time.lineEdit() else None)
- # 毛重时间当前时间按钮 - 隐藏
- gross_time_now_btn = QPushButton("时间")
- gross_time_now_btn.setMinimumHeight(45)
- gross_time_now_btn.setFont(QFont("微软雅黑", 12))
- gross_time_now_btn.setMaximumWidth(80)
- apply_button_style(gross_time_now_btn, 'blue')
- gross_time_now_btn.clicked.connect(lambda: self._set_time_to_now(self.gross_weight_time))
- gross_time_now_btn.hide() # 隐藏时间按钮
- # 将时间框和按钮放在同一个水平布局中
- gross_time_input_layout = QHBoxLayout()
- gross_time_input_layout.setContentsMargins(0, 0, 0, 0)
- gross_time_input_layout.setSpacing(5)
- gross_time_input_layout.addWidget(self.gross_weight_time)
- gross_time_input_layout.addWidget(gross_time_now_btn)
- gross_time_widget = QWidget()
- gross_time_widget.setLayout(gross_time_input_layout)
- gross_time_layout.addWidget(gross_time_label)
- gross_time_layout.addWidget(gross_time_widget, 1)
- form_layout.addLayout(gross_time_layout)
- # 第六行:皮重(必填)
- tare_weight_layout = QHBoxLayout()
- tare_weight_layout.setSpacing(10)
- tare_weight_label = QLabel("<span style='color: white;'>皮重(kg) *</span>:")
- tare_weight_label.setFont(QFont("微软雅黑", 16))
- tare_weight_label.setTextFormat(Qt.RichText)
- tare_weight_label.setMinimumWidth(120)
- tare_weight_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
- tare_weight_label.setStyleSheet("""
- QLabel {
- background-color: #1E40AF;
- color: white;
- padding: 4px 0px 4px 8px;
- border: 1px solid #1D4ED8;
- border-radius: 4px;
- }
- """)
- self.tare_weight_input = EmptyDoubleSpinBox()
- self.tare_weight_input.setMinimumHeight(45)
- self.tare_weight_input.setFont(QFont("微软雅黑", 16))
- self.tare_weight_input.setDecimals(2)
- self.tare_weight_input.setMinimum(-1)
- self.tare_weight_input.setMaximum(999999)
- self.tare_weight_input.setSpecialValueText("")
- self.tare_weight_input.setValue(-1)
- self.tare_weight_input.setMinimumWidth(0)
- self.tare_weight_input.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
- self.tare_weight_input.valueChanged.connect(self.on_tare_weight_changed)
- # 皮重删除按钮 - 隐藏
- tare_weight_clear_btn = QPushButton("删除")
- tare_weight_clear_btn.setMinimumHeight(45)
- tare_weight_clear_btn.setFont(QFont("微软雅黑", 12))
- tare_weight_clear_btn.setMaximumWidth(60)
- apply_button_style(tare_weight_clear_btn, 'red')
- tare_weight_clear_btn.clicked.connect(lambda: self.tare_weight_input.setValue(-1))
- tare_weight_clear_btn.hide() # 隐藏删除按钮
- tare_weight_input_layout = QHBoxLayout()
- tare_weight_input_layout.setContentsMargins(0, 0, 0, 0)
- tare_weight_input_layout.setSpacing(5)
- tare_weight_input_layout.addWidget(self.tare_weight_input)
- tare_weight_input_layout.addWidget(tare_weight_clear_btn)
- tare_weight_widget = QWidget()
- tare_weight_widget.setLayout(tare_weight_input_layout)
- tare_weight_layout.addWidget(tare_weight_label)
- tare_weight_layout.addWidget(tare_weight_widget, 1)
- form_layout.addLayout(tare_weight_layout)
- # 第七行:皮重时间(必填)
- tare_time_layout = QHBoxLayout()
- tare_time_layout.setSpacing(10)
- tare_time_label = QLabel("<span style='color: black;'>皮重时间 *</span>:")
- tare_time_label.setFont(QFont("微软雅黑", 16))
- tare_time_label.setTextFormat(Qt.RichText)
- tare_time_label.setMinimumWidth(120)
- tare_time_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
- self.tare_weight_time = EmptyDateTimeEdit()
- self.tare_weight_time.setMinimumHeight(45)
- self.tare_weight_time.setFont(QFont("微软雅黑", 16))
- self.tare_weight_time.setCalendarPopup(True)
- self.tare_weight_time.setDateTime(QDateTime())
- self.tare_weight_time.setDisplayFormat("yyyy-MM-dd HH:mm:ss")
- self.tare_weight_time.setMinimumWidth(0)
- self.tare_weight_time.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
- # 清空显示
- if self.tare_weight_time.lineEdit():
- self.tare_weight_time.lineEdit().setText("")
- QTimer.singleShot(0, lambda: self.tare_weight_time.lineEdit().setText("") if self.tare_weight_time.lineEdit() else None)
- # 皮重时间当前时间按钮 - 隐藏
- tare_time_now_btn = QPushButton("时间")
- tare_time_now_btn.setMinimumHeight(45)
- tare_time_now_btn.setFont(QFont("微软雅黑", 12))
- tare_time_now_btn.setMaximumWidth(80)
- apply_button_style(tare_time_now_btn, 'blue')
- tare_time_now_btn.clicked.connect(lambda: self._set_time_to_now(self.tare_weight_time))
- tare_time_now_btn.hide() # 隐藏时间按钮
- # 将时间框和按钮放在同一个水平布局中
- tare_time_input_layout = QHBoxLayout()
- tare_time_input_layout.setContentsMargins(0, 0, 0, 0)
- tare_time_input_layout.setSpacing(5)
- tare_time_input_layout.addWidget(self.tare_weight_time)
- tare_time_input_layout.addWidget(tare_time_now_btn)
- tare_time_widget = QWidget()
- tare_time_widget.setLayout(tare_time_input_layout)
- tare_time_layout.addWidget(tare_time_label)
- tare_time_layout.addWidget(tare_time_widget, 1)
- form_layout.addLayout(tare_time_layout)
- # 第八行:扣杂
- deduction_layout = QHBoxLayout()
- deduction_layout.setSpacing(10)
- deduction_label = QLabel("扣杂(kg):")
- deduction_label.setFont(QFont("微软雅黑", 16))
- deduction_label.setMinimumWidth(120)
- deduction_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
- self.deduction_input = EmptyDoubleSpinBox()
- self.deduction_input.setMinimumHeight(45)
- self.deduction_input.setFont(QFont("微软雅黑", 16))
- self.deduction_input.setDecimals(2)
- self.deduction_input.setMinimum(-1)
- self.deduction_input.setMaximum(999999)
- self.deduction_input.setSpecialValueText("")
- self.deduction_input.setValue(-1)
- self.deduction_input.setMinimumWidth(0)
- self.deduction_input.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
- try:
- self.deduction_input.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
- except Exception:
- pass
- try:
- self.deduction_input.setReadOnly(True)
- except Exception:
- pass
- self.deduction_input.valueChanged.connect(self.calculate_net_weight)
- deduction_layout.addWidget(deduction_label)
- deduction_layout.addWidget(self.deduction_input, 1)
- form_layout.addLayout(deduction_layout)
- # 第九行:净重和本次量(一行文本展示)
- weight_info_layout = QHBoxLayout()
- weight_info_layout.setSpacing(10)
- weight_info_label = QLabel("净重:")
- weight_info_label.setFont(QFont("微软雅黑", 16))
- weight_info_label.setMinimumWidth(60)
- weight_info_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
- self.net_weight_display = QLabel("0.000 t")
- self.net_weight_display.setMinimumHeight(45)
- self.net_weight_display.setFont(QFont("微软雅黑", 18, QFont.Bold))
- self.net_weight_display.setStyleSheet("""
- QLabel {
- background-color: #1E40AF;
- color: white;
- padding: 6px 10px;
- border: 2px solid #1D4ED8;
- border-radius: 6px;
- font-weight: bold;
- min-width: 80px;
- }
- """)
- self.net_weight_display.setAlignment(Qt.AlignCenter)
- current_quantity_info_label = QLabel("本次计划量:")
- current_quantity_info_label.setFont(QFont("微软雅黑", 16))
- current_quantity_info_label.setMinimumWidth(70)
- current_quantity_info_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
- self.current_quantity_display = QLabel("0.000 t")
- self.current_quantity_display.setMinimumHeight(45)
- self.current_quantity_display.setFont(QFont("微软雅黑", 18, QFont.Bold))
- self.current_quantity_display.setStyleSheet("""
- QLabel {
- background-color: #EA580C;
- color: white;
- padding: 6px 10px;
- border: 2px solid #DC2626;
- border-radius: 6px;
- font-weight: bold;
- min-width: 80px;
- }
- """)
- self.current_quantity_display.setAlignment(Qt.AlignCenter)
- weight_info_layout.addStretch()
- weight_info_layout.addWidget(weight_info_label)
- weight_info_layout.addWidget(self.net_weight_display)
- weight_info_layout.addWidget(current_quantity_info_label)
- weight_info_layout.addWidget(self.current_quantity_display)
- weight_info_layout.addStretch()
- form_layout.addLayout(weight_info_layout)
- layout.addLayout(form_layout)
- widget.setLayout(layout)
- return widget
-
- def refresh_dropdowns(self):
- """刷新下拉列表"""
- # 刷新货物名称
- self.cargo_combo.clear()
- self.cargo_combo.addItem("")
- cargos = self.db.get_all_cargos()
- for cargo in cargos:
- self.cargo_combo.addItem(cargo['name'])
- self.cargo_combo.setCurrentIndex(0)
-
- # 刷新公司名称 - 隐藏供货单位和收货单位字段
- # self.supplier_combo.clear()
- # self.supplier_combo.addItem("")
- # self.consignee_combo.clear()
- # self.consignee_combo.addItem("")
- # companies = self.db.get_all_companies()
- # for company in companies:
- # self.supplier_combo.addItem(company['name'])
- # self.consignee_combo.addItem(company['name'])
- # self.supplier_combo.setCurrentIndex(0)
- # self.consignee_combo.setCurrentIndex(0)
-
- def _prefill_from_inbound(self):
- """从出入库单预填数据"""
- # 如果已存在地磅单,加载地磅单数据
- if self.existing_slip:
- logger.info(f"加载已存在的地磅单数据,ID: {self.existing_slip.get('id')}")
- logger.debug(f"地磅单数据: gross_weight_time={self.existing_slip.get('gross_weight_time')}, tare_weight_time={self.existing_slip.get('tare_weight_time')}")
- self._load_slip_data(self.existing_slip)
- return
-
- # 否则从出入库单预填
- self.vehicle_no_input.setText(self.inbound.get('vehicle_no', ''))
-
- inbound_quantity_ton = self.inbound.get('quantity')
- if inbound_quantity_ton is not None and inbound_quantity_ton > 0:
- self.current_quantity_display.setText(f"{inbound_quantity_ton:.3f} t")
- else:
- self.current_quantity_display.setText("0.000 t")
-
- # 隐藏字段,从出入库单获取数据用于保存(界面不显示)
- self._hidden_plan_no = self.inbound.get('plan_no', '')
- self._hidden_batch_no = self.inbound.get('batch_no', '')
-
- # 业务类型
- if self.inbound['business_type'] == '入库':
- self.business_purchase_radio.setChecked(True)
- elif self.inbound['business_type'] == '出库':
- self.business_sale_radio.setChecked(True)
-
- # 货物名称(产品)
- product_name = self.inbound.get('product', '').strip()
- if product_name:
- index = self.cargo_combo.findText(product_name)
- if index >= 0:
- self.cargo_combo.setCurrentIndex(index)
-
- # 供货单位和收货单位:根据业务类型设置 - 隐藏字段,跳过设置
- # fixed_company_name = "安庆市山峡化工有限公司"
- # partner_name = self.inbound.get('partner_company', '').strip()
- #
- # if self.inbound['business_type'] == '入库':
- # # 入库:往来单位是供货单位,固定公司是收货单位
- # index = self.supplier_combo.findText(partner_name)
- # if index >= 0:
- # self.supplier_combo.setCurrentIndex(index)
- # index = self.consignee_combo.findText(fixed_company_name)
- # if index >= 0:
- # self.consignee_combo.setCurrentIndex(index)
- # elif self.inbound['business_type'] == '出库':
- # # 出库:固定公司是供货单位,往来单位是收货单位
- # index = self.supplier_combo.findText(fixed_company_name)
- # if index >= 0:
- # self.supplier_combo.setCurrentIndex(index)
- # index = self.consignee_combo.findText(partner_name)
- # if index >= 0:
- # self.consignee_combo.setCurrentIndex(index)
-
- def _load_slip_data(self, slip: dict):
- """加载地磅单数据到表单"""
- self.vehicle_no_input.setText(slip.get('vehicle_no', ''))
- # 隐藏字段,跳过设置
- # self.plan_no_input.setText(slip.get('plan_no', ''))
- # self.batch_no_input.setText(slip.get('batch_no', ''))
-
- business_type = slip.get('business_type')
- if business_type == '出库':
- self.business_sale_radio.setChecked(True)
- elif business_type == '入库':
- self.business_purchase_radio.setChecked(True)
-
- index = self.cargo_combo.findText(slip.get('cargo_name', ''))
- if index >= 0:
- self.cargo_combo.setCurrentIndex(index)
-
- # 隐藏供货单位和收货单位字段,跳过设置
- # index = self.supplier_combo.findText(slip.get('supplier', ''))
- # if index >= 0:
- # self.supplier_combo.setCurrentIndex(index)
- #
- # index = self.consignee_combo.findText(slip.get('consignee', ''))
- # if index >= 0:
- # self.consignee_combo.setCurrentIndex(index)
-
- gross_weight = slip.get('gross_weight', 0)
- if gross_weight > 0:
- self.gross_weight_input.setValue(gross_weight)
- else:
- self.gross_weight_input.setValue(-1)
-
- # 处理毛重时间
- gross_time = slip.get('gross_weight_time', '')
- if gross_time:
- gross_time = str(gross_time).strip()
- if gross_time:
- gross_dt = QDateTime.fromString(gross_time, "yyyy-MM-dd HH:mm:ss")
- if gross_dt.isValid():
- QTimer.singleShot(10, lambda dt=gross_dt: self._set_time_with_display(self.gross_weight_time, dt))
- else:
- # 尝试其他格式
- gross_dt = QDateTime.fromString(gross_time, "yyyy-MM-dd HH:mm")
- if gross_dt.isValid():
- QTimer.singleShot(10, lambda dt=gross_dt: self._set_time_with_display(self.gross_weight_time, dt))
- else:
- QTimer.singleShot(10, lambda: self._clear_time_display(self.gross_weight_time))
- else:
- QTimer.singleShot(10, lambda: self._clear_time_display(self.gross_weight_time))
- else:
- QTimer.singleShot(10, lambda: self._clear_time_display(self.gross_weight_time))
- tare_weight = slip.get('tare_weight', 0)
- if tare_weight > 0:
- self.tare_weight_input.setValue(tare_weight)
- else:
- self.tare_weight_input.setValue(-1)
- # 处理皮重时间
- tare_time = slip.get('tare_weight_time', '')
- if tare_time:
- tare_time = str(tare_time).strip()
- if tare_time:
- tare_dt = QDateTime.fromString(tare_time, "yyyy-MM-dd HH:mm:ss")
- if tare_dt.isValid():
- QTimer.singleShot(11, lambda dt=tare_dt: self._set_time_with_display(self.tare_weight_time, dt))
- else:
- # 尝试其他格式
- tare_dt = QDateTime.fromString(tare_time, "yyyy-MM-dd HH:mm")
- if tare_dt.isValid():
- QTimer.singleShot(11, lambda dt=tare_dt: self._set_time_with_display(self.tare_weight_time, dt))
- else:
- QTimer.singleShot(11, lambda: self._clear_time_display(self.tare_weight_time))
- else:
- QTimer.singleShot(11, lambda: self._clear_time_display(self.tare_weight_time))
- else:
- QTimer.singleShot(11, lambda: self._clear_time_display(self.tare_weight_time))
-
- deduction_value = slip.get('deduction')
- self.deduction_input.setValue(deduction_value if deduction_value is not None else -1)
-
- # 隐藏字段,跳过设置
- # planned_quantity = slip.get('planned_quantity')
- # planned_quantity_tons = kg_to_tons(planned_quantity) if planned_quantity is not None else None
- # self.planned_quantity_input.setValue(planned_quantity_tons if planned_quantity_tons is not None else -1)
- # executed_quantity = slip.get('executed_quantity')
- # executed_quantity_tons = kg_to_tons(executed_quantity) if executed_quantity is not None else None
- # self.executed_quantity_input.setValue(executed_quantity_tons if executed_quantity_tons is not None else -1)
-
- current_quantity = slip.get('current_quantity')
- current_quantity_tons = kg_to_tons(current_quantity) if current_quantity is not None else None
- if current_quantity_tons is not None:
- self.current_quantity_display.setText(f"{current_quantity_tons:.3f} t")
- else:
- self.current_quantity_display.setText("0.000 t")
-
- # 隐藏字段,跳过设置
- # self.remarks_input.setPlainText(slip.get('remarks', ''))
- self.calculate_net_weight()
-
- def calculate_net_weight(self):
- """计算净重"""
- gross = self._get_weight_input_value(self.gross_weight_input) or 0
- tare = self._get_weight_input_value(self.tare_weight_input) or 0
- deduction = self._get_deduction_value()
- net = gross - tare - deduction
- net_tons = kg_to_tons(net)
- if net_tons is None:
- net_tons = 0
- self.net_weight_display.setText(f"{net_tons:.3f} t")
-
- def on_gross_weight_changed(self, value: float):
- """毛重改变时自动更新时间"""
- self.calculate_net_weight()
- self._maybe_update_weight_time(value, self.gross_weight_time)
-
- def on_tare_weight_changed(self, value: float):
- """皮重改变时自动更新时间"""
- self.calculate_net_weight()
- self._maybe_update_weight_time(value, self.tare_weight_time)
-
- def _maybe_update_weight_time(self, value: float, time_edit: EmptyDateTimeEdit):
- """根据重量变化自动填充或清空时间"""
- if self._is_clearing_form:
- return
- if value > 0:
- self._set_time_to_now(time_edit)
- elif value < 0:
- self._clear_time_edit(time_edit)
-
- def _set_time_to_now(self, time_edit: EmptyDateTimeEdit):
- """将指定时间控件设置为当前时间"""
- current_dt = QDateTime.currentDateTime()
- time_edit.setDateTime(current_dt)
-
- def _clear_time_edit(self, time_edit: EmptyDateTimeEdit):
- """清空时间控件"""
- time_edit.setDateTime(QDateTime())
-
- def _set_time_with_display(self, time_edit: EmptyDateTimeEdit, dt: QDateTime):
- """设置时间并更新显示"""
- time_edit.setDateTime(dt)
- self._update_time_display(time_edit, dt)
- def _update_time_display(self, time_edit: EmptyDateTimeEdit, dt: QDateTime):
- """更新时间控件的显示"""
- if time_edit.lineEdit() and dt.isValid():
- time_edit.lineEdit().setText(dt.toString("yyyy-MM-dd HH:mm:ss"))
- def _clear_time_display(self, time_edit: EmptyDateTimeEdit):
- """清空时间控件的显示"""
- time_edit.setDateTime(QDateTime())
- if time_edit.lineEdit():
- time_edit.lineEdit().setText("")
-
- def _get_weight_input_value(self, spinbox: EmptyDoubleSpinBox) -> Optional[float]:
- """获取重量输入的实际值,未填则返回None"""
- value = spinbox.value()
- return value if value >= 0 else None
-
- def _get_deduction_value(self) -> float:
- """获取扣杂值,未填返回0"""
- value = self.deduction_input.value()
- return value if value >= 0 else 0
-
- def _get_datetime_str(self, time_edit: EmptyDateTimeEdit) -> str:
- """将时间控件转换为字符串"""
- if time_edit.dateTime().isValid():
- line_edit = time_edit.lineEdit()
- if line_edit and line_edit.text().strip():
- return time_edit.dateTime().toString("yyyy-MM-dd HH:mm:ss")
- return ""
-
- def validate_form(self) -> tuple:
- """验证表单数据"""
- if not self.vehicle_no_input.text().strip():
- return False, "请填写车号"
-
- if self.cargo_combo.currentIndex() <= 0 or not self.cargo_combo.currentText().strip():
- return False, "请选择货物名称"
-
- if not self.business_type_group.checkedButton():
- return False, "请选择业务类型"
-
- # 隐藏供货单位和收货单位字段,跳过验证
- # if self.supplier_combo.currentIndex() <= 0 or not self.supplier_combo.currentText().strip():
- # return False, "请选择供货单位"
- #
- # if self.consignee_combo.currentIndex() <= 0 or not self.consignee_combo.currentText().strip():
- # return False, "请选择收货单位"
-
- gross_value = self._get_weight_input_value(self.gross_weight_input)
- tare_value = self._get_weight_input_value(self.tare_weight_input)
-
- gross_time_text = self._get_datetime_str(self.gross_weight_time)
- tare_time_text = self._get_datetime_str(self.tare_weight_time)
-
- # 移除毛重和皮重必须大于0的校验,允许保存任意值
- # if gross_value is not None and gross_value <= 0:
- # return False, "毛重必须大于0"
- # if tare_value is not None and tare_value <= 0:
- # return False, "皮重必须大于0"
-
- # 移除毛重、皮重、毛重时间、皮重时间之间的关联校验,允许独立删除
- # if gross_value is not None and not gross_time_text:
- # return False, "已填写毛重后必须填写毛重时间"
- # if gross_time_text and gross_value is None:
- # return False, "填写毛重时间前需要填写毛重"
- #
- # if tare_value is not None and not tare_time_text:
- # return False, "已填写皮重后必须填写皮重时间"
- # if tare_time_text and tare_value is None:
- # return False, "填写皮重时间前需要填写皮重"
-
- if gross_value is not None and tare_value is not None:
- deduction = self._get_deduction_value()
- net_weight = gross_value - tare_value - deduction
- if net_weight <= 0:
- return False, "净重必须大于0,请检查毛重、皮重和扣杂的数值"
-
- return True, ""
-
- def save_weighing_slip(self):
- """保存地磅单"""
- valid, error_msg = self.validate_form()
- if not valid:
- QMessageBox.warning(self, "验证失败", error_msg)
- return
-
- gross_value = self._get_weight_input_value(self.gross_weight_input)
- tare_value = self._get_weight_input_value(self.tare_weight_input)
- deduction_value = self._get_deduction_value()
-
- gross_weight = gross_value if gross_value is not None else 0
- tare_weight = tare_value if tare_value is not None else 0
-
- # 隐藏字段,使用默认值
- # planned_quantity_value = self.planned_quantity_input.value()
- # planned_quantity_tons = planned_quantity_value if planned_quantity_value >= 0 else None
- planned_quantity = None # tons_to_kg(planned_quantity_tons) if planned_quantity_tons is not None else None
- # executed_quantity_value = self.executed_quantity_input.value()
- # executed_quantity_tons = executed_quantity_value if executed_quantity_value >= 0 else None
- executed_quantity = None # tons_to_kg(executed_quantity_tons) if executed_quantity_tons is not None else None
-
- # 从标签文本中解析本次量数值
- current_quantity_text = self.current_quantity_display.text().replace(' t', '')
- try:
- current_quantity_tons = float(current_quantity_text) if current_quantity_text != '0.000' else None
- except ValueError:
- current_quantity_tons = None
- current_quantity = tons_to_kg(current_quantity_tons) if current_quantity_tons is not None else None
-
- # 对于隐藏的字段,如果是编辑现有地磅单,保持原有值;如果是新增,从出入库单获取值
- if self.existing_slip:
- # 编辑模式:保持数据库中的现有值
- plan_no_value = self.existing_slip.get('plan_no', '')
- batch_no_value = self.existing_slip.get('batch_no', '')
- supplier_value = self.existing_slip.get('supplier', '')
- consignee_value = self.existing_slip.get('consignee', '')
- remarks_value = self.existing_slip.get('remarks', '')
- else:
- # 新增模式:从出入库单获取值
- plan_no_value = getattr(self, '_hidden_plan_no', '')
- batch_no_value = getattr(self, '_hidden_batch_no', '')
- # 根据业务类型设置供货单位和收货单位
- if self.inbound['business_type'] == '入库':
- supplier_value = self.inbound.get('partner_company', '')
- consignee_value = '安庆市山峡化工有限公司'
- else: # 出库
- supplier_value = '安庆市山峡化工有限公司'
- consignee_value = self.inbound.get('partner_company', '')
- remarks_value = ''
- data = {
- 'vehicle_no': self.vehicle_no_input.text().strip(),
- 'plan_no': plan_no_value,
- 'cargo_name': self.cargo_combo.currentText(),
- 'business_type': self.business_type_group.checkedButton().text(),
- 'batch_no': batch_no_value,
- 'supplier': supplier_value,
- 'consignee': consignee_value,
- 'gross_weight': gross_weight,
- 'gross_weight_time': self._get_datetime_str(self.gross_weight_time),
- 'tare_weight': tare_weight,
- 'tare_weight_time': self._get_datetime_str(self.tare_weight_time),
- 'deduction': deduction_value,
- 'planned_quantity': planned_quantity,
- 'executed_quantity': executed_quantity,
- 'current_quantity': current_quantity,
- 'remarks': remarks_value,
- 'inbound_outbound_id': self.inbound['id'],
- 'weighing_point': '山峡地磅'
- }
-
- try:
- if self.editing_slip_id:
- if self.db.update_weighing_slip(self.editing_slip_id, data):
- QMessageBox.information(self, "成功", "地磅单更新成功!")
- # 毛重和皮重都有时,保存成功后自动打印
- if gross_weight > 0 and tare_weight > 0:
- try:
- self.printer.direct_print_weighing_slip(
- self.db.get_weighing_slip_by_id(self.editing_slip_id),
- copies=1
- )
- QMessageBox.information(self, "成功", "地磅单已自动打印!")
- except Exception as e:
- QMessageBox.warning(self, "打印失败", f"地磅单更新成功,但自动打印失败:{str(e)}")
- self.accept()
- else:
- QMessageBox.warning(self, "错误", "更新失败")
- else:
- slip_id = self.db.insert_weighing_slip(data)
- QMessageBox.information(self, "成功", "地磅单保存成功!")
- # 如果皮重和毛重都大于0,自动打印地磅单
- if gross_weight > 0 and tare_weight > 0:
- try:
- self.printer.direct_print_weighing_slip(
- self.db.get_weighing_slip_by_id(slip_id),
- copies=1
- )
- QMessageBox.information(self, "成功", "地磅单已自动打印!")
- except Exception as e:
- QMessageBox.warning(self, "打印失败", f"地磅单保存成功,但自动打印失败:{str(e)}")
- self.accept()
- except Exception as e:
- QMessageBox.critical(self, "错误", f"保存失败:{str(e)}")
-
- def _dialog_print_weighing_slip(self):
- """打印出入库单关联的地磅单(与列表中的打印功能一致:打开打印预览)"""
- slip = self.db.get_weighing_slip_by_inbound_id(self.inbound['id'], include_voided=False)
- if not slip:
- QMessageBox.warning(self, "提示", "该出入库单尚未生成地磅单,无法打印。")
- return
- try:
- self.printer.preview_weighing_slip(slip, copies=1)
- except Exception as e:
- QMessageBox.critical(self, "错误", f"打印失败:{str(e)}")
-
- def clear_form(self):
- """清空表单"""
- self._is_clearing_form = True
- try:
- self.vehicle_no_input.clear()
- # 隐藏字段,跳过清空
- # self.plan_no_input.clear()
- if self.cargo_combo.count() > 0:
- self.cargo_combo.setCurrentIndex(0)
- # 隐藏供货单位和收货单位字段,跳过清空
- # if self.supplier_combo.count() > 0:
- # self.supplier_combo.setCurrentIndex(0)
- # if self.consignee_combo.count() > 0:
- # self.consignee_combo.setCurrentIndex(0)
- if self.business_type_group.checkedButton():
- self.business_type_group.setExclusive(False)
- self.business_type_group.checkedButton().setChecked(False)
- self.business_type_group.setExclusive(True)
- # 隐藏字段,跳过清空
- # self.batch_no_input.clear()
- self.gross_weight_input.setValue(-1)
- self.gross_weight_time.setDateTime(QDateTime())
- if self.gross_weight_time.lineEdit():
- self.gross_weight_time.lineEdit().setText("")
- QTimer.singleShot(0, lambda: self.gross_weight_time.lineEdit().setText("") if self.gross_weight_time.lineEdit() else None)
- self.tare_weight_input.setValue(-1)
- self.tare_weight_time.setDateTime(QDateTime())
- if self.tare_weight_time.lineEdit():
- self.tare_weight_time.lineEdit().setText("")
- QTimer.singleShot(0, lambda: self.tare_weight_time.lineEdit().setText("") if self.tare_weight_time.lineEdit() else None)
- self.deduction_input.setValue(-1)
- self.net_weight_display.setText("0.000 t")
- # 隐藏字段,跳过清空
- # self.planned_quantity_input.setValue(-1)
- # self.executed_quantity_input.setValue(-1)
- self.current_quantity_display.setText("0.000 t")
- # self.remarks_input.clear()
- finally:
- self._is_clearing_form = False
- def _attach_serial_reader(self):
- """附加到串口读取器以接收实时重量更新"""
- sr = None
- try:
- if getattr(self, "main_window", None) and getattr(self.main_window, "yaohua_weighing_tab", None):
- sr = self.main_window.yaohua_weighing_tab.serial_reader
- except Exception:
- sr = None
- if sr is None:
- # 尝试根据配置创建并启动
- cfg = self._load_scale_config()
- if not cfg:
- return
- parity_map = {'无校验': 'N', '偶校验': 'E', '奇校验': 'O'}
- sr = get_reader_for_port(
- cfg.get("port"),
- baudrate=int(cfg.get("baudrate", 9600)),
- bytesize=int(cfg.get("bytesize", 8)),
- parity=parity_map.get(cfg.get("parity", "无校验"), 'N'),
- stopbits=int(cfg.get("stopbits", 1))
- )
- # 将其设置到主窗口的yaohua tab,供其他界面复用
- try:
- if getattr(self, "main_window", None) and getattr(self.main_window, "yaohua_weighing_tab", None):
- self.main_window.yaohua_weighing_tab.serial_reader = sr
- except Exception:
- pass
- # 连接信号
- try:
- # 若已连接则直接订阅信号,否则尝试连接后订阅
- if not sr.is_connected():
- try:
- sr.connect()
- except Exception:
- pass
- # 启动后台读取以保证持续接收
- if not getattr(sr, "is_running", False):
- try:
- sr.start_reading()
- except Exception:
- pass
- # 断开旧连接(如果有)
- if getattr(self, "_serial_reader", None) is not None and getattr(self, "_serial_reader", "dummy") != sr:
- try:
- old = self._serial_reader
- old.weight_received.disconnect(self._on_realtime_weight)
- except Exception:
- pass
- self._serial_reader = sr
- # 订阅实时重量更新
- sr.weight_received.connect(self._on_realtime_weight)
- # 订阅连接状态改变以更新显示
- try:
- sr.connection_status_changed.connect(self._on_connection_status_changed)
- except Exception:
- pass
- except Exception:
- logger.exception("附加串口读取器失败")
- def _on_realtime_weight(self, weight: float):
- """来自串口读取器的实时重量更新(主线程)"""
- try:
- self.instrument_weight = weight
- # 若为None或NaN则显示未连接
- if weight is None or (isinstance(weight, float) and weight != weight):
- self.instrument_weight_label.setText("—")
- else:
- self.instrument_weight_label.setText(f"{weight:.2f} kg")
- except Exception:
- logger.exception("处理实时重量更新失败")
- def _on_connection_status_changed(self, connected: bool):
- """串口连接状态改变"""
- try:
- if not connected:
- self.instrument_weight_label.setText("未连接")
- self.instrument_weight = None
- except Exception:
- logger.exception("处理连接状态改变失败")
- def _start_read_from_instrument(self, target: str):
- """在后台线程读取一次仪表数据,target='gross'|'tare'"""
- # 确保只有一个并发读取
- if getattr(self, "_reading_thread", None) and self._reading_thread.is_alive():
- QMessageBox.information(self, "提示", "正在读取,请稍候...")
- return
- # 如果已有实时读取的最新值,优先使用该值,避免再次同步读取超时问题
- try:
- if getattr(self, "instrument_weight", None) is not None:
- # 直接触发槽函数,主线程安全
- self.instrument_weight_received.emit(self.instrument_weight, target)
- return
- except Exception:
- pass
- # 尝试从主窗口的耀华tab复用串口读取器
- serial_reader = None
- # 优先复用主窗口 yaohua_weighing_tab 的 serial_reader(更可靠)
- try:
- if getattr(self, "main_window", None) and getattr(self.main_window, "yaohua_weighing_tab", None):
- serial_reader = self.main_window.yaohua_weighing_tab.serial_reader
- except Exception:
- serial_reader = None
- # 其次尝试通过父控件查找(兼容不同创建方式)
- if serial_reader is None:
- try:
- parent_widget = self.parent() # 通常是 InboundOutboundTab
- if parent_widget and hasattr(parent_widget, "main_window") and getattr(parent_widget.main_window, "yaohua_weighing_tab", None):
- serial_reader = parent_widget.main_window.yaohua_weighing_tab.serial_reader
- except Exception:
- serial_reader = None
- # 如果没有复用到读取器,尝试新建一个(仅在主界面无可复用读取器时创建)
- if serial_reader is None:
- # 如果主窗口存在且 yaohua tab 已创建但尚无 serial_reader,则根据配置创建单例读取器并附加到主窗口以供复用
- try:
- cfg = self._load_scale_config()
- if cfg and cfg.get("port"):
- parity_map = {'无校验': 'N', '偶校验': 'E', '奇校验': 'O'}
- serial_reader = get_reader_for_port(
- cfg.get("port"),
- baudrate=int(cfg.get("baudrate", 9600)),
- bytesize=int(cfg.get("bytesize", 8)),
- parity=parity_map.get(cfg.get("parity", "无校验"), 'N'),
- stopbits=int(cfg.get("stopbits", 1))
- )
- else:
- # 创建未注册的临时实例
- serial_reader = get_reader_for_port('')
- if getattr(self, "main_window", None) and getattr(self.main_window, "yaohua_weighing_tab", None):
- if getattr(self.main_window.yaohua_weighing_tab, "serial_reader", None) is None:
- self.main_window.yaohua_weighing_tab.serial_reader = serial_reader
- else:
- serial_reader = self.main_window.yaohua_weighing_tab.serial_reader
- except Exception:
- serial_reader = None
- self._serial_reader = serial_reader
- self._pending_read_target = target
- # 在后台线程执行同步读取,避免阻塞UI
- def _worker():
- try:
- weight = None
- # 优先使用已经连接的读取器
- if getattr(serial_reader, "is_connected", lambda: False)() and getattr(serial_reader, "is_running", False):
- weight = serial_reader.read_weight_once(timeout=3.0)
- else:
- # 尝试连接并读取一次
- try:
- serial_reader.connect()
- except Exception:
- pass
- weight = serial_reader.read_weight_once(timeout=3.0)
- if weight is not None:
- # 通过 Qt 信号回到主线程
- self.instrument_weight_received.emit(weight, target)
- else:
- # 发出一个特殊值为None通过信号用以提示读取失败
- self.instrument_weight_received.emit(float("nan"), target)
- except Exception as e:
- # 更详细记录异常,方便排查端口被占用等问题
- logger.exception("读取仪表失败")
- try:
- self.instrument_weight_received.emit(float("nan"), target)
- except Exception:
- pass
- import threading
- self._reading_thread = threading.Thread(target=_worker, daemon=True)
- self._reading_thread.start()
- def _on_instrument_weight_received(self, weight: float, target: str):
- """收到仪表重量后的槽函数(在主线程中执行)"""
- # weight为nan表示读取失败
- if weight != weight: # NaN 检测
- QMessageBox.warning(self, "读取失败", "未能从仪表读取到有效数据,请检查连接和参数。")
- return
- # 显示到界面
- self.instrument_weight = weight
- try:
- self.instrument_weight_label.setText(".2f")
- except Exception:
- self.instrument_weight_label.setText(str(weight))
- # 根据目标将值填入对应控件并更新时间
- now = QDateTime.currentDateTime()
- if target == 'gross':
- # 仪表读到的通常是kg单位,UI中的输入控件也使用kg
- try:
- self.gross_weight_input.setValue(float(f"{weight:.2f}"))
- self._set_time_to_now(self.gross_weight_time)
- except Exception:
- pass
- elif target == 'tare':
- try:
- self.tare_weight_input.setValue(float(f"{weight:.2f}"))
- self._set_time_to_now(self.tare_weight_time)
- except Exception:
- pass
- def _load_scale_config(self) -> Optional[Dict]:
- """从 scale_config.json 加载地磅配置"""
- try:
- import os
- from database import get_base_path
- cfg_path = os.path.join(get_base_path(), "scale_config.json")
- if not os.path.exists(cfg_path):
- return None
- with open(cfg_path, "r", encoding="utf-8") as f:
- cfg = json.load(f)
- return cfg
- except Exception as e:
- logger.exception("加载地磅配置失败")
- return None
|