-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_window_test.py
More file actions
2708 lines (2298 loc) · 108 KB
/
main_window_test.py
File metadata and controls
2708 lines (2298 loc) · 108 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import os
import sys
import glob
import pathlib
import threading
import time
import json
import csv
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple
from pathlib import Path
from datetime import datetime, timedelta, timezone as _TZ # ← timezone 추가(별칭은 _TZ)
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError # ← 예외 추가
import socket
import psycopg2
import psycopg2.extras
import traceback
import shlex
from PySide6.QtCore import (
Qt,
QTimer,
QThread,
Signal,
Slot,
QDate,
QRect
)
from PySide6.QtGui import QPixmap, QColor, QFontMetrics ,QBrush, QPalette ,QGuiApplication,QTextOption
from PySide6.QtWidgets import (
QApplication,
QMainWindow,
QDialog,
QVBoxLayout,
QHBoxLayout,
QLabel,
QPushButton,
QLineEdit,
QDateEdit,
QComboBox,
QTableWidget,
QTableWidgetItem,
QMessageBox,
QHeaderView,
QAbstractItemView,
QScrollArea,
QStyledItemDelegate,
QWidget,
QFormLayout,
QSizePolicy,
QFrame,
QStyle,
QStyleOptionSpinBox,
QCalendarWidget,
QStyleOptionViewItem,
QFileDialog,
QListWidget,
QListWidgetItem,
QPlainTextEdit
)
from PySide6.QtNetwork import QTcpSocket, QHostAddress
from datetime import date as _date
# --------------------------------------------------------------
# 외부 모듈: auto-generated UI + 암호화 설정 로더
# --------------------------------------------------------------
from ui_main_window import Ui_MainWindow # noqa
from config_loader import load_encrypted_config # noqa
# ---- Global QSS Loader ------------------------------------------------------
def apply_global_stylesheet(app: QApplication) -> None: ## CSS 전역 로더
"""
전역 QSS를 여러 경로 후보에서 찾아 적용한다.
우선순위:
1) PyInstaller 임시폴더(_MEIPASS)/styles/style.css
2) (frozen) 실행파일 옆 /styles/style.css
(script) 이 파일(__file__) 폴더(ui)/styles/style.css
3) (script) 이 파일(__file__) 폴더(ui)/style.css ← ★ 너 지금 경로
4) 프로젝트 루트(= ui 상위)/styles/style.css
5) 현재 작업 디렉터리(CWD)/styles/style.css
6) 환경변수 APP_STYLE_PATH(파일 또는 폴더)
"""
def candidates():
# 1) PyInstaller 임시폴더
meipass = getattr(sys, "_MEIPASS", None)
if meipass:
yield Path(meipass) / "styles" / "style.css"
# 2) 실행파일/스크립트 기준
base = Path(sys.executable).parent if getattr(sys, "frozen", False) else Path(__file__).resolve().parent
yield base / "styles" / "style.css" # ui/styles/style.css
yield base / "style.css" # ui/style.css ← ★ 너의 현재 위치
yield base.parent / "styles" / "style.css" # 프로젝트루트/styles/style.css
# 3) 현재 작업 디렉터리
yield Path.cwd() / "styles" / "style.css"
# 4) 환경변수
env = os.getenv("APP_STYLE_PATH")
if env:
p = Path(env)
yield p if p.suffix.lower() == ".css" else (p / "style.css")
for p in candidates():
try:
if p.is_file():
app.setStyleSheet(p.read_text(encoding="utf-8"))
print(f"[style] loaded: {p}")
return
except Exception as e:
print(f"[style] fail: {p} -> {e}")
print("[style] no stylesheet found; running without custom QSS")
def strip_inline_styles(root: QWidget, keep: set[str] | None = None) -> None: ##
"""
.ui에서 각 위젯에 박힌 인라인 setStyleSheet를 제거해서
전역 style.css(QSS)가 적용되도록 만든다.
keep: objectName을 넣으면 해당 위젯은 비우지 않음.
"""
if keep is None:
keep = set()
# 자신
try:
if root.objectName() not in keep and root.styleSheet():
root.setStyleSheet("")
except Exception:
pass
# 자식들
for w in root.findChildren(QWidget):
try:
if w.objectName() not in keep and w.styleSheet():
w.setStyleSheet("")
except Exception:
continue
class AlignDelegate(QStyledItemDelegate): ## 중앙정렬 메서드
def __init__(self, alignment: Qt.AlignmentFlag, parent=None):
super().__init__(parent)
self._alignment = alignment
def initStyleOption(self, option, index):
super().initStyleOption(option, index)
option.displayAlignment = self._alignment
def resolve_kst():
"""tzdata가 없어도 죽지 않게 Asia/Seoul 시도 후 KST(+09:00)로 폴백."""
try:
return ZoneInfo("Asia/Seoul")
except ZoneInfoNotFoundError:
return _TZ(timedelta(hours=9), name="KST")
def bg_color_for_status(text: str, *, allow_green: bool = True) -> QColor | None:
"""
결과 텍스트 전용 최소 매핑:
- 'NG' → 연한 빨강
- '작업 완료' → 연한 초록
- '작업중' → 연한 노랑
- 그 외 → 색 없음
"""
t = (text or "").strip()
# print("bg_color_for_status:", t) # 디버깅용
if not t:
return None
if t == "NG":
return QColor("#EF5350") # red-ish
if allow_green and t in {"작업 완료", "COMPLETED"}:
return QColor("#A5D6A7") # green-ish
if t == "작업중":
return QColor(255, 224, 130) # yellow-ish
return None
class _CompatLogView(QPlainTextEdit):
"""QLabel 대체용: QLabel처럼 setText(...)를 그대로 쓸 수 있게 래핑."""
def setText(self, s: str) -> None: # QLabel 호환
self.setPlainText(s)
def text(self) -> str: # 필요시 QLabel 호환
return self.toPlainText()
# ---- 검색 헬퍼 ---------------------------------------------------
STATUS_SYNONYMS = {
"ok": ["작업 완료"],
"완료": ["작업 완료"],
"ng": ["NG"],
"fail": ["NG"],
"에러": ["NG"],
}
def _escape_like(s: str) -> str:
# LIKE/ILIKE 패턴용 이스케이프:
# - \, %, _ 를 파라미터 문자열 내에서 안전하게 이스케이프
# ※ SQL에 literal로 넣지 않고 항상 %s 바인딩으로 전달하므로 ESCAPE 절 불필요
s = s.replace("\\", "\\\\") # backslash 자체 이스케이프
s = s.replace("%", r"\%").replace("_", r"\_")
return s
def _tokenize(query: str) -> list[str]:
"""
공백 AND, 따옴표로 phrase 유지:
ex) abc "foo bar" -bad pid:123 x|y
"""
try:
toks = shlex.split(query, posix=True)
except Exception:
toks = query.split()
return [t for t in (tok.strip() for tok in toks) if t]
def _split_field_token(tok: str) -> tuple[str|None, str]:
"""
'pid:123', 'destination:ok' 같은 필드 지정 문법 파싱.
반환: (field_alias or None, value)
"""
if ":" in tok:
k, v = tok.split(":", 1)
k = k.strip().lower()
v = v.strip()
if k:
return k, v
return None, tok
def _alts(val: str) -> list[str]:
"""토큰 내 OR 지원: 'a|b|c' → ['a','b','c']"""
return [a for a in (p.strip() for p in val.split("|")) if a]
def _barcode_expr(col: str) -> str:
"""
barcode 특수 처리: 하이픈/공백 제거 후 부분일치도 허용
(정규식 치환 사용, ESCAPE 절 불필요)
"""
return f"regexp_replace({col}, '[-\\s]', '', 'g') ILIKE %s"
def _build_keyword_filters(kw: str, search_cols: list[str], colnames: set[str]):
"""
공백 분리 다중 토큰 + 따옴표 묶음 + 제외(-토큰) + OR(|) + 대소문자 무시(ILIKE)
- field alias: pid:, sscc:, destination:/status:, barcode:, error_reason:
- barcode는 하이픈/공백 제거 비교를 추가로 수행
- status 동의어(OK/NG 등) 확장 지원
반환: (where_parts: list[str], params: list[Any])
"""
tokens = _tokenize(kw)
where_parts: list[str] = []
params: list[str] = []
# UI에서 'Destination' 이 실제 status 컬럼을 의미
alias_map = {
"pid": "pid",
"sscc": "sscc",
"destination": "status",
"status": "status",
"barcode": "barcode",
"error_reason": "error_reason",
}
def build_like_set(cols: list[str], one_val: str, negate: bool) -> tuple[str, list[str]]:
"""
한 개 값(one_val)을 여러 컬럼(cols)에 적용:
- 포지티브: (col1 LIKE ? OR col2 LIKE ? ...)
- 네거티브: NOT(...) 을 alt 단위로 만들고 AND로 묶음
- barcode는 normalize 비교 + 일반 ILIKE 둘다 추가
"""
safe = _escape_like(one_val)
pat = f"%{safe}%"
# 이 값에 대한 '한 번의' 컬럼 집합식 (OR)
col_exprs: list[str] = []
col_params: list[str] = []
for c in cols:
if c == "barcode" and "barcode" in colnames and one_val:
norm = one_val.replace("-", "").replace(" ", "")
col_exprs.append(_barcode_expr("barcode"))
col_params.append(f"%{_escape_like(norm)}%")
col_exprs.append(f"{c} ILIKE %s")
col_params.append(pat)
else:
col_exprs.append(f"{c} ILIKE %s")
col_params.append(pat)
expr = "(" + " OR ".join(col_exprs) + ")"
if negate:
# 이 값(one_val)이 어떤 컬럼에도 나타나면 안 된다 → NOT (col1 OR col2 ...)
return f"NOT {expr}", col_params
else:
return expr, col_params
for raw in tokens:
negate = raw.startswith("-")
tok = raw[1:].strip() if negate else raw
if not tok:
continue
field_alias, val = _split_field_token(tok)
alt_vals = _alts(val)
if not alt_vals:
continue
# 이번 토큰에 적용할 컬럼
if field_alias:
mapped = alias_map.get(field_alias)
cols = [mapped] if mapped else list(search_cols)
else:
cols = list(search_cols)
# status 동의어 확장
if any(c == "status" for c in cols):
expanded: list[str] = []
for a in alt_vals:
k = a.lower()
expanded.extend(STATUS_SYNONYMS.get(k, [a]))
alt_vals = expanded
# alt (a|b|c) 를 묶는 규칙:
# - 포지티브: ( alt(a) OR alt(b) OR alt(c) )
# - 네거티브: ( NOT alt(a) AND NOT alt(b) AND NOT alt(c) )
alt_group_exprs: list[str] = []
alt_group_params: list[str] = []
for a in alt_vals:
expr, p = build_like_set(cols, a, negate)
alt_group_exprs.append(expr)
alt_group_params.extend(p)
if negate:
where_parts.append("(" + " AND ".join(alt_group_exprs) + ")")
else:
where_parts.append("(" + " OR ".join(alt_group_exprs) + ")")
params.extend(alt_group_params)
return where_parts, params
# ---- 로고 경로 ----
def resource_path(*parts: str) -> str:
"""여러 베이스 경로 후보를 순회하며 첫 번째로 존재하는 파일 경로를 반환."""
rel = Path(*parts)
candidates = []
# 1) PyInstaller 런타임 임시 폴더
meipass = getattr(sys, "_MEIPASS", None)
if meipass:
candidates.append(Path(meipass) / rel)
# 2) 이 파일이 있는 폴더 / 그 부모들
here = Path(__file__).resolve().parent
candidates += [
here / rel,
here.parent / rel,
here.parent.parent / rel,
]
# 3) 실행 파일 있는 폴더, 현재 작업 폴더
candidates += [
Path(sys.argv[0]).resolve().parent / rel,
Path.cwd() / rel,
]
# 존재 확인
for c in candidates:
if c.exists():
return str(c)
# 못 찾으면 디버그용으로 후보들을 찍고, 마지막 후보를 돌려준다(문구 표시용)
try:
print("[resource_path] not found. tried:")
for c in candidates:
print(" -", c)
except Exception:
pass
return str(candidates[-1] if candidates else rel)
# ---- 호환 상수: StateFlag 없으면 State로 폴백 ----
StateEnum = getattr(QStyle, "StateFlag", QStyle)
STATE_MOUSEOVER = getattr(StateEnum, "State_MouseOver")
STATE_SELECTED = getattr(StateEnum, "State_Selected")
class StatusBGDelegate(QStyledItemDelegate):
def __init__(self, parent=None, *, allow_green: bool = True):
super().__init__(parent)
self.allow_green = allow_green
def initStyleOption(self, option, index):
super().initStyleOption(option, index)
# 처리 상태 컬럼 정렬을 가운데로
option.displayAlignment = Qt.AlignmentFlag.AlignCenter
def paint(self, painter, option, index):
text = (index.data() or "").strip()
bg = bg_color_for_status(text, allow_green=self.allow_green)
opt = QStyleOptionViewItem(option)
self.initStyleOption(opt, index)
opt.state = opt.state & ~STATE_MOUSEOVER
if bg and not (opt.state & STATE_SELECTED):
opt.backgroundBrush = QBrush(bg) # ✔ 배경은 스타일에게 맡김
super().paint(painter, opt, index) # ✔ 직접 fillRect 안 함
def apply_status_cell_colors(item: QTableWidgetItem, *, text_color: str = "#000000", allow_green: bool = True) -> None:
text = (item.text() or "").strip()
bg = bg_color_for_status(text, allow_green=allow_green)
if bg is not None:
item.setBackground(QBrush(bg))
item.setForeground(QBrush(QColor(text_color)))
else:
item.setBackground(QBrush())
item.setForeground(QBrush())
# ---------------------------------------------------------------------------
# 데이터 모델 정의
# ---------------------------------------------------------------------------
@dataclass
class DBConfig:
host: str
port: int
dbname: str
user: str
password: str
table_jobs: str # 최근 20건, 전체 조회용 테이블명
@classmethod
def from_config(cls, cfg: Dict[str, Any]) -> "DBConfig":
"""
암호화 설정에서 DB 접속정보를 추출.
- 신형(nested) 포맷: cfg['db']['host' | 'port' | ...]
- 구형(flat) 포맷: cfg['DB_HOST' | 'DB_PORT' | 'DB_NAME' | 'DB_USER' | 'DB_PASSWORD']
"""
db_nested = cfg.get("db", {})
tbl_nested = cfg.get("table", {})
# --- flat 키 추출 (구형 포맷 호환) ---
flat_host = cfg.get("DB_HOST")
flat_port = cfg.get("DB_PORT")
flat_name = cfg.get("DB_NAME")
flat_user = cfg.get("DB_USER")
flat_pass = cfg.get("DB_PASSWORD")
flat_table = cfg.get("DB_TABLE") or cfg.get("JOBS_TABLE")
# host
host = db_nested.get("host") or flat_host or "127.0.0.1"
# port (정수 변환)
port = db_nested.get("port") or flat_port or 5432
try:
port = int(port)
except Exception:
port = 5432
# dbname
dbname = (
db_nested.get("dbname")
or db_nested.get("name")
or flat_name
or "postgres"
)
# user
user = db_nested.get("user") or flat_user or "postgres"
# password
password = (
db_nested.get("password")
or db_nested.get("passwd")
or flat_pass
or ""
)
# jobs 테이블명
table_jobs = tbl_nested.get("jobs") or tbl_nested.get("table") or flat_table or "tb_send"
return cls(
host=host,
port=port,
dbname=dbname,
user=user,
password=password,
table_jobs=table_jobs,
)
def qdate_to_date(qd) -> _date:
"""PySide QDate → Python date 안전 변환."""
# PySide6 >=6.7? qd.toPython() 존재하지만 호환성 위해 수동 변환
try:
return qd.toPython() # 일부 버전에서 정상 동작
except Exception:
pass
return _date(qd.year(), qd.month(), qd.day())
@dataclass
class PathConfig:
mapped_image_root: pathlib.Path
@classmethod
def from_config(cls, cfg: Dict[str, Any]) -> "PathConfig":
paths = cfg.get("paths", {})
root = paths.get("mapped_image_root", r"D:/mapped_image")
return cls(mapped_image_root=pathlib.Path(root))
@dataclass
class AppConfig:
center_name: str
db: DBConfig
paths: PathConfig
poll_interval_sec: float = 1.0 # DB 주기
image_poll_interval_sec: float = 3.0 # 이미지 주기
@classmethod
def load(cls, enc_path: str = "path.enc") -> "AppConfig":
cfg = load_encrypted_config(enc_path=enc_path)
return cls(
center_name=cfg.get("center_name", "센터 미지정"),
db=DBConfig.from_config(cfg),
paths=PathConfig.from_config(cfg),
poll_interval_sec=float(cfg.get("poll_interval_sec", 1.0)),
image_poll_interval_sec=float(cfg.get("image_poll_interval_sec", 3.0)),
)
# ---------------------------------------------------------------------------
# DB Poller Thread
# ---------------------------------------------------------------------------
class DBPollerThread(QThread):
"""주기적으로 DB에서 오늘 건수 및 최신 20건을 읽어오는 쓰레드."""
daily_count_signal = Signal(int)
latest_rows_signal = Signal(list) # list[dict]
db_error_signal = Signal(str)
def __init__(self, cfg: AppConfig, tz: ZoneInfo, parent=None):
super().__init__(parent)
self.cfg = cfg
self.tz = tz
self._stop = threading.Event()
self._conn = None # type: Optional[psycopg2.extensions.connection]
# psycopg2 연결
def _connect(self):
try:
self._conn = psycopg2.connect(
host=self.cfg.db.host,
port=self.cfg.db.port,
dbname=self.cfg.db.dbname,
user=self.cfg.db.user,
password=self.cfg.db.password,
connect_timeout=5,
)
self._conn.autocommit = True
except Exception as e: # pragma: no cover - 연결 실패 로깅용
self.db_error_signal.emit(f"DB 연결 실패: {e}")
self._conn = None
def stop(self):
self._stop.set()
# 오늘 자정~내일 자정 범위
def _today_range(self) -> Tuple[datetime, datetime]:
now = datetime.now(self.tz)
start = now.replace(hour=0, minute=0, second=0, microsecond=0)
end = start + timedelta(days=1)
return start, end
def _fetch_daily_count(self, cur) -> Optional[int]:
table = self.cfg.db.table_jobs
start, end = self._today_range()
# created_at 컬럼 이름은 프로젝트별 상이 → 후보 리스트 중 존재하는 컬럼 찾기
# 가장 흔한 이름: created_at, ts, timestamp, created, dt
column_candidates = ["created_at", "ts", "timestamp", "created", "dt"]
col = None
# 스키마 검사 한 번만 해도 되지만 간단히 try 순차 실행
for c in column_candidates:
try:
cur.execute(
f"SELECT COUNT(*) FROM {table} WHERE {c} >= %s AND {c} < %s",
(start, end),
)
col = c
break
except Exception: # ignore, 컬럼 없음
self._conn.rollback()
if col is None:
return None
row = cur.fetchone()
return int(row[0]) if row and row[0] is not None else 0
def _fetch_latest_rows(self, cur, limit: int = 20) -> List[Dict[str, Any]]:
table = self.cfg.db.table_jobs
query_order = [
# id 있는 경우: 시간 필드 추가(created_at)
("id",
f"SELECT id, pid, sscc, barcode, status AS destination, error_reason, created_at FROM {table} ORDER BY id DESC LIMIT %s"),
# created_at 대체 경우
("created_at",
f"SELECT pid, sscc, barcode, status AS destination, error_reason, created_at FROM {table} ORDER BY created_at DESC LIMIT %s"),
]
for col, q in query_order:
try:
cur.execute(q, (limit,))
cols = [d.name for d in cur.description]
rows = cur.fetchall()
return [dict(zip(cols, r)) for r in rows]
except Exception:
# 해당 컬럼(또는 쿼리) 실패 시 롤백 후 다음 후보 시도
self._conn.rollback()
return []
def run(self): # noqa: D401
self._connect()
if self._conn is None:
return
cur = self._conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
poll = self.cfg.poll_interval_sec
while not self._stop.is_set():
try:
count = self._fetch_daily_count(cur)
if count is not None:
self.daily_count_signal.emit(count)
rows = self._fetch_latest_rows(cur, 20)
self.latest_rows_signal.emit(rows)
except Exception as e:
self.db_error_signal.emit(str(e))
finally:
time.sleep(poll)
cur.close()
if self._conn:
self._conn.close()
# ---------------------------------------------------------------------------
# 전체 데이터 팝업 다이얼로그
# ---------------------------------------------------------------------------
class AllDataDialog(QDialog):
"""전체 DB 레코드 보기 + 필터."""
class _NumericItem(QTableWidgetItem):
def __lt__(self, other):
try:
a = int(self.text().replace(',', ''))
b = int(other.text().replace(',', ''))
return a < b
except Exception:
return super().__lt__(other)
class _NoStepDateEdit(QDateEdit):
"""마우스 클릭/휠로 값이 +1 되는 것을 막고, 캘린더 버튼만 동작하게."""
def wheelEvent(self, e): # 휠로 증감 방지
e.ignore()
def stepBy(self, steps): # 키/버튼 스텝 자체 차단(캘린더 선택은 영향 없음)
return
def mousePressEvent(self, e):
# 캘린더/스핀 버튼 영역 클릭만 통과, 나머지 빈 영역 클릭은 증감 차단
opt = QStyleOptionSpinBox()
opt.initFrom(self)
opt.buttonSymbols = self.buttonSymbols()
up_rect = self.style().subControlRect(QStyle.ComplexControl.CC_SpinBox, opt, QStyle.SubControl.SC_SpinBoxUp, self)
down_rect = self.style().subControlRect(QStyle.ComplexControl.CC_SpinBox, opt, QStyle.SubControl.SC_SpinBoxDown, self)
if up_rect.contains(e.pos()) or down_rect.contains(e.pos()):
return super().mousePressEvent(e) # (캘린더 팝업 버튼 포함) 버튼 클릭은 허용
# 빈 배경 클릭은 포커스만 주고 증감은 막기
self.setFocus()
e.accept()
def __init__(self, cfg: AppConfig, tz: ZoneInfo, parent=None): ##
super().__init__(parent)
self.cfg = cfg
self.tz = tz
self.setWindowTitle("작업 전체 조회")
## 스타일 스코프용 objectName 부여(중요)
self.setObjectName("AllDataDialog")
# 위젯(이 아래 부분은 위젯의 '구조'와 '동작'에 관한 것이므로 분리 대상이 아님)
layout = QVBoxLayout(self)
# 필터 행
filter_row = QHBoxLayout()
# self.date_from = QDateEdit(self)
self.date_from = self._NoStepDateEdit(self) # 변경
self.date_from.setCalendarPopup(True)
# self.date_to = QDateEdit(self)
self.date_to = self._NoStepDateEdit(self) # 변경
self.date_to.setCalendarPopup(True)
today = QDate.currentDate()
self.date_from.setDate(today)
self.date_to.setDate(today)
# __init__ 안쪽, date_from/date_to 만든 직후에 추가
for de in (self.date_from, self.date_to):
self._inflate_calendar_popup(de)
self.search_field = QComboBox(self)
self.search_field.addItems(["PID", "SSCC", "Destination", "barcode", "전체"])
self.search_input = QLineEdit(self)
self.search_input.setPlaceholderText("검색어...")
self.search_btn = QPushButton("검색", self)
self.search_btn.clicked.connect(self._on_search_clicked)
filter_row.addWidget(QLabel("시작일:"))
filter_row.addWidget(self.date_from)
filter_row.addWidget(QLabel("종료일:"))
filter_row.addWidget(self.date_to)
filter_row.addWidget(self.search_field)
filter_row.addWidget(self.search_input)
filter_row.addWidget(self.search_btn)
layout.addLayout(filter_row)
# 테이블
self.table = QTableWidget(self)
self.table.setColumnCount(8) # 컬럼 8개로 증가
self.table.setHorizontalHeaderLabels(
["No.", "PID", "SSCC", "Destination", "barcode", "error_reason", "이미지", "시간"])
self.table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
self.table.setItemDelegateForColumn(3, StatusBGDelegate(self.table, allow_green=False))
# 기본 헤더 라벨 저장
self._base_headers = ["No.", "PID", "SSCC", "Destination", "barcode", "error_reason", "이미지", "시간"]
# 정렬 관련 상태 ←★ 먼저 정의해 둡니다
self._sorting_guard = False
self._allowed_sort_cols = {0, 1, 7} # No., PID, 시간
self._sort_col = -1 # 현재 정렬 컬럼 없음
self._sort_order = Qt.SortOrder.AscendingOrder
# 헤더를 item 기반으로 교체(▲/▼ 텍스트 갱신하기 위해)
for i, text in enumerate(self._base_headers):
self.table.setHorizontalHeaderItem(i, QTableWidgetItem(text))
# 줄무늬 등 각종 설정 (생략 가능)
self.table.setAlternatingRowColors(True)
# 헤더/정렬 연결
hdr = self.table.horizontalHeader()
hdr.setSortIndicatorShown(True)
self.table.setSortingEnabled(False) # 기본 자동정렬은 끔
hdr.sectionClicked.connect(self._on_header_clicked)
# ✅ 기본 정렬: 시간(컬럼 7) 내림차순
self._sort_col = 7
self._sort_order = Qt.SortOrder.DescendingOrder
hdr.setSortIndicator(self._sort_col, self._sort_order)
self._update_header_sort_icons()
# ★ 이제 아이콘(▲/▼) 초기 반영
self._update_header_sort_icons()
kb_btn = QPushButton("⌨", self) # 또는 아이콘 사용
kb_btn.setToolTip("화상 키보드 열기")
kb_btn.setFixedWidth(32)
kb_btn.clicked.connect(self._open_virtual_keyboard)
filter_row.addWidget(kb_btn)
# (이하 칼럼 폭, 버튼, DB 연결, _load_all() 호출 등 기존 그대로)
# 더블클릭 이벤트 연결
self.table.cellDoubleClicked.connect(self._on_cell_double_clicked)
# 테이블 컬럼 너비 설정 (이것은 스타일보다는 '동작 방식'에 가까움)
self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed) # No.
self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.Interactive) # PID
self.table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.Interactive) # SSCC
self.table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeMode.Interactive) # Destination
self.table.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeMode.Stretch) # barcode
self.table.horizontalHeader().setSectionResizeMode(5, QHeaderView.ResizeMode.Stretch) # error_reason
self.table.horizontalHeader().setSectionResizeMode(6, QHeaderView.ResizeMode.Interactive) # 이미지
self.table.horizontalHeader().setSectionResizeMode(7, QHeaderView.ResizeMode.Interactive) # 시간
# 초기 컬럼 너비 설정
## (여러 테이블에서 일관된 너비 정책을 쓸 거면 JSON 등 외부 설정으로 분리 고려. QSS로 직접 제어는 어려움)
self.table.setColumnWidth(0, 50) # No.
self.table.setColumnWidth(1, 100) # PID
self.table.setColumnWidth(2, 100) # SSCC
self.table.setColumnWidth(3, 100) # Destination
self.table.setColumnWidth(6, 150) # 이미지
self.table.setColumnWidth(7, 150) # 시간
layout.addWidget(self.table)
# CSV 내보내기 호출 버튼
export_btn = QPushButton("CSV 내보내기", self)
export_btn.clicked.connect(self._export_to_csv)
# 버튼이 가로로 늘어나지 않도록
export_btn.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
export_btn.setFixedWidth(120) # 폭은 취향대로 (예: 100~140)
# 바로 오른쪽 정렬로 추가
layout.addWidget(export_btn, 0, Qt.AlignmentFlag.AlignRight)
# 위젯들 다 만든 뒤에 호출 (가장 마지막쯤)
self._resize_to_ratio(w_ratio=0.70, h_ratio=0.50)
# DB 연결(열 때 바로 한번)
self._conn = None
self._connect_db()
self._load_all()
def _on_header_clicked(self, col: int):
if self._sorting_guard:
return
self._sorting_guard = True
try:
hdr = self.table.horizontalHeader()
# 허용 안 된 컬럼이면 기존 표시만 유지
if col not in self._allowed_sort_cols:
if self._sort_col >= 0:
hdr.setSortIndicator(self._sort_col, self._sort_order)
else:
hdr.setSortIndicator(-1, Qt.SortOrder.AscendingOrder)
self._update_header_sort_icons()
return
same = (self._sort_col == col)
# 정렬 순서 결정: 같은 컬럼 재클릭이면 토글, 다른 컬럼이면 ASC 시작
self._sort_order = (
Qt.SortOrder.DescendingOrder
if same and self._sort_order == Qt.SortOrder.AscendingOrder
else Qt.SortOrder.AscendingOrder
)
# 컬럼 선택: 다른 컬럼 클릭 시에만 변경
if not same:
self._sort_col = col
hdr.setSortIndicator(self._sort_col, self._sort_order)
self.table.setSortingEnabled(True)
self.table.sortItems(self._sort_col, self._sort_order)
self.table.setSortingEnabled(False)
self._update_header_sort_icons()
finally:
self._sorting_guard = False
def _resize_to_ratio(self, w_ratio: float = 0.70, h_ratio: float = 0.70) -> None:
screen = self.screen() or QGuiApplication.primaryScreen()
if not screen:
return
avail = screen.availableGeometry()
w = int(avail.width() * w_ratio)
h = int(avail.height() * h_ratio)
self.resize(w, h)
# 중앙 정렬
g = self.frameGeometry()
g.moveCenter(avail.center())
self.move(g.topLeft())
def _open_virtual_keyboard(self):
import os, sys, subprocess, ctypes
from ctypes import wintypes
if not sys.platform.startswith("win"):
QMessageBox.information(self, "알림",
"이 기능은 Windows에서만 지원됩니다.\n다른 운영체제에서는 시스템 화상 키보드를 수동으로 활성화해주세요.")
return
# --- ShellExecuteW 프로토타입 선언 ---
shell32 = ctypes.WinDLL("shell32", use_last_error=True)
ShellExecuteW = shell32.ShellExecuteW
ShellExecuteW.argtypes = [
wintypes.HWND, # hwnd
wintypes.LPCWSTR, # lpOperation
wintypes.LPCWSTR, # lpFile
wintypes.LPCWSTR, # lpParameters
wintypes.LPCWSTR, # lpDirectory
ctypes.c_int # nShowCmd
]
ShellExecuteW.restype = wintypes.HINSTANCE # 반환값 ≤ 32면 에러
try:
# 1) Run(Win+R)과 동일한 ShellExecute 경로
r = ShellExecuteW(None, "open", "osk.exe", None, None, 1) # SW_SHOWNORMAL=1
if r > 32:
return # 성공
# 2) 64비트 OS에서 32비트 파이썬 우회(Sysnative)
win = os.environ.get("WINDIR", r"C:\Windows")
candidates = [
os.path.join(win, "Sysnative", "osk.exe"),
os.path.join(win, "System32", "osk.exe"),
"osk.exe",
]
for path in candidates:
try:
subprocess.Popen([path], shell=False)
return
except Exception:
pass
# 3) 터치 키보드(TabTip)도 시도
tabtip = os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"),
"Common Files", "microsoft shared", "ink", "TabTip.exe")
subprocess.Popen([tabtip], shell=False)
except Exception as e:
QMessageBox.warning(self, "오류", f"화상 키보드를 여는 데 실패했습니다:\n{e}")
# 클래스 메서드로 추가
def _inflate_calendar_popup(self, de: QDateEdit):
cal = QCalendarWidget(self)
cal.setObjectName("AllDataCalendar") # QSS 타깃용
cal.setGridVisible(True) # 날짜 격자 보이기
cal.setMinimumSize(380, 320) # 팝업 자체를 조금 크게
# 폰트 키우기
f = cal.font()
f.setPointSize(max(14, f.pointSize() + 2))
cal.setFont(f)
# 이 커스텀 달력을 팝업으로 사용
de.setCalendarWidget(cal)
# 입력 필드 자체 클릭영역도 살짝 키우기(선택)
# de.setMinimumHeight(34)
def _update_header_sort_icons(self):
"""현재 self._sort_col / self._sort_order 상태를 헤더 텍스트(▲/▼)에 반영."""
for i, base in enumerate(self._base_headers):
text = base
if i == self._sort_col and i in self._allowed_sort_cols:
arrow = "▲" if self._sort_order == Qt.SortOrder.AscendingOrder else "▼"
text = f"{base} {arrow}"
item = self.table.horizontalHeaderItem(i)
if item is None:
item = QTableWidgetItem(text)
self.table.setHorizontalHeaderItem(i, item)
else:
item.setText(text)
def _connect_db(self):
try:
self._conn = psycopg2.connect(
host=self.cfg.db.host,
port=self.cfg.db.port,
dbname=self.cfg.db.dbname,
user=self.cfg.db.user,
password=self.cfg.db.password,
connect_timeout=5,
)
self._conn.autocommit = True
except Exception as e:
QMessageBox.critical(self, "DB 오류", f"DB 연결 실패: {e}")
def _exec_query(self, query: str, params: Tuple[Any, ...] = ()): # -> list[dict]
if self._conn is None:
return []
try:
with self._conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
cur.execute(query, params)
cols = [d.name for d in cur.description]
return [dict(zip(cols, r)) for r in cur.fetchall()]
except Exception as e:
QMessageBox.critical(self, "DB 오류", str(e))
return []
def _on_search_clicked(self):
self._load_all()
def _on_cell_double_clicked(self, row, col):
# 이미지 경로 컬럼(6번)을 더블 클릭했을 때만 처리
if col == 6:
# ✅ [NEW] 아이템/셀위젯 모두 대응해서 경로 얻기
w = self.table.cellWidget(row, col)
item = self.table.item(row, col)
image_path = (w.text().strip() if isinstance(w, QLabel) else (item.text().strip() if item else ""))
# ↓↓↓ 기존 로직은 그대로 유지 ↓↓↓
if not image_path:
QMessageBox.information(self, "알림", "이미지 경로가 없습니다.")
return
# 이미지 파일 존재 확인
if not os.path.exists(image_path):
QMessageBox.warning(self, "경고", f"이미지 파일을 찾을 수 없습니다:\n{image_path}")
return
# PyQt 이미지 뷰어 대화 상자로 열기
try:
# 이미지 로드
original_pixmap = QPixmap(image_path)
if original_pixmap.isNull():
QMessageBox.warning(self, "오류", "이미지를 로드할 수 없습니다.")
return
# 이미지 뷰어 대화 상자 생성
image_dialog = QDialog(self)
image_dialog.setWindowTitle(f"이미지 뷰어 - {os.path.basename(image_path)}")
image_dialog.setWindowFlags(Qt.WindowType.Window | Qt.WindowType.WindowStaysOnTopHint) # 항상 위에 표시