feat(inout): 오른쪽 발주·입고 달력·상품 그룹·색상·담당자 아이콘

- 모든 화면 2열, 오른쪽 300x320 달력(프로젝트 달력 모양) — 날짜별 발주·입고, 누르면 목록
- 옵션 → 상품 정보: 그룹(은 함유량·색상 한 번만), 상품별 그룹·색상(마이그레이션 006)
- 발주 메일 품목 표에서 색상 있는 품목 줄 배경을 그 색으로(발주 당시 색상 사본)
- 옵션 → 담당자 = 아이콘 + 이름, 아래 이메일
- 006 확인을 연결 열기 전에 해 동시 발주에서 연결 풀이 바닥나지 않게

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 14:03:33 +09:00
parent 981ad386bf
commit 0f4f8cabf0
17 changed files with 839 additions and 43 deletions
+16
View File
@@ -60,6 +60,22 @@
- 발주서·메일에 금액(수량 × 단가)·PP·은 함유량과 합계. - 발주서·메일에 금액(수량 × 단가)·PP·은 함유량과 합계.
- **발주 메일 표**(2026-10-19, `store.order_mail`): 전체 무게(kg) = 개당 g × 수량 · **PP 사용량(kg)** = 전체 무게 − 은 무게(은 함유량 왼쪽 열) · 은(Ag) 함유량 = `30% (76.5kg)`(괄호 = 전체 무게 × %, kg 소수 넷째). 합계 줄·요약(전체 무게·PP 사용량·은 총량)도 kg. 첫 요약 표는 항목·값 두 쌍씩 4열(4×4), 요청 사항은 맨 아래 한 줄 전체. 발주서 화면 표는 예전 그대로(PP g/개). - **발주 메일 표**(2026-10-19, `store.order_mail`): 전체 무게(kg) = 개당 g × 수량 · **PP 사용량(kg)** = 전체 무게 − 은 무게(은 함유량 왼쪽 열) · 은(Ag) 함유량 = `30% (76.5kg)`(괄호 = 전체 무게 × %, kg 소수 넷째). 합계 줄·요약(전체 무게·PP 사용량·은 총량)도 kg. 첫 요약 표는 항목·값 두 쌍씩 4열(4×4), 요청 사항은 맨 아래 한 줄 전체. 발주서 화면 표는 예전 그대로(PP g/개).
## 상품 그룹·색상 (006, 2026-10-21)
- 옵션 → 상품 정보 위 **그룹** 표(`inout_product_groups`: 이름·은 함유량·색상·순서, `POST /inout/settings/groups`·`…/{id}/delete`).
상품 줄 **그룹** 고르기 → 그 상품의 은 함유량·색상 = 그룹 값(자기 값 칸은 숨김·보존, 그룹 지우면 자기 값으로). 그룹 없는 상품은 상품마다.
계산은 `db._PRODUCT_SELECT_006`(silver_pct·color = 그룹 적용 값, own_* = 자기 값) 한 곳 — 목록·발주서 제품 고르기·발주 품목 사본이 같은 값.
- 색상 = 색없음·오렌지·파랑·회색·아이보리색(`store.COLORS` 키 none·orange·blue·gray·ivory → 이름·칸 색), 화면은 색 사각형 + 이름(`_macros.swatch`).
- 발주 품목에 그때 색상 사본(`inout_order_lines.color`, 006 전 품목 NULL = 지금 상품 색상). **발주 메일 품목 표에서 색상 있는 품목 줄 전체 배경 = 그 색**(tr + 칸마다).
- 006 확인(`groups_ready`)은 연결을 열기 **전에** — 미적용이면 1분 기억(발주 저장 트랜잭션 안에서 두 번째 연결을 잡아 동시 발주에서 풀이 바닥났었다).
- 옵션 → 담당자 = 아이콘(구글 프로필 사진, 없으면 기본 아이콘) + 이름, 아래 이메일.
## 오른쪽 달력 (2026-10-21)
- 입출고 **모든 화면** 2열(`.io-split` = 왼쪽 `section.io` | 오른쪽 `_calendar.html` 300px, 1100px 미만은 한 열). 달력 300×320, 스크롤해도 위에 붙음.
- 프로젝트 달력 모양(일요일 시작·요일 줄 회색·오늘 검은 동그라미·토 파랑·일/공휴일 빨강 — 공휴일 표는 `project.store.holiday_name` 재사용).
- 날짜 칸 = 발주(발주일, 파랑)·입고(입고일, 초록) 건수(취소된 발주 제외), 누르면 그날 목록 팝업 → 발주서. 달 이동은 새로고침 없이 `GET /inout/api/calendar?month=YYYY-MM`(`db.calendar`).
## 시각 / 날짜 ## 시각 / 날짜
- 시각은 DB 시간대와 무관하게 KST 로 읽음(`db._KstTimestamptzLoader`). - 시각은 DB 시간대와 무관하게 KST 로 읽음(`db._KstTimestamptzLoader`).
+155 -10
View File
@@ -8,10 +8,11 @@
from __future__ import annotations from __future__ import annotations
import time
from datetime import date, datetime from datetime import date, datetime
from typing import Any from typing import Any
from psycopg.errors import UndefinedColumn, UndefinedTable from psycopg.errors import UndefinedColumn, UndefinedTable, UniqueViolation
from psycopg.rows import dict_row from psycopg.rows import dict_row
from psycopg.types.datetime import TimestamptzLoader from psycopg.types.datetime import TimestamptzLoader
from psycopg_pool import ConnectionPool from psycopg_pool import ConnectionPool
@@ -23,6 +24,15 @@ from . import store
_SCAN_LIMIT = 20000 # 목록에서 상태 거르기 전에 읽는 발주서 상한 _SCAN_LIMIT = 20000 # 목록에서 상태 거르기 전에 읽는 발주서 상한
# 상품 정보 + 그룹(006) — 그룹 상품은 그룹의 은 함유량·색상, 그룹 없는 상품은 자기 값(own_*).
_PRODUCT_SELECT_006 = (
"SELECT p.item_code, p.item_name, p.unit_price, p.weight_g, p.imported_at, p.updated_by, p.updated_at, "
"p.group_id, g.name AS group_name, p.silver_pct AS own_silver_pct, COALESCE(p.color, 'none') AS own_color, "
"CASE WHEN g.id IS NULL THEN p.silver_pct ELSE g.silver_pct END AS silver_pct, "
"CASE WHEN g.id IS NULL THEN COALESCE(p.color, 'none') ELSE g.color END AS color "
"FROM inout_products p LEFT JOIN inout_product_groups g ON g.id = p.group_id"
)
class OverReceipt(Exception): class OverReceipt(Exception):
"""확인 없이 발주보다 많이 입고하려 함 — over = [{item_code, item_name, ordered, after, over}].""" """확인 없이 발주보다 많이 입고하려 함 — over = [{item_code, item_name, ordered, after, over}]."""
@@ -134,10 +144,21 @@ class InoutDBStore:
# ════════════════════════════════════════════════════════════ # ════════════════════════════════════════════════════════════
# 발주서 # 발주서
# ════════════════════════════════════════════════════════════ # ════════════════════════════════════════════════════════════
def _ready_flags(self) -> tuple[bool, bool]:
"""(004 상품 정보, 006 그룹·색상) — 발주 저장 트랜잭션을 열기 전에 확인해 _insert_line 에 넘긴다."""
return self.products_ready(), self.groups_ready()
def _insert_line(self, conn: Any, order_id: int, line_no: int, ln: dict[str, Any], names: dict[str, str], 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: specs: dict[str, dict[str, Any]], ready: tuple[bool, bool]) -> None:
"""발주 품목 한 줄 — 004 가 적용됐으면 상품 정보의 단가·무게·은 함유량을 그때 값으로 함께 남긴다.""" """발주 품목 한 줄 — 004 가 적용됐으면 상품 정보의 단가·무게·은 함유량을(006 이면 색상도) 그때 값으로 함께 남긴다."""
if self.products_ready(): products_ok, groups_ok = ready
if groups_ok: # 006 — 색상 사본도(그룹 상품은 그룹 색상)
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, color) "
"VALUES (%s,%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"), sp.get("color") or "none"))
elif products_ok:
sp = specs.get(ln["item_code"]) or {} 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) " 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)", "VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)",
@@ -150,6 +171,7 @@ class InoutDBStore:
def create_order(self, data: dict[str, Any], names: dict[str, str], *, by: str, 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]: specs: dict[str, dict[str, Any]] | None = None) -> dict[str, Any]:
"""data = store.validate_order 결과, names = {코드: 단품 이름}, specs = {코드: 상품 정보 행}(004). 반환 {id, order_no}.""" """data = store.validate_order 결과, names = {코드: 단품 이름}, specs = {코드: 상품 정보 행}(004). 반환 {id, order_no}."""
ready = self._ready_flags()
with self._pool.connection() as conn, conn.transaction(): with self._pool.connection() as conn, conn.transaction():
self._require_factory(conn, data["factory_id"]) self._require_factory(conn, data["factory_id"])
conn.execute("SELECT pg_advisory_xact_lock(hashtext('inout_order_no'))") conn.execute("SELECT pg_advisory_xact_lock(hashtext('inout_order_no'))")
@@ -166,13 +188,14 @@ class InoutDBStore:
(no, data["factory_id"], data["order_date"], data["due_date"], data["memo"], _norm_email(by), _norm_email(by)), (no, data["factory_id"], data["order_date"], data["due_date"], data["memo"], _norm_email(by), _norm_email(by)),
).fetchone()["id"] ).fetchone()["id"]
for i, ln in enumerate(data["lines"], start=1): for i, ln in enumerate(data["lines"], start=1):
self._insert_line(conn, oid, i, ln, names, specs or {}) self._insert_line(conn, oid, i, ln, names, specs or {}, ready)
return {"id": int(oid), "order_no": no} return {"id": int(oid), "order_no": no}
def update_order(self, order_id: int, data: dict[str, Any], names: dict[str, str], *, by: str, 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: specs: dict[str, dict[str, Any]] | None = None) -> None:
"""머리글·품목 고치기. 입고된 품목은 뺄 수 없다(입고 기록이 사라지므로) — 수량은 바꿀 수 있다. """머리글·품목 고치기. 입고된 품목은 뺄 수 없다(입고 기록이 사라지므로) — 수량은 바꿀 수 있다.
이미 있던 품목의 단가 등 사본은 그대로(발주 당시 값), 새로 넣은 품목만 지금 상품 정보 값으로(004).""" 이미 있던 품목의 단가 등 사본은 그대로(발주 당시 값), 새로 넣은 품목만 지금 상품 정보 값으로(004)."""
ready = self._ready_flags()
with self._pool.connection() as conn, conn.transaction(): with self._pool.connection() as conn, conn.transaction():
head = self._lock_order(conn, order_id) head = self._lock_order(conn, order_id)
if head["cancelled_at"]: if head["cancelled_at"]:
@@ -194,7 +217,7 @@ class InoutDBStore:
conn.execute("UPDATE inout_order_lines SET line_no=%s, qty=%s, memo=%s WHERE id=%s", 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"])) (i, ln["qty"], ln["memo"], existing[ln["item_code"]]["id"]))
else: else:
self._insert_line(conn, order_id, i, ln, names, specs or {}) self._insert_line(conn, order_id, i, ln, names, specs or {}, ready)
conn.execute("UPDATE inout_orders SET factory_id=%s, order_date=%s, due_date=%s, memo=%s, updated_by=%s WHERE id=%s", 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)) (data["factory_id"], data["order_date"], data["due_date"], data["memo"], _norm_email(by), order_id))
@@ -273,6 +296,11 @@ class InoutDBStore:
by_receipt: dict[int, list[dict[str, Any]]] = {} by_receipt: dict[int, list[dict[str, Any]]] = {}
for r in rlines: for r in rlines:
by_receipt.setdefault(int(r["receipt_id"]), []).append(r) by_receipt.setdefault(int(r["receipt_id"]), []).append(r)
if any("color" in ln and ln["color"] is None for ln in lines): # 006 전 품목 = 지금 상품 색상
cur = self.catalog_lookup([ln["item_code"] for ln in lines if ln["color"] is None])
for ln in lines:
if ln.get("color") is None and ln["item_code"] in cur:
ln["color"] = cur[ln["item_code"]].get("color")
lines = store.decorate_lines(lines) lines = store.decorate_lines(lines)
status = store.order_status(lines, closed=bool(head["closed_at"]), cancelled=bool(head["cancelled_at"])) status = store.order_status(lines, closed=bool(head["closed_at"]), cancelled=bool(head["cancelled_at"]))
return {**head, "lines": lines, "summary": store.summarize(lines), "status": status, return {**head, "lines": lines, "summary": store.summarize(lines), "status": status,
@@ -531,9 +559,13 @@ class InoutDBStore:
raise ValueError("DB 마이그레이션 inout_db 004(상품 정보)가 아직 적용되지 않았습니다.") raise ValueError("DB 마이그레이션 inout_db 004(상품 정보)가 아직 적용되지 않았습니다.")
def list_products(self) -> list[dict[str, Any]]: def list_products(self) -> list[dict[str, Any]]:
"""상품 정보 — 006 이면 그룹 이름·그룹 적용 값(silver_pct·color)·상품 자기 값(own_*)까지."""
if not self.products_ready(): if not self.products_ready():
return [] return []
grouped = self.groups_ready()
with self._pool.connection() as conn: with self._pool.connection() as conn:
if grouped:
return conn.execute(_PRODUCT_SELECT_006 + " ORDER BY p.item_code").fetchall()
return conn.execute("SELECT * FROM inout_products ORDER BY item_code").fetchall() return conn.execute("SELECT * FROM inout_products ORDER BY item_code").fetchall()
def list_excluded(self) -> list[dict[str, Any]]: def list_excluded(self) -> list[dict[str, Any]]:
@@ -571,9 +603,25 @@ class InoutDBStore:
return out return out
def save_products(self, rows: list[dict[str, Any]], *, by: str) -> int: def save_products(self, rows: list[dict[str, Any]], *, by: str) -> int:
"""값 저장 — rows = [{code, unit_price, weight_g, silver_pct}](store.validate_product_values 를 거친 값). 한 트랜잭션.""" """값 저장 — rows = [{code, unit_price, weight_g, silver_pct}](store.validate_product_values 를 거친 값). 한 트랜잭션.
006 이면 줄에 group_id·color(상품 자기 색상)도 — 그룹 상품의 은 함유량·색상은 그룹 값이 쓰인다."""
self._need_products() self._need_products()
grouped = self.groups_ready() and any("group_id" in r for r in rows)
with self._pool.connection() as conn, conn.transaction(): with self._pool.connection() as conn, conn.transaction():
if grouped:
known = {int(g["id"]) for g in conn.execute("SELECT id FROM inout_product_groups").fetchall()}
for r in rows:
gid = r.get("group_id")
if gid is not None and int(gid) not in known:
raise ValueError(f"{r['code']}: 없는 그룹입니다(다른 사람이 지웠을 수 있음 — 옵션을 다시 여세요).")
hit = conn.execute(
"UPDATE inout_products SET unit_price=%s, weight_g=%s, silver_pct=%s, group_id=%s, color=%s, "
"updated_by=%s, updated_at=now() WHERE item_code=%s RETURNING item_code",
(r["unit_price"], r["weight_g"], r["silver_pct"], gid, r.get("color") or "none",
_norm_email(by), r["code"])).fetchone()
if not hit:
raise ValueError(f"상품 정보에 없는 단품입니다: {r['code']}")
return len(rows)
for r in rows: 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() " 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", "WHERE item_code=%s RETURNING item_code",
@@ -614,20 +662,117 @@ class InoutDBStore:
esc = (q or "").strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") esc = (q or "").strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
if not esc: if not esc:
return [] return []
args = {"q": f"%{esc}%", "p": f"{esc}%", "n": int(limit)}
grouped = self.groups_ready()
with self._pool.connection() as conn: with self._pool.connection() as conn:
if grouped: # 그룹 상품은 그룹의 은 함유량·색상
return conn.execute(
_PRODUCT_SELECT_006 + " WHERE p.item_code ILIKE %(q)s OR p.item_name ILIKE %(q)s "
"ORDER BY (p.item_code ILIKE %(p)s) DESC, p.item_code LIMIT %(n)s", args).fetchall()
return conn.execute( return conn.execute(
"SELECT item_code, item_name, unit_price, weight_g, silver_pct FROM inout_products " "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 " "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", "ORDER BY (item_code ILIKE %(p)s) DESC, item_code LIMIT %(n)s", args).fetchall()
{"q": f"%{esc}%", "p": f"{esc}%", "n": int(limit)}).fetchall()
def catalog_lookup(self, codes: list[str]) -> dict[str, dict[str, Any]]: def catalog_lookup(self, codes: list[str]) -> dict[str, dict[str, Any]]:
if not codes or not self.products_ready(): if not codes or not self.products_ready():
return {} return {}
grouped = self.groups_ready()
with self._pool.connection() as conn: 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() if grouped: # 발주 품목 사본 = 그룹 적용 값
rows = conn.execute(_PRODUCT_SELECT_006 + " WHERE p.item_code = ANY(%s)", ([c.upper() for c in codes],)).fetchall()
else:
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} return {r["item_code"]: r for r in rows}
# ════════════════════════════════════════════════════════════
# 상품 그룹(006) — 은 함유량·색상을 그룹에 한 번만. 그룹을 지우면 그 상품들은 그룹 없음(자기 값)으로.
# ════════════════════════════════════════════════════════════
def groups_ready(self) -> bool:
"""006 이 적용됐나(그룹 표·상품 group_id·발주 품목 color). 적용됐으면 계속, 아직이면 1분 동안 기억한다 —
부를 때마다 연결을 하나 더 잡지 않게(발주 저장 트랜잭션이 연결을 쥔 채 부르면 동시 발주에서 풀이 바닥난다).
그래서 연결을 열기 전에 먼저 부른다."""
if getattr(self, "_groups_ok", False):
return True
if time.monotonic() - getattr(self, "_groups_checked", -1e9) < 60:
return False
if not self.products_ready():
return False
with self._pool.connection() as conn:
ok = bool(conn.execute(
"SELECT to_regclass('public.inout_product_groups') IS NOT NULL "
"AND EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'inout_products' AND column_name = 'group_id') "
"AND EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'inout_order_lines' AND column_name = 'color') AS ok"
).fetchone()["ok"])
self._groups_ok = ok
self._groups_checked = time.monotonic()
return ok
def _need_groups(self) -> None:
if not self.groups_ready():
raise ValueError("DB 마이그레이션 inout_db 006(상품 그룹·색상)이 아직 적용되지 않았습니다.")
def list_groups(self) -> list[dict[str, Any]]:
if not self.groups_ready():
return []
with self._pool.connection() as conn:
return conn.execute(
"SELECT g.*, (SELECT count(*) FROM inout_products p WHERE p.group_id = g.id)::int AS product_count "
"FROM inout_product_groups g ORDER BY g.sort_order, g.name").fetchall()
def save_group(self, *, group_id: int | None, name: str, silver_pct: Any, color: str, sort_order: int, by: str) -> int:
"""그룹 만들기·고치기(store.validate_group 를 거친 값). 같은 이름은 거절. 반환 = 그룹 id."""
self._need_groups()
try:
with self._pool.connection() as conn, conn.transaction():
if group_id:
row = conn.execute(
"UPDATE inout_product_groups SET name=%s, silver_pct=%s, color=%s, sort_order=%s, updated_by=%s, "
"updated_at=now() WHERE id=%s RETURNING id",
(name, silver_pct, color, sort_order, _norm_email(by), group_id)).fetchone()
if not row:
raise ValueError("그룹을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).")
else:
row = conn.execute(
"INSERT INTO inout_product_groups (name, silver_pct, color, sort_order, updated_by) "
"VALUES (%s,%s,%s,%s,%s) RETURNING id",
(name, silver_pct, color, sort_order, _norm_email(by))).fetchone()
except UniqueViolation:
raise ValueError(f"같은 이름의 그룹이 있습니다: {name}") from None
return int(row["id"])
def delete_group(self, group_id: int) -> str:
"""그룹 지우기 — 그 그룹 상품은 그룹 없음(상품 자기 은 함유량·색상)으로. 지난 발주서는 그대로. 반환 = 이름."""
self._need_groups()
with self._pool.connection() as conn, conn.transaction():
row = conn.execute("DELETE FROM inout_product_groups WHERE id=%s RETURNING name", (group_id,)).fetchone()
if not row:
raise ValueError("그룹을 찾을 수 없습니다.")
return str(row["name"])
# ════════════════════════════════════════════════════════════
# 달력(2026-10-21) — 화면 오른쪽 달력에 날짜별 발주(발주일)·입고(입고일). 취소된 발주는 뺀다.
# ════════════════════════════════════════════════════════════
def calendar(self, start: date, end: date) -> dict[str, list[dict[str, Any]]]:
with self._pool.connection() as conn:
orders = conn.execute(
"SELECT o.id, o.order_no, o.order_date, f.name AS factory_name, "
"(SELECT COALESCE(sum(qty), 0) FROM inout_order_lines l WHERE l.order_id = o.id)::int AS qty, "
"(SELECT count(*) FROM inout_order_lines l WHERE l.order_id = o.id)::int AS kinds, "
"(SELECT l.item_name FROM inout_order_lines l WHERE l.order_id = o.id ORDER BY l.line_no LIMIT 1) AS first_item "
"FROM inout_orders o JOIN inout_factories f ON f.id = o.factory_id "
"WHERE o.cancelled_at IS NULL AND o.order_date BETWEEN %s AND %s ORDER BY o.order_date, o.id",
(start, end)).fetchall()
receipts = conn.execute(
"SELECT r.id, r.order_id, r.receipt_date, o.order_no, f.name AS factory_name, "
"COALESCE(sum(rl.qty), 0)::int AS qty "
"FROM inout_receipts r JOIN inout_orders o ON o.id = r.order_id JOIN inout_factories f ON f.id = o.factory_id "
"LEFT JOIN inout_receipt_lines rl ON rl.receipt_id = r.id "
"WHERE o.cancelled_at IS NULL AND r.receipt_date BETWEEN %s AND %s "
"GROUP BY r.id, o.order_no, f.name ORDER BY r.receipt_date, r.id",
(start, end)).fetchall()
return {"orders": orders, "receipts": receipts}
# ════════════════════════════════════════════════════════════ # ════════════════════════════════════════════════════════════
# 미입고 현황 — 진행 중(종결·취소 아님) 발주의 남은 수량, 그리고 초과 입고 # 미입고 현황 — 진행 중(종결·취소 아님) 발주의 남은 수량, 그리고 초과 입고
# ════════════════════════════════════════════════════════════ # ════════════════════════════════════════════════════════════
+89 -4
View File
@@ -841,7 +841,8 @@ def _candidates() -> list[dict[str, str]]:
out = [] out = []
for u in user_store.list_all(): for u in user_store.list_all():
if has_module(u, "inout"): if has_module(u, "inout"):
out.append({"email": str(u.get("email") or "").lower(), "name": str(u.get("name") or "")}) out.append({"email": str(u.get("email") or "").lower(), "name": str(u.get("name") or ""),
"picture": str(u.get("picture") or "")}) # 옵션 → 담당자 = 아이콘 + 이름(2026-10-21)
return sorted(out, key=lambda x: x["email"]) return sorted(out, key=lambda x: x["email"])
@@ -852,13 +853,14 @@ def _options_ctx(request: Request, st: Any) -> dict[str, Any]:
for emails in roles.values(): # 권한이 빠졌어도 담당으로 남아 있는 사람은 보여 줘야 뺄 수 있다 for emails in roles.values(): # 권한이 빠졌어도 담당으로 남아 있는 사람은 보여 줘야 뺄 수 있다
for e in emails: for e in emails:
if e not in known: if e not in known:
cands.append({"email": e, "name": "(입출고 모듈 권한 없음)"}) cands.append({"email": e, "name": "(입출고 모듈 권한 없음)", "picture": ""})
known.add(e) known.add(e)
reader = _items(request) reader = _items(request)
products = st.list_products() products = st.list_products()
for pr in products: for pr in products:
pr["silver_g"] = store.silver_g(pr.get("weight_g"), pr.get("silver_pct")) 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(), return {"products": products, "excluded": st.list_excluded(), "products_ready": st.products_ready(),
"groups": st.list_groups(), "groups_ready": st.groups_ready(), "colors": store.COLORS,
"fmt_num": store.fmt_num, "fmt_num": store.fmt_num,
"factories": st.list_factories(include_inactive=True), "roles": roles, "role_labels": store.ROLE_LABELS, "factories": st.list_factories(include_inactive=True), "roles": roles, "role_labels": store.ROLE_LABELS,
"settings": st.get_settings(), "settings_ready": st.settings_ready(), "settings": st.get_settings(), "settings_ready": st.settings_ready(),
@@ -1013,7 +1015,14 @@ def settings_products_save(request: Request, payload: dict[str, Any] = Body(...)
for r in (payload.get("rows") or [])[:5000]: for r in (payload.get("rows") or [])[:5000]:
code = str((r or {}).get("code") or "").strip().upper() code = str((r or {}).get("code") or "").strip().upper()
try: try:
rows.append({"code": code, **store.validate_product_values(r)}) row = {"code": code, **store.validate_product_values(r)}
if "group_id" in (r or {}): # 006 — 그룹(빈칸 = 그룹 없음)·상품 자기 색상
gid = str(r.get("group_id") or "").strip()
if gid and not gid.isdigit():
raise ValueError("그룹이 올바르지 않습니다.")
row["group_id"] = int(gid) if gid else None
row["color"] = store.norm_color(r.get("color"))
rows.append(row)
except ValueError as exc: except ValueError as exc:
errors.append(f"{code}: {exc}") errors.append(f"{code}: {exc}")
if errors: if errors:
@@ -1027,6 +1036,38 @@ def settings_products_save(request: Request, payload: dict[str, Any] = Body(...)
return _options_done(request, f"상품 정보 {n}개를 저장했습니다.") return _options_done(request, f"상품 정보 {n}개를 저장했습니다.")
@router.post("/settings/groups")
async def settings_group_save(request: Request) -> Any:
"""상품 그룹 만들기·고치기(006) — 이름·은 함유량·색상·순서. 그룹 상품 모두에 은 함유량·색상이 적용된다."""
got = _ctx(request)
if not isinstance(got, tuple):
return got
st, user = got
_require(st, user, "admin")
form = await request.form()
try:
vals = store.validate_group(dict(form))
gid = _opt_int(form.get("id"))
st.save_group(group_id=gid, by=user.get("email", ""), **vals)
except ValueError as exc:
return _options_done(request, str(exc), ok=False)
return _options_done(request, f"그룹 '{vals['name']}' 을(를) {'저장' if gid else '추가'}했습니다.")
@router.post("/settings/groups/{group_id}/delete")
def settings_group_delete(request: Request, group_id: int) -> Any:
got = _ctx(request)
if not isinstance(got, tuple):
return got
st, user = got
_require(st, user, "admin")
try:
name = st.delete_group(group_id)
except ValueError as exc:
return _options_done(request, str(exc), ok=False)
return _options_done(request, f"그룹 '{name}' 을(를) 지웠습니다 — 그 상품들은 그룹 없음(상품마다 값)으로 바뀝니다.")
@router.post("/settings/products/{code}/exclude") @router.post("/settings/products/{code}/exclude")
def settings_product_exclude(request: Request, code: str) -> Any: def settings_product_exclude(request: Request, code: str) -> Any:
got = _ctx(request) got = _ctx(request)
@@ -1070,7 +1111,8 @@ def api_items(request: Request, q: str = "") -> JSONResponse:
"unit_price": store.fmt_num(r["unit_price"]) if r["unit_price"] is not None else "", "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, "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 "", "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]}) "silver_pct": store.fmt_num(r["silver_pct"], 4) if r["silver_pct"] is not None else "",
"color": r.get("color") or "none"} for r in rows]})
reader = _items(request) reader = _items(request)
if reader is None or not reader.enabled: if reader is None or not reader.enabled:
return JSONResponse({"items": [], "enabled": False, return JSONResponse({"items": [], "enabled": False,
@@ -1078,6 +1120,49 @@ def api_items(request: Request, q: str = "") -> JSONResponse:
return JSONResponse({"items": reader.search(q, limit=30), "enabled": True}) return JSONResponse({"items": reader.search(q, limit=30), "enabled": True})
@router.get("/api/calendar")
def api_calendar(request: Request, month: str = "") -> JSONResponse:
"""오른쪽 달력(2026-10-21) — month=YYYY-MM(없으면 이번 달) 앞뒤 주까지(6주 칸)의 날짜별 발주·입고.
days = {"YYYY-MM-DD": {"orders": [...], "receipts": [...]}}, holidays = {"YYYY-MM-DD": 이름}."""
from datetime import timedelta # noqa: WPS433
_user(request)
st = _store(request)
if st is None:
raise HTTPException(status_code=503, detail="입출고 관리 DB 가 설정되지 않았습니다.")
today = today_kst()
try:
y, m = (int(x) for x in month.split("-", 1)) if month else (today.year, today.month)
first = date(y, m, 1)
except ValueError:
raise HTTPException(status_code=400, detail="month 는 YYYY-MM 입니다.") from None
start = first - timedelta(days=(first.weekday() + 1) % 7) # 일요일 시작
end = start + timedelta(days=41)
data = st.calendar(start, end)
days: dict[str, dict[str, list[dict[str, Any]]]] = {}
for o in data["orders"]:
days.setdefault(o["order_date"].isoformat(), {"orders": [], "receipts": []})["orders"].append({
"id": int(o["id"]), "order_no": o["order_no"], "factory": o["factory_name"], "qty": int(o["qty"]),
"item": (o["first_item"] or "") + (f" 외 {int(o['kinds']) - 1}종" if int(o["kinds"]) > 1 else "")})
for r in data["receipts"]:
days.setdefault(r["receipt_date"].isoformat(), {"orders": [], "receipts": []})["receipts"].append({
"id": int(r["id"]), "order_id": int(r["order_id"]), "order_no": r["order_no"], "factory": r["factory_name"],
"qty": int(r["qty"])})
holidays: dict[str, str] = {}
try:
from app.modules.project.store import holiday_name # noqa: WPS433 — 프로젝트 달력과 같은 공휴일 표
d = start
while d <= end:
name = holiday_name(d.isoformat())
if name:
holidays[d.isoformat()] = name
d += timedelta(days=1)
except Exception: # noqa: BLE001 — 공휴일 표가 없어도 달력은 보인다
holidays = {}
return JSONResponse({"month": f"{first:%Y-%m}", "start": start.isoformat(), "end": end.isoformat(),
"today": today.isoformat(), "days": days, "holidays": holidays})
@router.get("/health") @router.get("/health")
def health(request: Request) -> dict[str, str]: def health(request: Request) -> dict[str, str]:
return {"status": "ok" if _store(request) is not None else "not_configured"} return {"status": "ok" if _store(request) is not None else "not_configured"}
+55 -7
View File
@@ -319,12 +319,17 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
rows = [] rows = []
for i, x in enumerate(lines, start=1): for i, x in enumerate(lines, start=1):
c = cells(x) c = cells(x)
# 색상 있는 품목(006) = 줄 전체 배경 그 색 — 메일 프로그램이 tr 배경을 무시하기도 해서 칸마다도 칠한다
hexc = color_hex(x.get("color"))
ctd = f"{td}background:{hexc};" if hexc else td
tr_style = f' style="background:{hexc}"' if hexc else ""
rows.append( 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'<tr{tr_style}><td style="{ctd}text-align:center">{i}</td>'
f'<td style="{td}">{e(x["item_name"])}</td><td style="{td}{r}">{int(x["qty"]):,}</td>' f'<td style="{ctd}font-family:Consolas,monospace">{e(x["item_code"])}</td>'
f'<td style="{td}{r}">{e(c["price"])}</td><td style="{td}{r}">{e(c["amount"])}</td>' f'<td style="{ctd}">{e(x["item_name"])}</td><td style="{ctd}{r}">{int(x["qty"]):,}</td>'
f'<td style="{td}{r}">{e(c["weight"])}</td><td style="{td}{r}">{e(c["pp_use"])}</td><td style="{td}{r}">{e(c["ag"])}</td>' f'<td style="{ctd}{r}">{e(c["price"])}</td><td style="{ctd}{r}">{e(c["amount"])}</td>'
f'<td style="{td}">{e(x.get("memo") or "")}</td></tr>') f'<td style="{ctd}{r}">{e(c["weight"])}</td><td style="{ctd}{r}">{e(c["pp_use"])}</td><td style="{ctd}{r}">{e(c["ag"])}</td>'
f'<td style="{ctd}">{e(x.get("memo") or "")}</td></tr>')
foot_amount = fmt_num(money["amount"]) if money["amount"] is not None else "" foot_amount = fmt_num(money["amount"]) if money["amount"] is not None else ""
foot_pp = fmt_num(money["pp_kg"], 3) if money["pp_kg"] is not None else "" foot_pp = fmt_num(money["pp_kg"], 3) if money["pp_kg"] is not None else ""
foot_use = fmt_num(money["pp_use_kg"], 3) if money["pp_use_kg"] is not None else "" foot_use = fmt_num(money["pp_use_kg"], 3) if money["pp_use_kg"] is not None else ""
@@ -437,8 +442,51 @@ def validate_product_values(values: dict[str, Any]) -> dict[str, Decimal | None]
def has_values(p: dict[str, Any]) -> bool: def has_values(p: dict[str, Any]) -> bool:
"""단가·무게·은 함유량 중 하나라도 넣었나 — 넣은 상품은 다시 불러와도 그대로 둔다.""" """단가·무게·은 함유량(·그룹·색상, 006) 중 하나라도 넣었나 — 넣은 상품은 다시 불러와도 그대로 둔다."""
return any(p.get(k) is not None for k in PRODUCT_LIMITS) return (any(p.get(k) is not None for k in PRODUCT_LIMITS) or p.get("group_id") is not None
or (p.get("color") or "none") != "none")
# ════════════════════════════════════════════════════════════
# 상품 그룹·색상(2026-10-21, 마이그레이션 006)
# 그룹에 은 함유량·색상을 한 번만 — 그룹 상품은 그룹 값, 그룹 없는 상품은 자기 값(effective_product).
# 색상 = 키 → (이름, 칸 색). 발주 메일 품목 표에서 색상 있는 품목 줄 전체 배경 = 칸 색(옅게 — 글자가 읽히게).
# ════════════════════════════════════════════════════════════
COLORS = {"none": ("색없음", ""), "orange": ("오렌지", "#FFD8B0"), "blue": ("파랑", "#CFE0FA"),
"gray": ("회색", "#DDDFE3"), "ivory": ("아이보리색", "#FFF6D9")}
MAX_GROUP_NAME = 100
def norm_color(raw: Any) -> str:
"""색상 키(none·orange·blue·gray·ivory). 빈칸 = none. 모르는 값은 ValueError."""
key = str(raw if raw is not None else "").strip().lower() or "none"
if key not in COLORS:
raise ValueError("색상은 " + "·".join(v[0] for v in COLORS.values()) + " 중에서 고르세요.")
return key
def color_hex(key: Any) -> str:
"""색상 키 → 칸 색(#RRGGBB). 색없음·모름 = ''."""
return COLORS.get(str(key or "none"), ("", ""))[1]
def color_name(key: Any) -> str:
return COLORS.get(str(key or "none"), COLORS["none"])[0]
def validate_group(values: dict[str, Any]) -> dict[str, Any]:
"""그룹 저장 값 — 이름(필수, 100자)·은 함유량(빈칸 = 미입력)·색상·순서."""
name = str(values.get("name") or "").strip()
if not name:
raise ValueError("그룹 이름을 넣으세요.")
if len(name) > MAX_GROUP_NAME:
raise ValueError(f"그룹 이름은 {MAX_GROUP_NAME}자까지입니다.")
try:
sort_order = int(str(values.get("sort_order") or "0").strip() or 0)
except ValueError:
raise ValueError("순서는 숫자로 넣으세요.") from None
return {"name": name, "silver_pct": parse_decimal(values.get("silver_pct"), key="silver_pct"),
"color": norm_color(values.get("color")), "sort_order": max(-9999, min(9999, sort_order))}
# ════════════════════════════════════════════════════════════ # ════════════════════════════════════════════════════════════
@@ -0,0 +1,20 @@
{# 오른쪽 달력(2026-10-21) — 입출고 모든 화면 오른쪽 위 300×320, 오른쪽 열 너비 = 달력 너비.
프로젝트 달력과 같은 모양(일요일 시작 · 요일 줄 회색 · 오늘 검은 동그라미 · 토 파랑 · 일/공휴일 빨강 · 다른 달 흐리게).
날짜 칸 = 발주(발주일, 파랑) · 입고(입고일, 초록) 건수, 누르면 그날 목록(발주서로 이동). 내용은 inout.js 가 GET /inout/api/calendar 로 그린다. #}
<aside class="io-side" aria-label="발주·입고 달력">
<div class="io-cal" id="io-cal" data-month="{{ today.strftime('%Y-%m') }}">
<div class="io-cal-head">
<button type="button" class="io-cal-nav" data-step="-1" aria-label="이전 달" title="이전 달">‹</button>
<h3 class="io-cal-title" aria-live="polite">{{ today.year }}년 {{ today.month }}월</h3>
<button type="button" class="io-cal-nav" data-step="1" aria-label="다음 달" title="다음 달">›</button>
<button type="button" class="io-cal-today">오늘</button>
</div>
<div class="io-cal-box">
<div class="io-cal-wd" aria-hidden="true">
<span class="is-sun">일</span><span>월</span><span>화</span><span>수</span><span>목</span><span>금</span><span class="is-sat">토</span>
</div>
<div class="io-cal-days" role="grid"></div>
</div>
</div>
<p class="io-cal-legend"><i class="io-cal-m is-order">n</i>발주 <i class="io-cal-m is-receipt">n</i>입고 <span class="io-sub">· 날짜를 누르면 목록</span></p>
</aside>
@@ -26,3 +26,8 @@
{%- endmacro %} {%- endmacro %}
{% macro n(v) -%}{{ '{:,}'.format(v or 0) }}{%- endmacro %} {% macro n(v) -%}{{ '{:,}'.format(v or 0) }}{%- endmacro %}
{# 색상 사각형(006) — 색이 칠해진 네모. 색없음은 빗금 없는 흰 네모 + 테두리. colors = store.COLORS #}
{% macro swatch(key, colors) -%}
<i class="io-swatch{% if not colors.get(key or 'none', ('', ''))[1] %} is-none{% endif %}" style="background:{{ colors.get(key or 'none', ('', ''))[1] or '#fff' }}" aria-hidden="true"></i>
{%- endmacro %}
@@ -1,4 +1,4 @@
{% from "inout/_macros.html" import ymd %} {% from "inout/_macros.html" import ymd, swatch %}
{# 옵션 팝업 내용(GET /inout/settings?panel=1) — 탭: 담당자 · 공장 · 상품 정보(004). 폼 저장은 inout.js 가 제자리에서(X-Inout-Options: 1 → JSON). {# 옵션 팝업 내용(GET /inout/settings?panel=1) — 탭: 담당자 · 공장 · 상품 정보(004). 폼 저장은 inout.js 가 제자리에서(X-Inout-Options: 1 → JSON).
공장 줄은 표(<table>) 안에 폼을 둘 수 없어 입력칸에 form="…" 속성으로 표 밖 폼에 묶는다 — 열이 머리 줄과 맞는다. #} 공장 줄은 표(<table>) 안에 폼을 둘 수 없어 입력칸에 form="…" 속성으로 표 밖 폼에 묶는다 — 열이 머리 줄과 맞는다. #}
<div class="io-dlg-tabs" role="tablist" aria-label="옵션 분류"> <div class="io-dlg-tabs" role="tablist" aria-label="옵션 분류">
@@ -20,7 +20,11 @@
<tbody> <tbody>
{% for c in candidates %} {% for c in candidates %}
<tr> <tr>
<td><b class="io-user">{{ c.name or c.email }}</b><span class="io-sub">{{ c.email }}</span></td> <td><span class="io-person">
{% if c.picture %}<img class="io-avatar" src="{{ c.picture }}" alt="" referrerpolicy="no-referrer" loading="lazy" />
{% else %}<svg class="io-avatar io-avatar-empty" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="12" fill="#d5d9de"/><circle cx="12" cy="9.5" r="4" fill="#fff"/><path d="M4.6 19.6a8.6 8.6 0 0 1 14.8 0A11.9 11.9 0 0 1 12 24a11.9 11.9 0 0 1-7.4-4.4z" fill="#fff"/></svg>{% endif %}
<span class="io-person-text"><b class="io-user">{{ c.name or c.email }}</b><span class="io-sub">{{ c.email }}</span></span>
</span></td>
{% for role in role_labels %} {% for role in role_labels %}
<td class="io-c"><input type="checkbox" name="{{ role }}_email" value="{{ c.email }}" {% if c.email in roles[role] %}checked{% endif %} <td class="io-c"><input type="checkbox" name="{{ role }}_email" value="{{ c.email }}" {% if c.email in roles[role] %}checked{% endif %}
aria-label="{{ c.email }} {{ role_labels[role] }}" /></td> aria-label="{{ c.email }} {{ role_labels[role] }}" /></td>
@@ -88,7 +92,50 @@
<p class="io-help"> <p class="io-help">
코드표의 단품을 불러와 <b>단가</b>(원)·<b>무게</b>(개당 g = PP량)·<b>은(Ag) 함유량</b>(%)을 넣습니다 — 은 함량(g)은 무게 × %로 자동 계산. 코드표의 단품을 불러와 <b>단가</b>(원)·<b>무게</b>(개당 g = PP량)·<b>은(Ag) 함유량</b>(%)을 넣습니다 — 은 함량(g)은 무게 × %로 자동 계산.
값을 넣은 상품은 다시 불러와도 그대로이고, 지운 단품은 다음 불러오기에서 빠집니다. 발주서 제품은 이 목록에서 고르며, 발주할 때의 값이 발주서에 남습니다. 값을 넣은 상품은 다시 불러와도 그대로이고, 지운 단품은 다음 불러오기에서 빠집니다. 발주서 제품은 이 목록에서 고르며, 발주할 때의 값이 발주서에 남습니다.
{% if groups_ready %}<b>그룹</b>을 고른 상품은 은 함유량·<b>색상</b>을 그룹 값으로 씁니다(그룹에서 한 번만 설정). 색상 있는 품목은 발주 메일 표에서 그 줄 배경이 그 색입니다.{% endif %}
</p> </p>
{% if groups_ready %}
{% for g in groups %}<form method="post" action="/inout/settings/groups" id="io-g{{ g.id }}" class="io-dlg-form io-group-form"><input type="hidden" name="id" value="{{ g.id }}" /></form>{% endfor %}
<form method="post" action="/inout/settings/groups" id="io-gnew" class="io-dlg-form io-group-form"></form>
<details class="io-groups" open>
<summary>그룹 {{ groups|length }}개 — 은 함유량·색상을 그룹마다 한 번만</summary>
<table class="io-dlg-table io-group-table">
<colgroup><col class="w-gname" /><col class="w-num" /><col class="w-color" /><col class="w-sort" /><col class="w-cnt" /><col class="w-btn" /></colgroup>
<thead><tr><th>그룹 이름</th><th class="io-r">은 함유량(%)</th><th>색상</th><th class="io-c">순서</th><th class="io-c">상품</th><th></th></tr></thead>
<tbody>
{% for g in groups %}
{% set gf = 'io-g' ~ g.id %}
<tr>
<td><input class="io-in" form="{{ gf }}" type="text" name="name" value="{{ g.name }}" maxlength="100" required aria-label="그룹 이름" /></td>
<td><input class="io-in io-in-num" form="{{ gf }}" type="text" name="silver_pct" value="{{ fmt_num(g.silver_pct, 4) if g.silver_pct is not none else '' }}" inputmode="decimal" aria-label="{{ g.name }} 은 함유량" /></td>
<td><span class="io-color">{{ swatch(g.color, colors) }}<select class="io-in io-color-select" form="{{ gf }}" name="color" aria-label="{{ g.name }} 색상">
{% for key, c in colors.items() %}<option value="{{ key }}" data-hex="{{ c[1] }}" {% if g.color == key %}selected{% endif %}>{{ c[0] }}</option>{% endfor %}
</select></span></td>
<td class="io-c"><input class="io-in io-in-num" form="{{ gf }}" type="number" name="sort_order" value="{{ g.sort_order }}" aria-label="순서" /></td>
<td class="io-c io-sub">{{ g.product_count }}개</td>
<td class="io-btns">
<button form="{{ gf }}" type="submit" class="erp-btn erp-btn-outline erp-btn-sm">저장</button>
<button form="{{ gf }}" type="submit" class="erp-btn erp-btn-outline erp-btn-sm" formaction="/inout/settings/groups/{{ g.id }}/delete"
formnovalidate data-confirm="그룹 '{{ g.name }}' 을(를) 지울까요? 그룹 상품 {{ g.product_count }}개는 그룹 없음(상품마다 값)으로 바뀝니다.">지우기</button>
</td>
</tr>
{% endfor %}
<tr class="io-new-row">
<td><input class="io-in" form="io-gnew" type="text" name="name" maxlength="100" required placeholder="새 그룹 이름" aria-label="새 그룹 이름" /></td>
<td><input class="io-in io-in-num" form="io-gnew" type="text" name="silver_pct" inputmode="decimal" placeholder="%" aria-label="새 그룹 은 함유량" /></td>
<td><span class="io-color">{{ swatch('none', colors) }}<select class="io-in io-color-select" form="io-gnew" name="color" aria-label="새 그룹 색상">
{% for key, c in colors.items() %}<option value="{{ key }}" data-hex="{{ c[1] }}">{{ c[0] }}</option>{% endfor %}
</select></span></td>
<td class="io-c"><input class="io-in io-in-num" form="io-gnew" type="number" name="sort_order" value="0" aria-label="순서" /></td>
<td></td>
<td class="io-btns"><button form="io-gnew" type="submit" class="erp-btn erp-btn-primary erp-btn-sm">+ 추가</button></td>
</tr>
</tbody>
</table>
</details>
{% else %}
<p class="io-error">상품 그룹·색상은 DB 마이그레이션 inout_db 006 적용 후 쓸 수 있습니다 — 관리자에게 알려 주세요.</p>
{% endif %}
<div class="io-prod-bar"> <div class="io-prod-bar">
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="io-prod-import">단품 불러오기</button> <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="상품 찾기" /> <input type="search" class="io-in io-prod-search" id="io-prod-search" placeholder="코드·제품명 찾기" aria-label="상품 찾기" />
@@ -98,18 +145,32 @@
</div> </div>
{% if products %} {% if products %}
<div class="io-prod-scroll"> <div class="io-prod-scroll">
<table class="io-dlg-table io-prod-table"> <table class="io-dlg-table io-prod-table{% if groups_ready %} has-groups{% endif %}">
<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> <colgroup><col class="w-code" /><col />{% if groups_ready %}<col class="w-group" />{% endif %}<col class="w-num" /><col class="w-num" /><col class="w-num" /><col class="w-ag" />{% if groups_ready %}<col class="w-color" />{% endif %}<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> <thead><tr><th>코드</th><th>제품명</th>{% if groups_ready %}<th>그룹</th>{% endif %}<th class="io-r">단가(원)</th><th class="io-r">무게·PP(g/개)</th><th class="io-r">은 함유량(%)</th><th class="io-r">은(g/개)</th>{% if groups_ready %}<th>색상</th>{% endif %}<th></th></tr></thead>
<tbody> <tbody>
{% for p in products %} {% for p in products %}
<tr data-code="{{ p.item_code }}" data-search="{{ (p.item_code ~ ' ' ~ p.item_name)|lower }}"> {% set own_pct = p.own_silver_pct if groups_ready else p.silver_pct %}
<tr data-code="{{ p.item_code }}" data-search="{{ (p.item_code ~ ' ' ~ p.item_name ~ ' ' ~ (p.group_name or ''))|lower }}"{% if groups_ready and p.group_id %} class="is-grouped"{% endif %}>
<td class="io-code">{{ p.item_code }}</td> <td class="io-code">{{ p.item_code }}</td>
<td class="io-prod-name">{{ p.item_name }}</td> <td class="io-prod-name">{{ p.item_name }}</td>
{% if groups_ready %}
<td><select class="io-in io-group-select" data-key="group_id" aria-label="{{ p.item_code }} 그룹">
<option value="" data-silver="" data-color="">그룹 없음</option>
{% for g in groups %}<option value="{{ g.id }}" data-silver="{{ fmt_num(g.silver_pct, 4) if g.silver_pct is not none else '' }}" data-color="{{ g.color }}" {% if p.group_id == g.id %}selected{% endif %}>{{ g.name }}</option>{% endfor %}
</select></td>
{% endif %}
<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="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="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><input class="io-in io-in-num io-own" data-key="silver_pct" value="{{ fmt_num(own_pct, 4) if own_pct is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 은 함유량" />
{% if groups_ready %}<span class="io-group-val io-r" title="그룹 값 — 그룹에서 바꿉니다">{{ fmt_num(p.silver_pct, 4) if p.silver_pct is not none else '-' }}</span>{% endif %}</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 io-ag" title="무게 × 은 함유량 ÷ 100">{{ fmt_num(p.silver_g, 4) if p.silver_g is not none else '-' }}</td>
{% if groups_ready %}
<td><span class="io-color io-own">{{ swatch(p.own_color, colors) }}<select class="io-in io-color-select" data-key="color" aria-label="{{ p.item_code }} 색상">
{% for key, c in colors.items() %}<option value="{{ key }}" data-hex="{{ c[1] }}" {% if p.own_color == key %}selected{% endif %}>{{ c[0] }}</option>{% endfor %}
</select></span>
<span class="io-color io-group-val" title="그룹 값 — 그룹에서 바꿉니다">{{ swatch(p.color, colors) }}<span class="io-color-name">{{ colors[p.color][0] if p.color in colors else '' }}</span></span></td>
{% endif %}
<td class="io-r"><button type="button" class="io-icon-btn" data-exclude="{{ p.item_code }}" title="지우기 — 다음 불러오기에서도 뺌" aria-label="{{ p.item_code }} 지우기">✕</button></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> </tr>
{% endfor %} {% endfor %}
+5 -2
View File
@@ -1,8 +1,9 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% from "inout/_macros.html" import order_badge, progress, due, n, ymd %} {% from "inout/_macros.html" import order_badge, progress, due, n, ymd %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019g" />{% endblock %} {% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021a" />{% endblock %}
{% block content %} {% block content %}
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
<section class="io"> <section class="io">
{% include "inout/_nav.html" %} {% include "inout/_nav.html" %}
@@ -67,5 +68,7 @@
</div> </div>
</div> </div>
</section> </section>
{% include "inout/_calendar.html" %}
</div>
{% endblock %} {% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261019c" defer></script>{% endblock %} {% block scripts %}<script src="/static/inout.js?v=20261021a" defer></script>{% endblock %}
@@ -20,7 +20,7 @@
</footer> </footer>
</dialog> </dialog>
{%- endmacro -%} {%- endmacro -%}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019g" />{% endblock %} {% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021a" />{% endblock %}
{% block content %} {% block content %}
{% set active = order.status in ('open', 'partial') %} {% set active = order.status in ('open', 'partial') %}
@@ -29,6 +29,7 @@
{% set recv_done = order.status in ('done', 'over') %} {% set recv_done = order.status in ('done', 'over') %}
{% set dis = ' disabled' if recv_done else '' %} {% set dis = ' disabled' if recv_done else '' %}
{% set photo_admin = perms.can_receive and not order.cancelled_at %} {% set photo_admin = perms.can_receive and not order.cancelled_at %}
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
<section class="io"> <section class="io">
{% include "inout/_nav.html" %} {% include "inout/_nav.html" %}
@@ -252,5 +253,7 @@
{% else %}{{ mail_dialog('io-rmail', '입고 요청 메일') }}{% endif %} {% else %}{{ mail_dialog('io-rmail', '입고 요청 메일') }}{% endif %}
{% endif %} {% endif %}
</section> </section>
{% include "inout/_calendar.html" %}
</div>
{% endblock %} {% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261019c" defer></script>{% endblock %} {% block scripts %}<script src="/static/inout.js?v=20261021a" defer></script>{% endblock %}
@@ -1,7 +1,8 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019g" />{% endblock %} {% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021a" />{% endblock %}
{% block content %} {% block content %}
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
<section class="io"> <section class="io">
{% include "inout/_nav.html" %} {% include "inout/_nav.html" %}
@@ -79,5 +80,7 @@
</div> </div>
</form> </form>
</section> </section>
{% include "inout/_calendar.html" %}
</div>
{% endblock %} {% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261019c" defer></script>{% endblock %} {% block scripts %}<script src="/static/inout.js?v=20261021a" defer></script>{% endblock %}
@@ -1,8 +1,9 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% from "inout/_macros.html" import due, n, ymd %} {% from "inout/_macros.html" import due, n, ymd %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019g" />{% endblock %} {% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021a" />{% endblock %}
{% block content %} {% block content %}
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
<section class="io"> <section class="io">
{% include "inout/_nav.html" %} {% include "inout/_nav.html" %}
@@ -87,5 +88,7 @@
</div> </div>
{% endif %} {% endif %}
</section> </section>
{% include "inout/_calendar.html" %}
</div>
{% endblock %} {% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261019c" defer></script>{% endblock %} {% block scripts %}<script src="/static/inout.js?v=20261021a" defer></script>{% endblock %}
+96 -1
View File
@@ -1,6 +1,6 @@
/* 입출고 관리(inout) — ERP 공용(erp.css·erp-shell.css) 위에 이 화면만의 것 */ /* 입출고 관리(inout) — ERP 공용(erp.css·erp-shell.css) 위에 이 화면만의 것 */
/* 공용 .erp-page 는 width:100% + 안쪽 여백(content-box)이라 표가 넓으면 48px 넘친다 — 이 화면에서만 테두리 기준으로 */ /* 공용 .erp-page 는 width:100% + 안쪽 여백(content-box)이라 표가 넓으면 48px 넘친다 — 이 화면에서만 테두리 기준으로 */
.erp-page:has(> .io) { box-sizing: border-box; } .erp-page:has(> .io), .erp-page:has(> .io-split) { box-sizing: border-box; }
.io { display: flex; flex-direction: column; gap: 14px; min-width: 0; } /* 넓은 표는 안에서 가로 스크롤(페이지가 화면보다 넓어지지 않게) */ .io { display: flex; flex-direction: column; gap: 14px; min-width: 0; } /* 넓은 표는 안에서 가로 스크롤(페이지가 화면보다 넓어지지 않게) */
.io-nav { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } .io-nav { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.io-nav-gap { flex: 1 1 auto; } .io-nav-gap { flex: 1 1 auto; }
@@ -321,3 +321,98 @@
.io-receipt-bar #io-fill-remaining.is-filled { border-color: #1e7a34; color: #1e7a34; background: #f3fbf5; } .io-receipt-bar #io-fill-remaining.is-filled { border-color: #1e7a34; color: #1e7a34; background: #f3fbf5; }
/* 발주 메일 창 — 입고 담당 발주 알림 자동 발송 안내 */ /* 발주 메일 창 — 입고 담당 발주 알림 자동 발송 안내 */
.io-mail-notice { margin: -4px 0 12px; padding: 8px 12px; border-radius: 8px; background: #f0f6ff; border: 1px solid #cfe0fb; color: #1d4f91; font-size: 12.5px; } .io-mail-notice { margin: -4px 0 12px; padding: 8px 12px; border-radius: 8px; background: #f0f6ff; border: 1px solid #cfe0fb; color: #1d4f91; font-size: 12.5px; }
/* ── 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21). 오른쪽 열 너비 = 달력 너비(300px), 스크롤해도 위에 붙어 있음.
좁은 화면(1100px 미만)은 한 열 — 달력은 아래로. ── */
.io-split { display: grid; grid-template-columns: minmax(0, 1fr) 300px; gap: 20px; align-items: start; }
.io-split > .io { min-width: 0; }
.io-side { width: 300px; position: sticky; top: 12px; display: flex; flex-direction: column; gap: 6px; }
@media (max-width: 1100px) {
.io-split { grid-template-columns: minmax(0, 1fr); }
.io-side { position: static; }
}
/* 달력 300×320 — 프로젝트 달력 모양(.pj-cal)을 작게: 머리(제목 ‹ › 오늘) + 둥근 테두리 안 요일 줄(회색) + 6주 */
.io-cal { width: 300px; height: 320px; box-sizing: border-box; display: flex; flex-direction: column; }
.io-cal.is-loading .io-cal-days { opacity: .55; }
.io-cal-head { flex: none; height: 36px; display: flex; align-items: center; gap: 4px; }
.io-cal-title { margin: 0 2px; font-size: 16px; font-weight: 600; letter-spacing: -0.3px; white-space: nowrap; color: #0a0a0a; }
.io-cal-nav, .io-cal-today {
border: 1px solid var(--color-subtle-ash, #e5e5e5); background: #fff; border-radius: 8px; cursor: pointer; color: #0a0a0a;
height: 28px; line-height: 1; padding: 0 9px; font-size: 13px;
}
.io-cal-nav { font-size: 18px; padding: 0 8px; }
.io-cal-nav:hover, .io-cal-today:hover { background: #f5f5f5; }
.io-cal-today { margin-left: auto; }
.io-cal-box { flex: 1 1 auto; min-height: 0; border: 1px solid #e5e5e5; border-radius: 10px; overflow: hidden; display: flex; flex-direction: column; background: #fff; }
.io-cal-wd { flex: none; display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); background: #f2f2f2; border-bottom: 1px solid #e5e5e5; }
.io-cal-wd span { text-align: center; padding: 4px 0; font-size: 12px; font-weight: 600; color: #0a0a0a; }
.io-cal-wd .is-sun { color: #c22b10; }
.io-cal-wd .is-sat { color: #1d4ed8; }
.io-cal-days { flex: 1 1 auto; min-height: 0; display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); grid-template-rows: repeat(6, minmax(0, 1fr)); }
.io-cal-day {
all: unset; box-sizing: border-box; min-width: 0; min-height: 0; padding: 3px 3px 2px; cursor: default;
display: flex; flex-direction: column; align-items: center; gap: 1px;
border-right: 1px solid #efefef; border-bottom: 1px solid #efefef;
}
.io-cal-day:nth-child(7n) { border-right: 0; }
.io-cal-day:nth-last-child(-n+7) { border-bottom: 0; }
.io-cal-day.has-ev { cursor: pointer; }
.io-cal-day.has-ev:hover { background: #f2f6ff; }
.io-cal-day:focus-visible { outline: 2px solid #1d4ed8; outline-offset: -2px; }
.io-cal-num { font-size: 12px; font-weight: 600; color: #0a0a0a; line-height: 18px; min-width: 18px; text-align: center; border-radius: 9999px; }
.io-cal-day.is-sun .io-cal-num { color: #c22b10; }
.io-cal-day.is-sat .io-cal-num { color: #1d4ed8; }
.io-cal-day.is-out { background: #fafafa; }
.io-cal-day.is-out .io-cal-num { color: #bbb; }
.io-cal-day.is-today { background: #f5f5f5; }
.io-cal-day.is-today .io-cal-num { background: #0a0a0a; color: #fff; padding: 0 5px; }
.io-cal-day.is-today.is-sun .io-cal-num { background: #c22b10; color: #fff; }
.io-cal-day.is-today.is-sat .io-cal-num { background: #1d4ed8; color: #fff; }
.io-cal-marks { display: flex; gap: 2px; flex-wrap: wrap; justify-content: center; }
.io-cal-m { font-style: normal; display: inline-block; min-width: 14px; height: 14px; line-height: 14px; padding: 0 3px; box-sizing: border-box;
border-radius: 7px; font-size: 10px; font-weight: 700; color: #fff; text-align: center; }
.io-cal-m.is-order { background: #2f6fde; }
.io-cal-m.is-receipt { background: #1e8e5a; }
.io-cal-err { grid-column: 1 / -1; margin: auto; font-size: 12px; color: #a1261b; }
.io-cal-legend { margin: 0; font-size: 11.5px; color: var(--color-midtone-gray, #666); display: flex; align-items: center; gap: 4px; flex-wrap: wrap; }
.io-cal-legend .io-cal-m { margin-left: 4px; }
.io-cal-legend .io-cal-m:first-child { margin-left: 0; }
/* 그날 목록 팝업 — 프로젝트 달력 .pj-daypop 모양 */
.io-calpop { position: absolute; z-index: 2100; width: 280px; max-height: 320px; overflow: auto; background: #fff; border: 1px solid #e2e5e9;
border-radius: 12px; box-shadow: 0 8px 28px rgba(0,0,0,.16); padding: 8px; box-sizing: border-box; }
.io-calpop-head { font-size: 12px; font-weight: 700; color: #525860; padding: 4px 6px 8px; }
.io-calpop-head .is-hol { color: #c22b10; }
.io-calpop-item { display: grid; grid-template-columns: auto minmax(0, 1fr); column-gap: 8px; align-items: center; padding: 6px; border-radius: 8px;
text-decoration: none; color: #1e1f21; font-size: 12.5px; }
.io-calpop-item:hover { background: #f2f4f6; }
.io-calpop-item .io-cal-m { grid-row: span 2; height: 18px; line-height: 18px; border-radius: 9px; padding: 0 6px; font-size: 11px; }
.io-calpop-main { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.io-calpop-sub { color: #6b6f76; font-size: 11.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* ── 옵션 → 담당자: 아이콘 + 이름, 아래 이메일(2026-10-21) ── */
.io-person { display: inline-flex; align-items: center; gap: 8px; }
.io-avatar { flex: none; width: 28px; height: 28px; border-radius: 50%; object-fit: cover; }
.io-person-text { display: flex; flex-direction: column; line-height: 1.3; }
.io-person-text .io-sub { display: block; }
/* ── 옵션 → 상품 정보: 그룹·색상(2026-10-21, 006) ── */
.io-swatch { display: inline-block; flex: none; width: 14px; height: 14px; border-radius: 3px; border: 1px solid rgba(0,0,0,.18); vertical-align: middle; box-sizing: border-box; }
.io-swatch.is-none { background: #fff !important; border-style: dashed; border-color: #b9bdc3; }
.io-color { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
.io-color .io-color-select { width: auto; min-width: 96px; }
.io-groups { margin: 12px 20px 0; border: 1px solid #e6e8eb; border-radius: 10px; padding: 8px 10px; background: #fbfbfc; }
.io-groups > summary { cursor: pointer; font-weight: 600; font-size: 13px; padding: 2px 0 6px; }
.io-group-table col.w-gname { width: auto; }
.io-group-table col.w-num { width: 120px; }
.io-group-table col.w-color { width: 170px; }
.io-group-table col.w-sort { width: 72px; }
.io-group-table col.w-cnt { width: 60px; }
.io-group-table col.w-btn { width: 128px; }
.io-prod-table col.w-group { width: 130px; }
.io-prod-table col.w-color { width: 150px; }
.io-prod-table .io-group-select { width: 100%; }
.io-prod-table .io-group-val { display: none; color: #4b5563; }
.io-prod-table tr.is-grouped .io-own { display: none; }
.io-prod-table tr.is-grouped .io-group-val { display: inline-flex; }
.io-prod-table tr.is-grouped .io-group-val.io-r { display: block; padding-right: 9px; font-variant-numeric: tabular-nums; }
.io-prod-table tr.is-grouped td:has(> .io-group-val) { background: #f6f8fb; }
+161 -6
View File
@@ -332,6 +332,9 @@
e.preventDefault(); e.preventDefault();
const sub = e.submitter; const sub = e.submitter;
if (sub && sub.dataset.confirm && !(await confirmMsg(sub.dataset.confirm))) return; if (sub && sub.dataset.confirm && !(await confirmMsg(sub.dataset.confirm))) return;
// 그룹 저장은 옵션을 다시 그린다 — 저장 안 한 상품 정보 변경이 사라지기 전에 묻는다
if (form.classList.contains("io-group-form") && dirtyRows().length &&
!(await confirmMsg("저장 안 한 상품 정보 변경이 있습니다. 버리고 그룹을 저장할까요?"))) return;
const action = sub && sub.getAttribute("formaction") ? sub.getAttribute("formaction") : form.getAttribute("action"); const action = sub && sub.getAttribute("formaction") ? sub.getAttribute("formaction") : form.getAttribute("action");
const buttons = Array.from(dlg.querySelectorAll("button[type=submit]")); const buttons = Array.from(dlg.querySelectorAll("button[type=submit]"));
buttons.forEach(function (b) { b.disabled = true; }); buttons.forEach(function (b) { b.disabled = true; });
@@ -351,10 +354,43 @@
} }
}); });
// ── 상품 정보 탭(004) — 단가·무게·은 함유량, 바뀐 줄만 [변경 저장], 불러오기·지우기·되살리기 ── // ── 상품 정보 탭(004) — 단가·무게·은 함유량, 바뀐 줄만 [변경 저장], 불러오기·지우기·되살리기 ──
// 006: 그룹(select)·색상(select) — 그룹 상품은 은 함유량·색상을 그룹 값으로 보여 준다(자기 값 칸은 숨김, 저장은 그대로).
function isChanged(el) {
if (el.tagName === "SELECT") {
const d = Array.from(el.options).find(function (o) { return o.defaultSelected; }) || el.options[0];
return el.value !== (d ? d.value : "");
}
return el.value.trim() !== el.defaultValue.trim();
}
function rowChanged(tr) { return Array.from(tr.querySelectorAll("[data-key]")).some(isChanged); }
function dirtyRows() { function dirtyRows() {
return Array.from(body.querySelectorAll(".io-prod-table tbody tr")).filter(function (tr) { return Array.from(body.querySelectorAll(".io-prod-table tbody tr")).filter(rowChanged);
return Array.from(tr.querySelectorAll("input[data-key]")).some(function (i) { return i.value.trim() !== i.defaultValue.trim(); }); }
}); function paintSwatch(sel) {
const sw = sel.parentNode && sel.parentNode.querySelector(".io-swatch");
const opt = sel.options[sel.selectedIndex];
const hex = opt ? opt.dataset.hex : "";
if (!sw) return;
sw.style.background = hex || "#fff";
sw.classList.toggle("is-none", !hex);
}
// 그룹을 바꾸면 그 줄의 그룹 값(은 함유량·색상)을 고른 그룹 것으로 다시 보여 준다
function paintGroup(tr) {
const sel = tr.querySelector(".io-group-select");
if (!sel) return;
const opt = sel.options[sel.selectedIndex];
const grouped = !!sel.value;
tr.classList.toggle("is-grouped", grouped);
const vals = tr.querySelectorAll(".io-group-val");
if (vals[0]) vals[0].textContent = (opt && opt.dataset.silver) || "-";
if (vals[1]) {
const key = (opt && opt.dataset.color) || "none";
const csel = tr.querySelector(".io-color-select");
const copt = csel && Array.from(csel.options).find(function (o) { return o.value === key; });
const sw = vals[1].querySelector(".io-swatch"), nm = vals[1].querySelector(".io-color-name");
if (sw) { sw.style.background = (copt && copt.dataset.hex) || "#fff"; sw.classList.toggle("is-none", !(copt && copt.dataset.hex)); }
if (nm) nm.textContent = copt ? copt.textContent : "";
}
} }
function paintDirty() { function paintDirty() {
const n = dirtyRows().length; const n = dirtyRows().length;
@@ -391,12 +427,17 @@
if (cnt) cnt.textContent = q ? shown + "개 찾음" : cnt.dataset.base; if (cnt) cnt.textContent = q ? shown + "개 찾음" : cnt.dataset.base;
return; return;
} }
if (inp.classList && inp.classList.contains("io-color-select")) paintSwatch(inp); // 그룹 표·상품 표 공통
if (!inp.dataset || !inp.dataset.key) return; if (!inp.dataset || !inp.dataset.key) return;
const tr = inp.closest("tr"); const tr = inp.closest("tr");
const w = dec(tr.querySelector('[data-key="weight_g"]').value), pct = dec(tr.querySelector('[data-key="silver_pct"]').value); if (inp.dataset.key === "group_id") paintGroup(tr);
const gsel = tr.querySelector(".io-group-select");
const gopt = gsel && gsel.value ? gsel.options[gsel.selectedIndex] : null;
const w = dec(tr.querySelector('[data-key="weight_g"]').value);
const pct = gopt ? dec(gopt.dataset.silver) : dec(tr.querySelector('[data-key="silver_pct"]').value);
const ag = tr.querySelector(".io-ag"); 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 }) : "-"; 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(); })); tr.classList.toggle("is-dirty", rowChanged(tr));
paintDirty(); paintDirty();
}); });
body.addEventListener("click", async function (e) { body.addEventListener("click", async function (e) {
@@ -409,7 +450,9 @@
} else if (t.closest("#io-prod-save")) { } else if (t.closest("#io-prod-save")) {
const rows = dirtyRows().map(function (tr) { const rows = dirtyRows().map(function (tr) {
const v = function (k) { return tr.querySelector('[data-key="' + k + '"]').value.trim(); }; 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") }; const row = { code: tr.dataset.code, unit_price: v("unit_price"), weight_g: v("weight_g"), silver_pct: v("silver_pct") };
if (tr.querySelector('[data-key="group_id"]')) { row.group_id = v("group_id"); row.color = v("color"); } // 006
return row;
}); });
if (rows.length) await act("/inout/settings/products/save", { rows: rows }); if (rows.length) await act("/inout/settings/products/save", { rows: rows });
} else if (t.dataset && t.dataset.exclude) { } else if (t.dataset && t.dataset.exclude) {
@@ -696,4 +739,116 @@
}); });
return { open: open }; return { open: open };
} }
// ── 오른쪽 달력(2026-10-21) — 입출고 모든 화면. 프로젝트 달력과 같은 모양(일요일 시작·오늘 검은 동그라미·토 파랑·일/공휴일 빨강),
// 날짜 칸 = 발주(파랑)·입고(초록) 건수, 누르면 그날 목록 팝업(발주서로 이동). 달 이동은 새로고침 없이 GET /inout/api/calendar.
const calEl = document.getElementById("io-cal");
if (calEl) initCalendar(calEl);
function initCalendar(cal) {
const daysEl = cal.querySelector(".io-cal-days"), titleEl = cal.querySelector(".io-cal-title");
let month = cal.dataset.month, data = null, pop = null, seq = 0;
const pad = function (n) { return String(n).padStart(2, "0"); };
const isoOf = function (d) { return d.getFullYear() + "-" + pad(d.getMonth() + 1) + "-" + pad(d.getDate()); };
const escH = function (v) { const d = document.createElement("div"); d.textContent = v == null ? "" : String(v); return d.innerHTML; };
const WD = "일월화수목금토";
function shift(ym, step) {
const p = ym.split("-").map(Number);
const d = new Date(p[0], p[1] - 1 + step, 1);
return d.getFullYear() + "-" + pad(d.getMonth() + 1);
}
function closePop() { if (pop) { pop.remove(); pop = null; } }
async function load() {
closePop();
const p = month.split("-").map(Number);
titleEl.textContent = p[0] + "년 " + p[1] + "월";
const mine = ++seq; // 빠르게 넘기면 늦게 온 앞 달 응답이 덮지 않게
cal.classList.add("is-loading");
try {
const res = await fetch("/inout/api/calendar?month=" + encodeURIComponent(month));
if (!res.ok) throw new Error("HTTP " + res.status);
const got = await res.json();
if (mine !== seq) return;
data = got;
render();
} catch (_) {
if (mine !== seq) return;
data = null;
daysEl.innerHTML = '<p class="io-cal-err">달력을 불러오지 못했습니다.</p>';
} finally {
if (mine === seq) cal.classList.remove("is-loading");
}
}
function render() {
const start = new Date(data.start + "T00:00:00");
let html = "";
for (let i = 0; i < 42; i++) {
const d = new Date(start.getFullYear(), start.getMonth(), start.getDate() + i);
const iso = isoOf(d), wd = d.getDay();
const ev = data.days[iso] || { orders: [], receipts: [] };
const hol = data.holidays[iso] || "";
const cls = ["io-cal-day"];
if (iso.slice(0, 7) !== data.month) cls.push("is-out");
if (iso === data.today) cls.push("is-today");
if (wd === 0 || hol) cls.push("is-sun"); else if (wd === 6) cls.push("is-sat");
if (ev.orders.length || ev.receipts.length) cls.push("has-ev");
const tip = [iso.replace(/-/g, ".") + "(" + WD[wd] + ")" + (hol ? " " + hol : "")];
if (ev.orders.length) tip.push("발주 " + ev.orders.length + "건");
if (ev.receipts.length) tip.push("입고 " + ev.receipts.length + "건");
html += '<button type="button" class="' + cls.join(" ") + '" data-date="' + iso + '" title="' + escH(tip.join(" · ")) + '">' +
'<span class="io-cal-num">' + d.getDate() + "</span>" +
'<span class="io-cal-marks">' +
(ev.orders.length ? '<i class="io-cal-m is-order">' + ev.orders.length + "</i>" : "") +
(ev.receipts.length ? '<i class="io-cal-m is-receipt">' + ev.receipts.length + "</i>" : "") +
"</span></button>";
}
daysEl.innerHTML = html;
}
// 그날 목록 — body 에 붙이는 작은 팝업(달력 칸 아래, 화면 밖이면 위로)
function openDay(btn) {
closePop();
const iso = btn.dataset.date;
const ev = (data && data.days[iso]) || { orders: [], receipts: [] };
if (!ev.orders.length && !ev.receipts.length) return;
const d = new Date(iso + "T00:00:00"), hol = (data.holidays || {})[iso];
const item = function (href, kind, label, main, sub) {
return '<a class="io-calpop-item" href="' + href + '"><i class="io-cal-m ' + kind + '">' + label + "</i>" +
'<span class="io-calpop-main">' + main + '</span><span class="io-calpop-sub">' + sub + "</span></a>";
};
let html = '<div class="io-calpop-head">' + iso.replace(/-/g, ".") + "(" + WD[d.getDay()] + ")" + (hol ? ' <span class="is-hol">' + escH(hol) + "</span>" : "") + "</div>";
ev.orders.forEach(function (o) {
html += item("/inout/orders/" + o.id, "is-order", "발주", escH(o.order_no) + " · " + escH(o.factory),
escH(o.item) + " · " + Number(o.qty).toLocaleString("ko-KR") + "개");
});
ev.receipts.forEach(function (r) {
html += item("/inout/orders/" + r.order_id, "is-receipt", "입고", escH(r.order_no) + " · " + escH(r.factory),
Number(r.qty).toLocaleString("ko-KR") + "개 입고");
});
pop = document.createElement("div");
pop.className = "io-calpop";
pop.setAttribute("role", "dialog");
pop.setAttribute("aria-label", iso + " 발주·입고");
pop.innerHTML = html;
document.body.appendChild(pop);
const r = btn.getBoundingClientRect(), w = pop.offsetWidth, h = pop.offsetHeight;
let left = Math.min(Math.max(8, r.left + r.width / 2 - w / 2), window.innerWidth - w - 8);
let top = r.bottom + 6;
if (top + h > window.innerHeight - 8) top = Math.max(8, r.top - h - 6);
pop.style.left = left + window.scrollX + "px";
pop.style.top = top + window.scrollY + "px";
}
cal.addEventListener("click", function (e) {
const nav = e.target.closest(".io-cal-nav");
if (nav) { month = shift(month, Number(nav.dataset.step)); load(); return; }
if (e.target.closest(".io-cal-today")) { month = (data && data.today ? data.today : cal.dataset.month).slice(0, 7); load(); return; }
const day = e.target.closest(".io-cal-day");
if (day) { if (pop && pop.dataset.date === day.dataset.date) closePop(); else { openDay(day); if (pop) pop.dataset.date = day.dataset.date; } }
});
document.addEventListener("mousedown", function (e) {
if (pop && !pop.contains(e.target) && !e.target.closest(".io-cal-day")) closePop();
});
document.addEventListener("keydown", function (e) { if (e.key === "Escape") closePop(); });
window.addEventListener("resize", closePop);
load();
}
})(); })();
+13
View File
@@ -333,6 +333,19 @@ cd /opt/www/main && git pull && docker exec postgres-db pg_dump -U postgres proj
cd /opt/www/main && git pull && docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_031_$(date +%Y%m%d%H%M).sql && docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_031_owner_as_member.sql && docker compose build web && docker compose up -d web cd /opt/www/main && git pull && docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_031_$(date +%Y%m%d%H%M).sql && docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_031_owner_as_member.sql && docker compose build web && docker compose up -d web
``` ```
## 입출고 관리 상품 그룹·색상 마이그레이션 (inout_db 006)
006은 표 1개·열 3개만 추가한다 — `inout_product_groups`(그룹 이름·은 함유량·색상·순서)·`inout_products.group_id`·`inout_products.color`·
`inout_order_lines.color`(발주 당시 색상 사본). 다시 실행 가능, 기존 데이터 변경 없음, 새 환경변수 없음. 004 다음에 적용한다.
미적용이어도 발주·입고·메일은 그대로 — 옵션 → 상품 정보에 "006 필요" 안내만 나오고 그룹·색상 칸이 없다.
적용 뒤 옵션(톱니) → **상품 정보** → 그룹을 만들고(은 함유량·색상) 상품마다 그룹을 고른 뒤 [변경 저장].
```bash
cd /opt/www/main && git pull && docker exec postgres-db pg_dump -U postgres inout_db > ~/inout_db_before_006_$(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_006_product_groups.sql && docker compose up --build -d --no-deps web
```
되돌리기(그룹·색상만 사라짐): 백업에서 복원.
## 입출고 관리 물류센터 이메일·입고 요청 메일 마이그레이션 (inout_db 005) ## 입출고 관리 물류센터 이메일·입고 요청 메일 마이그레이션 (inout_db 005)
005는 표 2개만 추가한다 — `inout_settings`(모듈 설정: 물류센터 담당자 이메일·입고 요청 메일 참조, 참조 기본값 `king@dbxcorp.co.kr, bj@dbxcorp.co.kr` 한 줄 넣음)· 005는 표 2개만 추가한다 — `inout_settings`(모듈 설정: 물류센터 담당자 이메일·입고 요청 메일 참조, 참조 기본값 `king@dbxcorp.co.kr, bj@dbxcorp.co.kr` 한 줄 넣음)·
+17
View File
@@ -73,6 +73,10 @@ cupang·malaysia 와 같은 DSN). 화면에서 코드·이름으로 검색(`GET
| `/inout/orders/{id}` | 발주서 — 품목별 발주·(발주 담당) **단가·금액·PP(g/개)·은(Ag)** ·입고·미입고·상태 + 합계 줄(금액·PP kg·은 g), **이번 입고** 칸(입고 담당) + [남은 수량 모두 채우기], 입고 기록, 종결·취소. 입고 담당만이면 이름·발주 수량만 | | `/inout/orders/{id}` | 발주서 — 품목별 발주·(발주 담당) **단가·금액·PP(g/개)·은(Ag)** ·입고·미입고·상태 + 합계 줄(금액·PP kg·은 g), **이번 입고** 칸(입고 담당) + [남은 수량 모두 채우기], 입고 기록, 종결·취소. 입고 담당만이면 이름·발주 수량만 |
| 톱니 → 옵션 팝업 | 관리자만. 탭 **담당자**(발주·입고 체크) · **공장**(이름·담당자·연락처·메모·순서·사용, 발주 기록 없을 때만 지우기) · **상품 정보**(6-3) · **물류센터**(6-4). 내용은 `GET /inout/settings?panel=1`, 저장은 팝업 안에서(`X-Inout-Options: 1` → JSON, 같은 탭 그대로 다시 그림), 바뀐 게 있으면 닫을 때 화면 새로고침. 예전 주소 `/inout/settings` = 목록으로 가서 팝업(`?options=1`) | | 톱니 → 옵션 팝업 | 관리자만. 탭 **담당자**(발주·입고 체크) · **공장**(이름·담당자·연락처·메모·순서·사용, 발주 기록 없을 때만 지우기) · **상품 정보**(6-3) · **물류센터**(6-4). 내용은 `GET /inout/settings?panel=1`, 저장은 팝업 안에서(`X-Inout-Options: 1` → JSON, 같은 탭 그대로 다시 그림), 바뀐 게 있으면 닫을 때 화면 새로고침. 예전 주소 `/inout/settings` = 목록으로 가서 팝업(`?options=1`) |
**2열 + 오른쪽 달력(2026-10-21)** — 모든 화면이 왼쪽 화면 | 오른쪽 300px(달력 300×320, 프로젝트 달력 모양). 날짜별 발주(발주일)·입고(입고일) 건수,
누르면 그날 목록 팝업, 달 이동은 `GET /inout/api/calendar?month=YYYY-MM`(6주 칸 = 일요일 시작 42일, 취소된 발주 제외, 공휴일 이름 포함).
옵션 → 담당자 표 = 아이콘(구글 프로필 사진) + 이름, 아래 이메일.
화면은 서버 폼(POST → 303 + `?msg=` 안내). `static/inout.js` 는 입력 보조만(제품 검색 드롭다운 — `position: fixed` 로 body 에 붙여 화면은 서버 폼(POST → 303 + `?msg=` 안내). `static/inout.js` 는 입력 보조만(제품 검색 드롭다운 — `position: fixed` 로 body 에 붙여
표 가로 스크롤에 잘리지 않음, 줄 추가·삭제·합계, 남은 수량 채우기, 버튼별 확인 `data-erp-confirm-btn`). 표 가로 스크롤에 잘리지 않음, 줄 추가·삭제·합계, 남은 수량 채우기, 버튼별 확인 `data-erp-confirm-btn`).
공용 스타일과 겹치는 것 — 이 모듈 안에서만 바로잡는다(공용 파일은 그대로): 공용 스타일과 겹치는 것 — 이 모듈 안에서만 바로잡는다(공용 파일은 그대로):
@@ -173,6 +177,19 @@ cupang·malaysia 와 같은 DSN). 화면에서 코드·이름으로 검색(`GET
두 표 사이는 표 margin 대신 높이 18px 빈 줄(`<div style="height:18px;line-height:18px;font-size:1px">`) — 메일 프로그램이 표 margin 을 무시하기도 해서. 글 본문(HTML 못 보는 메일 프로그램용)도 같은 값. 발주서 화면 표는 그대로. 두 표 사이는 표 margin 대신 높이 18px 빈 줄(`<div style="height:18px;line-height:18px;font-size:1px">`) — 메일 프로그램이 표 margin 을 무시하기도 해서. 글 본문(HTML 못 보는 메일 프로그램용)도 같은 값. 발주서 화면 표는 그대로.
- 004 미적용이면 탭에 "마이그레이션 004 필요" 안내, 발주서는 예전처럼 코드표에서(`products_ready`). - 004 미적용이면 탭에 "마이그레이션 004 필요" 안내, 발주서는 예전처럼 코드표에서(`products_ready`).
## 6-3-1. 상품 그룹·색상(2026-10-21, 마이그레이션 006)
- 사용자 요청: 은 함유량이 그룹마다 다르다 → 그룹별로 한 번만 설정. 아이템별 색상도 같은 방식(그룹에 한 번). 그룹 기준은 사용자 선택 = **옵션에서 직접 그룹을 만들고 상품마다 고름**
(코드 앞부분·이름 자동 묶음은 쓰지 않음).
- 표 `inout_product_groups`(id·name UNIQUE·silver_pct·color·sort_order), `inout_products.group_id`(FK, 그룹 지우면 NULL)·`color`, `inout_order_lines.color`.
- 적용 값: 그룹 상품 = 그룹의 은 함유량·색상, 그룹 없는 상품 = 상품 자기 값. 상품 자기 값은 그룹에 넣어도 지우지 않는다(그룹에서 빼면 다시 보임).
다시 불러오기에서 그룹·색상만 넣은 상품도 "값 있는 상품"(`store.has_values`)이라 그대로.
- 색상: 색없음(none)·오렌지(orange `#FFD8B0`)·파랑(blue `#CFE0FA`)·회색(gray `#DDDFE3`)·아이보리색(ivory `#FFF6D9`) — 메일 글자가 읽히게 옅은 색.
- 발주 메일(6-1) 품목 표: 색상 있는 품목은 줄 전체 배경을 그 색으로(`<tr style="background:…">` + 칸마다 — 메일 프로그램이 tr 배경을 무시하기도 함).
색상 = 발주 품목 사본(발주 당시), 006 전 품목은 지금 상품 색상.
- 옵션 화면: 그룹 표(이름·은 함유량·색상[사각형 + 고르기]·순서·상품 수·저장/지우기·추가), 상품 표에 그룹·색상 열. 그룹 상품은 은 함유량·색상 칸 대신 그룹 값(회색 칸),
그룹을 바꾸면 그 자리에서 그룹 값·은 g 다시 계산. 저장 안 한 상품 변경이 있으면 그룹 저장 전에 묻는다.
## 6-4. 입고 요청 메일 — 물류센터 전산 등록 부탁(2026-10-19, 마이그레이션 005) ## 6-4. 입고 요청 메일 — 물류센터 전산 등록 부탁(2026-10-19, 마이그레이션 005)
- **왜**(사용자 요청): 물류에 들어온 입고를 물류센터 입고 담당자가 전산에 등록하도록, 입고 담당이 입고를 저장하면 메일로 알린다. - **왜**(사용자 요청): 물류에 들어온 입고를 물류센터 입고 담당자가 전산에 등록하도록, 입고 담당이 입고를 저장하면 메일로 알린다.
@@ -0,0 +1,45 @@
-- =====================================================================
-- inout_db 마이그레이션 006 — 상품 그룹(은 함유량·색상 한 번에) · 상품 색상 · 발주 품목 색상 사본(2026-10-21)
-- =====================================================================
-- 멱등(idempotent). 표·열 추가만, 기존 값 변경·삭제 없음. 004 다음에 적용. 운영: /opt/www/main 에서 기존 inout_db 에 적용(백업 먼저).
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d inout_db < scripts/sql/inout_db_006_product_groups.sql
--
-- 왜(사용자 요청):
-- 은 함유량이 그룹마다 다르다 → 옵션 → 상품 정보에서 그룹을 직접 만들고 상품마다 그룹을 고른다. 그룹의 은 함유량·색상을
-- 한 번만 넣으면 그 그룹 상품 모두에 적용(그룹 없는 상품은 예전처럼 상품마다 입력).
-- 색상 = 색없음·오렌지·파랑·회색·아이보리색. 발주 메일 품목 표에서 색상 있는 품목 줄 전체 배경을 그 색으로.
-- 발주 품목에는 그때 색상 사본(color) — 단가 등과 같은 방식(나중에 바꿔도 지난 발주는 그대로, 006 전 품목은 지금 색상).
-- 되돌리기: 백업에서 복원(새 표·열만 생기므로 남아 있어도 이전 앱은 동작).
-- =====================================================================
\set ON_ERROR_STOP on
BEGIN;
CREATE TABLE IF NOT EXISTS inout_product_groups (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL UNIQUE CHECK (char_length(name) BETWEEN 1 AND 100),
silver_pct NUMERIC(9,4) NULL CHECK (silver_pct IS NULL OR (silver_pct >= 0 AND silver_pct <= 100)), -- 은(Ag) 함유량 %
color TEXT NOT NULL DEFAULT 'none' CHECK (color IN ('none', 'orange', 'blue', 'gray', 'ivory')),
sort_order INT NOT NULL DEFAULT 0,
updated_by TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
COMMENT ON TABLE inout_product_groups IS '입출고 — 상품 그룹(은 함유량·색상을 그룹에 한 번만)';
-- 상품 — 그룹(지우면 그룹 없음으로) · 그룹 없을 때 쓰는 상품 자신의 색상
ALTER TABLE inout_products ADD COLUMN IF NOT EXISTS group_id INT NULL REFERENCES inout_product_groups(id) ON DELETE SET NULL;
ALTER TABLE inout_products ADD COLUMN IF NOT EXISTS color TEXT NULL;
DO $$ BEGIN
ALTER TABLE inout_products ADD CONSTRAINT inout_products_color_chk
CHECK (color IS NULL OR color IN ('none', 'orange', 'blue', 'gray', 'ivory'));
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
CREATE INDEX IF NOT EXISTS idx_inout_products_group ON inout_products (group_id);
-- 발주 품목 — 발주 당시 색상 사본(NULL = 006 전 품목 → 지금 상품 색상으로 보여 줌)
ALTER TABLE inout_order_lines ADD COLUMN IF NOT EXISTS color TEXT NULL;
GRANT SELECT, INSERT, UPDATE, DELETE ON inout_product_groups TO inout_app;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO inout_app;
COMMIT;
SELECT 'inout_db 006 product groups ready' AS status;
+79
View File
@@ -335,6 +335,85 @@ class InoutDbTests(unittest.TestCase):
pass pass
self.assertEqual(self.st.catalog_count(), before) self.assertEqual(self.st.catalog_count(), before)
def test_product_groups_colors_and_calendar(self):
"""006 — 그룹의 은 함유량·색상이 그룹 상품에 적용(그룹 없는 상품은 자기 값), 같은 이름 거절, 발주 품목 색상 사본,
메일 품목 줄 배경, 그룹 지우면 자기 값으로, 다시 불러와도 그룹·색상만 넣은 상품은 그대로. 달력 = 발주일·입고일(취소 제외)."""
from decimal import Decimal as D
from app.modules.inout import store
if not self.st.groups_ready():
self.skipTest("inout_db 006 미적용")
T = self.tag.upper()
A, B, C = f"ZG-{T}-A", f"ZG-{T}-B", f"ZG-{T}-C"
before = self.st.catalog_count()
gid = None
try:
self.st.import_products([{"code": A, "name": "가"}, {"code": B, "name": "나"}, {"code": C, "name": "다"}], by="b@x")
gid = self.st.save_group(group_id=None, by="b@x", **store.validate_group(
{"name": f"은30-{T}", "silver_pct": "30", "color": "orange", "sort_order": "1"}))
with self.assertRaisesRegex(ValueError, "같은 이름"):
self.st.save_group(group_id=None, by="b@x", **store.validate_group({"name": f"은30-{T}", "color": "blue"}))
with self.assertRaisesRegex(ValueError, "색상은"):
store.validate_group({"name": "x", "color": "pink"})
vals = store.validate_product_values({"weight_g": "50", "silver_pct": "5"})
self.st.save_products([{"code": A, **vals, "group_id": gid, "color": "blue"}, # 그룹 → 그룹 값(30%·오렌지)
{"code": B, **vals, "group_id": None, "color": "ivory"}], by="b@x") # 자기 값(5%·아이보리)
with self.assertRaisesRegex(ValueError, "없는 그룹"):
self.st.save_products([{"code": C, **vals, "group_id": 999999999, "color": "none"}], by="b@x")
got = self.st.catalog_lookup([A, B, C])
self.assertEqual((got[A]["silver_pct"], got[A]["color"], got[A]["own_silver_pct"], got[A]["own_color"], got[A]["group_name"]),
(D("30.0000"), "orange", D("5.0000"), "blue", f"은30-{T}"))
self.assertEqual((got[B]["silver_pct"], got[B]["color"], got[B]["group_id"]), (D("5.0000"), "ivory", None))
self.assertEqual(got[C]["color"], "none")
self.assertEqual([x["color"] for x in self.st.catalog_search(f"ZG-{T}")], ["orange", "ivory", "none"])
g = next(x for x in self.st.list_groups() if x["id"] == gid)
self.assertEqual((g["product_count"], g["color"]), (1, "orange"))
# 발주 = 그룹 적용 값·색상 사본, 메일 품목 줄 배경
data = store.validate_order(factory_id=self.fid, order_date="2026-10-21", due_date="", memo="",
codes=[A, B, C], quantities=["10", "10", "10"])
o = self.st.create_order(data, {A: "가", B: "나", C: "다"}, by="b@x", specs=self.st.catalog_lookup([A, B, C]))
order = self.st.get_order(o["id"])
lines = {x["item_code"]: x for x in order["lines"]}
self.assertEqual((lines[A]["silver_pct"], lines[A]["color"], lines[B]["color"], lines[C]["color"]),
(D("30.0000"), "orange", "ivory", "none"))
html = store.order_mail(order, sender_name="", sender_email="b@x")["html"]
self.assertEqual(html.count('<tr style="background:' + store.color_hex("orange") + '">'), 1)
self.assertEqual(html.count('<tr style="background:' + store.color_hex("ivory") + '">'), 1)
self.assertEqual(html.count("<tr><td"), 1) # 색없음 줄은 배경 없음
# 그룹을 바꿔도 지난 발주서는 사본 그대로 / 그룹 지우면 상품은 자기 값으로
self.st.save_group(group_id=gid, by="b@x", **store.validate_group({"name": f"은30-{T}", "silver_pct": "31", "color": "gray"}))
self.assertEqual(self.st.get_order(o["id"])["lines"][0]["color"], "orange")
self.assertEqual(self.st.catalog_lookup([A])[A]["color"], "gray")
self.assertEqual(self.st.delete_group(gid), f"은30-{T}")
gid = None
got = self.st.catalog_lookup([A])[A]
self.assertEqual((got["group_id"], got["silver_pct"], got["color"]), (None, D("5.0000"), "blue"))
# 다시 불러와도 그룹·색상만 넣은 상품은 그대로(값 있는 상품)
self.st.save_products([{"code": C, "unit_price": None, "weight_g": None, "silver_pct": None, "group_id": None,
"color": "gray"}], by="b@x")
self.assertEqual(self.st.import_products([{"code": C, "name": "다2"}], by="b@x")["kept"], 1)
# 달력 — 발주일·입고일, 취소된 발주는 빠짐
ids = self.line_ids(o["id"])
self.st.add_receipt(o["id"], {ids[A]: "4"}, receipt_date="2026-10-23", memo="", confirm_over=False, by="w@x")
cal = self.st.calendar(date(2026, 10, 1), date(2026, 10, 31))
mine = [x for x in cal["orders"] if x["id"] == o["id"]]
self.assertEqual((len(mine), mine[0]["qty"], mine[0]["kinds"], mine[0]["first_item"]), (1, 30, 3, "가"))
rec = [x for x in cal["receipts"] if x["order_id"] == o["id"]]
self.assertEqual((len(rec), rec[0]["qty"], rec[0]["receipt_date"]), (1, 4, date(2026, 10, 23)))
o2 = self.order([("MT-X", 1)], order_date="2026-10-22")
self.st.cancel_order(o2["id"], by="b@x")
self.assertFalse([x for x in self.st.calendar(date(2026, 10, 22), date(2026, 10, 22))["orders"] if x["id"] == o2["id"]])
finally:
if gid:
self.st.delete_group(gid)
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)
def test_delete_order_cascades(self): def test_delete_order_cascades(self):
"""수퍼관리자 발주 삭제 — 품목·입고 기록·입고증 사진·메일 기록까지 함께 지워진다.""" """수퍼관리자 발주 삭제 — 품목·입고 기록·입고증 사진·메일 기록까지 함께 지워진다."""