diff --git a/CLAUDE.md b/CLAUDE.md index f5503fc..9349197 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`). 이카운트 "발주 대비 미입고"·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`). 이카운트 "발주 대비 미입고"·Odoo 분할 입고/종결 참고. 상세 `docs/INOUT_MODULE.md` 상세는 `docs/PROJECT_OVERVIEW.md`. diff --git a/app/modules/inout/router.py b/app/modules/inout/router.py index 6f0f0b5..4382bfe 100644 --- a/app/modules/inout/router.py +++ b/app/modules/inout/router.py @@ -614,7 +614,7 @@ def mail_preview(request: Request, order_id: int) -> JSONResponse: "callback_url": _callback_url(request), # 구글 클라우드 승인된 리디렉션 URI 에 등록해야 하는 주소(안내용) "from": user.get("email", ""), "to": order.get("factory_email") or "", "factory": order["factory_name"], "subject": mail["subject"], "html": mail["html"], - "sent": [{"at": m["sent_at"].strftime("%Y-%m-%d %H:%M"), "by": m["sent_by"], "to": m["to_addrs"]} for m in order["mails"]], + "sent": [{"at": store.fmt_datetime(m["sent_at"]), "by": m["sent_by"], "to": m["to_addrs"]} for m in order["mails"]], }) diff --git a/app/modules/inout/store.py b/app/modules/inout/store.py index 43fc7bc..a627978 100644 --- a/app/modules/inout/store.py +++ b/app/modules/inout/store.py @@ -10,7 +10,7 @@ from __future__ import annotations import html as _html import re -from datetime import date +from datetime import date, datetime from decimal import ROUND_HALF_UP, Decimal, InvalidOperation from typing import Any, Iterable @@ -29,7 +29,8 @@ LINE_LABELS = {LINE_NONE: "미입고", LINE_PARTIAL: "부분입고", LINE_DONE: # 발주서 상태 — 진행(open·partial)은 미입고 현황에 나온다 ST_OPEN, ST_PARTIAL, ST_DONE, ST_OVER, ST_CLOSED, ST_CANCELLED = "open", "partial", "done", "over", "closed", "cancelled" -ORDER_LABELS = {ST_OPEN: "발주", ST_PARTIAL: "부분입고", ST_DONE: "입고완료", ST_OVER: "초과입고", +# 모든 품목이 입고완료·초과입고 = "전체 입고 완료"(2026-10-17 요청 — 초과가 있으면 화면에 "초과 포함"만 덧붙인다) +ORDER_LABELS = {ST_OPEN: "발주", ST_PARTIAL: "부분입고", ST_DONE: "전체 입고 완료", ST_OVER: "전체 입고 완료", ST_CLOSED: "종결", ST_CANCELLED: "취소"} ACTIVE_STATUSES = (ST_OPEN, ST_PARTIAL) # 아직 더 들어올 것이 있는 발주 STATUS_FILTERS = { # 목록 거르기 @@ -40,6 +41,21 @@ STATUS_FILTERS = { # 목록 거르기 } +WEEKDAYS_KO = "월화수목금토일" + + +def fmt_date(d: date | None) -> str: + """날짜 서식 — 2026.10.17(토). 입출고 화면·메일 모두 이 모양(2026-10-17 요청). 화면 쪽은 _macros.html ymd 와 같다.""" + if not d: + return "" + return f"{d:%Y.%m.%d}({WEEKDAYS_KO[d.weekday()]})" + + +def fmt_datetime(dt: datetime | None) -> str: + """2026.10.17(토) 15:14 — 시각은 DB 에서 KST 로 읽는다(db._KstTimestamptzLoader).""" + return f"{fmt_date(dt)} {dt:%H:%M}" if dt else "" + + def line_status(qty: int, received: int) -> str: if received <= 0: return LINE_NONE @@ -240,10 +256,10 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) -> subject = f"[발주] {order['order_no']} · {order['factory_name']} · {first}{more}" total = sum(int(x["qty"]) for x in lines) money = order_totals(lines) - due = order["due_date"].strftime("%Y-%m-%d") if order.get("due_date") else "협의" + due = fmt_date(order["due_date"]) if order.get("due_date") else "협의" greet = f"{order['factory_manager']}님, 안녕하세요." if order.get("factory_manager") else "안녕하세요." who = sender_name or sender_email - facts = [("발주번호", order["order_no"]), ("발주일", order["order_date"].strftime("%Y-%m-%d")), + facts = [("발주번호", order["order_no"]), ("발주일", fmt_date(order["order_date"])), ("입고 예정일", due), ("품목", f"{len(lines)}종 · 총 {total:,}개")] if money["amount"] is not None: note = f" (단가 미입력 {money['missing_price']}종 제외)" if money["missing_price"] else "" diff --git a/app/modules/inout/templates/inout/_macros.html b/app/modules/inout/templates/inout/_macros.html index 5af00c6..1659553 100644 --- a/app/modules/inout/templates/inout/_macros.html +++ b/app/modules/inout/templates/inout/_macros.html @@ -10,9 +10,19 @@ {{ summary.pct }}% {%- endmacro %} +{# 날짜 서식 — 2026.10.17(토) / 2026.10.17(토) 15:14 (2026-10-17 요청, 메일·JSON 은 store.fmt_date·fmt_datetime) #} +{% macro ymd(d) -%}{% if d %}{{ d.strftime('%Y.%m.%d') }}({{ '월화수목금토일'[d.weekday()] }}){% endif %}{%- endmacro %} +{% macro ymdhm(d) -%}{% if d %}{{ ymd(d) }} {{ d.strftime('%H:%M') }}{% endif %}{%- endmacro %} + +{# 발주서 상태 — 모든 품목이 입고완료·초과입고면 초록 "✓ 전체 입고 완료"(초과가 있으면 "초과 포함"), 나머지는 상태 배지 #} +{% macro order_badge(status, label) -%} +{% if status in ('done', 'over') %}✓ {{ label }}{% if status == 'over' %}초과 포함{% endif %} +{%- else %}{{ status_badge(status, label) }}{% endif %} +{%- endmacro %} + {# 입고 예정일 — 지났는데 남은 게 있으면 빨강 "지연 N일" #} {% macro due(due_date, today, active) -%} -{% if due_date %}{{ due_date.strftime('%Y-%m-%d') }}{% if active and due_date < today %} 지연 {{ (today - due_date).days }}일{% elif active %} D-{{ (due_date - today).days }}{% endif %}{% else %}-{% endif %} +{% if due_date %}{{ ymd(due_date) }}{% if active and due_date < today %} 지연 {{ (today - due_date).days }}일{% elif active %} D-{{ (due_date - today).days }}{% endif %}{% else %}-{% endif %} {%- endmacro %} {% macro n(v) -%}{{ '{:,}'.format(v or 0) }}{%- endmacro %} diff --git a/app/modules/inout/templates/inout/_options_panel.html b/app/modules/inout/templates/inout/_options_panel.html index 791148f..0928649 100644 --- a/app/modules/inout/templates/inout/_options_panel.html +++ b/app/modules/inout/templates/inout/_options_panel.html @@ -1,3 +1,4 @@ +{% from "inout/_macros.html" import ymd %} {# 옵션 팝업 내용(GET /inout/settings?panel=1) — 탭: 담당자 · 공장 · 상품 정보(004). 폼 저장은 inout.js 가 제자리에서(X-Inout-Options: 1 → JSON). 공장 줄은 표(
| {{ o.order_no }} | {{ o.factory_name }} | {{ o.items_label }} {{ o.line_count }}종 |
- {{ o.order_date.strftime('%Y-%m-%d') }} | +{{ ymd(o.order_date) }} | {{ due(o.due_date, today, active) }} | {{ n(o.summary.ordered) }} | {{ n(o.summary.received) }} | {{ n(o.summary.remaining) }}{% if o.summary.over %} 초과 +{{ n(o.summary.over) }} {% endif %} |
{{ progress(o.summary) }} | -{{ status_badge(o.status, o.status_label) }} | +{{ order_badge(o.status, o.status_label) }} | {% else %}
| {% if filters.status == 'active' %}진행 중인 발주가 없습니다.{% else %}조건에 맞는 발주가 없습니다.{% endif %} | |||||||||
| {{ r.receipt_date.strftime('%Y-%m-%d') }}{% if r.memo %} {{ r.memo }} {% endif %} |
+ {{ ymd(r.receipt_date) }}{% if r.memo %} {{ r.memo }} {% endif %} |
{% for x in r.lines %}{% if items_limited %}{{ x.item_name }}{% else %}{{ x.item_code }}{% endif %} {{ n(x.qty) }}{% endfor %} | {{ n(r.total) }} | @@ -173,10 +173,10 @@ {% elif not r.photos %}-{% endif %} | -{{ r.created_by }} {{ r.created_at.strftime('%Y-%m-%d %H:%M') }} |
+ {{ r.created_by }} {{ ymdhm(r.created_at) }} |
{% if photo_admin %}
{% endif %} | ||
| {{ due(r.due_date, today, True) }} | -{{ r.order_no }} 발주 {{ r.order_date.strftime('%Y-%m-%d') }} |
+ {{ r.order_no }} 발주 {{ ymd(r.order_date) }} |
{{ r.factory_name }} | {{ r.item_code }} | {{ r.item_name }} | {{ n(r.qty) }} | {{ n(r.received) }} | {{ n(r.remaining) }} | diff --git a/app/static/inout.css b/app/static/inout.css index 87c3a09..cc183ad 100644 --- a/app/static/inout.css +++ b/app/static/inout.css @@ -274,6 +274,10 @@ /* 발주서 단가·금액 칸 */ .io-col-money { width: 110px; text-align: right; white-space: nowrap; font-variant-numeric: tabular-nums; } .io-col-spec { width: 96px; white-space: nowrap; font-variant-numeric: tabular-nums; } -.io-table tfoot .io-total-row td { background: #fafbfc; font-weight: 500; border-top: 1px solid var(--color-subtle-ash); } +.io-table tfoot .io-total-row td { padding: 10px var(--sp-16, 16px); vertical-align: middle; background: #fafbfc; font-weight: 500; border-top: 1px solid var(--color-subtle-ash); } .io-suggest-price { float: right; margin-left: 12px; color: var(--color-midtone-gray); font-size: 12px; font-variant-numeric: tabular-nums; } .io-table th.io-col-money, .io-table th.io-col-spec { text-align: right; } +/* 전체 입고 완료(모든 품목 입고완료·초과입고) — 2026-10-17 */ +.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; } diff --git a/docs/INOUT_MODULE.md b/docs/INOUT_MODULE.md index 90b1809..ab870d1 100644 --- a/docs/INOUT_MODULE.md +++ b/docs/INOUT_MODULE.md @@ -23,6 +23,10 @@ - 상태는 **저장하지 않고** 품목별 누적 입고로 계산한다(`store.order_status`, `store.line_status`) — 어긋날 수 없다. - 품목 상태: 미입고 / 부분입고 / 입고완료 / 초과입고. 발주서는 하나라도 남으면 부분입고(초과가 섞여 있어도). +- **모든 품목이 입고완료 또는 초과입고**(발주서 done·over)면 목록·발주서 머리에 초록 **"✓ 전체 입고 완료"**, 초과가 있으면 옆에 빨강 "초과 포함" + (`_macros.html order_badge`, 2026-10-17 요청). 품목 줄의 초과입고 배지는 그대로 빨강. +- **날짜 서식은 모두 `yyyy.mm.dd(요일)`** — 예 `2026.10.17(토)`, 시각이 있으면 `2026.10.17(토) 15:14`(화면 `_macros.html ymd·ymdhm`, + 메일·JSON `store.fmt_date·fmt_datetime`, 2026-10-17 요청). 날짜 입력 칸(달력)은 브라우저 모양 그대로. - **미입고 현황**(`/inout/pending`)은 종결·취소가 아닌 발주의 남은 수량만 — 제품별 합계, 발주별(입고 예정일 순, 지난 것 빨강), 초과 입고 목록. - **초과 입고**: 입고 저장 때 발주를 넘는 품목이 있으면 저장하지 않고 확인 화면(409, 넣은 숫자 유지) → [초과 입고로 저장](`confirm_over=1`). 판단은 DB 트랜잭션 안에서 발주서 행을 잠그고(`FOR UPDATE`) 누적 입고를 다시 읽어 한다 — 동시에 입고해도 확인을 건너뛰지 않음. diff --git a/tests/test_inout_mail_photo.py b/tests/test_inout_mail_photo.py index e7f06c8..2b95105 100644 --- a/tests/test_inout_mail_photo.py +++ b/tests/test_inout_mail_photo.py @@ -40,7 +40,7 @@ class MailContentTests(unittest.TestCase): def test_order_mail_summary_and_escaping(self): m = s.order_mail(_order(), sender_name="King", sender_email="king@dbxcorp.co.kr") self.assertEqual(m["subject"], "[발주] PO-261016-01 · 엘리화학 · 미라클 통 320ml 외 1종") - for part in ("이석준님, 안녕하세요.", "발주번호: PO-261016-01", "입고 예정일: 2026-10-30", "2종 · 총 6,200개", + for part in ("이석준님, 안녕하세요.", "발주번호: PO-261016-01", "발주일: 2026.10.16(금)", "입고 예정일: 2026.10.30(금)", "2종 · 총 6,200개", "1. MT-0320 미라클 통 320ml — 5,000개", "(흰색)", "발주 담당: King (king@dbxcorp.co.kr)"): self.assertIn(part, m["text"]) h = m["html"] diff --git a/tests/test_inout_store.py b/tests/test_inout_store.py index 9901802..ecbf82b 100644 --- a/tests/test_inout_store.py +++ b/tests/test_inout_store.py @@ -26,6 +26,21 @@ class StatusTests(unittest.TestCase): self.assertEqual(s.summarize([{"qty": 1, "received": 5}])["pct"], 100) # 막대는 100% 에서 멈춤 self.assertEqual(s.summarize([])["pct"], 0) + def test_date_format(self): + """날짜 서식 yyyy.mm.dd(요일) — 2026-10-17 요청.""" + from datetime import datetime, timedelta, timezone + self.assertEqual(s.fmt_date(date(2026, 10, 17)), "2026.10.17(토)") + self.assertEqual(s.fmt_date(date(2026, 10, 19)), "2026.10.19(월)") + self.assertEqual(s.fmt_date(None), "") + kst = timezone(timedelta(hours=9)) + self.assertEqual(s.fmt_datetime(datetime(2026, 10, 18, 9, 5, tzinfo=kst)), "2026.10.18(일) 09:05") + self.assertEqual(s.fmt_datetime(None), "") + + def test_all_received_label(self): + """모든 품목이 입고완료·초과입고면 '전체 입고 완료'.""" + self.assertEqual(s.ORDER_LABELS[s.ST_DONE], "전체 입고 완료") + self.assertEqual(s.ORDER_LABELS[s.ST_OVER], "전체 입고 완료") + def test_order_no(self): self.assertEqual(s.order_no(date(2026, 10, 6), 3), "PO-261006-03") self.assertEqual(s.order_no(date(2026, 10, 6), 123), "PO-261006-123") diff --git a/tests/test_inout_web.py b/tests/test_inout_web.py index 0b8b60d..7d1b4a0 100644 --- a/tests/test_inout_web.py +++ b/tests/test_inout_web.py @@ -172,6 +172,11 @@ def body(c): assert r.status_code == 303 and "%EC%B4%88%EA%B3%BC" in r.headers["location"] # "초과 입고 포함" 안내 got = st.get_order(oid) assert (got["status"], got["summary"]["over"]) == ("over", 5) + page = c.get("/inout/orders/%d" % oid).text + assert "✓ 전체 입고 완료" in page and "초과 포함" in page # 모든 품목 입고완료·초과입고 + assert "2026.10.18(일)" in page and "2026.10.16(금)" in page # 날짜 서식(입고일·발주일) + lst = c.get("/inout/?status=done").text + assert got["order_no"] in lst and "✓ 전체 입고 완료" in lst and "2026.10.16(금)" in lst pend = c.get("/inout/pending").text assert "초과 입고" in pend and got["order_no"] in pend|