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>
599 lines
39 KiB
Python
599 lines
39 KiB
Python
"""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, datetime
|
|
from typing import Any
|
|
|
|
from psycopg.errors import UndefinedColumn, UndefinedTable
|
|
from psycopg.rows import dict_row
|
|
from psycopg.types.datetime import TimestamptzLoader
|
|
from psycopg_pool import ConnectionPool
|
|
|
|
from app.timezone import KST
|
|
|
|
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 _KstTimestamptzLoader(TimestamptzLoader):
|
|
"""TIMESTAMPTZ → 한국 시각(KST) datetime. 화면·메일에 찍는 시각(입력·보낸 시각 등)이 DB 서버 시간대(보통 UTC)와 무관하게."""
|
|
|
|
def load(self, data: Any) -> datetime:
|
|
return super().load(data).astimezone(KST)
|
|
|
|
|
|
def _kst_session(conn: Any) -> None:
|
|
# 세션 시간대(SET TIME ZONE)는 쓰지 않는다 — 'Asia/Seoul' 은 시간대 자료가 없는 서버에서 접속이 실패하고,
|
|
# 고정 오프셋은 psycopg 가 못 읽어 UTC 로 돌아간다. 읽을 때 파이썬에서 바꾼다.
|
|
conn.adapters.register_loader("timestamptz", _KstTimestamptzLoader)
|
|
|
|
|
|
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}, configure=_kst_session, 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 _insert_line(self, conn: Any, order_id: int, line_no: int, ln: dict[str, Any], names: dict[str, str],
|
|
specs: dict[str, dict[str, Any]]) -> None:
|
|
"""발주 품목 한 줄 — 004 가 적용됐으면 상품 정보의 단가·무게·은 함유량을 그때 값으로 함께 남긴다."""
|
|
if self.products_ready():
|
|
sp = specs.get(ln["item_code"]) or {}
|
|
conn.execute("INSERT INTO inout_order_lines (order_id, line_no, item_code, item_name, qty, memo, unit_price, weight_g, silver_pct) "
|
|
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)",
|
|
(order_id, line_no, ln["item_code"], names.get(ln["item_code"], ""), ln["qty"], ln["memo"],
|
|
sp.get("unit_price"), sp.get("weight_g"), sp.get("silver_pct")))
|
|
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, line_no, ln["item_code"], names.get(ln["item_code"], ""), ln["qty"], ln["memo"]))
|
|
|
|
def create_order(self, data: dict[str, Any], names: dict[str, str], *, by: str,
|
|
specs: dict[str, dict[str, Any]] | None = None) -> dict[str, Any]:
|
|
"""data = store.validate_order 결과, names = {코드: 단품 이름}, specs = {코드: 상품 정보 행}(004). 반환 {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]
|
|
# 순번은 숫자로 비교 — 글자 max 면 "-99" 가 "-100" 보다 커서 100번째부터 같은 번호가 나온다
|
|
row = conn.execute("SELECT max(substr(order_no, %s)::int) AS m FROM inout_orders "
|
|
"WHERE order_no LIKE %s AND substr(order_no, %s) ~ '^[0-9]{1,9}$'",
|
|
(len(prefix) + 1, prefix + "%", len(prefix) + 1)).fetchone()
|
|
seq = (row["m"] or 0) + 1 if row 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):
|
|
self._insert_line(conn, oid, i, ln, names, specs or {})
|
|
return {"id": int(oid), "order_no": no}
|
|
|
|
def update_order(self, order_id: int, data: dict[str, Any], names: dict[str, str], *, by: str,
|
|
specs: dict[str, dict[str, Any]] | None = None) -> None:
|
|
"""머리글·품목 고치기. 입고된 품목은 뺄 수 없다(입고 기록이 사라지므로) — 수량은 바꿀 수 있다.
|
|
이미 있던 품목의 단가 등 사본은 그대로(발주 당시 값), 새로 넣은 품목만 지금 상품 정보 값으로(004)."""
|
|
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:
|
|
self._insert_line(conn, order_id, i, ln, names, specs or {})
|
|
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))
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# 상품 정보(004) — 코드표 단품 + 단가·무게(개당 g)·은 함유량(%) 수기 입력, 지운 단품은 제외 목록
|
|
# ════════════════════════════════════════════════════════════
|
|
def products_ready(self) -> bool:
|
|
"""004 가 적용됐나(상품 표·발주 품목 값 칸). 한 번 확인되면 기억."""
|
|
if getattr(self, "_products_ok", False):
|
|
return True
|
|
with self._pool.connection() as conn:
|
|
ok = bool(conn.execute(
|
|
"SELECT to_regclass('public.inout_products') IS NOT NULL AND EXISTS (SELECT 1 FROM information_schema.columns "
|
|
"WHERE table_name = 'inout_order_lines' AND column_name = 'unit_price') AS ok").fetchone()["ok"])
|
|
self._products_ok = ok
|
|
return ok
|
|
|
|
def _need_products(self) -> None:
|
|
if not self.products_ready():
|
|
raise ValueError("DB 마이그레이션 inout_db 004(상품 정보)가 아직 적용되지 않았습니다.")
|
|
|
|
def list_products(self) -> list[dict[str, Any]]:
|
|
if not self.products_ready():
|
|
return []
|
|
with self._pool.connection() as conn:
|
|
return conn.execute("SELECT * FROM inout_products ORDER BY item_code").fetchall()
|
|
|
|
def list_excluded(self) -> list[dict[str, Any]]:
|
|
if not self.products_ready():
|
|
return []
|
|
with self._pool.connection() as conn:
|
|
return conn.execute("SELECT * FROM inout_products_excluded ORDER BY item_code").fetchall()
|
|
|
|
def import_products(self, items: list[dict[str, str]], *, by: str) -> dict[str, int]:
|
|
"""코드표 단품 → 상품 정보. 새 단품은 추가, 값(단가·무게·은 함유량)을 넣은 상품은 그대로(이름도),
|
|
값이 없는 상품은 이름만 최신으로, 제외 목록의 단품은 건너뛴다."""
|
|
self._need_products()
|
|
out = {"added": 0, "renamed": 0, "kept": 0, "excluded": 0, "same": 0}
|
|
with self._pool.connection() as conn, conn.transaction():
|
|
have = {r["item_code"]: r for r in conn.execute("SELECT * FROM inout_products FOR UPDATE").fetchall()}
|
|
skip = {r["item_code"] for r in conn.execute("SELECT item_code FROM inout_products_excluded").fetchall()}
|
|
for it in items:
|
|
code, name = it["code"].strip().upper(), (it.get("name") or "").strip()[:300]
|
|
if not code:
|
|
continue
|
|
if code in skip:
|
|
out["excluded"] += 1
|
|
elif code not in have:
|
|
conn.execute("INSERT INTO inout_products (item_code, item_name, updated_by) VALUES (%s,%s,%s) "
|
|
"ON CONFLICT (item_code) DO NOTHING", (code, name, _norm_email(by)))
|
|
have[code] = {"item_code": code}
|
|
out["added"] += 1
|
|
elif store.has_values(have[code]):
|
|
out["kept"] += 1
|
|
elif have[code].get("item_name") != name:
|
|
conn.execute("UPDATE inout_products SET item_name=%s, updated_at=now() WHERE item_code=%s", (name, code))
|
|
out["renamed"] += 1
|
|
else:
|
|
out["same"] += 1
|
|
return out
|
|
|
|
def save_products(self, rows: list[dict[str, Any]], *, by: str) -> int:
|
|
"""값 저장 — rows = [{code, unit_price, weight_g, silver_pct}](store.validate_product_values 를 거친 값). 한 트랜잭션."""
|
|
self._need_products()
|
|
with self._pool.connection() as conn, conn.transaction():
|
|
for r in rows:
|
|
hit = conn.execute("UPDATE inout_products SET unit_price=%s, weight_g=%s, silver_pct=%s, updated_by=%s, updated_at=now() "
|
|
"WHERE item_code=%s RETURNING item_code",
|
|
(r["unit_price"], r["weight_g"], r["silver_pct"], _norm_email(by), r["code"])).fetchone()
|
|
if not hit:
|
|
raise ValueError(f"상품 정보에 없는 단품입니다: {r['code']}")
|
|
return len(rows)
|
|
|
|
def exclude_product(self, code: str, *, by: str) -> None:
|
|
"""상품 정보에서 지우고 제외 목록에 — 다음 불러오기에서 빠진다(지난 발주서는 그대로)."""
|
|
self._need_products()
|
|
with self._pool.connection() as conn, conn.transaction():
|
|
row = conn.execute("DELETE FROM inout_products WHERE item_code=%s RETURNING item_name", (code,)).fetchone()
|
|
if not row:
|
|
raise ValueError("상품을 찾을 수 없습니다.")
|
|
conn.execute("INSERT INTO inout_products_excluded (item_code, item_name, excluded_by) VALUES (%s,%s,%s) "
|
|
"ON CONFLICT (item_code) DO UPDATE SET excluded_at=now(), excluded_by=EXCLUDED.excluded_by",
|
|
(code, row["item_name"], _norm_email(by)))
|
|
|
|
def restore_product(self, code: str, *, by: str) -> None:
|
|
"""제외 목록에서 되살리기 — 바로 상품 정보로(값은 빈칸)."""
|
|
self._need_products()
|
|
with self._pool.connection() as conn, conn.transaction():
|
|
row = conn.execute("DELETE FROM inout_products_excluded WHERE item_code=%s RETURNING item_name", (code,)).fetchone()
|
|
if not row:
|
|
raise ValueError("제외 목록에 없는 단품입니다.")
|
|
conn.execute("INSERT INTO inout_products (item_code, item_name, updated_by) VALUES (%s,%s,%s) ON CONFLICT DO NOTHING",
|
|
(code, row["item_name"], _norm_email(by)))
|
|
|
|
def catalog_count(self) -> int:
|
|
if not self.products_ready():
|
|
return 0
|
|
with self._pool.connection() as conn:
|
|
return int(conn.execute("SELECT count(*) AS n FROM inout_products").fetchone()["n"])
|
|
|
|
def catalog_search(self, q: str, *, limit: int = 30) -> list[dict[str, Any]]:
|
|
"""발주서 제품 고르기 — 상품 정보에서(지운 단품 제외). 코드 앞부분 일치 먼저."""
|
|
esc = (q or "").strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
|
if not esc:
|
|
return []
|
|
with self._pool.connection() as conn:
|
|
return conn.execute(
|
|
"SELECT item_code, item_name, unit_price, weight_g, silver_pct FROM inout_products "
|
|
"WHERE item_code ILIKE %(q)s OR item_name ILIKE %(q)s "
|
|
"ORDER BY (item_code ILIKE %(p)s) DESC, item_code LIMIT %(n)s",
|
|
{"q": f"%{esc}%", "p": f"{esc}%", "n": int(limit)}).fetchall()
|
|
|
|
def catalog_lookup(self, codes: list[str]) -> dict[str, dict[str, Any]]:
|
|
if not codes or not self.products_ready():
|
|
return {}
|
|
with self._pool.connection() as conn:
|
|
rows = conn.execute("SELECT * FROM inout_products WHERE item_code = ANY(%s)", ([c.upper() for c in codes],)).fetchall()
|
|
return {r["item_code"]: r for r in rows}
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# 미입고 현황 — 진행 중(종결·취소 아님) 발주의 남은 수량, 그리고 초과 입고
|
|
# ════════════════════════════════════════════════════════════
|
|
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("사용하지 않는 공장입니다(옵션에서 '사용'으로 바꾸세요).")
|