| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628 |
- """
- 出入库管理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()
- # 地磅单和打印按钮放在前面
- # 地磅单按钮始终显示(无论是否完成)
- jump_btn_main = QPushButton("地磅单")
- jump_font = QFont("微软雅黑", 15)
- jump_font.setBold(True)
- jump_btn_main.setFont(jump_font)
- jump_btn_main.setMinimumWidth(90)
- jump_btn_main.setMinimumHeight(38)
- jump_btn_main.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
- apply_button_style(jump_btn_main, 'blue')
- jump_btn_main.clicked.connect(lambda checked, iid=inbound["id"]: self.jump_to_weighing(iid))
- btn_layout.addWidget(jump_btn_main)
-
- # 如果有地磅单,显示打印按钮(无论是否完成)
- 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
|