diff --git a/app/modules/inout/CLAUDE.md b/app/modules/inout/CLAUDE.md
index 6b7f8cf..9643263 100644
--- a/app/modules/inout/CLAUDE.md
+++ b/app/modules/inout/CLAUDE.md
@@ -60,6 +60,22 @@
- 발주서·메일에 금액(수량 × 단가)·PP·은 함유량과 합계.
- **발주 메일 표**(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`).
diff --git a/app/modules/inout/db.py b/app/modules/inout/db.py
index 0951be6..ee87061 100644
--- a/app/modules/inout/db.py
+++ b/app/modules/inout/db.py
@@ -8,10 +8,11 @@
from __future__ import annotations
+import time
from datetime import date, datetime
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.types.datetime import TimestamptzLoader
from psycopg_pool import ConnectionPool
@@ -23,6 +24,15 @@ from . import store
_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):
"""확인 없이 발주보다 많이 입고하려 함 — 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],
- specs: dict[str, dict[str, Any]]) -> None:
- """발주 품목 한 줄 — 004 가 적용됐으면 상품 정보의 단가·무게·은 함유량을 그때 값으로 함께 남긴다."""
- if self.products_ready():
+ specs: dict[str, dict[str, Any]], ready: tuple[bool, bool]) -> None:
+ """발주 품목 한 줄 — 004 가 적용됐으면 상품 정보의 단가·무게·은 함유량을(006 이면 색상도) 그때 값으로 함께 남긴다."""
+ 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 {}
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)",
@@ -150,6 +171,7 @@ class InoutDBStore:
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}."""
+ ready = self._ready_flags()
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'))")
@@ -166,13 +188,14 @@ 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):
- 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}
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)."""
+ ready = self._ready_flags()
with self._pool.connection() as conn, conn.transaction():
head = self._lock_order(conn, order_id)
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",
(i, ln["qty"], ln["memo"], existing[ln["item_code"]]["id"]))
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",
(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]]] = {}
for r in rlines:
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)
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,
@@ -531,9 +559,13 @@ class InoutDBStore:
raise ValueError("DB 마이그레이션 inout_db 004(상품 정보)가 아직 적용되지 않았습니다.")
def list_products(self) -> list[dict[str, Any]]:
+ """상품 정보 — 006 이면 그룹 이름·그룹 적용 값(silver_pct·color)·상품 자기 값(own_*)까지."""
if not self.products_ready():
return []
+ grouped = self.groups_ready()
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()
def list_excluded(self) -> list[dict[str, Any]]:
@@ -571,9 +603,25 @@ class InoutDBStore:
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 를 거친 값). 한 트랜잭션."""
+ """값 저장 — rows = [{code, unit_price, weight_g, silver_pct}](store.validate_product_values 를 거친 값). 한 트랜잭션.
+ 006 이면 줄에 group_id·color(상품 자기 색상)도 — 그룹 상품의 은 함유량·색상은 그룹 값이 쓰인다."""
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():
+ 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:
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",
@@ -614,20 +662,117 @@ class InoutDBStore:
esc = (q or "").strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
if not esc:
return []
+ args = {"q": f"%{esc}%", "p": f"{esc}%", "n": int(limit)}
+ grouped = self.groups_ready()
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(
"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()
+ "ORDER BY (item_code ILIKE %(p)s) DESC, item_code LIMIT %(n)s", args).fetchall()
def catalog_lookup(self, codes: list[str]) -> dict[str, dict[str, Any]]:
if not codes or not self.products_ready():
return {}
+ grouped = self.groups_ready()
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}
+ # ════════════════════════════════════════════════════════════
+ # 상품 그룹(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}
+
# ════════════════════════════════════════════════════════════
# 미입고 현황 — 진행 중(종결·취소 아님) 발주의 남은 수량, 그리고 초과 입고
# ════════════════════════════════════════════════════════════
diff --git a/app/modules/inout/router.py b/app/modules/inout/router.py
index 537b6fa..a983431 100644
--- a/app/modules/inout/router.py
+++ b/app/modules/inout/router.py
@@ -841,7 +841,8 @@ def _candidates() -> list[dict[str, str]]:
out = []
for u in user_store.list_all():
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"])
@@ -852,13 +853,14 @@ def _options_ctx(request: Request, st: Any) -> dict[str, Any]:
for emails in roles.values(): # 권한이 빠졌어도 담당으로 남아 있는 사람은 보여 줘야 뺄 수 있다
for e in emails:
if e not in known:
- cands.append({"email": e, "name": "(입출고 모듈 권한 없음)"})
+ cands.append({"email": e, "name": "(입출고 모듈 권한 없음)", "picture": ""})
known.add(e)
reader = _items(request)
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(),
+ "groups": st.list_groups(), "groups_ready": st.groups_ready(), "colors": store.COLORS,
"fmt_num": store.fmt_num,
"factories": st.list_factories(include_inactive=True), "roles": roles, "role_labels": store.ROLE_LABELS,
"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]:
code = str((r or {}).get("code") or "").strip().upper()
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:
errors.append(f"{code}: {exc}")
if errors:
@@ -1027,6 +1036,38 @@ def settings_products_save(request: Request, payload: dict[str, Any] = Body(...)
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")
def settings_product_exclude(request: Request, code: str) -> Any:
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 "",
"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]})
+ "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)
if reader is None or not reader.enabled:
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})
+@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")
def health(request: Request) -> dict[str, str]:
return {"status": "ok" if _store(request) is not None else "not_configured"}
diff --git a/app/modules/inout/store.py b/app/modules/inout/store.py
index fe76b71..78cd9b2 100644
--- a/app/modules/inout/store.py
+++ b/app/modules/inout/store.py
@@ -319,12 +319,17 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
rows = []
for i, x in enumerate(lines, start=1):
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(
- f'
| {i} | {e(x["item_code"])} | '
- f'{e(x["item_name"])} | {int(x["qty"]):,} | '
- f'{e(c["price"])} | {e(c["amount"])} | '
- f'{e(c["weight"])} | {e(c["pp_use"])} | {e(c["ag"])} | '
- f'{e(x.get("memo") or "")} |
')
+ f'| {i} | '
+ f'{e(x["item_code"])} | '
+ f'{e(x["item_name"])} | {int(x["qty"]):,} | '
+ f'{e(c["price"])} | {e(c["amount"])} | '
+ f'{e(c["weight"])} | {e(c["pp_use"])} | {e(c["ag"])} | '
+ f'{e(x.get("memo") or "")} |
')
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_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:
- """단가·무게·은 함유량 중 하나라도 넣었나 — 넣은 상품은 다시 불러와도 그대로 둔다."""
- return any(p.get(k) is not None for k in PRODUCT_LIMITS)
+ """단가·무게·은 함유량(·그룹·색상, 006) 중 하나라도 넣었나 — 넣은 상품은 다시 불러와도 그대로 둔다."""
+ 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))}
# ════════════════════════════════════════════════════════════
diff --git a/app/modules/inout/templates/inout/_calendar.html b/app/modules/inout/templates/inout/_calendar.html
new file mode 100644
index 0000000..f4fdda6
--- /dev/null
+++ b/app/modules/inout/templates/inout/_calendar.html
@@ -0,0 +1,20 @@
+{# 오른쪽 달력(2026-10-21) — 입출고 모든 화면 오른쪽 위 300×320, 오른쪽 열 너비 = 달력 너비.
+ 프로젝트 달력과 같은 모양(일요일 시작 · 요일 줄 회색 · 오늘 검은 동그라미 · 토 파랑 · 일/공휴일 빨강 · 다른 달 흐리게).
+ 날짜 칸 = 발주(발주일, 파랑) · 입고(입고일, 초록) 건수, 누르면 그날 목록(발주서로 이동). 내용은 inout.js 가 GET /inout/api/calendar 로 그린다. #}
+
diff --git a/app/modules/inout/templates/inout/_macros.html b/app/modules/inout/templates/inout/_macros.html
index 1659553..dc8b817 100644
--- a/app/modules/inout/templates/inout/_macros.html
+++ b/app/modules/inout/templates/inout/_macros.html
@@ -26,3 +26,8 @@
{%- endmacro %}
{% macro n(v) -%}{{ '{:,}'.format(v or 0) }}{%- endmacro %}
+
+{# 색상 사각형(006) — 색이 칠해진 네모. 색없음은 빗금 없는 흰 네모 + 테두리. colors = store.COLORS #}
+{% macro swatch(key, colors) -%}
+
+{%- endmacro %}
diff --git a/app/modules/inout/templates/inout/_options_panel.html b/app/modules/inout/templates/inout/_options_panel.html
index f269827..4f493fb 100644
--- a/app/modules/inout/templates/inout/_options_panel.html
+++ b/app/modules/inout/templates/inout/_options_panel.html
@@ -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).
공장 줄은 표() 안에 폼을 둘 수 없어 입력칸에 form="…" 속성으로 표 밖 폼에 묶는다 — 열이 머리 줄과 맞는다. #}