a475f0b2f6
- 마이그레이션 004: inout_products(단가·개당 무게 g·은 함유량 %), inout_products_excluded(지운 단품), inout_order_lines 에 발주할 때 값 사본(unit_price·weight_g·silver_pct) - 옵션 → 상품 정보: [단품 불러오기](값을 넣은 상품은 그대로, 지운 단품은 다음에도 빠짐), 바뀐 줄만 저장, 은 g = 무게 × % 자동, 지우기·되살리기 - 상품 정보가 있으면 발주서 제품은 그 목록에서(단가 함께), 금액 = 수량 × 단가 실시간 합계 - 발주서 화면(발주 담당)·발주 메일에 단가·금액·PP(g/개)·은 함유량과 합계(금액·PP kg·은 g) - 입고 담당(발주 담당 아님)은 품목을 제품 이름·발주 수량(+ 이번 입고)만, 입고 기록 칩도 이름 - 고침: 그날 100번째 발주서부터 번호가 겹치던 문제(순번 숫자 비교), 시각을 DB 시간대와 무관하게 KST 로 읽음 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
92 lines
4.4 KiB
Python
92 lines
4.4 KiB
Python
"""itemcode_db 읽기 전용 — 단품(single_items)만 검색·확인.
|
|
|
|
입출고 발주서의 제품은 코드표 DB 의 단품 아이템에서만 고른다(2026-10-16 사용자 요청 — 세트는 공장 발주 대상이 아님).
|
|
itemcode_db 실제 스키마(운영 확인됨, malaysia/itemcode.py 와 같음): single_items(item_code, sabangnet_code, name).
|
|
환경변수 `ITEMCODE_DB_URL`(읽기 전용 역할 itemcode_ro) — cupang·malaysia 모듈과 공유.
|
|
미설정/실패 시 enabled=False, 빈 결과(앱/모듈을 죽이지 않음) — 그때 발주서 저장은 "코드표 연결 필요"로 막는다.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import os
|
|
from typing import Any
|
|
|
|
logger = logging.getLogger("inout.itemcode")
|
|
|
|
_SEARCH_SQL = (
|
|
"SELECT item_code, name FROM single_items "
|
|
"WHERE item_code ILIKE %(q)s OR name ILIKE %(q)s "
|
|
"ORDER BY (item_code ILIKE %(prefix)s) DESC, item_code ASC LIMIT %(limit)s"
|
|
)
|
|
_LOOKUP_SQL = "SELECT item_code, name FROM single_items WHERE upper(item_code) = ANY(%(codes)s)"
|
|
|
|
|
|
class SingleItemReader:
|
|
def __init__(self, dsn: str | None = None) -> None:
|
|
self._pool: Any = None
|
|
self.enabled = False
|
|
self.reason = ""
|
|
self.last_error = ""
|
|
self._configure(dsn if dsn is not None else os.getenv("ITEMCODE_DB_URL", "").strip())
|
|
|
|
def _configure(self, dsn: str) -> None:
|
|
if not dsn:
|
|
self.reason = "ITEMCODE_DB_URL 미설정 — 코드표(단품) 조회 비활성."
|
|
return
|
|
try:
|
|
from psycopg.rows import dict_row
|
|
from psycopg_pool import ConnectionPool
|
|
|
|
self._pool = ConnectionPool(conninfo=dsn, min_size=1, max_size=3,
|
|
kwargs={"row_factory": dict_row, "autocommit": True}, open=False)
|
|
self._pool.open(wait=False)
|
|
self.enabled = True
|
|
except Exception as exc: # noqa: BLE001 — 설정/드라이버 문제로 모듈을 죽이지 않음
|
|
self.reason = f"itemcode_db 연결 풀 생성 실패: {type(exc).__name__}"
|
|
|
|
def search(self, query: str, *, limit: int = 30) -> list[dict[str, str]]:
|
|
"""코드·이름 부분 일치(코드 앞부분 일치 먼저). 반환 [{"code","name"}]. 실패는 빈 목록."""
|
|
q = (query or "").strip()
|
|
if not q or not self.enabled or not self._pool:
|
|
return []
|
|
esc = q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
|
rows = self._run(_SEARCH_SQL, {"q": f"%{esc}%", "prefix": f"{esc}%", "limit": int(limit)})
|
|
return [{"code": str(r["item_code"]).strip(), "name": str(r.get("name") or "").strip()} for r in rows or []]
|
|
|
|
def list_all(self, *, limit: int = 20000) -> list[dict[str, str]] | None:
|
|
"""단품 전체(옵션 → 상품 정보 → 단품 불러오기). 조회 불가면 None(빈 목록과 구분)."""
|
|
if not self.enabled or not self._pool:
|
|
return None
|
|
rows = self._run("SELECT item_code, name FROM single_items ORDER BY item_code LIMIT %(limit)s", {"limit": int(limit)})
|
|
if rows is None:
|
|
return None
|
|
return [{"code": str(r["item_code"]).strip().upper(), "name": str(r.get("name") or "").strip()} for r in rows if r.get("item_code")]
|
|
|
|
def lookup(self, codes: list[str]) -> dict[str, str] | None:
|
|
"""코드들 → {코드(대문자): 이름}. 단품 표에 없는 코드는 빠진다. 조회 불가면 None."""
|
|
if not self.enabled or not self._pool:
|
|
return None
|
|
wanted = sorted({c.strip().upper() for c in codes if c and c.strip()})
|
|
if not wanted:
|
|
return {}
|
|
rows = self._run(_LOOKUP_SQL, {"codes": wanted})
|
|
if rows is None:
|
|
return None
|
|
return {str(r["item_code"]).strip().upper(): str(r.get("name") or "").strip() for r in rows}
|
|
|
|
def _run(self, sql: str, params: dict[str, Any]) -> list[dict[str, Any]] | None:
|
|
try:
|
|
with self._pool.connection() as conn:
|
|
rows = conn.execute(sql, params).fetchall()
|
|
self.last_error = ""
|
|
return rows
|
|
except Exception as exc: # noqa: BLE001 — 모듈을 죽이지 않음
|
|
self.last_error = f"{type(exc).__name__}"
|
|
logger.exception("itemcode(single_items) 조회 실패")
|
|
return None
|
|
|
|
def close(self) -> None:
|
|
if self._pool is not None:
|
|
self._pool.close()
|