"""inout_db PostgreSQL 저장소 — 공장·담당자·발주서·입고. - 드라이버: psycopg 3 + pool(다른 모듈과 같은 패턴), 연결 `INOUT_DB_URL`. 스키마는 scripts/sql/inout_db_init.sql(앱이 만들지 않음). - 상태(발주·부분입고·입고완료·초과·종결·취소)는 저장하지 않고 품목별 누적 입고로 계산한다(store.order_status) — 어긋날 일이 없다. - 쓰기는 한 트랜잭션. 입고 저장은 발주서 행을 잠그고(FOR UPDATE) 그 안에서 누적 입고를 다시 읽어 초과를 판단한다 (두 사람이 동시에 입고해도 초과 확인을 건너뛰지 않게). """ from __future__ import annotations from datetime import date from typing import Any from psycopg.errors import UndefinedColumn, UndefinedTable from psycopg.rows import dict_row from psycopg_pool import ConnectionPool from . import store _SCAN_LIMIT = 20000 # 목록에서 상태 거르기 전에 읽는 발주서 상한 class OverReceipt(Exception): """확인 없이 발주보다 많이 입고하려 함 — over = [{item_code, item_name, ordered, after, over}].""" def __init__(self, over: list[dict[str, Any]]) -> None: super().__init__("초과 입고") self.over = over def _norm_email(e: str) -> str: return (e or "").strip().lower() class InoutDBStore: def __init__(self, dsn: str, *, min_size: int = 1, max_size: int = 5): self._pool = ConnectionPool(conninfo=dsn, min_size=min_size, max_size=max_size, kwargs={"row_factory": dict_row, "autocommit": True}, open=False) self._pool.open(wait=False) def close(self) -> None: self._pool.close() # ════════════════════════════════════════════════════════════ # 공장 # ════════════════════════════════════════════════════════════ def list_factories(self, *, include_inactive: bool = False) -> list[dict[str, Any]]: where = "" if include_inactive else "WHERE f.is_active" with self._pool.connection() as conn: return conn.execute( "SELECT f.*, (SELECT count(*) FROM inout_orders o WHERE o.factory_id = f.id) AS order_count " f"FROM inout_factories f {where} ORDER BY f.is_active DESC, f.sort_order, f.name" ).fetchall() def save_factory(self, *, factory_id: int | None, name: str, manager: str = "", contact: str = "", email: str = "", memo: str = "", is_active: bool = True, sort_order: int = 0) -> int: """공장 추가·수정. 담당자(manager, 002)·연락처(contact)·이메일(email, 003 — 여러 개는 쉼표).""" name = (name or "").strip() if not name or len(name) > 100: raise ValueError("공장 이름을 1~100자로 입력하세요.") emails = ", ".join(store.parse_emails(email, label="공장 이메일")) vals = (name, (manager or "").strip()[:100], (contact or "").strip()[:200], emails, (memo or "").strip()[:store.MEMO_MAX], bool(is_active), int(sort_order)) try: with self._pool.connection() as conn: dup = conn.execute("SELECT id FROM inout_factories WHERE lower(name) = lower(%s) AND id <> %s", (name, factory_id or 0)).fetchone() if dup: raise ValueError(f"같은 이름의 공장이 이미 있습니다: {name}") if factory_id: row = conn.execute( "UPDATE inout_factories SET name=%s, manager=%s, contact=%s, email=%s, memo=%s, is_active=%s, sort_order=%s " "WHERE id=%s RETURNING id", (*vals, factory_id)).fetchone() if not row: raise ValueError("공장을 찾을 수 없습니다.") return int(row["id"]) return int(conn.execute( "INSERT INTO inout_factories (name, manager, contact, email, memo, is_active, sort_order) " "VALUES (%s,%s,%s,%s,%s,%s,%s) RETURNING id", vals).fetchone()["id"]) except UndefinedColumn: raise ValueError("DB 마이그레이션 inout_db 002·003(공장 담당자·이메일 칸)이 아직 적용되지 않았습니다.") from None def delete_factory(self, factory_id: int) -> None: """발주 기록이 없는 공장만 지운다(있으면 '사용 안 함'으로 숨김).""" with self._pool.connection() as conn: used = conn.execute("SELECT 1 FROM inout_orders WHERE factory_id=%s LIMIT 1", (factory_id,)).fetchone() if used: raise ValueError("발주 기록이 있는 공장은 지울 수 없습니다 — '사용 안 함'으로 바꾸세요.") conn.execute("DELETE FROM inout_factories WHERE id=%s", (factory_id,)) # ════════════════════════════════════════════════════════════ # 담당자(발주 담당·입고 담당) # ════════════════════════════════════════════════════════════ def list_roles(self) -> dict[str, list[str]]: out: dict[str, list[str]] = {r: [] for r in store.ROLES} with self._pool.connection() as conn: for r in conn.execute("SELECT email, role FROM inout_roles ORDER BY email").fetchall(): out.setdefault(r["role"], []).append(r["email"]) return out def roles_of(self, email: str) -> set[str]: with self._pool.connection() as conn: rows = conn.execute("SELECT role FROM inout_roles WHERE email=%s", (_norm_email(email),)).fetchall() return {r["role"] for r in rows} def set_role_members(self, role: str, emails: list[str], *, by: str) -> None: """그 역할 담당자를 통째로 바꾼다(한 트랜잭션).""" if role not in store.ROLES: raise ValueError("알 수 없는 담당 종류입니다.") clean = sorted({_norm_email(e) for e in emails if _norm_email(e)}) with self._pool.connection() as conn, conn.transaction(): conn.execute("DELETE FROM inout_roles WHERE role=%s AND NOT (email = ANY(%s))", (role, clean)) for e in clean: conn.execute("INSERT INTO inout_roles (email, role, created_by) VALUES (%s,%s,%s) ON CONFLICT DO NOTHING", (e, role, _norm_email(by))) # ════════════════════════════════════════════════════════════ # 발주서 # ════════════════════════════════════════════════════════════ def create_order(self, data: dict[str, Any], names: dict[str, str], *, by: str) -> dict[str, Any]: """data = store.validate_order 결과, names = {코드: 단품 이름}. 반환 {id, order_no}.""" with self._pool.connection() as conn, conn.transaction(): self._require_factory(conn, data["factory_id"]) conn.execute("SELECT pg_advisory_xact_lock(hashtext('inout_order_no'))") prefix = store.order_no(data["order_date"], 0)[:-2] row = conn.execute("SELECT max(order_no) AS m FROM inout_orders WHERE order_no LIKE %s", (prefix + "%",)).fetchone() last = row["m"] if row else None seq = int(last.rsplit("-", 1)[1]) + 1 if last and last.rsplit("-", 1)[1].isdigit() else 1 no = store.order_no(data["order_date"], seq) oid = conn.execute( "INSERT INTO inout_orders (order_no, factory_id, order_date, due_date, memo, created_by, updated_by) " "VALUES (%s,%s,%s,%s,%s,%s,%s) RETURNING id", (no, data["factory_id"], data["order_date"], data["due_date"], data["memo"], _norm_email(by), _norm_email(by)), ).fetchone()["id"] for i, ln in enumerate(data["lines"], start=1): conn.execute("INSERT INTO inout_order_lines (order_id, line_no, item_code, item_name, qty, memo) " "VALUES (%s,%s,%s,%s,%s,%s)", (oid, i, ln["item_code"], names.get(ln["item_code"], ""), ln["qty"], ln["memo"])) return {"id": int(oid), "order_no": no} def update_order(self, order_id: int, data: dict[str, Any], names: dict[str, str], *, by: str) -> None: """머리글·품목 고치기. 입고된 품목은 뺄 수 없다(입고 기록이 사라지므로) — 수량은 바꿀 수 있다.""" with self._pool.connection() as conn, conn.transaction(): head = self._lock_order(conn, order_id) if head["cancelled_at"]: raise ValueError("취소된 발주서는 고칠 수 없습니다.") self._require_factory(conn, data["factory_id"], allow_inactive_id=head["factory_id"]) existing = {r["item_code"]: r for r in conn.execute( "SELECT l.id, l.item_code, COALESCE(sum(rl.qty), 0) AS received FROM inout_order_lines l " "LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id WHERE l.order_id=%s GROUP BY l.id", (order_id,)).fetchall()} wanted = {ln["item_code"] for ln in data["lines"]} blocked = [c for c, r in existing.items() if c not in wanted and int(r["received"]) > 0] if blocked: raise ValueError("입고 기록이 있는 품목은 뺄 수 없습니다: " + ", ".join(sorted(blocked))) for code, r in existing.items(): if code not in wanted: conn.execute("DELETE FROM inout_order_lines WHERE id=%s", (r["id"],)) for i, ln in enumerate(data["lines"], start=1): if ln["item_code"] in existing: conn.execute("UPDATE inout_order_lines SET line_no=%s, qty=%s, memo=%s WHERE id=%s", (i, ln["qty"], ln["memo"], existing[ln["item_code"]]["id"])) else: conn.execute("INSERT INTO inout_order_lines (order_id, line_no, item_code, item_name, qty, memo) " "VALUES (%s,%s,%s,%s,%s,%s)", (order_id, i, ln["item_code"], names.get(ln["item_code"], ""), ln["qty"], ln["memo"])) conn.execute("UPDATE inout_orders SET factory_id=%s, order_date=%s, due_date=%s, memo=%s, updated_by=%s WHERE id=%s", (data["factory_id"], data["order_date"], data["due_date"], data["memo"], _norm_email(by), order_id)) def set_closed(self, order_id: int, *, closed: bool, reason: str = "", by: str) -> None: """종결(남은 미입고를 더 기다리지 않음) / 종결 풀기.""" with self._pool.connection() as conn, conn.transaction(): head = self._lock_order(conn, order_id) if head["cancelled_at"]: raise ValueError("취소된 발주서입니다.") if closed: conn.execute("UPDATE inout_orders SET closed_at=now(), closed_by=%s, close_reason=%s, updated_by=%s WHERE id=%s", (_norm_email(by), (reason or "").strip()[:store.MEMO_MAX], _norm_email(by), order_id)) else: conn.execute("UPDATE inout_orders SET closed_at=NULL, closed_by='', close_reason='', updated_by=%s WHERE id=%s", (_norm_email(by), order_id)) def cancel_order(self, order_id: int, *, by: str) -> None: """잘못 넣은 발주 — 입고 기록이 없을 때만 취소(기록은 남김).""" with self._pool.connection() as conn, conn.transaction(): self._lock_order(conn, order_id) if conn.execute("SELECT 1 FROM inout_receipts WHERE order_id=%s LIMIT 1", (order_id,)).fetchone(): raise ValueError("입고 기록이 있는 발주서는 취소할 수 없습니다 — 남은 수량은 '종결'하세요.") conn.execute("UPDATE inout_orders SET cancelled_at=now(), cancelled_by=%s, updated_by=%s WHERE id=%s", (_norm_email(by), _norm_email(by), order_id)) def get_order(self, order_id: int) -> dict[str, Any] | None: with self._pool.connection() as conn: head = conn.execute( # 담당자(manager)는 002 열 — 미적용 DB 에서도 깨지지 않게 to_jsonb 로 읽는다 "SELECT o.*, f.name AS factory_name, to_jsonb(f) ->> 'manager' AS factory_manager, f.contact AS factory_contact, " "COALESCE(to_jsonb(f) ->> 'email', '') AS factory_email " "FROM inout_orders o JOIN inout_factories f ON f.id = o.factory_id WHERE o.id=%s", (order_id,)).fetchone() if not head: return None lines = conn.execute( "SELECT l.*, COALESCE(sum(rl.qty), 0)::int AS received FROM inout_order_lines l " "LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id WHERE l.order_id=%s " "GROUP BY l.id ORDER BY l.line_no", (order_id,)).fetchall() receipts = conn.execute("SELECT * FROM inout_receipts WHERE order_id=%s ORDER BY receipt_date, id", (order_id,)).fetchall() rlines = conn.execute( "SELECT rl.receipt_id, rl.order_line_id, rl.qty, l.item_code, l.item_name FROM inout_receipt_lines rl " "JOIN inout_order_lines l ON l.id = rl.order_line_id JOIN inout_receipts r ON r.id = rl.receipt_id " "WHERE r.order_id=%s ORDER BY l.line_no", (order_id,)).fetchall() # 입고증 사진(목록만 — 내용은 /inout/photos/{id})·발주 메일 기록 — 003 미적용이면 빈 목록 try: photos = conn.execute( "SELECT p.id, p.receipt_id, p.filename, p.content_type, p.size_bytes FROM inout_receipt_photos p " "JOIN inout_receipts r ON r.id = p.receipt_id WHERE r.order_id=%s ORDER BY p.id", (order_id,)).fetchall() mails = conn.execute("SELECT * FROM inout_order_mails WHERE order_id=%s ORDER BY sent_at, id", (order_id,)).fetchall() except UndefinedTable: photos, mails = [], [] by_photo: dict[int, list[dict[str, Any]]] = {} for ph in photos: by_photo.setdefault(int(ph["receipt_id"]), []).append(ph) by_receipt: dict[int, list[dict[str, Any]]] = {} for r in rlines: by_receipt.setdefault(int(r["receipt_id"]), []).append(r) lines = store.decorate_lines(lines) status = store.order_status(lines, closed=bool(head["closed_at"]), cancelled=bool(head["cancelled_at"])) return {**head, "lines": lines, "summary": store.summarize(lines), "status": status, "status_label": store.ORDER_LABELS[status], "receipts": [{**r, "lines": by_receipt.get(int(r["id"]), []), "photos": by_photo.get(int(r["id"]), []), "total": sum(int(x["qty"]) for x in by_receipt.get(int(r["id"]), []))} for r in receipts], "mails": mails} def list_orders(self, *, status: str = "active", factory_id: int | None = None, q: str = "", date_from: date | None = None, date_to: date | None = None, limit: int = 500) -> list[dict[str, Any]]: """목록 — 상태는 품목 합계로 계산한 뒤 거른다. q = 발주번호·제품 코드·제품 이름.""" where, params = ["TRUE"], [] if factory_id: where.append("o.factory_id = %s") params.append(factory_id) if date_from: where.append("o.order_date >= %s") params.append(date_from) if date_to: where.append("o.order_date <= %s") params.append(date_to) if q.strip(): like = "%" + q.strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%" where.append("(o.order_no ILIKE %s OR EXISTS (SELECT 1 FROM inout_order_lines x WHERE x.order_id = o.id " "AND (x.item_code ILIKE %s OR x.item_name ILIKE %s)))") params += [like, like, like] with self._pool.connection() as conn: heads = conn.execute( "SELECT o.*, f.name AS factory_name FROM inout_orders o JOIN inout_factories f ON f.id = o.factory_id " # 상태는 품목 합계로 계산해 아래에서 거르므로 넉넉히 읽는다(발주서는 많아야 연 수천 건) f"WHERE {' AND '.join(where)} ORDER BY o.order_date DESC, o.id DESC LIMIT {_SCAN_LIMIT}", params ).fetchall() ids = [h["id"] for h in heads] lines = conn.execute( "SELECT l.order_id, l.item_code, l.item_name, l.qty, COALESCE(sum(rl.qty), 0)::int AS received " "FROM inout_order_lines l LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id " "WHERE l.order_id = ANY(%s) GROUP BY l.id ORDER BY l.line_no", (ids,)).fetchall() if ids else [] by_order: dict[int, list[dict[str, Any]]] = {} for ln in lines: by_order.setdefault(int(ln["order_id"]), []).append(ln) allowed = store.STATUS_FILTERS.get(status, store.STATUS_FILTERS["active"])[1] out = [] for h in heads: ls = by_order.get(int(h["id"]), []) st = store.order_status(ls, closed=bool(h["closed_at"]), cancelled=bool(h["cancelled_at"])) if st not in allowed: continue names = [x["item_name"] or x["item_code"] for x in ls] out.append({**h, "status": st, "status_label": store.ORDER_LABELS[st], "summary": store.summarize(ls), "line_count": len(ls), "items_label": (names[0] + (f" 외 {len(names) - 1}종" if len(names) > 1 else "")) if names else ""}) if len(out) >= limit: break return out # ════════════════════════════════════════════════════════════ # 입고 # ════════════════════════════════════════════════════════════ def add_receipt(self, order_id: int, quantities: dict[int, Any], *, receipt_date: Any, memo: Any, confirm_over: bool, by: str, photos: list[dict[str, Any]] | None = None) -> dict[str, Any]: """입고 1건 저장. 발주를 넘는 품목이 있는데 confirm_over 가 아니면 OverReceipt(아무것도 저장 안 함). photos = store.validate_photos 결과(입고증) — 입고와 한 트랜잭션(사진 저장이 실패하면 입고도 저장 안 함).""" try: return self._add_receipt(order_id, quantities, receipt_date=receipt_date, memo=memo, confirm_over=confirm_over, by=by, photos=photos or []) except UndefinedTable: raise ValueError("DB 마이그레이션 inout_db 003(입고증 사진)이 아직 적용되지 않아 사진을 저장할 수 없습니다 — " "사진 없이 저장하거나 관리자에게 알려 주세요.") from None def _add_receipt(self, order_id: int, quantities: dict[int, Any], *, receipt_date: Any, memo: Any, confirm_over: bool, by: str, photos: list[dict[str, Any]]) -> dict[str, Any]: with self._pool.connection() as conn, conn.transaction(): head = self._lock_order(conn, order_id) if head["cancelled_at"]: raise ValueError("취소된 발주서에는 입고할 수 없습니다.") if head["closed_at"]: raise ValueError("종결된 발주서입니다 — 입고하려면 발주 담당이 종결을 풀어야 합니다.") lines = conn.execute( "SELECT l.id, l.item_code, l.item_name, l.qty, COALESCE(sum(rl.qty), 0)::int AS received " "FROM inout_order_lines l LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id " "WHERE l.order_id=%s GROUP BY l.id", (order_id,)).fetchall() data = store.validate_receipt(lines, quantities, receipt_date=receipt_date, memo=memo) if data["over"] and not confirm_over: raise OverReceipt(data["over"]) rid = conn.execute("INSERT INTO inout_receipts (order_id, receipt_date, memo, created_by) VALUES (%s,%s,%s,%s) RETURNING id", (order_id, data["receipt_date"], data["memo"], _norm_email(by))).fetchone()["id"] for it in data["items"]: conn.execute("INSERT INTO inout_receipt_lines (receipt_id, order_line_id, qty) VALUES (%s,%s,%s)", (rid, it["order_line_id"], it["qty"])) self._insert_photos(conn, int(rid), photos, by) return {"id": int(rid), "over": data["over"], "total": sum(it["qty"] for it in data["items"]), "photos": len(photos)} # ── 입고증 사진(003) ── @staticmethod def _insert_photos(conn: Any, receipt_id: int, photos: list[dict[str, Any]], by: str) -> None: for ph in photos: conn.execute("INSERT INTO inout_receipt_photos (receipt_id, filename, content_type, size_bytes, data, created_by) " "VALUES (%s,%s,%s,%s,%s,%s)", (receipt_id, ph["filename"], ph["content_type"], len(ph["data"]), ph["data"], _norm_email(by))) def add_receipt_photos(self, order_id: int, receipt_id: int, files: list[tuple[str, bytes]], *, by: str) -> int: """이미 있는 입고에 사진 더하기(빠뜨렸을 때). 장수 한도는 잠근 뒤 다시 센다. 반환 = 더한 장수.""" try: with self._pool.connection() as conn, conn.transaction(): head = self._lock_order(conn, order_id) if head["cancelled_at"]: raise ValueError("취소된 발주서입니다.") if not conn.execute("SELECT 1 FROM inout_receipts WHERE id=%s AND order_id=%s", (receipt_id, order_id)).fetchone(): raise ValueError("입고 기록을 찾을 수 없습니다.") have = int(conn.execute("SELECT count(*) AS n FROM inout_receipt_photos WHERE receipt_id=%s", (receipt_id,)).fetchone()["n"]) photos = store.validate_photos(files, existing=have) if not photos: raise ValueError("올릴 사진을 고르세요.") self._insert_photos(conn, receipt_id, photos, by) return len(photos) except UndefinedTable: raise ValueError("DB 마이그레이션 inout_db 003(입고증 사진)이 아직 적용되지 않았습니다.") from None def delete_receipt_photo(self, order_id: int, photo_id: int) -> None: with self._pool.connection() as conn, conn.transaction(): self._lock_order(conn, order_id) row = conn.execute("DELETE FROM inout_receipt_photos p USING inout_receipts r " "WHERE p.id=%s AND p.receipt_id = r.id AND r.order_id=%s RETURNING p.id", (photo_id, order_id)).fetchone() if not row: raise ValueError("사진을 찾을 수 없습니다.") def get_photo(self, photo_id: int) -> dict[str, Any] | None: """사진 내용(+ 발주서 id) — 보여 주기용.""" try: with self._pool.connection() as conn: return conn.execute("SELECT p.id, p.filename, p.content_type, p.data, r.order_id FROM inout_receipt_photos p " "JOIN inout_receipts r ON r.id = p.receipt_id WHERE p.id=%s", (photo_id,)).fetchone() except UndefinedTable: return None # ════════════════════════════════════════════════════════════ # Gmail 연결(사람별, 갱신 토큰 암호문만) · 발주 메일 기록 — 003 # ════════════════════════════════════════════════════════════ def gmail_token(self, email: str) -> dict[str, Any] | None: try: with self._pool.connection() as conn: return conn.execute("SELECT * FROM inout_gmail_tokens WHERE email=%s", (_norm_email(email),)).fetchone() except UndefinedTable: return None def save_gmail_token(self, email: str, *, refresh_token_enc: str, scopes: str) -> None: try: with self._pool.connection() as conn: conn.execute("INSERT INTO inout_gmail_tokens (email, refresh_token_enc, scopes, connected_at, last_error) " "VALUES (%s,%s,%s,now(),'') ON CONFLICT (email) DO UPDATE SET refresh_token_enc=EXCLUDED.refresh_token_enc, " "scopes=EXCLUDED.scopes, connected_at=now(), last_error=''", (_norm_email(email), refresh_token_enc, scopes[:500])) except UndefinedTable: raise ValueError("DB 마이그레이션 inout_db 003(발주 메일)이 아직 적용되지 않았습니다.") from None def delete_gmail_token(self, email: str) -> None: try: with self._pool.connection() as conn: conn.execute("DELETE FROM inout_gmail_tokens WHERE email=%s", (_norm_email(email),)) except UndefinedTable: pass def mark_gmail(self, email: str, *, error: str = "") -> None: """보낸 뒤 — 성공이면 마지막 사용 시각, 실패면 오류 문구(비밀값 없음).""" with self._pool.connection() as conn: conn.execute("UPDATE inout_gmail_tokens SET last_used_at = CASE WHEN %s = '' THEN now() ELSE last_used_at END, " "last_error=%s WHERE email=%s", (error[:300], error[:300], _norm_email(email))) def add_order_mail(self, order_id: int, *, sent_by: str, to: list[str], cc: list[str], subject: str, gmail_id: str) -> None: with self._pool.connection() as conn: conn.execute("INSERT INTO inout_order_mails (order_id, sent_by, to_addrs, cc_addrs, subject, gmail_id) " "VALUES (%s,%s,%s,%s,%s,%s)", (order_id, _norm_email(sent_by), ", ".join(to), ", ".join(cc), subject[:300], gmail_id[:100])) def delete_receipt(self, order_id: int, receipt_id: int, *, by: str) -> None: """잘못 넣은 입고 1건을 지운다(그 수량만큼 다시 미입고).""" with self._pool.connection() as conn, conn.transaction(): head = self._lock_order(conn, order_id) if head["cancelled_at"]: raise ValueError("취소된 발주서입니다.") row = conn.execute("DELETE FROM inout_receipts WHERE id=%s AND order_id=%s RETURNING id", (receipt_id, order_id)).fetchone() if not row: raise ValueError("입고 기록을 찾을 수 없습니다.") conn.execute("UPDATE inout_orders SET updated_by=%s WHERE id=%s", (_norm_email(by), order_id)) # ════════════════════════════════════════════════════════════ # 미입고 현황 — 진행 중(종결·취소 아님) 발주의 남은 수량, 그리고 초과 입고 # ════════════════════════════════════════════════════════════ def outstanding(self, *, factory_id: int | None = None, q: str = "") -> dict[str, list[dict[str, Any]]]: where, params = ["o.closed_at IS NULL", "o.cancelled_at IS NULL"], [] if factory_id: where.append("o.factory_id = %s") params.append(factory_id) if q.strip(): like = "%" + q.strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%" where.append("(l.item_code ILIKE %s OR l.item_name ILIKE %s OR o.order_no ILIKE %s)") params += [like, like, like] with self._pool.connection() as conn: rows = conn.execute( "SELECT o.id AS order_id, o.order_no, o.order_date, o.due_date, f.name AS factory_name, " "l.item_code, l.item_name, l.qty, COALESCE(sum(rl.qty), 0)::int AS received " "FROM inout_order_lines l JOIN inout_orders o ON o.id = l.order_id " "JOIN inout_factories f ON f.id = o.factory_id " "LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id " f"WHERE {' AND '.join(where)} GROUP BY l.id, o.id, f.name " "ORDER BY o.due_date NULLS LAST, o.order_date, o.id, l.line_no", params).fetchall() rows = store.decorate_lines(rows) return {"pending": [r for r in rows if r["remaining"] > 0], "over": [r for r in rows if r["over"] > 0]} # ── 내부 ── @staticmethod def _lock_order(conn: Any, order_id: int) -> dict[str, Any]: head = conn.execute("SELECT * FROM inout_orders WHERE id=%s FOR UPDATE", (order_id,)).fetchone() if not head: raise LookupError("발주서를 찾을 수 없습니다.") return head @staticmethod def _require_factory(conn: Any, factory_id: int, *, allow_inactive_id: int | None = None) -> None: row = conn.execute("SELECT is_active FROM inout_factories WHERE id=%s", (factory_id,)).fetchone() if not row: raise ValueError("공장을 찾을 수 없습니다.") if not row["is_active"] and factory_id != allow_inactive_id: raise ValueError("사용하지 않는 공장입니다(옵션에서 '사용'으로 바꾸세요).")