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'
| {{ c.name or c.email }}{{ c.email }} | +
+ {% if c.picture %} |
{% for role in role_labels %}
@@ -88,7 +92,50 @@ |
| 그룹 이름 | 은 함유량(%) | 색상 | 순서 | 상품 | |
|---|---|---|---|---|---|
| + | + | {{ swatch(g.color, colors) }} | ++ | {{ g.product_count }}개 | ++ + + | +
| + | + | {{ swatch('none', colors) }} | ++ | + | + |
상품 그룹·색상은 DB 마이그레이션 inout_db 006 적용 후 쓸 수 있습니다 — 관리자에게 알려 주세요.
+ {% endif %} {% if products %}| 코드 | 제품명 | 단가(원) | 무게·PP(g/개) | 은 함유량(%) | 은(g/개) |
|---|
| 코드 | 제품명 | {% if groups_ready %}그룹 | {% endif %}단가(원) | 무게·PP(g/개) | 은 함유량(%) | 은(g/개) | {% if groups_ready %}색상 | {% endif %}||
|---|---|---|---|---|---|---|---|---|---|
| {{ p.item_code }} | {{ p.item_name }} | + {% if groups_ready %} ++ {% endif %} | - | + | + {% if groups_ready %}{{ fmt_num(p.silver_pct, 4) if p.silver_pct is not none else '-' }}{% endif %} | {{ fmt_num(p.silver_g, 4) if p.silver_g is not none else '-' }} | + {% if groups_ready %} +{{ swatch(p.own_color, colors) }} + {{ swatch(p.color, colors) }}{{ colors[p.color][0] if p.color in colors else '' }} | + {% endif %}||
| link공유 | 이 업무의 주소를 복사합니다. 메신저로 보내면 받은 멤버가 바로 이 업무를 엽니다. | ||||||||
| ✓ 완료로 표시 | 업무를 완료합니다. 다시 누르면 ↩ 완료 취소. | ||||||||
| 삭제 | 업무를 지웁니다(만든 사람만). 세부 업무가 있으면 함께 지울지 한 번 더 묻습니다. 지운 업무는 휴지통에 3개월 보관됩니다. | ||||||||
| 작성자 | 삭제 오른쪽에 업무를 만든 사람(아이콘 + 이름)과 만든 시각 yyyy.mm.dd(요일) hh:mm:ss가 보입니다. 세부 업무도 같습니다. | ||||||||
| 저장됨 | 저장 버튼이 없습니다 — 고치는 즉시 저장되고, 버튼 줄 오른쪽에 저장 중… → ✓ 저장됨이 잠깐 보입니다. 저장이 안 되면 저장 실패 · 다시 시도(눌러서 다시 저장)가 뜨고, 이 상태로 창을 닫거나 다른 업무를 열면 한 번 더 저장해 본 뒤 버리고 넘어갈지 / 계속 편집할지 묻습니다 — 모른 채 내용이 사라지지 않습니다. 이미지를 올리는 중이면 다 올라갈 때까지 기다렸다가 넘어갑니다. |
업무는 하나라서 원래 프로젝트에서 고친 내용이 연결된 보드에도 반영됩니다. 원래 프로젝트의 멤버가 아니면 연결된 업무의 내용·댓글·첨부는 읽기만 할 수 있습니다. 연결된 보드 안에서 섹션을 옮기는 것은 가능합니다.
업무 창 맨 아래에 항상 고정된 댓글 칸에 쓰고 Enter(스크롤해도 그 자리에 있습니다). 칸 오른쪽 ☺는 이모티콘, @는 멤버 태그입니다. 답글은 원 댓글 아래 들여 쓰여 ↳ 표시와 함께 보입니다. 내가 쓴 댓글은 ✎로 고치고 ×로 지웁니다. 댓글 속 웹 주소는 링크가 됩니다. 댓글에 붙인 파일은 그 댓글 아래에 보이고(파일만 보낸 댓글도), 첨부 파일 목록에는 댓글 표시가 붙습니다.
+캡처한 이미지를 댓글 칸에 Ctrl+V로 붙여넣으면 칸 위에 작은 미리보기로 담기고(×로 빼기), 등록하면 글과 함께 댓글 첨부로 올라갑니다. 글 없이 이미지만 보내도 됩니다. 복사한 내용에 글자가 함께 있으면 글자가 붙습니다.
댓글 대화창에서 파일을 보낼 때 보낼 수 없는 파일(빈 파일, 20MB 초과)이 있으면 댓글을 만들지 않고 그 파일만 빨갛게 표시합니다 — 빼고 다시 보내세요. 인터넷이 끊겨도 쓴 내용과 파일은 그대로 남아 다시 보낼 수 있고, 같은 댓글이 두 번 올라가지 않습니다. @태그는 이 업무를 볼 수 있는 사람만 고를 수 있습니다. 한글을 입력하는 중(조합 중)의 Enter는 글자 확정만 하고 보내지 않습니다.
diff --git a/app/modules/project/templates/project/inbox.html b/app/modules/project/templates/project/inbox.html index 0673a4c..4afd057 100644 --- a/app/modules/project/templates/project/inbox.html +++ b/app/modules/project/templates/project/inbox.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -106,5 +106,5 @@ {% include "project/_side_modals.html" %} {% include "project/_member_tasks_modal.html" %} - + {% endblock %} diff --git a/app/modules/project/templates/project/mytasks.html b/app/modules/project/templates/project/mytasks.html index cf66089..6c7a680 100644 --- a/app/modules/project/templates/project/mytasks.html +++ b/app/modules/project/templates/project/mytasks.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -100,5 +100,5 @@ "today": {{ today | tojson }} } - + {% endblock %} diff --git a/app/modules/project/templates/project/notifier.html b/app/modules/project/templates/project/notifier.html index db8e974..c846ad9 100644 --- a/app/modules/project/templates/project/notifier.html +++ b/app/modules/project/templates/project/notifier.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -108,5 +108,5 @@ }); })(); - + {% endblock %} diff --git a/app/modules/project/templates/project/project.html b/app/modules/project/templates/project/project.html index c192fd0..a38800b 100644 --- a/app/modules/project/templates/project/project.html +++ b/app/modules/project/templates/project/project.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + @@ -244,6 +244,8 @@ + +