Merge branch 'feat/inout-products'
This commit is contained in:
@@ -42,7 +42,7 @@ Claude Code는 이 저장소에서 작업을 시작하기 전에 **반드시 아
|
||||
|
||||
- 긴급 공지 (`app/modules/notice/`, `project_db` 마이그레이션 024 `urgent_notice*`) — 수퍼관리자만 작성(`/notice/`, ERP 왼쪽 아래·Project ⚙ 옵션). 제목·내용(이미지 bytea)·띄울 시각·전체/고른 사람 → ERP 모든 화면(`erp_base.html`·`main.html`·`admin.html` 의 `static/erp-notice.js`) 가로·세로 정가운데에 [확인] 누를 때까지(Esc·바깥 클릭 무시), 확인 기록. 연결 풀은 `ProjectStore.pool` 공유, 새 환경변수 없음. PC 알림 프로그램은 아직 미지원. 상세는 `docs/NOTICE_MODULE.md`
|
||||
|
||||
- 입출고 관리 (`app/modules/inout/`, `inout_db`, 2026-10-16) — 본사 → 공장 제품 제작 발주(발주서 `PO-YYMMDD-NN`, 제품 = `itemcode_db.single_items` 단품만, 검색 `GET /inout/api/items`·저장 때 서버 재확인), 물류 입고를 여러 번 나눠 입력, 품목별 발주·입고·미입고, 미입고 현황(제품별 합계·발주별·지연), 초과 입고는 확인 화면 후 허용(트랜잭션 안에서 발주서 잠그고 판단, `confirm_over`), 잔량 종결·취소(입고 없을 때만). 상태는 저장하지 않고 누적 입고로 계산(`store.order_status`). 권한키 `inout`(조회), **발주 담당·입고 담당·공장(담당자·연락처 따로, 002)은 모듈 옵션 — 상단 톱니 → 팝업**(`/inout/settings?panel=1`, ERP 관리자, `inout_roles`·`inout_factories`, 공용 `.erp-input`·`.erp-table-wrap` 겹침은 `.io` 안에서만 바로잡음), 관리자는 둘 다. **발주 메일**(003): 새 발주서 저장 → 미리보기 팝업(받는 사람 = 공장 이메일, 요약 표 본문) → 사람이 [메일 발송]을 눌러야 **발주 담당 본인 Gmail**(Gmail API `gmail.send`, 사람마다 [Gmail 연결] 1회 — 고른 구글 계정 = ERP 계정 확인, 갱신 토큰은 `APP_ENCRYPTION_KEY` AES-GCM 암호문, `app/modules/inout/gmail.py`)로 보냄, 보낸 기록·재발송 확인. **입고증 사진**(003): 입고 저장 때 첨부(브라우저가 2000px JPEG 로 줄임, 10장·10MB, 파일 머리 검사, 입고와 한 트랜잭션, bytea), 썸네일·크게 보기·나중에 더하기, 초과 확인은 브라우저가 먼저(사진 유지). 이카운트 "발주 대비 미입고"·Odoo 분할 입고/종결 참고. 상세 `docs/INOUT_MODULE.md`
|
||||
- 입출고 관리 (`app/modules/inout/`, `inout_db`, 2026-10-16) — 본사 → 공장 제품 제작 발주(발주서 `PO-YYMMDD-NN`, 제품 = `itemcode_db.single_items` 단품만, 검색 `GET /inout/api/items`·저장 때 서버 재확인), 물류 입고를 여러 번 나눠 입력, 품목별 발주·입고·미입고, 미입고 현황(제품별 합계·발주별·지연), 초과 입고는 확인 화면 후 허용(트랜잭션 안에서 발주서 잠그고 판단, `confirm_over`), 잔량 종결·취소(입고 없을 때만). 상태는 저장하지 않고 누적 입고로 계산(`store.order_status`). 권한키 `inout`(조회), **발주 담당·입고 담당·공장(담당자·연락처 따로, 002)은 모듈 옵션 — 상단 톱니 → 팝업**(`/inout/settings?panel=1`, ERP 관리자, `inout_roles`·`inout_factories`, 공용 `.erp-input`·`.erp-table-wrap` 겹침은 `.io` 안에서만 바로잡음), 관리자는 둘 다. **발주 메일**(003): 새 발주서 저장 → 미리보기 팝업(받는 사람 = 공장 이메일, 요약 표 본문) → 사람이 [메일 발송]을 눌러야 **발주 담당 본인 Gmail**(Gmail API `gmail.send`, 사람마다 [Gmail 연결] 1회 — 고른 구글 계정 = ERP 계정 확인, 갱신 토큰은 `APP_ENCRYPTION_KEY` AES-GCM 암호문, `app/modules/inout/gmail.py`)로 보냄, 보낸 기록·재발송 확인. **입고증 사진**(003): 입고 저장 때 첨부(브라우저가 2000px JPEG 로 줄임, 10장·10MB, 파일 머리 검사, 입고와 한 트랜잭션, bytea), 썸네일·크게 보기·나중에 더하기, 초과 확인은 브라우저가 먼저(사진 유지). **상품 정보**(004, 옵션 세 번째 탭, `inout_products`·`inout_products_excluded`): [단품 불러오기] = 코드표 단품 → 목록(값을 넣은 상품은 그대로·지운 단품은 다음에도 빠짐, 제외 목록에서 되살리기), 단가(원)·무게(개당 g = PP량)·은(Ag) 함유량(%) 수기 입력(은 g = 무게 × % 자동) — 한 번 불러오면 발주서 제품은 이 목록에서, 발주 품목에 그때 값 사본(`unit_price`·`weight_g`·`silver_pct`), 발주서·메일에 금액(수량 × 단가)·PP·은 함유량과 합계. **입고 담당(발주 담당 아님)은 품목을 이름·발주 수량만**(`items_limited`), 옵션은 관리자만. 시각은 DB 시간대와 무관하게 KST 로 읽음(`db._KstTimestamptzLoader`). 이카운트 "발주 대비 미입고"·Odoo 분할 입고/종결 참고. 상세 `docs/INOUT_MODULE.md`
|
||||
|
||||
상세는 `docs/PROJECT_OVERVIEW.md`.
|
||||
|
||||
|
||||
+161
-16
@@ -8,13 +8,16 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
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
|
||||
|
||||
|
||||
@@ -33,10 +36,23 @@ 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}, open=False)
|
||||
kwargs={"row_factory": dict_row, "autocommit": True}, configure=_kst_session, open=False)
|
||||
self._pool.open(wait=False)
|
||||
|
||||
def close(self) -> None:
|
||||
@@ -118,16 +134,31 @@ class InoutDBStore:
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 발주서
|
||||
# ════════════════════════════════════════════════════════════
|
||||
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}."""
|
||||
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]
|
||||
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
|
||||
# 순번은 숫자로 비교 — 글자 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) "
|
||||
@@ -135,13 +166,13 @@ class InoutDBStore:
|
||||
(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"]))
|
||||
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) -> None:
|
||||
"""머리글·품목 고치기. 입고된 품목은 뺄 수 없다(입고 기록이 사라지므로) — 수량은 바꿀 수 있다."""
|
||||
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"]:
|
||||
@@ -163,9 +194,7 @@ class InoutDBStore:
|
||||
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"]))
|
||||
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))
|
||||
|
||||
@@ -412,6 +441,122 @@ class InoutDBStore:
|
||||
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}
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 미입고 현황 — 진행 중(종결·취소 아님) 발주의 남은 수량, 그리고 초과 입고
|
||||
# ════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -54,6 +54,15 @@ class SingleItemReader:
|
||||
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:
|
||||
|
||||
+126
-10
@@ -10,6 +10,7 @@
|
||||
POST /inout/orders/{id}/receipts/{rid}/delete 잘못 넣은 입고 지우기(입고 담당)
|
||||
GET /inout/settings?panel=1 옵션 팝업 내용(톱니, ERP 관리자) — 공장 목록·발주 담당·입고 담당
|
||||
POST /inout/settings/… 옵션 저장 — 팝업(X-Inout-Options: 1)이면 JSON, 아니면 목록으로 이동
|
||||
POST /inout/settings/products/import|save · /products/{code}/exclude|restore 옵션 → 상품 정보(단가·무게·은 함유량, 004)
|
||||
POST /inout/orders/{id}/receipts/{rid}/photos · /orders/{id}/photos/{pid}/delete · GET /inout/photos/{pid} 입고증 사진
|
||||
GET|POST /inout/orders/{id}/mail 발주 메일 미리보기·발송(발주 담당 본인 Gmail, 사람이 눌러야 보냄)
|
||||
GET /inout/gmail/connect · /gmail/callback · POST /gmail/disconnect Gmail 연결(사람별, gmail.send 만)
|
||||
@@ -209,13 +210,21 @@ def _form_values(form: Any) -> dict[str, Any]:
|
||||
"quantities": form.getlist("qty"), "line_memos": form.getlist("line_memo")}
|
||||
|
||||
|
||||
def _validated(request: Request, st: Any, vals: dict[str, Any], *, keep_codes: set[str]) -> tuple[dict[str, Any], dict[str, str]]:
|
||||
"""폼 검사 + 코드표(단품) 확인. keep_codes = 이미 발주서에 있던 코드(코드표에서 빠졌어도 그대로 둔다)."""
|
||||
def _validated(request: Request, st: Any, vals: dict[str, Any], *,
|
||||
keep_codes: set[str]) -> tuple[dict[str, Any], dict[str, str], dict[str, dict[str, Any]]]:
|
||||
"""폼 검사 + 제품 확인 → (값, {코드: 이름}, {코드: 상품 정보 행}). keep_codes = 이미 발주서에 있던 코드(그대로 둔다).
|
||||
옵션 → 상품 정보에 불러온 단품이 있으면 그 목록에서만(지운 단품은 안 됨, 단가 등 사본은 여기서), 없으면 코드표(004 이전과 같게)."""
|
||||
data = store.validate_order(factory_id=vals["factory_id"], order_date=vals["order_date"], due_date=vals["due_date"],
|
||||
memo=vals["memo"], codes=vals["codes"], quantities=vals["quantities"],
|
||||
line_memos=vals["line_memos"])
|
||||
new_codes = [ln["item_code"] for ln in data["lines"] if ln["item_code"] not in keep_codes]
|
||||
names: dict[str, str] = {}
|
||||
if new_codes and st.catalog_count() > 0:
|
||||
found_rows = st.catalog_lookup(new_codes)
|
||||
missing = [c for c in new_codes if c not in found_rows]
|
||||
if missing:
|
||||
raise ValueError("상품 정보에 없는 단품입니다(옵션 → 상품 정보에서 불러오거나 되살리세요): " + ", ".join(missing))
|
||||
return data, {c: found_rows[c]["item_name"] for c in new_codes}, found_rows
|
||||
if new_codes:
|
||||
reader = _items(request)
|
||||
found = reader.lookup(new_codes) if reader is not None else None
|
||||
@@ -226,7 +235,7 @@ def _validated(request: Request, st: Any, vals: dict[str, Any], *, keep_codes: s
|
||||
if missing:
|
||||
raise ValueError("코드표 단품에 없는 제품입니다: " + ", ".join(missing))
|
||||
names = {c: found[c] for c in new_codes}
|
||||
return data, names
|
||||
return data, names, {}
|
||||
|
||||
|
||||
def _form_page(request: Request, user: dict[str, Any], st: Any, *, order: dict[str, Any] | None, vals: dict[str, Any],
|
||||
@@ -235,12 +244,20 @@ def _form_page(request: Request, user: dict[str, Any], st: Any, *, order: dict[s
|
||||
"qty": vals["quantities"][i] if i < len(vals["quantities"]) else "",
|
||||
"memo": vals["line_memos"][i] if i < len(vals["line_memos"]) else ""}
|
||||
for i, c in enumerate(vals["codes"]) if (c or "").strip() or (i < len(vals["quantities"]) and vals["quantities"][i])]
|
||||
# 단가 — 이미 있던 품목은 발주 당시 값(사본), 새 품목은 지금 상품 정보 값(004). 금액은 화면이 수량 × 단가로 계산.
|
||||
snap = {x["item_code"]: x.get("unit_price") for x in (order["lines"] if order else [])}
|
||||
catalog = st.catalog_lookup([ln["code"] for ln in lines if ln["code"] and ln["code"] not in snap])
|
||||
for ln in lines:
|
||||
price = snap[ln["code"]] if ln["code"] in snap else (catalog.get(ln["code"]) or {}).get("unit_price")
|
||||
ln["price"] = float(price) if price is not None else None
|
||||
ln["price_label"] = store.fmt_num(price) if price is not None else ""
|
||||
reader = _items(request)
|
||||
catalog_n = st.catalog_count()
|
||||
return _render(request, "inout/order_form.html", user, {
|
||||
"tab": "orders", "order": order, "vals": vals, "lines": lines, "error": error,
|
||||
"factories": [f for f in st.list_factories(include_inactive=True)
|
||||
if f["is_active"] or (order and f["id"] == order["factory_id"])],
|
||||
"items_enabled": bool(reader is not None and reader.enabled),
|
||||
"items_enabled": bool(reader is not None and reader.enabled) or catalog_n > 0, "from_catalog": catalog_n > 0,
|
||||
}, status_code=status_code)
|
||||
|
||||
|
||||
@@ -265,8 +282,8 @@ async def order_create(request: Request) -> Any:
|
||||
_require(st, user, "order")
|
||||
vals = _form_values(await request.form())
|
||||
try:
|
||||
data, names = _validated(request, st, vals, keep_codes=set())
|
||||
res = st.create_order(data, names, by=user.get("email", ""))
|
||||
data, names, specs = _validated(request, st, vals, keep_codes=set())
|
||||
res = st.create_order(data, names, by=user.get("email", ""), specs=specs)
|
||||
except ValueError as exc:
|
||||
return _form_page(request, user, st, order=None, vals=vals, error=str(exc), status_code=400)
|
||||
return _redirect(f"/inout/orders/{res['id']}?mail=1", f"발주서 {res['order_no']} 을(를) 만들었습니다.") # 메일 미리보기 바로
|
||||
@@ -297,8 +314,8 @@ async def order_update(request: Request, order_id: int) -> Any:
|
||||
order = _order_or_404(st, order_id)
|
||||
vals = _form_values(await request.form())
|
||||
try:
|
||||
data, names = _validated(request, st, vals, keep_codes={x["item_code"] for x in order["lines"]})
|
||||
st.update_order(order_id, data, names, by=user.get("email", ""))
|
||||
data, names, specs = _validated(request, st, vals, keep_codes={x["item_code"] for x in order["lines"]})
|
||||
st.update_order(order_id, data, names, by=user.get("email", ""), specs=specs)
|
||||
except ValueError as exc:
|
||||
return _form_page(request, user, st, order=order, vals=vals, error=str(exc), status_code=400)
|
||||
return _redirect(f"/inout/orders/{order_id}", "발주서를 고쳤습니다.")
|
||||
@@ -314,6 +331,10 @@ def _detail(request: Request, user: dict[str, Any], st: Any, order: dict[str, An
|
||||
return _render(request, "inout/order_detail.html", user, {
|
||||
"tab": "orders", "order": order, "error": error, "over": over or [], "photos_lost": photos_lost,
|
||||
"open_mail": request.query_params.get("mail") == "1" and perms["can_order"] and not order["cancelled_at"],
|
||||
# 입고 담당(발주 담당 아님)은 품목을 이름·발주 수량(+ 이번 입고 칸)만 — 2026-10-16 사용자 요청
|
||||
"items_limited": perms["can_receive"] and not perms["can_order"],
|
||||
"show_prices": perms["can_order"], "totals": store.order_totals(order["lines"]),
|
||||
"fmt_num": store.fmt_num, "line_amount": store.line_amount, "silver_g": store.silver_g,
|
||||
"max_photos": store.MAX_PHOTOS,
|
||||
"receipt_form": receipt_form or {"receipt_date": today_kst().isoformat(), "memo": "", "qty": {}},
|
||||
"can_receive_now": order["status"] in (store.ST_OPEN, store.ST_PARTIAL, store.ST_DONE, store.ST_OVER),
|
||||
@@ -658,7 +679,12 @@ def _options_ctx(request: Request, st: Any) -> dict[str, Any]:
|
||||
cands.append({"email": e, "name": "(입출고 모듈 권한 없음)"})
|
||||
known.add(e)
|
||||
reader = _items(request)
|
||||
return {"factories": st.list_factories(include_inactive=True), "roles": roles, "role_labels": store.ROLE_LABELS,
|
||||
products = st.list_products()
|
||||
for pr in products:
|
||||
pr["silver_g"] = store.silver_g(pr.get("weight_g"), pr.get("silver_pct"))
|
||||
return {"products": products, "excluded": st.list_excluded(), "products_ready": st.products_ready(),
|
||||
"fmt_num": store.fmt_num,
|
||||
"factories": st.list_factories(include_inactive=True), "roles": roles, "role_labels": store.ROLE_LABELS,
|
||||
"candidates": cands,
|
||||
"items_status": "연결됨" if reader is not None and reader.enabled else (reader.reason if reader else "없음")}
|
||||
|
||||
@@ -735,13 +761,103 @@ async def settings_roles(request: Request) -> Any:
|
||||
return _options_done(request, "담당자를 저장했습니다.")
|
||||
|
||||
|
||||
@router.post("/settings/products/import")
|
||||
def settings_products_import(request: Request) -> Any:
|
||||
"""[단품 불러오기] — 코드표 단품 전체 → 상품 정보. 값을 넣은 상품·제외한 단품은 그대로."""
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "admin")
|
||||
reader = _items(request)
|
||||
items = reader.list_all() if reader is not None else None
|
||||
if items is None:
|
||||
return _options_done(request, "코드표 DB(itemcode_db)에 연결할 수 없어 단품을 불러오지 못했습니다"
|
||||
+ ("" if reader is None or reader.enabled else " (ITEMCODE_DB_URL 미설정)") + ".", ok=False)
|
||||
try:
|
||||
r = st.import_products(items, by=user.get("email", ""))
|
||||
except ValueError as exc:
|
||||
return _options_done(request, str(exc), ok=False)
|
||||
parts = [f"새 단품 {r['added']}개"]
|
||||
if r["renamed"]:
|
||||
parts.append(f"이름 바뀐 {r['renamed']}개")
|
||||
if r["kept"]:
|
||||
parts.append(f"값을 넣은 {r['kept']}개는 그대로")
|
||||
if r["excluded"]:
|
||||
parts.append(f"지운 {r['excluded']}개는 건너뜀")
|
||||
return _options_done(request, "단품을 불러왔습니다 — " + ", ".join(parts) + ".")
|
||||
|
||||
|
||||
@router.post("/settings/products/save")
|
||||
def settings_products_save(request: Request, payload: dict[str, Any] = Body(...)) -> Any:
|
||||
"""단가·무게·은 함유량 저장 — rows = [{code, unit_price, weight_g, silver_pct}](바뀐 줄만). 하나라도 틀리면 아무것도 저장 안 함."""
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "admin")
|
||||
rows, errors = [], []
|
||||
for r in (payload.get("rows") or [])[:5000]:
|
||||
code = str((r or {}).get("code") or "").strip().upper()
|
||||
try:
|
||||
rows.append({"code": code, **store.validate_product_values(r)})
|
||||
except ValueError as exc:
|
||||
errors.append(f"{code}: {exc}")
|
||||
if errors:
|
||||
return _options_done(request, "저장하지 못했습니다 — " + " / ".join(errors[:5]) + (" …" if len(errors) > 5 else ""), ok=False)
|
||||
if not rows:
|
||||
return _options_done(request, "바뀐 값이 없습니다.", ok=False)
|
||||
try:
|
||||
n = st.save_products(rows, by=user.get("email", ""))
|
||||
except ValueError as exc:
|
||||
return _options_done(request, str(exc), ok=False)
|
||||
return _options_done(request, f"상품 정보 {n}개를 저장했습니다.")
|
||||
|
||||
|
||||
@router.post("/settings/products/{code}/exclude")
|
||||
def settings_product_exclude(request: Request, code: str) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "admin")
|
||||
try:
|
||||
st.exclude_product(code.strip().upper(), by=user.get("email", ""))
|
||||
except ValueError as exc:
|
||||
return _options_done(request, str(exc), ok=False)
|
||||
return _options_done(request, f"{code} 를 지웠습니다 — 다음 불러오기에서도 빠집니다(제외 목록에서 되살릴 수 있음).")
|
||||
|
||||
|
||||
@router.post("/settings/products/{code}/restore")
|
||||
def settings_product_restore(request: Request, code: str) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "admin")
|
||||
try:
|
||||
st.restore_product(code.strip().upper(), by=user.get("email", ""))
|
||||
except ValueError as exc:
|
||||
return _options_done(request, str(exc), ok=False)
|
||||
return _options_done(request, f"{code} 를 되살렸습니다.")
|
||||
|
||||
|
||||
# ────────────────────────────────────────────────────────────
|
||||
# API · 상태
|
||||
# ────────────────────────────────────────────────────────────
|
||||
@router.get("/api/items")
|
||||
def api_items(request: Request, q: str = "") -> JSONResponse:
|
||||
"""코드표 단품 검색 — 발주서 제품 고르기."""
|
||||
"""발주서 제품 고르기 — 옵션 → 상품 정보(불러온 단품, 지운 것 제외)가 있으면 거기서, 없으면 코드표 단품."""
|
||||
_user(request)
|
||||
st = _store(request)
|
||||
if st is not None and st.catalog_count() > 0:
|
||||
rows = st.catalog_search(q, limit=30)
|
||||
return JSONResponse({"enabled": True, "source": "products", "items": [
|
||||
{"code": r["item_code"], "name": r["item_name"],
|
||||
"unit_price": store.fmt_num(r["unit_price"]) if r["unit_price"] is not None else "",
|
||||
"price": float(r["unit_price"]) if r["unit_price"] is not None else None,
|
||||
"weight_g": store.fmt_num(r["weight_g"]) if r["weight_g"] is not None else "",
|
||||
"silver_pct": store.fmt_num(r["silver_pct"], 4) if r["silver_pct"] is not None else ""} for r in rows]})
|
||||
reader = _items(request)
|
||||
if reader is None or not reader.enabled:
|
||||
return JSONResponse({"items": [], "enabled": False,
|
||||
|
||||
+132
-12
@@ -11,6 +11,7 @@ from __future__ import annotations
|
||||
import html as _html
|
||||
import re
|
||||
from datetime import date
|
||||
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
||||
from typing import Any, Iterable
|
||||
|
||||
ROLE_ORDER = "order" # 발주 담당
|
||||
@@ -231,50 +232,169 @@ def parse_emails(raw: Any, *, label: str = "이메일", required: bool = False)
|
||||
|
||||
|
||||
def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) -> dict[str, str]:
|
||||
"""발주서 → 메일 제목·글 본문·HTML 본문(요약). order = db.get_order 결과."""
|
||||
"""발주서 → 메일 제목·글 본문·HTML 본문(요약). order = db.get_order 결과.
|
||||
품목마다 단가·금액(수량 × 단가)·PP량(개당 g = 무게)·은 함유량(%·개당 g) — 발주 품목에 남긴 그때 값(004). 없으면 '-'."""
|
||||
lines = order["lines"]
|
||||
first = (lines[0]["item_name"] or lines[0]["item_code"]) if lines else ""
|
||||
more = f" 외 {len(lines) - 1}종" if len(lines) > 1 else ""
|
||||
subject = f"[발주] {order['order_no']} · {order['factory_name']} · {first}{more}"
|
||||
total = sum(int(x["qty"]) for x in lines)
|
||||
money = order_totals(lines)
|
||||
due = order["due_date"].strftime("%Y-%m-%d") if order.get("due_date") else "협의"
|
||||
greet = f"{order['factory_manager']}님, 안녕하세요." if order.get("factory_manager") else "안녕하세요."
|
||||
who = sender_name or sender_email
|
||||
facts = [("발주번호", order["order_no"]), ("발주일", order["order_date"].strftime("%Y-%m-%d")),
|
||||
("입고 예정일", due), ("품목", f"{len(lines)}종 · 총 {total:,}개")]
|
||||
if money["amount"] is not None:
|
||||
note = f" (단가 미입력 {money['missing_price']}종 제외)" if money["missing_price"] else ""
|
||||
facts.append(("발주 금액", f"{fmt_num(money['amount'])}원{note}"))
|
||||
if money["pp_kg"] is not None:
|
||||
facts.append(("PP 총량", f"{fmt_num(money['pp_kg'], 2)} kg"))
|
||||
if money["silver_g"] is not None:
|
||||
facts.append(("은(Ag) 총량", f"{fmt_num(money['silver_g'], 2)} g"))
|
||||
if order.get("memo"):
|
||||
facts.append(("요청 사항", order["memo"]))
|
||||
|
||||
def cells(x: dict[str, Any]) -> dict[str, str]:
|
||||
price, w, pct = to_dec(x.get("unit_price")), to_dec(x.get("weight_g")), to_dec(x.get("silver_pct"))
|
||||
amt = line_amount(int(x["qty"]), price)
|
||||
ag = silver_g(w, pct)
|
||||
return {"price": fmt_num(price) if price is not None else "-", "amount": fmt_num(amt) if amt is not None else "-",
|
||||
"pp": fmt_num(w) if w is not None else "-",
|
||||
"ag": (f"{fmt_num(pct, 4)}%" + (f" ({fmt_num(ag, 4)}g)" if ag is not None else "")) if pct is not None else "-"}
|
||||
|
||||
# 글 본문(HTML 을 못 보는 메일 프로그램용)
|
||||
text = [greet, "", "아래와 같이 제품 제작을 발주합니다.", ""]
|
||||
text += [f"- {k}: {v}" for k, v in facts]
|
||||
text += ["", "[발주 품목]"]
|
||||
text += ["", "[발주 품목] 수량 · 단가 · 금액 · PP(g/개) · 은 함유량"]
|
||||
for i, x in enumerate(lines, start=1):
|
||||
text.append(f"{i}. {x['item_code']} {x['item_name']} — {int(x['qty']):,}개" + (f" ({x['memo']})" if x.get("memo") else ""))
|
||||
c = cells(x)
|
||||
text.append(f"{i}. {x['item_code']} {x['item_name']} — {int(x['qty']):,}개 · 단가 {c['price']} · 금액 {c['amount']}"
|
||||
f" · PP {c['pp'] + 'g' if c['pp'] != '-' else '-'} · 은 {c['ag']}" + (f" ({x['memo']})" if x.get("memo") else ""))
|
||||
text += ["", "입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.", "", f"발주 담당: {who} ({sender_email})"]
|
||||
# HTML 본문 — 값은 모두 escape
|
||||
e = _html.escape
|
||||
td = "padding:6px 10px;border:1px solid #d9dce1;"
|
||||
r = "text-align:right;white-space:nowrap;"
|
||||
fact_rows = "".join(f'<tr><th style="{td}background:#f6f7f9;text-align:left;white-space:nowrap">{e(k)}</th>'
|
||||
f'<td style="{td}">{e(str(v))}</td></tr>' for k, v in facts)
|
||||
item_rows = "".join(
|
||||
f'<tr><td style="{td}text-align:center">{i}</td><td style="{td}font-family:Consolas,monospace">{e(x["item_code"])}</td>'
|
||||
f'<td style="{td}">{e(x["item_name"])}</td><td style="{td}text-align:right">{int(x["qty"]):,}</td>'
|
||||
f'<td style="{td}">{e(x.get("memo") or "")}</td></tr>' for i, x in enumerate(lines, start=1))
|
||||
rows = []
|
||||
for i, x in enumerate(lines, start=1):
|
||||
c = cells(x)
|
||||
rows.append(
|
||||
f'<tr><td style="{td}text-align:center">{i}</td><td style="{td}font-family:Consolas,monospace">{e(x["item_code"])}</td>'
|
||||
f'<td style="{td}">{e(x["item_name"])}</td><td style="{td}{r}">{int(x["qty"]):,}</td>'
|
||||
f'<td style="{td}{r}">{e(c["price"])}</td><td style="{td}{r}">{e(c["amount"])}</td>'
|
||||
f'<td style="{td}{r}">{e(c["pp"])}</td><td style="{td}{r}">{e(c["ag"])}</td>'
|
||||
f'<td style="{td}">{e(x.get("memo") or "")}</td></tr>')
|
||||
foot_amount = fmt_num(money["amount"]) if money["amount"] is not None else ""
|
||||
foot_pp = f'{fmt_num(money["pp_kg"], 2)} kg' if money["pp_kg"] is not None else ""
|
||||
foot_ag = f'{fmt_num(money["silver_g"], 2)} g' if money["silver_g"] is not None else ""
|
||||
bg = "background:#f6f7f9;"
|
||||
html = (
|
||||
'<div style="font-family:\'Malgun Gothic\',\'Apple SD Gothic Neo\',sans-serif;font-size:14px;color:#1d1d1f;line-height:1.6">'
|
||||
f"<p>{e(greet)}<br>아래와 같이 제품 제작을 발주합니다.</p>"
|
||||
f'<table style="border-collapse:collapse;margin:8px 0 16px">{fact_rows}</table>'
|
||||
'<table style="border-collapse:collapse;min-width:520px">'
|
||||
f'<thead><tr style="background:#f6f7f9"><th style="{td}">No</th><th style="{td}">제품 코드</th><th style="{td}">제품명</th>'
|
||||
f'<th style="{td}">수량</th><th style="{td}">비고</th></tr></thead><tbody>{item_rows}</tbody>'
|
||||
f'<tfoot><tr><th colspan="3" style="{td}text-align:right;background:#f6f7f9">합계</th>'
|
||||
f'<th style="{td}text-align:right;background:#f6f7f9">{total:,}</th><th style="{td}background:#f6f7f9"></th></tr></tfoot></table>'
|
||||
'<table style="border-collapse:collapse;min-width:640px">'
|
||||
f'<thead><tr style="{bg}"><th style="{td}">No</th><th style="{td}">제품 코드</th><th style="{td}">제품명</th>'
|
||||
f'<th style="{td}">수량</th><th style="{td}">단가(원)</th><th style="{td}">금액(원)</th>'
|
||||
f'<th style="{td}">PP(g/개)</th><th style="{td}">은(Ag) 함유량</th><th style="{td}">비고</th></tr></thead>'
|
||||
f'<tbody>{"".join(rows)}</tbody>'
|
||||
f'<tfoot><tr><th colspan="3" style="{td}{bg}text-align:right">합계</th>'
|
||||
f'<th style="{td}{bg}{r}">{total:,}</th><th style="{td}{bg}"></th><th style="{td}{bg}{r}">{e(foot_amount)}</th>'
|
||||
f'<th style="{td}{bg}{r}">{e(foot_pp)}</th><th style="{td}{bg}{r}">{e(foot_ag)}</th><th style="{td}{bg}"></th></tr></tfoot></table>'
|
||||
"<p>입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.</p>"
|
||||
f'<p style="color:#555">발주 담당: {e(who)} (<a href="mailto:{e(sender_email)}">{e(sender_email)}</a>)</p></div>'
|
||||
)
|
||||
return {"subject": subject, "text": "\n".join(text), "html": html}
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 상품 정보(2026-10-16, 마이그레이션 004) — 단가·무게(개당 g = PP량)·은(Ag) 함유량(%) 수기 입력
|
||||
# 은 함량(g/개) = 무게 × 은 함유량 ÷ 100 — 저장하지 않고 계산(silver_g).
|
||||
# ════════════════════════════════════════════════════════════
|
||||
PRODUCT_LIMITS = {"unit_price": ("단가", Decimal("1000000000"), 2), "weight_g": ("무게", Decimal("1000000"), 2),
|
||||
"silver_pct": ("은 함유량", Decimal("100"), 4)}
|
||||
|
||||
|
||||
def to_dec(v: Any) -> Decimal | None:
|
||||
if v is None or v == "":
|
||||
return None
|
||||
try:
|
||||
return Decimal(str(v))
|
||||
except (InvalidOperation, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def fmt_num(v: Any, places: int = 2) -> str:
|
||||
"""1234.50 → '1,234.5', 1234 → '1,234' (소수 끝 0 은 뺀다)."""
|
||||
d = to_dec(v)
|
||||
if d is None:
|
||||
return ""
|
||||
q = d.quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP)
|
||||
s = f"{q:,.{places}f}"
|
||||
return s.rstrip("0").rstrip(".") if "." in s else s
|
||||
|
||||
|
||||
def silver_g(weight_g: Any, silver_pct: Any) -> Decimal | None:
|
||||
w, p = to_dec(weight_g), to_dec(silver_pct)
|
||||
if w is None or p is None:
|
||||
return None
|
||||
return (w * p / Decimal(100)).quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP)
|
||||
|
||||
|
||||
def line_amount(qty: int, unit_price: Any) -> Decimal | None:
|
||||
p = to_dec(unit_price)
|
||||
return None if p is None else (p * int(qty)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||||
|
||||
|
||||
def order_totals(lines: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""발주 금액 합(단가 있는 줄만, 없으면 None)·단가 없는 줄 수·PP 총량(kg)·은 총량(g)."""
|
||||
amount = pp = ag = None
|
||||
missing = 0
|
||||
for x in lines:
|
||||
q = int(x["qty"])
|
||||
a = line_amount(q, x.get("unit_price"))
|
||||
if a is None:
|
||||
missing += 1
|
||||
else:
|
||||
amount = (amount or Decimal(0)) + a
|
||||
w = to_dec(x.get("weight_g"))
|
||||
if w is not None:
|
||||
pp = (pp or Decimal(0)) + w * q / Decimal(1000)
|
||||
p = to_dec(x.get("silver_pct"))
|
||||
if w is not None and p is not None: # 개당 은 g 를 반올림하기 전 값으로 곱한다(합계 오차 방지)
|
||||
ag = (ag or Decimal(0)) + w * p / Decimal(100) * q
|
||||
return {"amount": amount, "missing_price": missing if amount is not None else len(lines), "pp_kg": pp, "silver_g": ag}
|
||||
|
||||
|
||||
def parse_decimal(raw: Any, *, key: str) -> Decimal | None:
|
||||
"""상품 정보 칸 하나 — 빈칸은 None(미입력), 숫자·쉼표·0 이상·한도 안·소수 자리."""
|
||||
label, limit, places = PRODUCT_LIMITS[key]
|
||||
s = str(raw if raw is not None else "").replace(",", "").replace("%", "").strip()
|
||||
if not s:
|
||||
return None
|
||||
try:
|
||||
d = Decimal(s)
|
||||
except InvalidOperation:
|
||||
raise ValueError(f"{label}은(는) 숫자로 입력하세요.") from None
|
||||
if not d.is_finite() or d < 0:
|
||||
raise ValueError(f"{label}은(는) 0 이상이어야 합니다.")
|
||||
if d > limit:
|
||||
raise ValueError(f"{label}이(가) 너무 큽니다(최대 {fmt_num(limit, 0)}).")
|
||||
return d.quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP)
|
||||
|
||||
|
||||
def validate_product_values(values: dict[str, Any]) -> dict[str, Decimal | None]:
|
||||
"""{"unit_price","weight_g","silver_pct"} → 정리된 값. 틀리면 ValueError(칸 이름 포함)."""
|
||||
return {k: parse_decimal(values.get(k), key=k) for k in PRODUCT_LIMITS}
|
||||
|
||||
|
||||
def has_values(p: dict[str, Any]) -> bool:
|
||||
"""단가·무게·은 함유량 중 하나라도 넣었나 — 넣은 상품은 다시 불러와도 그대로 둔다."""
|
||||
return any(p.get(k) is not None for k in PRODUCT_LIMITS)
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 입고증 사진(2026-10-16, 마이그레이션 003)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
{# 옵션 팝업 내용(GET /inout/settings?panel=1) — 탭: 담당자 · 공장. 폼 저장은 inout.js 가 제자리에서(X-Inout-Options: 1 → JSON).
|
||||
{# 옵션 팝업 내용(GET /inout/settings?panel=1) — 탭: 담당자 · 공장 · 상품 정보(004). 폼 저장은 inout.js 가 제자리에서(X-Inout-Options: 1 → JSON).
|
||||
공장 줄은 표(<table>) 안에 폼을 둘 수 없어 입력칸에 form="…" 속성으로 표 밖 폼에 묶는다 — 열이 머리 줄과 맞는다. #}
|
||||
<div class="io-dlg-tabs" role="tablist" aria-label="옵션 분류">
|
||||
<button type="button" role="tab" class="is-active" aria-selected="true" data-pane="roles">담당자</button>
|
||||
<button type="button" role="tab" aria-selected="false" data-pane="factories" tabindex="-1">공장 <span class="io-dlg-count">{{ factories|length }}</span></button>
|
||||
<button type="button" role="tab" aria-selected="false" data-pane="products" tabindex="-1">상품 정보 <span class="io-dlg-count">{{ products|length }}</span></button>
|
||||
</div>
|
||||
|
||||
<section class="io-dlg-pane" data-pane="roles" role="tabpanel">
|
||||
@@ -72,4 +73,56 @@
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<section class="io-dlg-pane" data-pane="products" role="tabpanel" hidden>
|
||||
{% if not products_ready %}
|
||||
<p class="io-error">DB 마이그레이션 inout_db 004(상품 정보)가 아직 적용되지 않았습니다 — 관리자에게 알려 주세요.</p>
|
||||
{% else %}
|
||||
<p class="io-help">
|
||||
코드표의 단품을 불러와 <b>단가</b>(원)·<b>무게</b>(개당 g = PP량)·<b>은(Ag) 함유량</b>(%)을 넣습니다 — 은 함량(g)은 무게 × %로 자동 계산.
|
||||
값을 넣은 상품은 다시 불러와도 그대로이고, 지운 단품은 다음 불러오기에서 빠집니다. 발주서 제품은 이 목록에서 고르며, 발주할 때의 값이 발주서에 남습니다.
|
||||
</p>
|
||||
<div class="io-prod-bar">
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="io-prod-import">단품 불러오기</button>
|
||||
<input type="search" class="io-in io-prod-search" id="io-prod-search" placeholder="코드·제품명 찾기" aria-label="상품 찾기" />
|
||||
<span class="io-sub" id="io-prod-count">{{ products|length }}개{% if excluded %} · 제외 {{ excluded|length }}개{% endif %}</span>
|
||||
<span class="io-nav-gap"></span>
|
||||
<button type="button" class="erp-btn erp-btn-primary erp-btn-sm" id="io-prod-save" disabled>변경 저장 <span id="io-prod-dirty"></span></button>
|
||||
</div>
|
||||
{% if products %}
|
||||
<div class="io-prod-scroll">
|
||||
<table class="io-dlg-table io-prod-table">
|
||||
<colgroup><col class="w-code" /><col /><col class="w-num" /><col class="w-num" /><col class="w-num" /><col class="w-ag" /><col class="w-del" /></colgroup>
|
||||
<thead><tr><th>코드</th><th>제품명</th><th class="io-r">단가(원)</th><th class="io-r">무게·PP(g/개)</th><th class="io-r">은 함유량(%)</th><th class="io-r">은(g/개)</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{% for p in products %}
|
||||
<tr data-code="{{ p.item_code }}" data-search="{{ (p.item_code ~ ' ' ~ p.item_name)|lower }}">
|
||||
<td class="io-code">{{ p.item_code }}</td>
|
||||
<td class="io-prod-name">{{ p.item_name }}</td>
|
||||
<td><input class="io-in io-in-num" data-key="unit_price" value="{{ fmt_num(p.unit_price) if p.unit_price is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 단가" /></td>
|
||||
<td><input class="io-in io-in-num" data-key="weight_g" value="{{ fmt_num(p.weight_g) if p.weight_g is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 무게" /></td>
|
||||
<td><input class="io-in io-in-num" data-key="silver_pct" value="{{ fmt_num(p.silver_pct, 4) if p.silver_pct is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 은 함유량" /></td>
|
||||
<td class="io-r io-ag" title="무게 × 은 함유량 ÷ 100">{{ fmt_num(p.silver_g, 4) if p.silver_g is not none else '-' }}</td>
|
||||
<td class="io-r"><button type="button" class="io-icon-btn" data-exclude="{{ p.item_code }}" title="지우기 — 다음 불러오기에서도 뺌" aria-label="{{ p.item_code }} 지우기">✕</button></td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="io-empty">아직 불러온 단품이 없습니다 — [단품 불러오기]를 누르세요. (그 전에는 발주서에서 코드표 단품을 바로 고릅니다)</p>
|
||||
{% endif %}
|
||||
{% if excluded %}
|
||||
<details class="io-excluded">
|
||||
<summary>제외 목록 {{ excluded|length }}개 — 불러오기에서 빠지는 단품</summary>
|
||||
<ul>
|
||||
{% for x in excluded %}
|
||||
<li><span class="io-code">{{ x.item_code }}</span> {{ x.item_name }} <span class="io-sub">· {{ x.excluded_at.strftime('%Y-%m-%d') }}</span>
|
||||
<button type="button" class="io-link-btn" data-restore="{{ x.item_code }}">되살리기</button></li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</details>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
<p class="io-dlg-foot">코드표(단품) 연결: {{ items_status }}</p>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% from "inout/_macros.html" import status_badge, progress, due, n %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261016e" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261017a" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="io">
|
||||
@@ -58,4 +58,4 @@
|
||||
</div>
|
||||
</section>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261016d" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261017a" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% from "inout/_macros.html" import status_badge, progress, due, n %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261016e" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261017a" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{% set active = order.status in ('open', 'partial') %}
|
||||
@@ -70,7 +70,7 @@
|
||||
{% if over %}
|
||||
<div class="io-over-box" role="alert">
|
||||
<b>발주보다 많이 입고하려고 합니다.</b> 맞으면 [초과 입고로 저장]을 누르세요.
|
||||
<ul>{% for o in over %}<li><span class="io-code">{{ o.item_code }}</span> {{ o.item_name }} — 발주 {{ n(o.ordered) }}개, 입고 후 {{ n(o.after) }}개 (<b>+{{ n(o.over) }}</b>)</li>{% endfor %}</ul>
|
||||
<ul>{% for o in over %}<li>{% if not items_limited %}<span class="io-code">{{ o.item_code }}</span> {% endif %}{{ o.item_name }} — 발주 {{ n(o.ordered) }}개, 입고 후 {{ n(o.after) }}개 (<b>+{{ n(o.over) }}</b>)</li>{% endfor %}</ul>
|
||||
{% if photos_lost %}<p class="io-photo-lost">고른 입고증 사진은 다시 첨부해야 합니다(화면이 다시 열리면서 빠졌습니다).</p>{% endif %}
|
||||
<button type="submit" class="io-btn-over" name="confirm_over" value="1">초과 입고로 저장</button>
|
||||
<span class="erp-muted">숫자를 고치려면 아래 칸을 고친 뒤 [입고 저장]</span>
|
||||
@@ -81,25 +81,49 @@
|
||||
|
||||
<div class="erp-table-wrap">
|
||||
<table class="erp-table io-table">
|
||||
<thead><tr><th class="io-col-no">#</th><th>제품 코드</th><th>제품</th><th class="io-num">발주</th><th class="io-num">입고</th><th class="io-num">미입고</th><th>상태</th>
|
||||
{# 입고 담당(발주 담당 아님) = 제품 이름·발주 수량(+ 이번 입고)만, 발주 담당 = 단가·금액·PP·은 함께 #}
|
||||
<thead><tr><th class="io-col-no">#</th>{% if not items_limited %}<th>제품 코드</th>{% endif %}<th>제품</th><th class="io-num">발주</th>
|
||||
{% if show_prices %}<th class="io-num io-col-money">단가(원)</th><th class="io-num io-col-money">금액(원)</th><th class="io-num io-col-spec">PP(g/개)</th><th class="io-num io-col-spec">은(Ag)</th>{% endif %}
|
||||
{% if not items_limited %}<th class="io-num">입고</th><th class="io-num">미입고</th><th>상태</th>{% endif %}
|
||||
{% if receiving %}<th class="io-col-recv">이번 입고</th>{% endif %}</tr></thead>
|
||||
<tbody>
|
||||
{% for ln in order.lines %}
|
||||
<tr>
|
||||
<td class="io-col-no">{{ loop.index }}</td>
|
||||
<td class="io-code">{{ ln.item_code }}</td>
|
||||
{% if not items_limited %}<td class="io-code">{{ ln.item_code }}</td>{% endif %}
|
||||
<td>{{ ln.item_name }}{% if ln.memo %}<div class="erp-row-sub">{{ ln.memo }}</div>{% endif %}</td>
|
||||
<td class="io-num">{{ n(ln.qty) }}</td>
|
||||
{% if show_prices %}
|
||||
{% set amt = line_amount(ln.qty, ln.unit_price) %}{% set ag = silver_g(ln.weight_g, ln.silver_pct) %}
|
||||
<td class="io-num io-col-money">{{ fmt_num(ln.unit_price) if ln.unit_price is not none else '-' }}</td>
|
||||
<td class="io-num io-col-money">{{ fmt_num(amt) if amt is not none else '-' }}</td>
|
||||
<td class="io-num io-col-spec">{{ fmt_num(ln.weight_g) if ln.weight_g is not none else '-' }}</td>
|
||||
<td class="io-num io-col-spec">{% if ln.silver_pct is not none %}{{ fmt_num(ln.silver_pct, 4) }}%{% if ag is not none %}<div class="erp-row-sub">{{ fmt_num(ag, 4) }}g/개</div>{% endif %}{% else %}-{% endif %}</td>
|
||||
{% endif %}
|
||||
{% if not items_limited %}
|
||||
<td class="io-num">{{ n(ln.received) }}</td>
|
||||
<td class="io-num{% if ln.remaining and active %} io-remaining{% endif %}">{{ n(ln.remaining) }}{% if ln.over %}<div class="io-over-sub">초과 +{{ n(ln.over) }}</div>{% endif %}</td>
|
||||
<td>{{ status_badge(ln.status, ln.status_label) }}</td>
|
||||
{% endif %}
|
||||
{% if receiving %}<td class="io-col-recv"><input class="erp-input io-qty io-recv" type="text" inputmode="numeric" name="qty_{{ ln.id }}"
|
||||
value="{{ receipt_form.qty.get(ln.id, '') }}" data-remaining="{{ ln.remaining }}" data-ordered="{{ ln.qty }}" data-received="{{ ln.received }}"
|
||||
data-code="{{ ln.item_code }}" data-name="{{ ln.item_name }}" placeholder="{{ ln.remaining if ln.remaining else '' }}"
|
||||
aria-label="{{ ln.item_code }} 이번 입고 수량" /></td>{% endif %}
|
||||
data-code="{{ ln.item_code }}" data-name="{{ ln.item_name }}" placeholder="{{ ln.remaining if ln.remaining and not items_limited else '' }}"
|
||||
aria-label="{{ ln.item_name }} 이번 입고 수량" /></td>{% endif %}
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
{% if show_prices and order.lines %}
|
||||
<tfoot><tr class="io-total-row">
|
||||
<td colspan="3">합계</td>
|
||||
<td class="io-num">{{ n(order.summary.ordered) }}</td>
|
||||
<td class="io-num io-col-money"></td>
|
||||
<td class="io-num io-col-money"><b>{{ fmt_num(totals.amount) if totals.amount is not none else '-' }}</b>{% if totals.missing_price %}<div class="erp-row-sub">단가 미입력 {{ totals.missing_price }}종 제외</div>{% endif %}</td>
|
||||
<td class="io-num io-col-spec">{% if totals.pp_kg is not none %}{{ fmt_num(totals.pp_kg, 3) }}kg{% else %}-{% endif %}</td>
|
||||
<td class="io-num io-col-spec">{% if totals.silver_g is not none %}{{ fmt_num(totals.silver_g, 2) }}g{% else %}-{% endif %}</td>
|
||||
{% if not items_limited %}<td colspan="3"></td>{% endif %}
|
||||
{% if receiving %}<td></td>{% endif %}
|
||||
</tr></tfoot>
|
||||
{% endif %}
|
||||
</table>
|
||||
</div>
|
||||
{% if receiving %}
|
||||
@@ -131,7 +155,7 @@
|
||||
{% for r in order.receipts %}
|
||||
<tr>
|
||||
<td>{{ r.receipt_date.strftime('%Y-%m-%d') }}{% if r.memo %}<div class="erp-row-sub">{{ r.memo }}</div>{% endif %}</td>
|
||||
<td>{% for x in r.lines %}<span class="io-chip"><span class="io-code">{{ x.item_code }}</span> {{ n(x.qty) }}</span>{% endfor %}</td>
|
||||
<td>{% for x in r.lines %}<span class="io-chip">{% if items_limited %}{{ x.item_name }}{% else %}<span class="io-code">{{ x.item_code }}</span>{% endif %} {{ n(x.qty) }}</span>{% endfor %}</td>
|
||||
<td class="io-num">{{ n(r.total) }}</td>
|
||||
<td class="io-photos-cell">
|
||||
{% for ph in r.photos %}
|
||||
@@ -200,4 +224,4 @@
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261016d" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261017a" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261016e" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261017a" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="io">
|
||||
@@ -9,10 +9,10 @@
|
||||
action="{% if order %}/inout/orders/{{ order.id }}/edit{% else %}/inout/orders/new{% endif %}">
|
||||
<div class="erp-card-block-head">
|
||||
<h2>{% if order %}발주서 고치기 · {{ order.order_no }}{% else %}새 발주서{% endif %}</h2>
|
||||
<span class="erp-muted">제품은 코드표의 단품에서 고릅니다</span>
|
||||
<span class="erp-muted">{% if from_catalog %}제품은 옵션 → 상품 정보의 단품에서 고릅니다(단가 함께){% else %}제품은 코드표의 단품에서 고릅니다{% endif %}</span>
|
||||
</div>
|
||||
{% if error %}<div class="io-error" role="alert">{% for line in error.split('\n') %}<div>{{ line }}</div>{% endfor %}</div>{% endif %}
|
||||
{% if not items_enabled %}<div class="io-error" role="alert">코드표 DB(ITEMCODE_DB_URL)가 연결되지 않아 제품을 검색할 수 없습니다 — 관리자에게 알려 주세요.</div>{% endif %}
|
||||
{% if not items_enabled %}<div class="io-error" role="alert">제품을 고를 목록이 없습니다 — 관리자가 옵션 → 상품 정보에서 단품을 불러오거나 코드표 DB(ITEMCODE_DB_URL)를 연결해야 합니다.</div>{% endif %}
|
||||
|
||||
<div class="erp-form-grid">
|
||||
<label class="erp-field"><span>공장 *</span>
|
||||
@@ -29,11 +29,11 @@
|
||||
|
||||
<div class="erp-table-wrap">
|
||||
<table class="erp-table io-table io-lines" id="io-lines">
|
||||
<thead><tr><th class="io-col-no">#</th><th>제품(코드·이름으로 검색)</th><th class="io-col-qty">발주 수량</th><th>줄 메모</th><th class="io-col-del"></th></tr></thead>
|
||||
<thead><tr><th class="io-col-no">#</th><th>제품(코드·이름으로 검색)</th><th class="io-col-qty">발주 수량</th><th class="io-col-money">단가(원)</th><th class="io-col-money">금액(원)</th><th>줄 메모</th><th class="io-col-del"></th></tr></thead>
|
||||
<tbody>
|
||||
{% for ln in lines %}
|
||||
{% set received = (order.lines | selectattr('item_code', 'equalto', ln.code) | map(attribute='received') | first) if order else 0 %}
|
||||
<tr class="io-line">
|
||||
<tr class="io-line" data-price="{{ ln.price if ln.price is not none else '' }}">
|
||||
<td class="io-col-no"></td>
|
||||
<td class="io-item-cell">
|
||||
<input type="hidden" name="item_code" value="{{ ln.code }}" />
|
||||
@@ -43,14 +43,16 @@
|
||||
{% if received %}<div class="erp-row-sub">입고 {{ '{:,}'.format(received) }}개 — 제품은 그대로, 수량만 바꿀 수 있습니다</div>{% endif %}
|
||||
</td>
|
||||
<td class="io-col-qty"><input class="erp-input io-qty" type="text" inputmode="numeric" name="qty" value="{{ ln.qty }}" placeholder="0" /></td>
|
||||
<td class="io-col-money io-price">{{ ln.price_label or '-' }}</td>
|
||||
<td class="io-col-money io-amount">-</td>
|
||||
<td><input class="erp-input" type="text" name="line_memo" value="{{ ln.memo }}" maxlength="500" /></td>
|
||||
<td class="io-col-del">{% if not received %}<button type="button" class="erp-btn erp-btn-outline erp-btn-sm io-del" aria-label="이 줄 지우기" title="이 줄 지우기">✕</button>{% endif %}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
<tfoot><tr><td colspan="5">
|
||||
<tfoot><tr><td colspan="7">
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="io-add-line">+ 제품 줄 추가</button>
|
||||
<span class="erp-muted io-total">합계 <b id="io-total-qty">0</b>개 · <b id="io-total-lines">0</b>종</span>
|
||||
<span class="erp-muted io-total">합계 <b id="io-total-qty">0</b>개 · <b id="io-total-lines">0</b>종 · 금액 <b id="io-total-amount">0</b>원<span id="io-total-noprice"></span></span>
|
||||
</td></tr></tfoot>
|
||||
</table>
|
||||
</div>
|
||||
@@ -64,6 +66,8 @@
|
||||
<input class="erp-input io-item-search" type="text" value="" autocomplete="off" placeholder="코드 또는 이름" />
|
||||
</td>
|
||||
<td class="io-col-qty"><input class="erp-input io-qty" type="text" inputmode="numeric" name="qty" value="" placeholder="0" /></td>
|
||||
<td class="io-col-money io-price">-</td>
|
||||
<td class="io-col-money io-amount">-</td>
|
||||
<td><input class="erp-input" type="text" name="line_memo" value="" maxlength="500" /></td>
|
||||
<td class="io-col-del"><button type="button" class="erp-btn erp-btn-outline erp-btn-sm io-del" aria-label="이 줄 지우기" title="이 줄 지우기">✕</button></td>
|
||||
</tr>
|
||||
@@ -76,4 +80,4 @@
|
||||
</form>
|
||||
</section>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261016d" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261017a" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% from "inout/_macros.html" import due, n %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261016e" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261017a" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="io">
|
||||
@@ -88,4 +88,4 @@
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261016d" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261017a" defer></script>{% endblock %}
|
||||
|
||||
@@ -250,3 +250,30 @@
|
||||
@media (max-width: 900px) {
|
||||
.io-mail-fields { grid-template-columns: 1fr; }
|
||||
}
|
||||
|
||||
/* ── 상품 정보 탭(004) — 단가·무게(PP)·은 함유량 ── */
|
||||
.io-prod-bar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-bottom: 10px; }
|
||||
.io-prod-search { width: 220px; }
|
||||
.io-prod-scroll { max-height: min(440px, calc(100vh - 340px)); overflow-y: auto; border: 1px solid var(--color-subtle-ash); border-radius: 8px; }
|
||||
.io-prod-table thead th { position: sticky; top: 0; z-index: 1; background: #fafbfc; }
|
||||
.io-prod-table col.w-code { width: 128px; }
|
||||
.io-prod-table col.w-num { width: 120px; }
|
||||
.io-prod-table col.w-ag { width: 92px; }
|
||||
.io-prod-table col.w-del { width: 44px; }
|
||||
.io-prod-table th.io-r, .io-r { text-align: right; }
|
||||
.io-prod-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.io-ag { color: var(--color-midtone-gray); font-variant-numeric: tabular-nums; }
|
||||
.io-prod-table tr.is-dirty td { background: #fff8e1; }
|
||||
.io-icon-btn { width: 26px; height: 26px; padding: 0; border: 0; border-radius: 6px; background: none; color: #8a8b8c; font-size: 13px; cursor: pointer; }
|
||||
.io-icon-btn:hover { background: #fbe9e6; color: #a1261b; }
|
||||
.io-excluded { margin-top: 12px; font-size: 13px; }
|
||||
.io-excluded summary { cursor: pointer; color: var(--color-midtone-gray); }
|
||||
.io-excluded ul { margin: 8px 0 0; padding: 0; list-style: none; }
|
||||
.io-excluded li { display: flex; align-items: center; gap: 8px; padding: 5px 0; border-bottom: 1px solid var(--color-subtle-ash); }
|
||||
.io-excluded li .io-link-btn { margin-left: auto; }
|
||||
/* 발주서 단가·금액 칸 */
|
||||
.io-col-money { width: 110px; text-align: right; white-space: nowrap; font-variant-numeric: tabular-nums; }
|
||||
.io-col-spec { width: 96px; white-space: nowrap; font-variant-numeric: tabular-nums; }
|
||||
.io-table tfoot .io-total-row td { background: #fafbfc; font-weight: 500; border-top: 1px solid var(--color-subtle-ash); }
|
||||
.io-suggest-price { float: right; margin-left: 12px; color: var(--color-midtone-gray); font-size: 12px; font-variant-numeric: tabular-nums; }
|
||||
.io-table th.io-col-money, .io-table th.io-col-spec { text-align: right; }
|
||||
|
||||
+103
-2
@@ -51,15 +51,23 @@
|
||||
const totalQty = document.getElementById("io-total-qty");
|
||||
const totalLines = document.getElementById("io-total-lines");
|
||||
|
||||
const totalAmount = document.getElementById("io-total-amount"), noPrice = document.getElementById("io-total-noprice");
|
||||
function renumber() {
|
||||
let q = 0, k = 0;
|
||||
let q = 0, k = 0, amount = 0, missing = 0;
|
||||
body.querySelectorAll(".io-line").forEach(function (tr, i) {
|
||||
tr.querySelector(".io-col-no").textContent = String(i + 1);
|
||||
const n = num(tr.querySelector(".io-qty").value);
|
||||
if (tr.querySelector('input[name="item_code"]').value) { k++; q += n; }
|
||||
const has = !!tr.querySelector('input[name="item_code"]').value;
|
||||
const price = tr.dataset.price === "" || tr.dataset.price === undefined ? null : parseFloat(tr.dataset.price);
|
||||
const cell = tr.querySelector(".io-amount");
|
||||
// 금액 = 수량 × 단가(상품 정보 단가, 이미 있던 품목은 발주 당시 단가) — 표시만, 저장은 서버가 단가 사본으로
|
||||
if (cell) cell.textContent = has && price !== null && n ? (Math.round(price * n * 100) / 100).toLocaleString("ko-KR") : "-";
|
||||
if (has) { k++; q += n; if (price === null) missing++; else amount += price * n; }
|
||||
});
|
||||
totalQty.textContent = fmt(q);
|
||||
totalLines.textContent = fmt(k);
|
||||
if (totalAmount) totalAmount.textContent = (Math.round(amount * 100) / 100).toLocaleString("ko-KR");
|
||||
if (noPrice) noPrice.textContent = missing ? " (단가 없는 " + missing + "종 제외)" : "";
|
||||
}
|
||||
function addLine(focus) {
|
||||
const tr = tpl.content.firstElementChild.cloneNode(true);
|
||||
@@ -148,6 +156,12 @@
|
||||
c.textContent = it.code;
|
||||
opt.appendChild(c);
|
||||
opt.appendChild(document.createTextNode(" " + it.name));
|
||||
if (it.unit_price) {
|
||||
const pr = document.createElement("span");
|
||||
pr.className = "io-suggest-price";
|
||||
pr.textContent = it.unit_price + "원";
|
||||
opt.insertBefore(pr, c); // float:right 는 글자보다 앞에 둬야 같은 줄 오른쪽
|
||||
}
|
||||
opt.addEventListener("mousedown", function (e) { e.preventDefault(); choose(i); });
|
||||
box.appendChild(opt);
|
||||
});
|
||||
@@ -159,6 +173,12 @@
|
||||
const it = items[i];
|
||||
if (!it) return;
|
||||
codeEl.value = it.code;
|
||||
const row = input.closest("tr");
|
||||
if (row) { // 단가(상품 정보) — 금액 계산용
|
||||
row.dataset.price = it.price === null || it.price === undefined ? "" : String(it.price);
|
||||
const pc = row.querySelector(".io-price");
|
||||
if (pc) pc.textContent = it.unit_price || "-";
|
||||
}
|
||||
nameEl.value = it.name;
|
||||
input.value = it.code + " · " + it.name;
|
||||
input.classList.remove("is-invalid");
|
||||
@@ -187,6 +207,8 @@
|
||||
input.setAttribute("aria-autocomplete", "list");
|
||||
input.addEventListener("input", function () {
|
||||
codeEl.value = ""; // 글을 고치면 고른 제품은 풀린다(다시 골라야 저장)
|
||||
const row0 = input.closest("tr");
|
||||
if (row0 && row0.dataset.price !== undefined) { row0.dataset.price = ""; const pc0 = row0.querySelector(".io-price"); if (pc0) pc0.textContent = "-"; }
|
||||
nameEl.value = "";
|
||||
clearTimeout(timer);
|
||||
const q = input.value.trim();
|
||||
@@ -307,6 +329,85 @@
|
||||
buttons.forEach(function (b) { if (b.isConnected) b.disabled = false; });
|
||||
}
|
||||
});
|
||||
// ── 상품 정보 탭(004) — 단가·무게·은 함유량, 바뀐 줄만 [변경 저장], 불러오기·지우기·되살리기 ──
|
||||
function dirtyRows() {
|
||||
return Array.from(body.querySelectorAll(".io-prod-table tbody tr")).filter(function (tr) {
|
||||
return Array.from(tr.querySelectorAll("input[data-key]")).some(function (i) { return i.value.trim() !== i.defaultValue.trim(); });
|
||||
});
|
||||
}
|
||||
function paintDirty() {
|
||||
const n = dirtyRows().length;
|
||||
const save = body.querySelector("#io-prod-save"), badge = body.querySelector("#io-prod-dirty");
|
||||
if (save) save.disabled = !n;
|
||||
if (badge) badge.textContent = n ? "(" + n + ")" : "";
|
||||
}
|
||||
function dec(v) { const n = parseFloat(String(v || "").replace(/[,%\s]/g, "")); return Number.isFinite(n) ? n : null; }
|
||||
async function postJSON(url, payload) {
|
||||
const res = await fetch(url, { method: "POST", headers: { "X-Inout-Options": "1", "Content-Type": "application/json" },
|
||||
body: payload === undefined ? "{}" : JSON.stringify(payload) });
|
||||
let out = {};
|
||||
try { out = await res.json(); } catch (_) {}
|
||||
return { ok: res.ok && out.ok !== false, message: out.message || out.detail || (res.ok ? "" : "HTTP " + res.status) };
|
||||
}
|
||||
async function act(url, payload) {
|
||||
const r = await postJSON(url, payload);
|
||||
if (r.ok) { changed = true; await load(); }
|
||||
say(r.message || (r.ok ? "저장했습니다." : "저장하지 못했습니다."), !r.ok);
|
||||
return r.ok;
|
||||
}
|
||||
body.addEventListener("input", function (e) {
|
||||
const inp = e.target;
|
||||
if (inp.id === "io-prod-search") {
|
||||
const q = inp.value.trim().toLowerCase();
|
||||
let shown = 0;
|
||||
body.querySelectorAll(".io-prod-table tbody tr").forEach(function (tr) {
|
||||
const hit = !q || tr.dataset.search.indexOf(q) >= 0;
|
||||
tr.hidden = !hit;
|
||||
if (hit) shown++;
|
||||
});
|
||||
const cnt = body.querySelector("#io-prod-count");
|
||||
if (cnt) cnt.dataset.base = cnt.dataset.base || cnt.textContent;
|
||||
if (cnt) cnt.textContent = q ? shown + "개 찾음" : cnt.dataset.base;
|
||||
return;
|
||||
}
|
||||
if (!inp.dataset || !inp.dataset.key) return;
|
||||
const tr = inp.closest("tr");
|
||||
const w = dec(tr.querySelector('[data-key="weight_g"]').value), pct = dec(tr.querySelector('[data-key="silver_pct"]').value);
|
||||
const ag = tr.querySelector(".io-ag");
|
||||
if (ag) ag.textContent = w !== null && pct !== null ? (Math.round(w * pct / 100 * 10000) / 10000).toLocaleString("ko-KR", { maximumFractionDigits: 4 }) : "-";
|
||||
tr.classList.toggle("is-dirty", Array.from(tr.querySelectorAll("input[data-key]")).some(function (i) { return i.value.trim() !== i.defaultValue.trim(); }));
|
||||
paintDirty();
|
||||
});
|
||||
body.addEventListener("click", async function (e) {
|
||||
const t = e.target;
|
||||
if (t.id === "io-prod-import") {
|
||||
if (dirtyRows().length && !(await confirmMsg("저장 안 한 변경이 있습니다. 버리고 불러올까요?"))) return;
|
||||
t.disabled = true;
|
||||
say("코드표에서 단품을 불러오는 중…");
|
||||
try { await act("/inout/settings/products/import"); } finally { t.disabled = false; }
|
||||
} else if (t.closest("#io-prod-save")) {
|
||||
const rows = dirtyRows().map(function (tr) {
|
||||
const v = function (k) { return tr.querySelector('[data-key="' + k + '"]').value.trim(); };
|
||||
return { code: tr.dataset.code, unit_price: v("unit_price"), weight_g: v("weight_g"), silver_pct: v("silver_pct") };
|
||||
});
|
||||
if (rows.length) await act("/inout/settings/products/save", { rows: rows });
|
||||
} else if (t.dataset && t.dataset.exclude) {
|
||||
if (await confirmMsg(t.dataset.exclude + " 를 상품 정보에서 지울까요? 다음 불러오기에서도 빠집니다(지난 발주서는 그대로)."))
|
||||
await act("/inout/settings/products/" + encodeURIComponent(t.dataset.exclude) + "/exclude");
|
||||
} else if (t.dataset && t.dataset.restore) {
|
||||
await act("/inout/settings/products/" + encodeURIComponent(t.dataset.restore) + "/restore");
|
||||
}
|
||||
});
|
||||
// 저장 안 한 상품 정보가 있으면 닫기 전에 묻는다(✕·취소·Esc)
|
||||
dlg.addEventListener("cancel", function (e) {
|
||||
if (dirtyRows().length) { e.preventDefault(); confirmMsg("저장 안 한 상품 정보 변경이 있습니다. 닫을까요?").then(function (ok) { if (ok) dlg.close(); }); }
|
||||
});
|
||||
dlg.addEventListener("click", function (e) {
|
||||
if (e.target.closest("[data-close]") && dirtyRows().length) {
|
||||
e.stopImmediatePropagation();
|
||||
confirmMsg("저장 안 한 상품 정보 변경이 있습니다. 닫을까요?").then(function (ok) { if (ok) dlg.close(); });
|
||||
}
|
||||
}, true);
|
||||
if (btn.dataset.open === "1") open();
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@
|
||||
| `malaysia_stock_db` | 말레이시아 창고 재고관리 — 창고/아이템/세트 BOM/입출고 이력/일일 재고조사 |
|
||||
| `cafe24_db` | 카페24 연동 — OAuth 토큰/상품 캐시/상세페이지 버전/예약/감사·API 로그 |
|
||||
| `performance_db` | 실적(쇼핑몰 통합 매출) — 쇼핑몰 설정/수수료율 이력/API 인증정보(암호문)/연결 상태/매출 사건/동기화 기록 |
|
||||
| `inout_db` | 입출고 관리 — 공장/발주 담당·입고 담당/발주서·발주 품목/입고·입고 품목 (2026-10-16, 앱 계정 `inout_app`, `INOUT_DB_URL`, 초기화 `scripts/sql/inout_db_init.sql`, 상세 `docs/INOUT_MODULE.md`) |
|
||||
| `inout_db` | 입출고 관리 — 공장/발주 담당·입고 담당/발주서·발주 품목/입고·입고 품목/상품 정보(단가·무게·은 함유량, 004) (2026-10-16, 앱 계정 `inout_app`, `INOUT_DB_URL`, 초기화 `scripts/sql/inout_db_init.sql`, 상세 `docs/INOUT_MODULE.md`) |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -287,6 +287,19 @@ curl -s http://127.0.0.1:8080/inout/health # {"status":"ok"} — DSN
|
||||
그다음 ERP 관리자 화면에서 쓸 사람에게 **입출고 관리** 권한 → 입출고 관리 → 옵션에서 공장·발주 담당·입고 담당 지정.
|
||||
백업: 매일 `docker exec postgres-db pg_dump -U postgres inout_db > /var/backups/postgres/inout_db_$(date +%F).sql`.
|
||||
|
||||
## 입출고 관리 상품 정보 마이그레이션 (inout_db 004)
|
||||
|
||||
004는 표 2개(`inout_products` 상품 정보 — 단가·무게(개당 g)·은 함유량(%), `inout_products_excluded` 지운 단품)와
|
||||
`inout_order_lines` 의 `unit_price`·`weight_g`·`silver_pct` 열(발주할 때 값 사본)을 추가한다. 다시 실행 가능, 기존 데이터 변경 없음, 새 환경변수 없음.
|
||||
적용 뒤 옵션(톱니) → 상품 정보 → [단품 불러오기] 를 한 번 누르면 그때부터 발주서 제품은 그 목록에서 고른다.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main && git pull
|
||||
docker exec postgres-db pg_dump -U postgres inout_db > ~/inout_db_before_004_$(date +%Y%m%d%H%M).sql
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d inout_db < scripts/sql/inout_db_004_products.sql
|
||||
docker compose up --build -d web
|
||||
```
|
||||
|
||||
## 입출고 관리 발주 메일·입고증 사진 마이그레이션 (inout_db 003)
|
||||
|
||||
003은 공장 이메일 열, Gmail 연결(토큰 암호문)·발주 메일 기록·입고증 사진 표만 추가한다(다시 실행 가능, 기존 값 변경 없음).
|
||||
|
||||
+35
-9
@@ -29,7 +29,8 @@
|
||||
Enter 키는 숨은 기본 버튼(일반 저장)으로 가게 해 확인 없이 초과가 저장되지 않게 했다.
|
||||
- 발주서 고치기: 입고된 품목은 **뺄 수 없다**(입고 기록이 사라지므로) — 수량은 바꿀 수 있다(입고보다 줄이면 초과로 보임).
|
||||
- 입고 기록 지우기(입고 담당): 잘못 넣은 1건을 지우면 그만큼 다시 미입고.
|
||||
- 발주번호: `PO-YYMMDD-NN`(발주일 기준 그날 순번, advisory lock 으로 동시 생성해도 겹치지 않음).
|
||||
- 발주번호: `PO-YYMMDD-NN`(발주일 기준 그날 순번, advisory lock 으로 동시 생성해도 겹치지 않음). 순번은 숫자로 비교한다 — 100번째부터 세 자리(`-100`).
|
||||
- 시각(입력·보낸·종결 시각 등)은 DB 서버 시간대와 무관하게 **한국 시각** — 연결마다 TIMESTAMPTZ 를 KST 로 읽는다(`db._KstTimestamptzLoader`).
|
||||
|
||||
## 3. 권한·담당자
|
||||
|
||||
@@ -37,8 +38,8 @@
|
||||
|---|---|
|
||||
| 모듈 권한 `inout` | 발주 목록·발주서·미입고 현황 조회 |
|
||||
| **발주 담당**(옵션에서 지정) | 발주서 작성·고치기·잔량 종결/풀기·취소 |
|
||||
| **입고 담당**(옵션에서 지정) | 입고 수량 입력·입고 기록 지우기 |
|
||||
| ERP 관리자(`role=admin`) | 위 전부 + **옵션**(공장 목록·담당자) — 상단 오른쪽 **톱니** → 팝업 |
|
||||
| **입고 담당**(옵션에서 지정) | 입고 수량 입력·입고 기록 지우기. 발주 담당이 아니면 발주서 품목은 **제품 이름·발주 수량**(+ 이번 입고 칸)만 보인다 — 코드·입고·미입고·상태·단가·금액 숨김, 입고 기록 칩도 이름(2026-10-16 요청) |
|
||||
| ERP 관리자(`role=admin`) | 위 전부 + **옵션**(공장 목록·담당자·상품 정보) — 상단 오른쪽 **톱니** → 팝업. 입고 담당·발주 담당은 옵션을 못 본다 |
|
||||
|
||||
담당자 후보 = ERP 관리자 화면에서 `inout` 권한을 받은 사용자. 권한이 빠졌는데 담당으로 남은 사람도 옵션에 보여서 뺄 수 있다.
|
||||
담당은 `inout_roles(email, role)` — role `order`(발주)·`receive`(입고).
|
||||
@@ -49,6 +50,7 @@
|
||||
cupang·malaysia 와 같은 DSN). 화면에서 코드·이름으로 검색(`GET /inout/api/items?q=`, 코드 앞부분 일치 먼저 30개),
|
||||
저장할 때 서버가 다시 코드표에 있는지 확인(`lookup`) — 없으면 "코드표 단품에 없는 제품". 발주 줄에는 코드·**발주 당시 이름** 사본을 둔다.
|
||||
이미 발주서에 있던 코드는 나중에 코드표에서 빠져도 그대로 고칠 수 있다. 코드표 연결이 안 되면 새 제품을 넣는 저장만 막힌다(안내 문구).
|
||||
**옵션 → 상품 정보에 단품을 한 번이라도 불러오면** 그때부터 발주서 제품은 그 목록에서만 고른다(지운 단품 제외, 단가 함께) — 6-3.
|
||||
|
||||
## 5. 화면
|
||||
|
||||
@@ -56,9 +58,9 @@ cupang·malaysia 와 같은 DSN). 화면에서 코드·이름으로 검색(`GET
|
||||
|---|---|
|
||||
| `/inout/` | 발주 목록 — 상태(진행 중·완료·종결·취소·전체)·공장·발주일 기간·검색(발주번호·제품 코드·이름), 진행률 막대, 지연 표시 |
|
||||
| `/inout/pending` | 미입고 현황 — 요약 숫자, 제품별 합계, 발주별, 초과 입고 |
|
||||
| `/inout/orders/new`, `/{id}/edit` | 발주서 폼 — 공장·발주일·입고 예정일·메모, 제품 줄(검색 드롭다운·수량·줄 메모), 합계 |
|
||||
| `/inout/orders/{id}` | 발주서 — 품목별 발주·입고·미입고·상태, **이번 입고** 칸(입고 담당) + [남은 수량 모두 채우기], 입고 기록, 종결·취소 |
|
||||
| 톱니 → 옵션 팝업 | 관리자만. 탭 **담당자**(발주·입고 체크) · **공장**(이름·담당자·연락처·메모·순서·사용, 발주 기록 없을 때만 지우기). 내용은 `GET /inout/settings?panel=1`, 저장은 팝업 안에서(`X-Inout-Options: 1` → JSON, 같은 탭 그대로 다시 그림), 바뀐 게 있으면 닫을 때 화면 새로고침. 예전 주소 `/inout/settings` = 목록으로 가서 팝업(`?options=1`) |
|
||||
| `/inout/orders/new`, `/{id}/edit` | 발주서 폼 — 공장·발주일·입고 예정일·메모, 제품 줄(검색 드롭다운·수량·**단가·금액**·줄 메모), 합계(수량·종·금액) |
|
||||
| `/inout/orders/{id}` | 발주서 — 품목별 발주·(발주 담당) **단가·금액·PP(g/개)·은(Ag)** ·입고·미입고·상태 + 합계 줄(금액·PP kg·은 g), **이번 입고** 칸(입고 담당) + [남은 수량 모두 채우기], 입고 기록, 종결·취소. 입고 담당만이면 이름·발주 수량만 |
|
||||
| 톱니 → 옵션 팝업 | 관리자만. 탭 **담당자**(발주·입고 체크) · **공장**(이름·담당자·연락처·메모·순서·사용, 발주 기록 없을 때만 지우기) · **상품 정보**(6-3). 내용은 `GET /inout/settings?panel=1`, 저장은 팝업 안에서(`X-Inout-Options: 1` → JSON, 같은 탭 그대로 다시 그림), 바뀐 게 있으면 닫을 때 화면 새로고침. 예전 주소 `/inout/settings` = 목록으로 가서 팝업(`?options=1`) |
|
||||
|
||||
화면은 서버 폼(POST → 303 + `?msg=` 안내). `static/inout.js` 는 입력 보조만(제품 검색 드롭다운 — `position: fixed` 로 body 에 붙여
|
||||
표 가로 스크롤에 잘리지 않음, 줄 추가·삭제·합계, 남은 수량 채우기, 버튼별 확인 `data-erp-confirm-btn`).
|
||||
@@ -77,7 +79,9 @@ cupang·malaysia 와 같은 DSN). 화면에서 코드·이름으로 검색(`GET
|
||||
| `inout_receipt_photos` | 입고증 사진(bytea, 003) |
|
||||
| `inout_roles` | 담당자 — (email, role: order/receive) |
|
||||
| `inout_orders` | 발주서 — 번호·공장·발주일·입고 예정일·메모·종결(시각·사람·사유)·취소 |
|
||||
| `inout_order_lines` | 발주 품목 — 단품 코드·이름 사본·수량·줄 메모, 발주서 안에서 코드 유일 |
|
||||
| `inout_order_lines` | 발주 품목 — 단품 코드·이름 사본·수량·줄 메모, 발주서 안에서 코드 유일. 004: 발주할 때의 `unit_price`·`weight_g`·`silver_pct` 사본 |
|
||||
| `inout_products` | 상품 정보(004) — 코드표에서 불러온 단품 + 단가(원)·무게(개당 g = PP량)·은(Ag) 함유량(%) |
|
||||
| `inout_products_excluded` | 상품 정보에서 지운 단품(004) — 다음 불러오기에서 빠진다 |
|
||||
| `inout_receipts` | 입고 1건(한 번 들어온 것) — 입고일·메모·입력자 |
|
||||
| `inout_receipt_lines` | 입고 품목별 수량 |
|
||||
|
||||
@@ -123,6 +127,26 @@ cupang·malaysia 와 같은 DSN). 화면에서 코드·이름으로 검색(`GET
|
||||
입고 기록을 지우면 사진도 함께 지워진다(CASCADE).
|
||||
- 보기 `GET /inout/photos/{id}` — 모듈 권한자, `X-Content-Type-Options: nosniff`·CSP sandbox, HEIC 는 내려받기(브라우저가 못 보여 줌).
|
||||
|
||||
## 6-3. 상품 정보 — 단가·무게(PP)·은 함유량(2026-10-16, 마이그레이션 004)
|
||||
|
||||
- 옵션 팝업 세 번째 탭 **상품 정보**(관리자만). **[단품 불러오기]** = 코드표(`itemcode_db.single_items`) 단품 전체 → `inout_products`
|
||||
(`itemcode.list_all`, `POST /inout/settings/products/import`).
|
||||
- 새 단품은 추가, **값(단가·무게·은 함유량 중 하나라도)을 넣은 상품은 그대로**(이름도), 값이 없는 상품은 이름만 최신으로.
|
||||
- **지운 단품**(제외 목록 `inout_products_excluded`)은 건너뛴다. 코드표에서 빠진 단품을 지우지는 않는다.
|
||||
- 표: 코드·제품명·**단가(원)**·**무게·PP(g/개)**·**은 함유량(%)**·은(g/개) = 무게 × % ÷ 100(자동, 화면에서 바로 계산).
|
||||
찾기 칸, 바뀐 줄은 노랗게 + **[변경 저장 (n)]**(`POST …/products/save`, 바뀐 줄만, 하나라도 틀리면 아무것도 저장 안 함),
|
||||
저장 안 하고 닫거나 다시 불러오면 확인. 빈칸 = 미입력. 단가 소수 둘째·무게 둘째·함유량 넷째 자리까지(넘치면 사사오입), 함유량 0~100%.
|
||||
- 사용자 확인(2026-10-16): 요청의 "PP함유량" = **은(Ag) 함유량(%)**, "PP량" = 무게(**개당 g**).
|
||||
- 줄 오른쪽 ✕ = 지우기(`…/products/{code}/exclude`) — 목록·발주서 고르기에서 빠지고 제외 목록에 남는다. 아래 **제외 목록**에서 [되살리기](`…/restore`, 값은 빈칸).
|
||||
지난 발주서는 그대로.
|
||||
- **발주서**: 상품 정보가 하나라도 있으면 제품 검색·저장 확인이 상품 정보 기준(없는 코드 = "상품 정보에 없는 단품", 그 전에는 코드표).
|
||||
저장할 때 **그때 값의 사본**을 발주 품목에 남긴다(`_insert_line`) — 나중에 단가를 바꿔도 지난 발주서·메일은 그대로.
|
||||
고치기에서 새로 넣은 줄만 지금 값, 원래 있던 줄은 사본 유지. 004 전 발주서는 단가 칸이 "-".
|
||||
- **금액** = 수량 × 단가(`store.line_amount`), 합계는 단가 있는 줄만(없는 줄 수 표시), PP 총량(kg) = Σ 무게 × 수량, 은 총량(g) = Σ 무게 × % × 수량
|
||||
(`store.order_totals`, 개당 은 g 를 반올림하기 전 값으로 곱함).
|
||||
- **발주 메일 본문**(6-1)에 발주 금액·PP 총량·은(Ag) 총량 줄과 품목 표 **단가(원)·금액(원)·PP(g/개)·은(Ag) 함유량(% (g))**, 합계 줄.
|
||||
- 004 미적용이면 탭에 "마이그레이션 004 필요" 안내, 발주서는 예전처럼 코드표에서(`products_ready`).
|
||||
|
||||
## 7. 테스트
|
||||
|
||||
```bash
|
||||
@@ -131,5 +155,7 @@ INOUT_TEST_DB_URL=postgresql://inout_app:<pw>@127.0.0.1:5432/inout_db \
|
||||
python -m pytest tests/test_inout_db.py tests/test_inout_web.py # 로컬 테스트 DB(초기화 SQL 적용, 앱 계정 — 권한도 확인)
|
||||
```
|
||||
|
||||
DB 테스트: 분할 입고·완료, 초과 확인, 미입고·종결·풀기·취소, 고치기(입고 품목 보호), 입고 지우기, 동시 발주번호, 담당자·공장.
|
||||
화면 흐름 테스트: 옵션 → 발주 담당 발주(코드표 아닌 제품 거부) → 입고 담당 분할·초과 확인 → 미입고 현황 → 종결, 권한별 403.
|
||||
DB 테스트: 분할 입고·완료, 초과 확인, 미입고·종결·풀기·취소, 고치기(입고 품목 보호), 입고 지우기, 동시 발주번호, 담당자·공장,
|
||||
시각 KST, 상품 정보(불러오기 유지·이름 갱신·제외·되살리기, 발주 품목 값 사본 — 끝나면 테스트 단품을 지워 목록을 처음 상태로).
|
||||
화면 흐름 테스트: 옵션 → 발주 담당 발주(코드표 아닌 제품 거부) → 입고 담당 분할·초과 확인 → 미입고 현황 → 종결, 권한별 403,
|
||||
상품 정보(관리자만·저장 검사·다시 불러와도 값 유지·지우기) → 단가로 발주 → 금액·PP·은 화면·메일 → 입고 담당은 이름·발주 수량만.
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
-- =====================================================================
|
||||
-- inout_db 마이그레이션 004 — 상품 정보(단가·무게·은 함유량) · 제외 목록 · 발주 품목 값 사본(2026-10-16)
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 표·열 추가만, 기존 값 변경·삭제 없음. 운영: /opt/www/main 에서 기존 inout_db 에 적용(백업 먼저).
|
||||
--
|
||||
-- 왜(사용자 요청):
|
||||
-- 옵션 → 상품 정보: 코드표(itemcode_db.single_items) 단품을 불러와 단가·무게(개당 g = PP량)·은(Ag) 함유량(%)을 직접 입력.
|
||||
-- 값을 넣은 상품은 다시 불러와도 그대로, 필요 없는 단품은 지우면 제외 목록에 남아 다음 불러오기에서 빠진다.
|
||||
-- 발주 메일 본문에 금액(수량 × 단가)·PP량·은 함유량 — 발주 품목에는 그때의 값 사본(나중에 단가를 바꿔도 지난 발주는 그대로).
|
||||
-- 은 함량(g/개) = 무게 × 은 함유량(%) ÷ 100 — 저장하지 않고 계산한다.
|
||||
-- 되돌리기: 백업에서 복원(새 표·열만 생기므로 남아 있어도 이전 앱은 동작).
|
||||
-- =====================================================================
|
||||
\set ON_ERROR_STOP on
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS inout_products (
|
||||
item_code TEXT PRIMARY KEY CHECK (char_length(item_code) BETWEEN 1 AND 64),
|
||||
item_name TEXT NOT NULL DEFAULT '',
|
||||
unit_price NUMERIC(14,2) NULL CHECK (unit_price IS NULL OR unit_price >= 0), -- 단가(원)
|
||||
weight_g NUMERIC(12,2) NULL CHECK (weight_g IS NULL OR weight_g >= 0), -- 무게(개당 g, PP량)
|
||||
silver_pct NUMERIC(9,4) NULL CHECK (silver_pct IS NULL OR (silver_pct >= 0 AND silver_pct <= 100)), -- 은(Ag) 함유량 %
|
||||
imported_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
COMMENT ON TABLE inout_products IS '입출고 — 상품 정보(코드표 단품 + 단가·무게·은 함유량 수기 입력)';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS inout_products_excluded (
|
||||
item_code TEXT PRIMARY KEY,
|
||||
item_name TEXT NOT NULL DEFAULT '',
|
||||
excluded_by TEXT NOT NULL DEFAULT '',
|
||||
excluded_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
COMMENT ON TABLE inout_products_excluded IS '입출고 — 상품 정보에서 지운 단품(다음 불러오기에서 뺌)';
|
||||
|
||||
-- 발주 품목 — 발주 당시 값 사본(없으면 NULL)
|
||||
ALTER TABLE inout_order_lines ADD COLUMN IF NOT EXISTS unit_price NUMERIC(14,2) NULL;
|
||||
ALTER TABLE inout_order_lines ADD COLUMN IF NOT EXISTS weight_g NUMERIC(12,2) NULL;
|
||||
ALTER TABLE inout_order_lines ADD COLUMN IF NOT EXISTS silver_pct NUMERIC(9,4) NULL;
|
||||
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON inout_products, inout_products_excluded TO inout_app;
|
||||
|
||||
COMMIT;
|
||||
SELECT 'inout_db 004 products ready' AS status;
|
||||
@@ -188,13 +188,41 @@ CREATE TABLE IF NOT EXISTS inout_receipt_photos (
|
||||
CREATE INDEX IF NOT EXISTS idx_inout_receipt_photos_receipt ON inout_receipt_photos (receipt_id, id);
|
||||
COMMENT ON TABLE inout_receipt_photos IS '입출고 — 입고증 사진(공장 → 물류)';
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 6) 상품 정보 · 제외 목록 · 발주 품목 값 사본 (= 마이그레이션 004)
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
CREATE TABLE IF NOT EXISTS inout_products (
|
||||
item_code TEXT PRIMARY KEY CHECK (char_length(item_code) BETWEEN 1 AND 64),
|
||||
item_name TEXT NOT NULL DEFAULT '',
|
||||
unit_price NUMERIC(14,2) NULL CHECK (unit_price IS NULL OR unit_price >= 0), -- 단가(원)
|
||||
weight_g NUMERIC(12,2) NULL CHECK (weight_g IS NULL OR weight_g >= 0), -- 무게(개당 g, PP량)
|
||||
silver_pct NUMERIC(9,4) NULL CHECK (silver_pct IS NULL OR (silver_pct >= 0 AND silver_pct <= 100)), -- 은(Ag) 함유량 %
|
||||
imported_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
COMMENT ON TABLE inout_products IS '입출고 — 상품 정보(코드표 단품 + 단가·무게·은 함유량 수기 입력)';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS inout_products_excluded (
|
||||
item_code TEXT PRIMARY KEY,
|
||||
item_name TEXT NOT NULL DEFAULT '',
|
||||
excluded_by TEXT NOT NULL DEFAULT '',
|
||||
excluded_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
COMMENT ON TABLE inout_products_excluded IS '입출고 — 상품 정보에서 지운 단품(다음 불러오기에서 뺌)';
|
||||
|
||||
-- 발주 품목 — 발주 당시 값 사본(없으면 NULL)
|
||||
ALTER TABLE inout_order_lines ADD COLUMN IF NOT EXISTS unit_price NUMERIC(14,2) NULL;
|
||||
ALTER TABLE inout_order_lines ADD COLUMN IF NOT EXISTS weight_g NUMERIC(12,2) NULL;
|
||||
ALTER TABLE inout_order_lines ADD COLUMN IF NOT EXISTS silver_pct NUMERIC(9,4) NULL;
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 권한 — 앱 계정은 읽기·쓰기만(스키마 변경 없음)
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
GRANT USAGE ON SCHEMA public TO inout_app;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON
|
||||
inout_factories, inout_roles, inout_orders, inout_order_lines, inout_receipts, inout_receipt_lines,
|
||||
inout_gmail_tokens, inout_order_mails, inout_receipt_photos
|
||||
inout_gmail_tokens, inout_order_mails, inout_receipt_photos, inout_products, inout_products_excluded
|
||||
TO inout_app;
|
||||
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO inout_app;
|
||||
|
||||
|
||||
+76
-1
@@ -43,7 +43,7 @@ class InoutDbTests(unittest.TestCase):
|
||||
|
||||
def test_partial_receipts_until_done(self):
|
||||
o = self.order([("MT-A", 100), ("MT-B", 50)])
|
||||
self.assertRegex(o["order_no"], r"^PO-261016-\d{2}$")
|
||||
self.assertRegex(o["order_no"], r"^PO-261016-\d{2,}$") # 100번째부터는 세 자리
|
||||
head = self.st.get_order(o["id"])
|
||||
self.assertEqual((head["factory_manager"], head["factory_contact"]), ("김공장", "010-1234")) # 담당자·연락처 따로(002)
|
||||
ids = self.line_ids(o["id"])
|
||||
@@ -227,5 +227,80 @@ class InoutDbTests(unittest.TestCase):
|
||||
self.st.delete_gmail_token(me)
|
||||
self.assertIsNone(self.st.gmail_token(me))
|
||||
|
||||
|
||||
def test_times_are_kst(self):
|
||||
"""TIMESTAMPTZ 는 한국 시각으로 읽힌다(화면·메일에 찍는 입력·보낸 시각) — DB 서버 시간대와 무관."""
|
||||
from datetime import timedelta
|
||||
|
||||
o = self.order([("MT-K", 1)])
|
||||
self.assertEqual(self.st.get_order(o["id"])["created_at"].utcoffset(), timedelta(hours=9))
|
||||
|
||||
def test_products_import_keep_exclude_snapshot(self):
|
||||
"""004 — 불러오기(값 있는 상품은 그대로·없는 상품은 새 이름·지운 단품은 건너뜀), 지우기·되살리기, 발주 품목 값 사본.
|
||||
끝나면 테스트 단품을 지워 상품 정보 목록을 처음 상태로 둔다(다른 테스트는 빈 목록 = 코드표를 가정할 수 있음)."""
|
||||
from decimal import Decimal as D
|
||||
|
||||
from app.modules.inout import store
|
||||
|
||||
if not self.st.products_ready():
|
||||
self.skipTest("inout_db 004 미적용")
|
||||
T = self.tag.upper()
|
||||
A, B, C = f"ZT-{T}-A", f"ZT-{T}-B", f"ZT-{T}-C"
|
||||
items = [{"code": A.lower(), "name": "가"}, {"code": B, "name": "나"}, {"code": C, "name": "다"}]
|
||||
before = self.st.catalog_count()
|
||||
try:
|
||||
r = self.st.import_products(items, by="Boss@Test.local")
|
||||
self.assertEqual(r["added"], 3)
|
||||
self.assertEqual(self.st.catalog_count(), before + 3)
|
||||
self.st.save_products([{"code": A, **store.validate_product_values({"unit_price": "1,500", "weight_g": "24.5",
|
||||
"silver_pct": "0.5"})}], by="b@x")
|
||||
with self.assertRaisesRegex(ValueError, "상품 정보에 없는"):
|
||||
self.st.save_products([{"code": "ZT-NOPE-" + T, "unit_price": None, "weight_g": None, "silver_pct": None}], by="b@x")
|
||||
# 이름이 바뀌어 다시 불러오기 — A(값 있음)는 그대로, B(값 없음)는 새 이름
|
||||
r = self.st.import_products([{"code": A, "name": "가2"}, {"code": B, "name": "나2"}, {"code": C, "name": "다"}], by="b@x")
|
||||
self.assertEqual((r["added"], r["kept"], r["renamed"], r["same"]), (0, 1, 1, 1))
|
||||
got = self.st.catalog_lookup([A, B])
|
||||
self.assertEqual((got[A]["item_name"], got[A]["unit_price"]), ("가", D("1500.00")))
|
||||
self.assertEqual(got[B]["item_name"], "나2")
|
||||
# 지우기 → 목록·검색에서 빠지고 다음 불러오기에서도 건너뜀 → 되살리기
|
||||
self.st.exclude_product(C, by="b@x")
|
||||
self.assertNotIn(C, self.st.catalog_lookup([C]))
|
||||
self.assertIn(C, [x["item_code"] for x in self.st.list_excluded()])
|
||||
self.assertEqual(self.st.import_products(items, by="b@x")["excluded"], 1)
|
||||
self.assertNotIn(C, self.st.catalog_lookup([C]))
|
||||
self.assertEqual([x["item_code"] for x in self.st.catalog_search(f"ZT-{T}")], [A, B])
|
||||
self.assertEqual([x["item_code"] for x in self.st.catalog_search("가", limit=500) if x["item_code"].startswith("ZT-" + T)], [A])
|
||||
self.st.restore_product(C, by="b@x")
|
||||
self.assertIn(C, self.st.catalog_lookup([C]))
|
||||
self.assertNotIn(C, [x["item_code"] for x in self.st.list_excluded()])
|
||||
with self.assertRaises(ValueError):
|
||||
self.st.restore_product(C, by="b@x")
|
||||
# 발주 품목 = 발주할 때의 값(사본) — 나중에 단가가 바뀌어도 지난 발주서는 그대로
|
||||
data = store.validate_order(factory_id=self.fid, order_date="2026-10-16", due_date="", memo="",
|
||||
codes=[A, B], quantities=["100", "3"])
|
||||
specs = self.st.catalog_lookup([A, B])
|
||||
o = self.st.create_order(data, {A: "가", B: "나2"}, by="b@x", specs=specs)
|
||||
self.st.save_products([{"code": A, **store.validate_product_values({"unit_price": "2000"})}], by="b@x")
|
||||
lines = {x["item_code"]: x for x in self.st.get_order(o["id"])["lines"]}
|
||||
self.assertEqual((lines[A]["unit_price"], lines[A]["weight_g"], lines[A]["silver_pct"]), (D("1500.00"), D("24.50"), D("0.5000")))
|
||||
self.assertIsNone(lines[B]["unit_price"])
|
||||
t = store.order_totals(list(lines.values()))
|
||||
self.assertEqual((t["amount"], t["missing_price"], t["silver_g"]), (D("150000.00"), 1, D("12.2500")))
|
||||
# 고칠 때 새로 넣은 줄만 지금 값, 원래 있던 줄은 사본 그대로
|
||||
data2 = store.validate_order(factory_id=self.fid, order_date="2026-10-16", due_date="", memo="",
|
||||
codes=[A, C], quantities=["120", "1"])
|
||||
self.st.update_order(o["id"], data2, {C: "다"}, by="b@x", specs=self.st.catalog_lookup([C]))
|
||||
lines = {x["item_code"]: x for x in self.st.get_order(o["id"])["lines"]}
|
||||
self.assertEqual((lines[A]["qty"], lines[A]["unit_price"]), (120, D("1500.00")))
|
||||
self.assertEqual(set(lines), {A, C})
|
||||
finally:
|
||||
for code in (A, B, C):
|
||||
try:
|
||||
self.st.exclude_product(code, by="cleanup@x")
|
||||
except ValueError:
|
||||
pass
|
||||
self.assertEqual(self.st.catalog_count(), before)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -154,5 +154,24 @@ class GmailTests(unittest.TestCase):
|
||||
gmail.send("1//r", b"x")
|
||||
|
||||
|
||||
class MailPriceTests(unittest.TestCase):
|
||||
"""004 — 메일 본문에 금액(수량 × 단가)·PP(g/개)·은(Ag) 함유량(%·g)과 합계."""
|
||||
|
||||
def test_order_mail_prices(self):
|
||||
from decimal import Decimal as D
|
||||
o = _order()
|
||||
o["lines"][0].update(unit_price=D("85.5"), weight_g=D("24.5"), silver_pct=D("0.5"))
|
||||
m = s.order_mail(o, sender_name="K", sender_email="k@x.com")
|
||||
for part in ("발주 금액: 427,500원 (단가 미입력 1종 제외)", "PP 총량: 122.5 kg", "은(Ag) 총량: 612.5 g",
|
||||
"단가 85.5 · 금액 427,500 · PP 24.5g · 은 0.5% (0.1225g)", "단가 - · 금액 - · PP - · 은 -"):
|
||||
self.assertIn(part, m["text"])
|
||||
h = m["html"]
|
||||
for part in ("단가(원)", "금액(원)", "PP(g/개)", "은(Ag) 함유량", "427,500", "0.5% (0.1225g)", "122.5 kg", "612.5 g"):
|
||||
self.assertIn(part, h)
|
||||
o2 = _order() # 단가가 하나도 없으면 금액 줄은 "-"
|
||||
t2 = s.order_mail(o2, sender_name="K", sender_email="k@x.com")["text"]
|
||||
self.assertNotIn("PP 총량", t2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -85,5 +85,49 @@ class ValidateReceiptTests(unittest.TestCase):
|
||||
s.validate_receipt(self.LINES, {1: "-1"}, receipt_date="2026-10-20", memo="")
|
||||
|
||||
|
||||
class ProductValueTests(unittest.TestCase):
|
||||
"""004 상품 정보 — 단가·무게(개당 g = PP량)·은(Ag) 함유량(%), 은 g 은 무게 × % 로 계산."""
|
||||
|
||||
def test_fmt_num(self):
|
||||
from decimal import Decimal as D
|
||||
self.assertEqual(s.fmt_num(D("1234.50")), "1,234.5")
|
||||
self.assertEqual(s.fmt_num(D("1500.00")), "1,500")
|
||||
self.assertEqual(s.fmt_num(D("0.12345"), 4), "0.1235") # 사사오입
|
||||
self.assertEqual(s.fmt_num(None), "")
|
||||
self.assertEqual(s.fmt_num(""), "")
|
||||
|
||||
def test_silver_and_amount(self):
|
||||
from decimal import Decimal as D
|
||||
self.assertEqual(s.silver_g(D("24.5"), D("0.5")), D("0.1225"))
|
||||
self.assertIsNone(s.silver_g(None, D("0.5")))
|
||||
self.assertIsNone(s.silver_g(D("24.5"), None))
|
||||
self.assertEqual(s.line_amount(100, D("85.5")), D("8550.00"))
|
||||
self.assertIsNone(s.line_amount(100, None))
|
||||
|
||||
def test_order_totals(self):
|
||||
from decimal import Decimal as D
|
||||
t = s.order_totals([{"qty": 100, "unit_price": D("85.5"), "weight_g": D("24.5"), "silver_pct": D("0.5")},
|
||||
{"qty": 10, "unit_price": None, "weight_g": None, "silver_pct": None}])
|
||||
self.assertEqual((t["amount"], t["missing_price"], t["pp_kg"], t["silver_g"]), (D("8550.00"), 1, D("2.45"), D("12.25")))
|
||||
empty = s.order_totals([{"qty": 5}]) # 004 전 발주서(값 칸 없음)
|
||||
self.assertEqual((empty["amount"], empty["missing_price"], empty["pp_kg"], empty["silver_g"]), (None, 1, None, None))
|
||||
|
||||
def test_parse_and_validate(self):
|
||||
from decimal import Decimal as D
|
||||
self.assertEqual(s.parse_decimal("1,500", key="unit_price"), D("1500"))
|
||||
self.assertEqual(s.parse_decimal(" 0.5 % ", key="silver_pct"), D("0.5"))
|
||||
self.assertIsNone(s.parse_decimal("", key="weight_g")) # 빈칸 = 미입력
|
||||
self.assertEqual(s.parse_decimal("1.235", key="unit_price"), D("1.24")) # 소수 자리 넘치면 사사오입
|
||||
for key, bad in (("unit_price", "abc"), ("unit_price", "-1"), ("silver_pct", "101"), ("weight_g", "NaN")):
|
||||
with self.subTest(key=key, bad=bad), self.assertRaises(ValueError):
|
||||
s.parse_decimal(bad, key=key)
|
||||
v = s.validate_product_values({"unit_price": "1,500", "weight_g": "24.5", "silver_pct": ""})
|
||||
self.assertEqual(v, {"unit_price": D("1500"), "weight_g": D("24.5"), "silver_pct": None})
|
||||
with self.assertRaisesRegex(ValueError, "은 함유량"):
|
||||
s.validate_product_values({"silver_pct": "200"})
|
||||
self.assertTrue(s.has_values({"weight_g": D("1")}))
|
||||
self.assertFalse(s.has_values({"unit_price": None, "item_name": "x"}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
+109
-2
@@ -37,6 +37,8 @@ class Items:
|
||||
return [{"code": c, "name": n} for c, n in self.NAMES.items() if q.upper() in c or q in n]
|
||||
def lookup(self, codes):
|
||||
return {c: self.NAMES[c] for c in codes if c in self.NAMES}
|
||||
def list_all(self, limit=20000):
|
||||
return [{"code": c, "name": n} for c, n in self.NAMES.items()]
|
||||
|
||||
def run(body):
|
||||
with patch.object(main, "get_current_user_record", side_effect=lambda r: who["u"]), \\
|
||||
@@ -138,7 +140,8 @@ def body(c):
|
||||
assert "공장-" + tag in form and "새 발주서" in form
|
||||
bad = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "due_date": "2026-10-20",
|
||||
"item_code": ["MT-A", "ZZ-9"], "item_name": ["", ""], "qty": ["100", "5"], "line_memo": ["", ""]})
|
||||
assert bad.status_code == 400 and "코드표 단품에 없는 제품입니다: ZZ-9" in bad.text and 'value="ZZ-9"' in bad.text
|
||||
assert bad.status_code == 400 and 'value="ZZ-9"' in bad.text
|
||||
assert "코드표 단품에 없는 제품입니다: ZZ-9" in bad.text or "상품 정보에 없는 단품입니다(옵션 → 상품 정보에서 불러오거나 되살리세요): ZZ-9" in bad.text
|
||||
r = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "due_date": "2026-10-20",
|
||||
"memo": "1차", "item_code": ["mt-a", "MT-B", ""], "item_name": ["", "", ""], "qty": ["1,00", "50", ""],
|
||||
"line_memo": ["", "포장 주의", ""]}, follow_redirects=False)
|
||||
@@ -153,7 +156,7 @@ def body(c):
|
||||
# ── 입고 담당: 분할 입고 → 초과 확인 ──
|
||||
who["u"] = wh
|
||||
detail = c.get("/inout/orders/%d" % oid).text
|
||||
ids = dict(zip(re.findall(r'aria-label="(MT-[AB]) 이번 입고', detail), re.findall(r'name="qty_(\\d+)"', detail)))
|
||||
ids = {code: lid for lid, code in re.findall(r'name="qty_(\\d+)"[^>]*?data-code="(MT-[AB])"', detail, re.S)}
|
||||
r = c.post("/inout/orders/%d/receipts" % oid, data={"receipt_date": "2026-10-17", "memo": "1차 트럭",
|
||||
"qty_" + ids["MT-A"]: "60"}, follow_redirects=False)
|
||||
assert r.status_code == 303
|
||||
@@ -288,5 +291,109 @@ run(body)
|
||||
self.assertIn("OK", res.stdout)
|
||||
|
||||
|
||||
@unittest.skipUnless(DB_ENABLED, "INOUT_TEST_DB_URL(localhost) not set")
|
||||
def test_products_prices_and_receiver_view(self):
|
||||
"""004 — 옵션 → 상품 정보(관리자), 발주서 단가·금액, 메일 본문 금액·PP·은, 입고 담당은 이름·발주 수량만."""
|
||||
res = _run('''
|
||||
import re, uuid
|
||||
from app.modules.inout.db import InoutDBStore
|
||||
st = InoutDBStore(__import__("os").environ["INOUT_TEST_DB_URL"])
|
||||
assert st.products_ready(), "inout_db 004 미적용"
|
||||
main.app.state.inout_store = st
|
||||
items = Items()
|
||||
main.app.state.inout_items = items
|
||||
tag = uuid.uuid4().hex[:6]
|
||||
T = tag.upper()
|
||||
X1, X2 = "ZT-%s-1" % T, "ZT-%s-2" % T
|
||||
items.NAMES = dict(Items.NAMES, **{X1: "지울 단품 " + T, X2: "둘째 단품 " + T})
|
||||
admin, buyer, wh = U("admin-%s@t.local" % tag, role="admin"), U("buyer-%s@t.local" % tag), U("wh-%s@t.local" % tag)
|
||||
users.extend([admin, buyer, wh])
|
||||
H = {"X-Inout-Options": "1"}
|
||||
|
||||
def body(c):
|
||||
who["u"] = admin
|
||||
assert c.post("/inout/settings/factories", data={"name": "공장P-" + tag, "email": "fp-%s@x.com" % tag, "is_active": "1"},
|
||||
headers=H).json()["ok"]
|
||||
fid = next(f["id"] for f in st.list_factories() if f["name"] == "공장P-" + tag)
|
||||
assert c.post("/inout/settings/roles", data={"order_email": [buyer["email"]], "receive_email": [wh["email"]]}, headers=H).json()["ok"]
|
||||
|
||||
# ── 옵션 → 상품 정보: 관리자만 ──
|
||||
for u in (buyer, wh):
|
||||
who["u"] = u
|
||||
assert c.post("/inout/settings/products/import", headers=H).status_code == 403
|
||||
assert c.get("/inout/settings?panel=1").status_code == 403 # 입고 담당은 옵션을 못 봄
|
||||
who["u"] = admin
|
||||
r = c.post("/inout/settings/products/import", headers=H).json()
|
||||
assert r["ok"] and "단품을 불러왔습니다" in r["message"], r
|
||||
assert {"MT-A", X1, X2} <= {p["item_code"] for p in st.list_products()}
|
||||
panel = c.get("/inout/settings?panel=1").text
|
||||
assert 'data-pane="products"' in panel and 'data-code="%s"' % X1 in panel and "단품 불러오기" in panel
|
||||
bad = c.post("/inout/settings/products/save", json={"rows": [{"code": X2, "unit_price": "abc"}]}, headers=H)
|
||||
assert bad.status_code == 400 and bad.json()["ok"] is False and X2 in bad.json()["message"]
|
||||
r = c.post("/inout/settings/products/save", headers=H, json={"rows": [
|
||||
{"code": "MT-A", "unit_price": "1,500", "weight_g": "24.5", "silver_pct": "0.5"},
|
||||
{"code": X2, "unit_price": "", "weight_g": "10", "silver_pct": ""}]}).json()
|
||||
assert r["ok"] and "2개" in r["message"], r
|
||||
panel = c.get("/inout/settings?panel=1").text
|
||||
assert 'value="1,500"' in panel and ">0.1225<" in panel # 은 g = 무게 × % (자동)
|
||||
# 다시 불러와도 값은 그대로
|
||||
c.post("/inout/settings/products/import", headers=H)
|
||||
a = st.catalog_lookup(["MT-A"])["MT-A"]
|
||||
assert (str(a["unit_price"]), str(a["weight_g"]), str(a["silver_pct"])) == ("1500.00", "24.50", "0.5000")
|
||||
# 지우기 → 다음 불러오기에서도 빠짐 → 제외 목록에 보임
|
||||
assert c.post("/inout/settings/products/%s/exclude" % X1, headers=H).json()["ok"]
|
||||
c.post("/inout/settings/products/import", headers=H)
|
||||
assert X1 not in st.catalog_lookup([X1])
|
||||
panel = c.get("/inout/settings?panel=1").text
|
||||
assert 'data-restore="%s"' % X1 in panel and 'data-code="%s"' % X1 not in panel
|
||||
|
||||
# ── 발주 담당: 제품 고르기 = 상품 정보(지운 단품 빼고), 단가 함께 ──
|
||||
who["u"] = buyer
|
||||
found = c.get("/inout/api/items?q=" + T).json()
|
||||
assert found["source"] == "products" and [x["code"] for x in found["items"]] == [X2]
|
||||
mta = c.get("/inout/api/items?q=MT-A").json()["items"][0]
|
||||
assert (mta["code"], mta["unit_price"], mta["price"]) == ("MT-A", "1,500", 1500.0)
|
||||
bad = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "item_code": [X1],
|
||||
"item_name": [""], "qty": ["5"], "line_memo": [""]})
|
||||
assert bad.status_code == 400 and "상품 정보에 없는 단품입니다" in bad.text
|
||||
r = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "item_code": ["MT-A", X2],
|
||||
"item_name": ["", ""], "qty": ["100", "3"], "line_memo": ["", ""]}, follow_redirects=False)
|
||||
assert r.status_code == 303, r.text[:300]
|
||||
oid = int(re.search(r"/inout/orders/(\\d+)", r.headers["location"]).group(1))
|
||||
# 그 뒤 단가가 바뀌어도 이 발주서는 발주할 때 값
|
||||
who["u"] = admin
|
||||
c.post("/inout/settings/products/save", headers=H, json={"rows": [{"code": "MT-A", "unit_price": "2000", "weight_g": "24.5", "silver_pct": "0.5"}]})
|
||||
who["u"] = buyer
|
||||
detail = c.get("/inout/orders/%d" % oid).text
|
||||
for part in ("단가(원)", "금액(원)", "150,000", "단가 미입력 1종 제외", "2.48kg", "12.25g", "0.5%", "<th>제품 코드</th>"):
|
||||
assert part in detail, part
|
||||
assert "200,000" not in detail
|
||||
assert 'data-price="1500"' in c.get("/inout/orders/%d/edit" % oid).text or "1,500" in c.get("/inout/orders/%d/edit" % oid).text
|
||||
pv = c.get("/inout/orders/%d/mail" % oid).json()
|
||||
for part in ("150,000", "PP(g/개)", "은(Ag) 함유량", "0.5% (0.1225g)", "2.48 kg", "12.25 g"):
|
||||
assert part in pv["html"], part
|
||||
|
||||
# ── 입고 담당: 품목은 제품 이름·발주 수량(+ 이번 입고)만 ──
|
||||
who["u"] = wh
|
||||
page = c.get("/inout/orders/%d" % oid).text
|
||||
assert "가 단품" in page and "이번 입고" in page
|
||||
for hidden in ("<th>제품 코드</th>", "단가(원)", "금액(원)", "150,000", "PP(g/개)", ">미입고</th>", ">상태</th>"):
|
||||
assert hidden not in page, hidden
|
||||
lid = re.search(r'name="qty_(\\d+)"[^>]*data-code="MT-A"', page, re.S).group(1)
|
||||
r = c.post("/inout/orders/%d/receipts" % oid, data={"receipt_date": "2026-10-20", "qty_" + lid: "40"}, follow_redirects=False)
|
||||
assert r.status_code == 303
|
||||
page = c.get("/inout/orders/%d" % oid).text
|
||||
assert '<span class="io-chip">가 단품 40</span>' in page # 입고 기록도 코드 없이 이름
|
||||
|
||||
# 정리 — 테스트 단품은 지운다(MT-A~C 는 남아도 다른 테스트에 영향 없음)
|
||||
who["u"] = admin
|
||||
c.post("/inout/settings/products/%s/exclude" % X2, headers=H)
|
||||
print("OK")
|
||||
run(body)
|
||||
''', {"INOUT_TEST_DB_URL": DSN})
|
||||
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
|
||||
self.assertIn("OK", res.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
Reference in New Issue
Block a user