diff --git a/CLAUDE.md b/CLAUDE.md index 9349197..007f788 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -42,7 +42,7 @@ Claude Code는 이 저장소에서 작업을 시작하기 전에 **반드시 아 - 긴급 공지 (`app/modules/notice/`, `project_db` 마이그레이션 024 `urgent_notice*`) — 수퍼관리자만 작성(`/notice/`, ERP 왼쪽 아래·Project ⚙ 옵션). 제목·내용(이미지 bytea)·띄울 시각·전체/고른 사람 → ERP 모든 화면(`erp_base.html`·`main.html`·`admin.html` 의 `static/erp-notice.js`) 가로·세로 정가운데에 [확인] 누를 때까지(Esc·바깥 클릭 무시), 확인 기록. 연결 풀은 `ProjectStore.pool` 공유, 새 환경변수 없음. PC 알림 프로그램은 아직 미지원. 상세는 `docs/NOTICE_MODULE.md` -- 입출고 관리 (`app/modules/inout/`, `inout_db`, 2026-10-16) — 본사 → 공장 제품 제작 발주(발주서 `PO-YYMMDD-NN`, 제품 = `itemcode_db.single_items` 단품만, 검색 `GET /inout/api/items`·저장 때 서버 재확인), 물류 입고를 여러 번 나눠 입력, 품목별 발주·입고·미입고, 미입고 현황(제품별 합계·발주별·지연), 초과 입고는 확인 화면 후 허용(트랜잭션 안에서 발주서 잠그고 판단, `confirm_over`), 잔량 종결·취소(입고 없을 때만). 상태는 저장하지 않고 누적 입고로 계산(`store.order_status`). 권한키 `inout`(조회), **발주 담당·입고 담당·공장(담당자·연락처 따로, 002)은 모듈 옵션 — 상단 톱니 → 팝업**(`/inout/settings?panel=1`, ERP 관리자, `inout_roles`·`inout_factories`, 공용 `.erp-input`·`.erp-table-wrap` 겹침은 `.io` 안에서만 바로잡음), 관리자는 둘 다. **발주 메일**(003): 새 발주서 저장 → 미리보기 팝업(받는 사람 = 공장 이메일, 요약 표 본문) → 사람이 [메일 발송]을 눌러야 **발주 담당 본인 Gmail**(Gmail API `gmail.send`, 사람마다 [Gmail 연결] 1회 — 고른 구글 계정 = ERP 계정 확인, 갱신 토큰은 `APP_ENCRYPTION_KEY` AES-GCM 암호문, `app/modules/inout/gmail.py`)로 보냄, 보낸 기록·재발송 확인. **입고증 사진**(003): 입고 저장 때 첨부(브라우저가 2000px JPEG 로 줄임, 10장·10MB, 파일 머리 검사, 입고와 한 트랜잭션, bytea), 썸네일·크게 보기·나중에 더하기, 초과 확인은 브라우저가 먼저(사진 유지). **상품 정보**(004, 옵션 세 번째 탭, `inout_products`·`inout_products_excluded`): [단품 불러오기] = 코드표 단품 → 목록(값을 넣은 상품은 그대로·지운 단품은 다음에도 빠짐, 제외 목록에서 되살리기), 단가(원)·무게(개당 g = PP량)·은(Ag) 함유량(%) 수기 입력(은 g = 무게 × % 자동) — 한 번 불러오면 발주서 제품은 이 목록에서, 발주 품목에 그때 값 사본(`unit_price`·`weight_g`·`silver_pct`), 발주서·메일에 금액(수량 × 단가)·PP·은 함유량과 합계. **입고 담당(발주 담당 아님)은 품목을 이름·발주 수량만**(`items_limited`), 옵션은 관리자만. 시각은 DB 시간대와 무관하게 KST 로 읽음(`db._KstTimestamptzLoader`). 모든 품목 입고완료·초과입고 = "✓ 전체 입고 완료"(초과면 "초과 포함", `order_badge`), 날짜 서식은 모두 `yyyy.mm.dd(요일)`(`ymd`·`ymdhm` 매크로, `store.fmt_date`). 이카운트 "발주 대비 미입고"·Odoo 분할 입고/종결 참고. 상세 `docs/INOUT_MODULE.md` +- 입출고 관리 (`app/modules/inout/`, `inout_db`, 2026-10-16) — 본사 → 공장 제품 제작 발주(발주서 `PO-YYMMDD-NN`, 제품 = `itemcode_db.single_items` 단품만, 검색 `GET /inout/api/items`·저장 때 서버 재확인), 물류 입고를 여러 번 나눠 입력, 품목별 발주·입고·미입고, 미입고 현황(제품별 합계·발주별·지연), 초과 입고는 확인 화면 후 허용(트랜잭션 안에서 발주서 잠그고 판단, `confirm_over`), 잔량 종결·취소(입고 없을 때만). 상태는 저장하지 않고 누적 입고로 계산(`store.order_status`). 권한키 `inout`(조회), **발주 담당·입고 담당·공장(담당자·연락처 따로, 002)은 모듈 옵션 — 상단 톱니 → 팝업**(`/inout/settings?panel=1`, ERP 관리자, `inout_roles`·`inout_factories`, 공용 `.erp-input`·`.erp-table-wrap` 겹침은 `.io` 안에서만 바로잡음), 관리자는 둘 다. **발주 메일**(003): 새 발주서 저장 → 미리보기 팝업(받는 사람 = 공장 이메일, 요약 표 본문) → 사람이 [메일 발송]을 눌러야 **발주 담당 본인 Gmail**(Gmail API `gmail.send`, 사람마다 [Gmail 연결] 1회 — 고른 구글 계정 = ERP 계정 확인, 갱신 토큰은 `APP_ENCRYPTION_KEY` AES-GCM 암호문, `app/modules/inout/gmail.py`)로 보냄, 보낸 기록·재발송 확인. **입고증 사진**(003): 입고 저장 때 첨부(브라우저가 2000px JPEG 로 줄임, 10장·10MB, 파일 머리 검사, 입고와 한 트랜잭션, bytea), 썸네일·크게 보기·나중에 더하기, 초과 확인은 브라우저가 먼저(사진 유지). **상품 정보**(004, 옵션 세 번째 탭, `inout_products`·`inout_products_excluded`): [단품 불러오기] = 코드표 단품 → 목록(값을 넣은 상품은 그대로·지운 단품은 다음에도 빠짐, 제외 목록에서 되살리기), 단가(원)·무게(개당 g = PP량)·은(Ag) 함유량(%) 수기 입력(은 g = 무게 × % 자동) — 한 번 불러오면 발주서 제품은 이 목록에서, 발주 품목에 그때 값 사본(`unit_price`·`weight_g`·`silver_pct`), 발주서·메일에 금액(수량 × 단가)·PP·은 함유량과 합계. **입고 담당(발주 담당 아님)은 품목을 이름·발주 수량만**(`items_limited`), 옵션은 관리자만. 시각은 DB 시간대와 무관하게 KST 로 읽음(`db._KstTimestamptzLoader`). 모든 품목 입고완료·초과입고 = "✓ 전체 입고 완료"(초과면 "초과 포함", `order_badge`), 날짜 서식은 모두 `yyyy.mm.dd(요일)`(`ymd`·`ymdhm` 매크로, `store.fmt_date`). 발주 삭제는 **수퍼관리자만**(발주 목록 🗑, `perms.super`, 입고·사진·메일 기록까지 CASCADE). 이카운트 "발주 대비 미입고"·Odoo 분할 입고/종결 참고. 상세 `docs/INOUT_MODULE.md` 상세는 `docs/PROJECT_OVERVIEW.md`. diff --git a/app/modules/inout/db.py b/app/modules/inout/db.py index 8f3d654..45630a4 100644 --- a/app/modules/inout/db.py +++ b/app/modules/inout/db.py @@ -220,6 +220,15 @@ class InoutDBStore: conn.execute("UPDATE inout_orders SET cancelled_at=now(), cancelled_by=%s, updated_by=%s WHERE id=%s", (_norm_email(by), _norm_email(by), order_id)) + def delete_order(self, order_id: int) -> dict[str, Any]: + """발주서 완전 삭제(수퍼관리자) — 품목·입고 기록·입고증 사진·메일 기록까지 함께(CASCADE). 되돌릴 수 없다. + 반환 {order_no, receipts} — 화면 안내·로그용.""" + with self._pool.connection() as conn, conn.transaction(): + self._lock_order(conn, order_id) + n = conn.execute("SELECT count(*) AS n FROM inout_receipts WHERE order_id=%s", (order_id,)).fetchone()["n"] + row = conn.execute("DELETE FROM inout_orders WHERE id=%s RETURNING order_no", (order_id,)).fetchone() + return {"order_no": row["order_no"], "receipts": int(n)} + def get_order(self, order_id: int) -> dict[str, Any] | None: with self._pool.connection() as conn: head = conn.execute( diff --git a/app/modules/inout/router.py b/app/modules/inout/router.py index 4382bfe..367f582 100644 --- a/app/modules/inout/router.py +++ b/app/modules/inout/router.py @@ -21,6 +21,7 @@ from __future__ import annotations +import logging from datetime import date from typing import Any from urllib.parse import urlencode @@ -33,6 +34,8 @@ from app.timezone import today_kst from . import store from .db import OverReceipt +_log = logging.getLogger(__name__) + router = APIRouter(prefix="/inout", tags=["inout"]) @@ -82,7 +85,8 @@ def _perms(st: Any, user: dict[str, Any]) -> dict[str, bool]: admin = _is_admin(user) roles = set() if admin else st.roles_of(user.get("email", "")) return {"admin": admin, "can_order": admin or store.ROLE_ORDER in roles, - "can_receive": admin or store.ROLE_RECEIVE in roles} + "can_receive": admin or store.ROLE_RECEIVE in roles, + "super": bool(user.get("is_super_admin"))} # 발주 삭제(2026-10-17) — 수퍼관리자 한 명만 def _require(st: Any, user: dict[str, Any], what: str) -> dict[str, bool]: @@ -93,6 +97,8 @@ def _require(st: Any, user: dict[str, Any], what: str) -> dict[str, bool]: raise HTTPException(status_code=403, detail="입고 담당만 할 수 있습니다(입출고 관리 → 옵션에서 지정).") if what == "admin" and not p["admin"]: raise HTTPException(status_code=403, detail="옵션은 ERP 관리자만 바꿀 수 있습니다.") + if what == "super" and not p["super"]: + raise HTTPException(status_code=403, detail="발주 삭제는 수퍼관리자만 할 수 있습니다.") return p @@ -393,6 +399,25 @@ def order_cancel(request: Request, order_id: int) -> Any: return _redirect(f"/inout/orders/{order_id}", "발주서를 취소했습니다.") +@router.post("/orders/{order_id}/delete") +async def order_delete(request: Request, order_id: int) -> Any: + """발주 목록 🗑 — 수퍼관리자만. 품목·입고 기록·입고증 사진·메일 기록까지 완전히 지운다(되돌릴 수 없음).""" + got = _ctx(request) + if not isinstance(got, tuple): + return got + st, user = got + _require(st, user, "super") + form = await request.form() + back = str(form.get("back") or "") + back = back if back.startswith("/inout/") and "//" not in back else "/inout/" # 보던 목록(거르기)으로 — 다른 사이트로는 안 보냄 + try: + r = st.delete_order(order_id) + except LookupError as exc: + return _redirect(back, str(exc)) + _log.warning("inout order deleted: %s (receipts=%d) by %s", r["order_no"], r["receipts"], user.get("email", "")) + return _redirect(back, f"발주서 {r['order_no']}를 삭제했습니다" + (f"(입고 기록 {r['receipts']}건 포함)." if r["receipts"] else ".")) + + # ──────────────────────────────────────────────────────────── # 입고 # ──────────────────────────────────────────────────────────── diff --git a/app/modules/inout/templates/inout/index.html b/app/modules/inout/templates/inout/index.html index 3727c76..1861a7e 100644 --- a/app/modules/inout/templates/inout/index.html +++ b/app/modules/inout/templates/inout/index.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} {% from "inout/_macros.html" import order_badge, progress, due, n, ymd %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
@@ -33,6 +33,7 @@ 발주번호공장제품발주일입고 예정일 발주입고미입고진행상태 + {% if perms.super %}삭제{% endif %} {% for o in orders %} @@ -48,9 +49,18 @@ {{ n(o.summary.remaining) }}{% if o.summary.over %}
초과 +{{ n(o.summary.over) }}
{% endif %} {{ progress(o.summary) }} {{ order_badge(o.status, o.status_label) }} + {% if perms.super %} + {# 수퍼관리자만 — 완전 삭제(품목·입고 기록·사진·메일 기록까지) #} +
+ +
+ {% endif %} {% else %} - {% if filters.status == 'active' %}진행 중인 발주가 없습니다.{% else %}조건에 맞는 발주가 없습니다.{% endif %} + {% if filters.status == 'active' %}진행 중인 발주가 없습니다.{% else %}조건에 맞는 발주가 없습니다.{% endif %} {% endfor %} diff --git a/app/modules/inout/templates/inout/order_detail.html b/app/modules/inout/templates/inout/order_detail.html index c2d0ecc..32feac0 100644 --- a/app/modules/inout/templates/inout/order_detail.html +++ b/app/modules/inout/templates/inout/order_detail.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} {% from "inout/_macros.html" import status_badge, order_badge, progress, due, n, ymd, ymdhm %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %} {% set active = order.status in ('open', 'partial') %} diff --git a/app/modules/inout/templates/inout/order_form.html b/app/modules/inout/templates/inout/order_form.html index a9d7c47..5058f64 100644 --- a/app/modules/inout/templates/inout/order_form.html +++ b/app/modules/inout/templates/inout/order_form.html @@ -1,5 +1,5 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
diff --git a/app/modules/inout/templates/inout/pending.html b/app/modules/inout/templates/inout/pending.html index 8995642..16556d9 100644 --- a/app/modules/inout/templates/inout/pending.html +++ b/app/modules/inout/templates/inout/pending.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} {% from "inout/_macros.html" import due, n, ymd %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
diff --git a/app/static/inout.css b/app/static/inout.css index cc183ad..2e92ff3 100644 --- a/app/static/inout.css +++ b/app/static/inout.css @@ -281,3 +281,8 @@ .io-st-all { gap: 3px; } .io-badge-note { margin-left: 4px; font-size: 11px; font-weight: 600; color: #b3261e; white-space: nowrap; } .io-status-cell { white-space: nowrap; } +/* 발주 삭제(수퍼관리자, 2026-10-17) */ +.io-table .io-col-trash { width: 44px; padding-left: 0; padding-right: 8px; text-align: center; } +.io-table .io-col-trash form { margin: 0; display: inline-flex; } +.io-del-btn { display: inline-flex; align-items: center; justify-content: center; } +.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; } diff --git a/docs/INOUT_MODULE.md b/docs/INOUT_MODULE.md index ab870d1..48c1b35 100644 --- a/docs/INOUT_MODULE.md +++ b/docs/INOUT_MODULE.md @@ -43,6 +43,7 @@ | 모듈 권한 `inout` | 발주 목록·발주서·미입고 현황 조회 | | **발주 담당**(옵션에서 지정) | 발주서 작성·고치기·잔량 종결/풀기·취소 | | **입고 담당**(옵션에서 지정) | 입고 수량 입력·입고 기록 지우기. 발주 담당이 아니면 발주서 품목은 **제품 이름·발주 수량**(+ 이번 입고 칸)만 보인다 — 코드·입고·미입고·상태·단가·금액 숨김, 입고 기록 칩도 이름(2026-10-16 요청) | +| **수퍼관리자**(`SUPER_ADMIN_EMAIL`) | 위 전부 + 발주 목록 줄 끝 🗑 **발주 삭제**(`POST /inout/orders/{id}/delete`) — 확인 후 품목·입고 기록·입고증 사진·발주 메일 기록까지 완전히 지움(CASCADE, 되돌릴 수 없음), 서버 로그에 남김, 보던 목록(거르기)으로 돌아감(2026-10-17) | | ERP 관리자(`role=admin`) | 위 전부 + **옵션**(공장 목록·담당자·상품 정보) — 상단 오른쪽 **톱니** → 팝업. 입고 담당·발주 담당은 옵션을 못 본다 | 담당자 후보 = ERP 관리자 화면에서 `inout` 권한을 받은 사용자. 권한이 빠졌는데 담당으로 남은 사람도 옵션에 보여서 뺄 수 있다. diff --git a/tests/test_inout_db.py b/tests/test_inout_db.py index 0c343bf..48594a4 100644 --- a/tests/test_inout_db.py +++ b/tests/test_inout_db.py @@ -302,5 +302,23 @@ class InoutDbTests(unittest.TestCase): self.assertEqual(self.st.catalog_count(), before) + def test_delete_order_cascades(self): + """수퍼관리자 발주 삭제 — 품목·입고 기록·입고증 사진·메일 기록까지 함께 지워진다.""" + o = self.order([("MT-D", 10), ("MT-E", 5)]) + ids = self.line_ids(o["id"]) + rid = self.st.add_receipt(o["id"], {ids["MT-D"]: "4"}, receipt_date="2026-10-20", memo="", confirm_over=False, by="w@x") + if isinstance(rid, dict): + rid = rid.get("receipt_id") or rid.get("id") + r = self.st.delete_order(o["id"]) + self.assertEqual((r["order_no"], r["receipts"]), (o["order_no"], 1)) + self.assertIsNone(self.st.get_order(o["id"])) + with self.st._pool.connection() as conn: + left = conn.execute("SELECT (SELECT count(*) FROM inout_order_lines WHERE order_id=%s) + " + "(SELECT count(*) FROM inout_receipts WHERE order_id=%s) AS n", (o["id"], o["id"])).fetchone()["n"] + self.assertEqual(left, 0) + with self.assertRaises(LookupError): + self.st.delete_order(o["id"]) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_inout_web.py b/tests/test_inout_web.py index 7d1b4a0..56983cd 100644 --- a/tests/test_inout_web.py +++ b/tests/test_inout_web.py @@ -400,5 +400,47 @@ run(body) self.assertIn("OK", res.stdout) + @unittest.skipUnless(DB_ENABLED, "INOUT_TEST_DB_URL(localhost) not set") + def test_super_admin_deletes_order(self): + """발주 목록 🗑 — 수퍼관리자만(ERP 관리자·발주 담당은 403·버튼 없음), 지운 뒤 보던 목록으로.""" + res = _run(''' +import re, uuid +from app.modules.inout.db import InoutDBStore +st = InoutDBStore(__import__("os").environ["INOUT_TEST_DB_URL"]) +main.app.state.inout_store = st +main.app.state.inout_items = Items() +tag = uuid.uuid4().hex[:6] +admin = U("admin-%s@t.local" % tag, role="admin") +boss = dict(U("boss-%s@t.local" % tag, role="admin"), is_super_admin=True) +users.extend([admin, boss]) + +def body(c): + who["u"] = admin + H = {"X-Inout-Options": "1"} + c.post("/inout/settings/factories", data={"name": "공장D-" + tag, "is_active": "1"}, headers=H) + fid = next(f["id"] for f in st.list_factories() if f["name"] == "공장D-" + tag) + r = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "item_code": ["MT-A"], + "item_name": [""], "qty": ["7"], "line_memo": [""]}, follow_redirects=False) + oid = int(re.search(r"/inout/orders/(\\d+)", r.headers["location"]).group(1)) + no = st.get_order(oid)["order_no"] + # ERP 관리자(수퍼 아님) — 버튼 없음, 직접 보내도 403 + assert 'action="/inout/orders/%d/delete"' % oid not in c.get("/inout/?status=all").text + assert c.post("/inout/orders/%d/delete" % oid).status_code == 403 + assert st.get_order(oid) is not None + # 수퍼관리자 — 목록에 🗑, 지우면 보던 목록(거르기 그대로)으로 + who["u"] = boss + lst = c.get("/inout/?status=all&q=" + no).text + assert 'action="/inout/orders/%d/delete"' % oid in lst and "완전히 삭제할까요?" in lst + r = c.post("/inout/orders/%d/delete" % oid, data={"back": "/inout/?status=all&q=" + no}, follow_redirects=False) + assert r.status_code == 303 and r.headers["location"].startswith("/inout/?status=all&q=" + no + "&msg="), r.headers["location"] + assert st.get_order(oid) is None + assert c.post("/inout/orders/%d/delete" % oid, data={"back": "https://evil.example/"}, follow_redirects=False).headers["location"].startswith("/inout/?msg=") + print("OK") +run(body) +''', {"INOUT_TEST_DB_URL": DSN}) + self.assertEqual(res.returncode, 0, res.stdout + res.stderr) + self.assertIn("OK", res.stdout) + + if __name__ == "__main__": unittest.main()