Files
king 96438d5078 feat(inout): 입고 기록 줄 [사방넷 입고 파일] 엑셀 다운로드
- 1행 제목 상품코드·가용수량·불용수량, A=코드표 사방넷 코드, B=입고 수량, C=상품 이름
- 사방넷 코드가 없는 상품·코드표 연결 불가면 파일 대신 안내
- 발주·입고 담당, 마이그레이션 없음

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:44:42 +09:00

104 lines
5.1 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 sabangnet_codes(self, codes: list[str]) -> dict[str, str] | None:
"""코드들 → {코드(대문자): 사방넷 코드}(사방넷 입고 파일, 2026-10-19). 사방넷 코드가 빈 단품은 ''. 조회 불가면 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("SELECT item_code, sabangnet_code FROM single_items WHERE upper(item_code) = ANY(%(codes)s)", {"codes": wanted})
if rows is None:
return None
return {str(r["item_code"]).strip().upper(): str(r.get("sabangnet_code") 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()