From 0ba6192e95716a0d18840053aadeeccc9650fcc8 Mon Sep 17 00:00:00 2001 From: king Date: Wed, 4 Nov 2026 15:43:19 +0900 Subject: [PATCH] =?UTF-8?q?feat(=EC=9E=85=EC=B6=9C=EA=B3=A0):=20=EB=8C=80?= =?UTF-8?q?=EC=84=B1=ED=99=94=ED=95=99=C2=B7=EC=9D=B8=EC=B2=9C=EA=B3=B5?= =?UTF-8?q?=EC=9E=A5=20=EB=B0=9C=EC=A3=BC=20=EB=A9=94=EC=9D=BC=20=ED=91=9C?= =?UTF-8?q?=EB=A5=BC=20=EA=B0=84=EB=8B=A8=ED=95=98=EA=B2=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 공장 이름에 대성화학·인천공장이 들어가면 품목 표를 번호·제품 코드· 제품명·수량·박스당 수량·박스 수·비고로 만들고, 요약 표와 글 본문에서도 금액·무게·PP·은을 뺀다. 박스 값은 메일을 만들 때의 상품 정보로 계산한다. Co-Authored-By: Claude Opus 5.5 --- app/modules/inout/CLAUDE.md | 3 ++ app/modules/inout/router.py | 4 ++ app/modules/inout/store.py | 81 +++++++++++++++++++++++++--------- docs/INOUT_MODULE.md | 1 + tests/test_inout_mail_photo.py | 45 +++++++++++++++++++ tests/test_inout_web.py | 41 +++++++++++++++++ 6 files changed, 154 insertions(+), 21 deletions(-) diff --git a/app/modules/inout/CLAUDE.md b/app/modules/inout/CLAUDE.md index 9d3fd82..f59473f 100644 --- a/app/modules/inout/CLAUDE.md +++ b/app/modules/inout/CLAUDE.md @@ -40,6 +40,9 @@ - **입고 담당 발주 알림 자동 발송**(2026-10-19): 발주 메일이 나가면 같은 Gmail 로 옵션 → 담당자의 입고 담당들에게 따로 보냄 — 제목은 발주 메일과 같고 내용은 발주번호·발주일·제품 코드·제품명·수량만(`store.order_notice_mail`, `router._send_order_notice`). 실패해도 공장 메일은 그대로(안내만), 미리보기 창에 받을 사람 안내. - **참조 기본값 `king@dbxcorp.co.kr`**(2026-10-19) — 미리보기 참조 칸에 미리 들어감, 옵션 → 공장 탭 "발주 메일 참조"에서 고침(`inout_settings` `order_mail_cc`, 행이 없으면 기본값 — 저장만 005 필요). +- **간단 발주 메일**(2026-11-04): 공장 이름에 "대성화학"·"인천공장"이 들어가면(`store.SIMPLE_MAIL_FACTORIES`, 띄어쓰기 무시) 품목 표 = 번호·제품 코드·제품명·수량·**박스당 수량·박스 수**·비고만, 요약 표·글 본문에서도 금액·무게·PP·은을 뺀다(단가가 공장에 나가지 않게). 색상 줄 배경·합계 수량은 그대로. + 박스 값은 발주 품목 사본이 아니라 **메일을 만들 때의 상품 정보**(`router._mail_order` → `store.line_boxes`, 뚜껑 있으면 통·뚜껑 따로, 입수 없으면 `-`). 다른 공장 메일엔 박스 칸 없음. + ## 입고 요청 메일 (005, 2026-10-19) - 입고 담당이 **입고 저장** → 발주서 화면 `?rmail={입고 id}` 로 미리보기 팝업이 바로 뜸 → [메일 발송](입고 담당 본인 Gmail, 발주 메일과 같은 연결 — Gmail 연결 권한은 발주·입고 담당 `_require(…, "mail")`). 입고 기록 줄 [보내기/다시 보내기]로 언제든. diff --git a/app/modules/inout/router.py b/app/modules/inout/router.py index f341450..b05c75e 100644 --- a/app/modules/inout/router.py +++ b/app/modules/inout/router.py @@ -709,6 +709,10 @@ def _mail_order(request: Request, order_id: int) -> tuple[Any, dict[str, Any], d order = _order_or_404(st, order_id) if order["cancelled_at"]: raise HTTPException(status_code=400, detail="취소된 발주서는 메일로 보낼 수 없습니다.") + if store.is_simple_mail_factory(order["factory_name"]) and st.boxes_ready(): # 박스 칸 — 발주 품목에 없어 지금 상품 정보 값 + found = st.catalog_lookup([x["item_code"] for x in order["lines"]]) + for x in order["lines"]: + x.update(store.box_info(found.get(x["item_code"]) or {})) return st, user, order diff --git a/app/modules/inout/store.py b/app/modules/inout/store.py index 07eeb99..3426075 100644 --- a/app/modules/inout/store.py +++ b/app/modules/inout/store.py @@ -248,6 +248,28 @@ def parse_emails(raw: Any, *, label: str = "이메일", required: bool = False) return out +# 간단 발주 메일(2026-11-04) — 이 공장들엔 품목 표를 번호·제품 코드·제품명·수량·박스당 수량·박스 수·비고만, 요약에서도 금액·무게·은을 뺀다. +SIMPLE_MAIL_FACTORIES = ("대성화학", "인천공장") + + +def is_simple_mail_factory(name: Any) -> bool: + """이름 일부·띄어쓰기가 달라도 맞게 — 놓치면 단가가 공장에 나간다.""" + compact = "".join(str(name or "").split()) + return any(word in compact for word in SIMPLE_MAIL_FACTORIES) + + +def line_boxes(x: dict[str, Any]) -> dict[str, Any]: + """간단 발주 메일 칸 — 박스당 수량·박스 수(올림). 뚜껑이 있으면 통·뚜껑 따로, 입수가 없으면 '-'(total None).""" + body, lid, qty = x.get("body_per_box"), x.get("lid_per_box"), int(x["qty"]) + if not body: + return {"per": "-", "count": "-", "total": None} + boxes = -(-qty // body) + if not lid: + return {"per": f"{body:,}개", "count": f"{boxes:,}박스", "total": boxes} + lids = -(-qty // lid) + return {"per": f"통 {body:,}개 · 뚜껑 {lid:,}개", "count": f"통 {boxes:,} · 뚜껑 {lids:,}박스", "total": boxes + lids} + + def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) -> dict[str, str]: """발주서 → 메일 제목·글 본문·HTML 본문(요약). order = db.get_order 결과. 품목마다 단가·금액(수량 × 단가)·전체 무게(개당 g × 수량, kg)·PP 사용량(전체 무게 − 은 무게, kg)·은 함유량(%·전체 무게 × %, kg) @@ -263,16 +285,18 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) -> who = sender_name or sender_email 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 "" - facts.append(("발주 금액", f"{fmt_num(money['amount'])}원{note}")) + simple = is_simple_mail_factory(order.get("factory_name")) ag_kg = money["silver_g"] / Decimal(1000) if money["silver_g"] is not None else None - if money["pp_kg"] is not None: - facts.append(("전체 무게", f"{fmt_num(money['pp_kg'], 3)} kg")) - if money["pp_use_kg"] is not None: - facts.append(("PP 사용량", f"{fmt_num(money['pp_use_kg'], 3)} kg")) - if ag_kg is not None: - facts.append(("은(Ag) 총량", f"{fmt_num(ag_kg, 4)} kg")) + if not simple: + if money["amount"] is not None: + note = f" (단가 미입력 {money['missing_price']}종 제외)" if money["missing_price"] else "" + facts.append(("발주 금액", f"{fmt_num(money['amount'])}원{note}")) + if money["pp_kg"] is not None: + facts.append(("전체 무게", f"{fmt_num(money['pp_kg'], 3)} kg")) + if money["pp_use_kg"] is not None: + facts.append(("PP 사용량", f"{fmt_num(money['pp_use_kg'], 3)} kg")) + if ag_kg is not None: + facts.append(("은(Ag) 총량", f"{fmt_num(ag_kg, 4)} kg")) if order.get("memo"): facts.append(("요청 사항", order["memo"])) @@ -289,12 +313,17 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) -> # 글 본문(HTML 을 못 보는 메일 프로그램용) text = [greet, "", "아래와 같이 제품 제작을 발주합니다.", ""] text += [f"- {k}: {v}" for k, v in facts] - text += ["", "[발주 품목] 수량 · 단가 · 금액 · 전체 무게 · PP 사용량 · 은 함유량"] + text += ["", "[발주 품목] 제품 코드 · 제품명 · 수량 · 박스당 수량 · 박스 수 · 비고" if simple else "[발주 품목] 수량 · 단가 · 금액 · 전체 무게 · PP 사용량 · 은 함유량"] for i, x in enumerate(lines, start=1): c = cells(x) - text.append(f"{i}. {x['item_code']} {x['item_name']} — {int(x['qty']):,}개 · 단가 {c['price']} · 금액 {c['amount']}" - f" · 전체 무게 {c['weight'] + 'kg' if c['weight'] != '-' else '-'}" - f" · PP 사용량 {c['pp_use'] + 'kg' if c['pp_use'] != '-' else '-'} · 은 {c['ag']}" + b = line_boxes(x) + if simple: + detail = f" · 박스당 {b['per']} · {b['count']}" if b["total"] is not None else "" + else: + detail = (f" · 단가 {c['price']} · 금액 {c['amount']}" + f" · 전체 무게 {c['weight'] + 'kg' if c['weight'] != '-' else '-'}" + f" · PP 사용량 {c['pp_use'] + 'kg' if c['pp_use'] != '-' else '-'} · 은 {c['ag']}") + text.append(f"{i}. {x['item_code']} {x['item_name']} — {int(x['qty']):,}개{detail}" + (f" ({x['memo']})" if x.get("memo") else "")) text += ["", "입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.", "", f"발주 담당: {who} ({sender_email})"] # HTML 본문 — 값은 모두 escape @@ -323,12 +352,14 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) -> hexc = color_hex(x.get("color")) ctd = f"{td}background:{hexc};" if hexc else td tr_style = f' style="background:{hexc}"' if hexc else "" + b = line_boxes(x) + detail = (f'{e(b["per"])}{e(b["count"])}') if simple else ( + f'{e(c["price"])}{e(c["amount"])}' + f'{e(c["weight"])}{e(c["pp_use"])}{e(c["ag"])}') rows.append( 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["item_name"])}{int(x["qty"]):,}{detail}' f'{e(x.get("memo") or "")}') # 합계 줄(2026-10-21) — 금액 뒤 " 원", 무게 뒤 " kg", 무게는 소수 첫째 자리에서 반올림(정수 kg) foot_amount = f'{fmt_num(money["amount"])} 원' if money["amount"] is not None else "" @@ -336,6 +367,16 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) -> foot_use = f'{fmt_num(money["pp_use_kg"], 0)} kg' if money["pp_use_kg"] is not None else "" foot_ag = f'{fmt_num(ag_kg, 0)} kg' if ag_kg is not None else "" bg = "background:#f6f7f9;" + box_totals = [t for t in (line_boxes(x)["total"] for x in lines) if t is not None] + foot_boxes = f"{sum(box_totals):,}박스" if box_totals else "" + if box_totals and len(box_totals) < len(lines): + foot_boxes += f" (미설정 {len(lines) - len(box_totals)}종 제외)" + head_detail = f'박스당 수량박스 수' if simple else ( + f'단가(원)금액(원)' + f'전체 무게(kg)PP 사용량(kg)은(Ag) 함유량') + foot_detail = f'{e(foot_boxes)}' if simple else ( + f'{e(foot_amount)}' + f'{e(foot_pp)}{e(foot_use)}{e(foot_ag)}') html = ( '
' f"

{e(greet)}
아래와 같이 제품 제작을 발주합니다.

" @@ -343,14 +384,12 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) -> # 두 표 사이 18px — 표 margin 은 메일 프로그램마다 무시되기도 해서 높이 18px 빈 줄로 띄운다 '
 
' '' - f'' - f'' - f'' + f'' + f'{head_detail}' f'' f'{"".join(rows)}' f'' - f'' - f'' + f'{foot_detail}' f'
No제품 코드제품명수량단가(원)금액(원)전체 무게(kg)PP 사용량(kg)은(Ag) 함유량
{"번호" if simple else "No"}제품 코드제품명수량비고
합계{total:,}{e(foot_amount)}{e(foot_pp)}{e(foot_use)}{e(foot_ag)}{total:,}
' "

입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.

" f'

발주 담당: {e(who)} ({e(sender_email)})

' diff --git a/docs/INOUT_MODULE.md b/docs/INOUT_MODULE.md index ec6d03c..381a84b 100644 --- a/docs/INOUT_MODULE.md +++ b/docs/INOUT_MODULE.md @@ -119,6 +119,7 @@ cupang·malaysia 와 같은 DSN). 화면에서 코드·이름으로 검색(`GET 사람이 **[메일 발송]**을 눌러야만 보낸다(자동 발송 없음). 머리 **[발주 메일 보내기 / 다시 보내기]**로 언제든 다시 연다. - **본문**(`store.order_mail`) = 인사(공장 담당자 이름) · 발주번호·발주일·입고 예정일·품목 수·총수량·요청 사항(메모) 표 · 품목 표(No·제품 코드·제품명·수량·비고, 합계) · 보낸 사람. HTML + 글 본문(둘 다), 값은 모두 escape. 제목 `[발주] {번호} · {공장} · {첫 품목} 외 n종`. +- **간단 발주 메일**(2026-11-04, 사용자 요청): 공장 이름에 "대성화학"·"인천공장"이 들어가면(띄어쓰기 무시) 품목 표 = 번호·제품 코드·제품명·수량·박스당 수량·박스 수·비고, 요약 표·글 본문에서도 금액·무게·PP·은을 뺀다. 박스 값은 메일을 만들 때의 상품 정보(올림, 뚜껑 있으면 통·뚜껑 따로, 입수 없으면 `-`, 합계는 있는 줄만). - **보내는 계정** = 누른 사람(발주 담당)의 Gmail — Gmail API `users.messages.send`(`gmail.py`). 사람마다 처음 한 번 **[Gmail 연결]**: 구글 동의 화면(로그인과 같은 OAuth 클라이언트, 범위 `openid email gmail.send` 만, `hd=` 회사 도메인, `login_hint` = ERP 계정) → `/inout/gmail/callback` 에서 **고른 구글 계정 = ERP 로그인 계정**인지(다르면 거절), gmail.send 허락·갱신 토큰 확인 → diff --git a/tests/test_inout_mail_photo.py b/tests/test_inout_mail_photo.py index 7b10f7d..422b253 100644 --- a/tests/test_inout_mail_photo.py +++ b/tests/test_inout_mail_photo.py @@ -2,6 +2,7 @@ import base64 import email import json +import re import unittest from datetime import date from email import policy @@ -118,6 +119,50 @@ class MailContentTests(unittest.TestCase): self.assertTrue(m2["text"].startswith("안녕하세요.")) self.assertNotIn("요청 사항", m2["text"]) + def test_order_mail_simple_factories(self): + """대성화학·인천공장 — 표는 번호·제품 코드·제품명·수량·박스당 수량·박스 수·비고만, 단가·금액·무게·은은 어디에도 없음. 다른 공장은 그대로.""" + from decimal import Decimal as D + + priced = [{"item_code": "MT-0320", "item_name": "통", "qty": 100, "memo": "흰색", "unit_price": D("7777"), + "weight_g": D("50"), "silver_pct": D("3")}] + for name in ("대성화학", "(주)대성화학", "인천공장", "인천 공장"): + with self.subTest(name=name): + m = s.order_mail(_order(factory_name=name, lines=priced), sender_name="K", sender_email="k@x.com") + head = m["html"][m["html"].index(""):m["html"].index("")] + self.assertEqual(re.findall(r"]*>([^<]*)", head), ["번호", "제품 코드", "제품명", "수량", "박스당 수량", "박스 수", "비고"]) + row = m["html"][m["html"].index(""):m["html"].index("")] + self.assertEqual(row.count(""):].count("No", other["html"]) + self.assertIn("단가 7,777", other["text"]) + self.assertNotIn("박스", other["html"].replace("박스당 24개", "")) # 다른 공장엔 박스 칸 없음(요청 사항 글 제외) + + def test_order_mail_simple_boxes(self): + """박스당 수량·박스 수(올림) — 뚜껑 있으면 통·뚜껑 따로, 입수 없으면 '-', 합계는 있는 줄만.""" + self.assertEqual(s.line_boxes({"qty": 100, "body_per_box": 30}), {"per": "30개", "count": "4박스", "total": 4}) + self.assertEqual(s.line_boxes({"qty": 90, "body_per_box": 30})["total"], 3) + self.assertEqual(s.line_boxes({"qty": 1000, "body_per_box": 120, "lid_per_box": 500}), + {"per": "통 120개 · 뚜껑 500개", "count": "통 9 · 뚜껑 2박스", "total": 11}) + self.assertEqual(s.line_boxes({"qty": 5}), {"per": "-", "count": "-", "total": None}) + lines = [{"item_code": "A", "item_name": "봉투", "qty": 2600, "memo": "", "body_per_box": 100, "lid_per_box": None}, + {"item_code": "B", "item_name": "통", "qty": 1000, "memo": "흰색", "body_per_box": 120, "lid_per_box": 500}, + {"item_code": "C", "item_name": "없음", "qty": 5, "memo": ""}] + m = s.order_mail(_order(factory_name="대성화학", memo="", lines=lines), sender_name="K", sender_email="k@x.com") + self.assertIn(">100개", m["html"]) + self.assertIn(">26박스", m["html"]) + self.assertIn("통 9 · 뚜껑 2박스", m["html"]) + self.assertIn("37박스 (미설정 1종 제외)", m["html"]) + self.assertIn("1. A 봉투 — 2,600개 · 박스당 100개 · 26박스", m["text"]) + self.assertIn("2. B 통 — 1,000개 · 박스당 통 120개 · 뚜껑 500개 · 통 9 · 뚜껑 2박스 (흰색)", m["text"]) + self.assertIn("3. C 없음 — 5개", m["text"]) + def test_build_message_utf8_and_alternative(self): raw = gmail.build_message(sender_name="킹", sender_email="king@dbxcorp.co.kr", to=["a@x.com", "b@y.com"], cc=["c@z.com"], subject="[발주] 테스트 · 한글", text="본문", html="

본문

") diff --git a/tests/test_inout_web.py b/tests/test_inout_web.py index 1b5aea2..ff307b8 100644 --- a/tests/test_inout_web.py +++ b/tests/test_inout_web.py @@ -461,6 +461,47 @@ def body(c): st.exclude_product(code, by=admin["email"]) print("OK") run(body) +''', {"INOUT_TEST_DB_URL": DSN}) + self.assertEqual(res.returncode, 0, res.stdout + res.stderr) + self.assertIn("OK", res.stdout) + + @unittest.skipUnless(DB_ENABLED, "INOUT_TEST_DB_URL(localhost) not set") + def test_simple_factory_mail_shows_boxes(self): + """대성화학 메일 미리보기 — 상품 정보의 박스 입수로 박스 칸이 차고 단가는 없음. 다른 공장은 예전 표.""" + 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].upper() +admin = U("admin-%s@t.local" % tag.lower(), role="admin") +users.append(admin) +CODE = "ZS-%s-A" % tag + +def order_for(c, factory): + c.post("/inout/settings/factories", data={"name": factory, "is_active": "1"}, headers={"X-Inout-Options": "1"}) + fid = next(f["id"] for f in st.list_factories() if f["name"] == factory) + r = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-11-04", "item_code": [CODE], + "item_name": [""], "qty": ["100"], "line_memo": [""]}, follow_redirects=False) + return int(re.search(r"/inout/orders/(\\d+)", r.headers["location"]).group(1)) + +def body(c): + who["u"] = admin + st.import_products([{"code": CODE, "name": "통 " + tag}], by=admin["email"]) + try: + r = c.post("/inout/settings/products/save", headers={"X-Inout-Options": "1"}, json={"rows": [ + {"code": CODE, "unit_price": "7777", "weight_g": "", "silver_pct": "", "body_per_box": "30", "lid_per_box": ""}]}) + assert r.json()["ok"], r.text + html = c.get("/inout/orders/%d/mail" % order_for(c, "대성화학-" + tag)).json()["html"] + assert "박스당 수량" in html and ">30개" in html and ">4박스" in html, html + assert "단가" not in html and "7,777" not in html + html = c.get("/inout/orders/%d/mail" % order_for(c, "보통공장-" + tag)).json()["html"] + assert "박스당 수량" not in html and "7,777" in html + finally: + st.exclude_product(CODE, by=admin["email"]) + print("OK") +run(body) ''', {"INOUT_TEST_DB_URL": DSN}) self.assertEqual(res.returncode, 0, res.stdout + res.stderr) self.assertIn("OK", res.stdout)