diff --git a/app/modules/inout/CLAUDE.md b/app/modules/inout/CLAUDE.md index 016875d..95993bf 100644 --- a/app/modules/inout/CLAUDE.md +++ b/app/modules/inout/CLAUDE.md @@ -29,6 +29,13 @@ - **발주 담당 본인 Gmail**(Gmail API `gmail.send`, 사람마다 [Gmail 연결] 1회 — 고른 구글 계정 = ERP 계정 확인). 갱신 토큰은 `APP_ENCRYPTION_KEY` AES-GCM 암호문(`gmail.py`). - 보낸 기록·재발송 확인. +## 입고 요청 메일 (005, 2026-10-19) + +- 입고 담당이 **입고 저장** → 발주서 화면 `?rmail={입고 id}` 로 미리보기 팝업이 바로 뜸 → [메일 발송](입고 담당 본인 Gmail, 발주 메일과 같은 연결 — Gmail 연결 권한은 발주·입고 담당 `_require(…, "mail")`). 입고 기록 줄 [보내기/다시 보내기]로 언제든. +- 받는 사람 = 옵션 → **물류센터** 탭 담당자 이메일(`inout_settings` `logistics_emails`), 참조 기본 = `receipt_mail_cc`(005 가 `king@dbxcorp.co.kr, bj@dbxcorp.co.kr` 넣음). 창에서 고칠 수 있음. +- 제목 `[입고 요청] yyyy년 mm월 dd일(요일) 입고 요청 합니다.`(입고일) · 본문 "입고된 아래 리스트 상품을 전산 등록 부탁드립니다." + 표(상품 이름·상품 코드·입고 수량·비고 = 발주 품목 줄 메모, 합계) + 메모 + **맨 아래 입고증 사진 = 본문 안 이미지**(CID `multipart/related`, 첨부 아님 — `gmail.build_message(inline_images=)`), 서버가 가로 600px 이하·비율 유지 JPEG 로 줄임(`store.mail_images`, EXIF 회전 반영, HEIC 는 빼고 안내). 미리보기는 cid → data: 로 바꿔 보여 줌. +- 보낸 기록 `inout_receipt_mails`(입고 지우면 CASCADE), 이미 보낸 입고는 `resend` 확인. + ## 입고증 사진 (003) - 입고 저장 때 첨부(브라우저가 2000px JPEG 로 줄임, 10장·10MB, 파일 머리 검사, 입고와 한 트랜잭션, bytea). diff --git a/app/modules/inout/db.py b/app/modules/inout/db.py index 45630a4..96d6d8c 100644 --- a/app/modules/inout/db.py +++ b/app/modules/inout/db.py @@ -257,6 +257,16 @@ class InoutDBStore: mails = conn.execute("SELECT * FROM inout_order_mails WHERE order_id=%s ORDER BY sent_at, id", (order_id,)).fetchall() except UndefinedTable: photos, mails = [], [] + # 입고 요청 메일 기록(005) — 미적용이면 빈 목록 + try: + rmails = conn.execute( + "SELECT m.* FROM inout_receipt_mails m JOIN inout_receipts r ON r.id = m.receipt_id " + "WHERE r.order_id=%s ORDER BY m.sent_at, m.id", (order_id,)).fetchall() + except UndefinedTable: + rmails = [] + by_rmail: dict[int, list[dict[str, Any]]] = {} + for m in rmails: + by_rmail.setdefault(int(m["receipt_id"]), []).append(m) by_photo: dict[int, list[dict[str, Any]]] = {} for ph in photos: by_photo.setdefault(int(ph["receipt_id"]), []).append(ph) @@ -268,6 +278,7 @@ class InoutDBStore: return {**head, "lines": lines, "summary": store.summarize(lines), "status": status, "status_label": store.ORDER_LABELS[status], "receipts": [{**r, "lines": by_receipt.get(int(r["id"]), []), "photos": by_photo.get(int(r["id"]), []), + "mails": by_rmail.get(int(r["id"]), []), "total": sum(int(x["qty"]) for x in by_receipt.get(int(r["id"]), []))} for r in receipts], "mails": mails} @@ -438,6 +449,54 @@ class InoutDBStore: "VALUES (%s,%s,%s,%s,%s,%s)", (order_id, _norm_email(sent_by), ", ".join(to), ", ".join(cc), subject[:300], gmail_id[:100])) + # ════════════════════════════════════════════════════════════ + # 모듈 설정(물류센터 이메일·입고 요청 메일 참조) · 입고 요청 메일 기록 — 005 + # ════════════════════════════════════════════════════════════ + def settings_ready(self) -> bool: + with self._pool.connection() as conn: + return bool(conn.execute("SELECT to_regclass('public.inout_settings') IS NOT NULL AND " + "to_regclass('public.inout_receipt_mails') IS NOT NULL AS ok").fetchone()["ok"]) + + def get_settings(self) -> dict[str, str]: + """설정 값 — 없는 키는 store.SETTING_DEFAULTS. 005 미적용이어도 기본값으로.""" + out = dict(store.SETTING_DEFAULTS) + try: + with self._pool.connection() as conn: + for r in conn.execute("SELECT key, value FROM inout_settings").fetchall(): + if r["key"] in out: + out[r["key"]] = r["value"] + except UndefinedTable: + pass + return out + + def save_settings(self, values: dict[str, str], *, by: str) -> None: + try: + with self._pool.connection() as conn, conn.transaction(): + for k, v in values.items(): + conn.execute("INSERT INTO inout_settings (key, value, updated_by, updated_at) VALUES (%s,%s,%s,now()) " + "ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value, updated_by=EXCLUDED.updated_by, updated_at=now()", + (k, v, _norm_email(by))) + except UndefinedTable: + raise ValueError("DB 마이그레이션 inout_db 005(물류센터 이메일·입고 요청 메일)가 아직 적용되지 않았습니다.") from None + + def receipt_photo_data(self, receipt_id: int) -> list[dict[str, Any]]: + """입고 1건의 사진 내용(메일 본문에 넣기) — 올린 순서.""" + try: + with self._pool.connection() as conn: + return conn.execute("SELECT id, filename, content_type, data FROM inout_receipt_photos WHERE receipt_id=%s ORDER BY id", + (receipt_id,)).fetchall() + except UndefinedTable: + return [] + + def add_receipt_mail(self, receipt_id: int, *, sent_by: str, to: list[str], cc: list[str], subject: str, gmail_id: str) -> None: + try: + with self._pool.connection() as conn: + conn.execute("INSERT INTO inout_receipt_mails (receipt_id, sent_by, to_addrs, cc_addrs, subject, gmail_id) " + "VALUES (%s,%s,%s,%s,%s,%s)", + (receipt_id, _norm_email(sent_by), ", ".join(to), ", ".join(cc), subject[:300], gmail_id[:100])) + except UndefinedTable: + pass # 메일은 이미 나갔다 — 기록만 못 남김(005 미적용) + def delete_receipt(self, order_id: int, receipt_id: int, *, by: str) -> None: """잘못 넣은 입고 1건을 지운다(그 수량만큼 다시 미입고).""" with self._pool.connection() as conn, conn.transaction(): diff --git a/app/modules/inout/gmail.py b/app/modules/inout/gmail.py index f7a0002..28612eb 100644 --- a/app/modules/inout/gmail.py +++ b/app/modules/inout/gmail.py @@ -140,7 +140,9 @@ def access_token(refresh_token: str) -> str: def build_message(*, sender_name: str, sender_email: str, to: list[str], cc: list[str], subject: str, - text: str, html: str) -> bytes: + text: str, html: str, inline_images: list[dict[str, Any]] | None = None) -> bytes: + """글 + HTML(multipart/alternative). inline_images = [{cid, data(JPEG)}] 면 HTML 쪽을 multipart/related 로 만들어 + 가 첨부가 아니라 본문 안 이미지로 보이게 한다(입고 요청 메일, 2026-10-19).""" msg = EmailMessage() msg["From"] = formataddr((sender_name or sender_email, sender_email)) msg["To"] = ", ".join(to) @@ -149,6 +151,10 @@ def build_message(*, sender_name: str, sender_email: str, to: list[str], cc: lis msg["Subject"] = subject msg.set_content(text) msg.add_alternative(html, subtype="html") + if inline_images: + html_part = msg.get_payload()[1] + for im in inline_images: # 파일 이름은 붙이지 않는다 — 메일 프로그램이 첨부 목록에 따로 띄우지 않게 + html_part.add_related(im["data"], maintype="image", subtype="jpeg", cid=f"<{im['cid']}>", disposition="inline") return msg.as_bytes() diff --git a/app/modules/inout/router.py b/app/modules/inout/router.py index 367f582..ec202da 100644 --- a/app/modules/inout/router.py +++ b/app/modules/inout/router.py @@ -13,6 +13,8 @@ POST /inout/settings/products/import|save · /products/{code}/exclude|restore 옵션 → 상품 정보(단가·무게·은 함유량, 004) POST /inout/orders/{id}/receipts/{rid}/photos · /orders/{id}/photos/{pid}/delete · GET /inout/photos/{pid} 입고증 사진 GET|POST /inout/orders/{id}/mail 발주 메일 미리보기·발송(발주 담당 본인 Gmail, 사람이 눌러야 보냄) + GET|POST /inout/orders/{id}/receipts/{rid}/mail 입고 요청 메일(물류센터, 입고 담당 본인 Gmail, 005) + POST /inout/settings/logistics 옵션 → 물류센터(입고 요청 메일 받는 주소·참조, 005) GET /inout/gmail/connect · /gmail/callback · POST /gmail/disconnect Gmail 연결(사람별, gmail.send 만) GET /inout/api/items?q= 코드표 단품 검색(JSON) @@ -95,6 +97,8 @@ def _require(st: Any, user: dict[str, Any], what: str) -> dict[str, bool]: raise HTTPException(status_code=403, detail="발주 담당만 할 수 있습니다(입출고 관리 → 옵션에서 지정).") if what == "receive" and not p["can_receive"]: raise HTTPException(status_code=403, detail="입고 담당만 할 수 있습니다(입출고 관리 → 옵션에서 지정).") + if what == "mail" and not (p["can_order"] or p["can_receive"]): # Gmail 연결 — 발주 메일·입고 요청 메일 보내는 사람 + raise HTTPException(status_code=403, detail="발주 담당·입고 담당만 Gmail 을 연결할 수 있습니다.") if what == "admin" and not p["admin"]: raise HTTPException(status_code=403, detail="옵션은 ERP 관리자만 바꿀 수 있습니다.") if what == "super" and not p["super"]: @@ -337,6 +341,8 @@ def _detail(request: Request, user: dict[str, Any], st: Any, order: dict[str, An return _render(request, "inout/order_detail.html", user, { "tab": "orders", "order": order, "error": error, "over": over or [], "photos_lost": photos_lost, "open_mail": request.query_params.get("mail") == "1" and perms["can_order"] and not order["cancelled_at"], + # 입고 저장 뒤 ?rmail={입고 id} — 입고 요청 메일 미리보기를 바로 연다(005) + "open_rmail": _opt_int(request.query_params.get("rmail")) if perms["can_receive"] else None, # 입고 담당(발주 담당 아님)은 품목을 이름·발주 수량(+ 이번 입고 칸)만 — 2026-10-16 사용자 요청 "items_limited": perms["can_receive"] and not perms["can_order"], "show_prices": perms["can_order"], "totals": store.order_totals(order["lines"]), @@ -452,7 +458,8 @@ async def receipt_add(request: Request, order_id: int) -> Any: photos_lost=had_photos, status_code=400) note = (f"입고 {res['total']:,}개를 저장했습니다." + (" (초과 입고 포함)" if res["over"] else "") + (f" 입고증 사진 {res['photos']}장." if res.get("photos") else "")) - return _redirect(f"/inout/orders/{order_id}", note) + # 바로 입고 요청 메일 미리보기(물류센터) — 보내기는 사람이 [메일 발송]을 눌러야 + return _redirect(f"/inout/orders/{order_id}?rmail={res['id']}", note) @router.post("/orders/{order_id}/receipts/{receipt_id}/delete") @@ -554,7 +561,7 @@ async def gmail_connect(request: Request, next: str = "/inout/") -> Any: # noqa if not isinstance(got, tuple): return got st, user = got - _require(st, user, "order") + _require(st, user, "mail") from app.main import ALLOWED_DOMAIN, public_url_for # noqa: WPS433 from . import gmail # noqa: WPS433 @@ -576,7 +583,7 @@ async def gmail_callback(request: Request) -> Any: if not isinstance(got, tuple): return got st, user = got - _require(st, user, "order") + _require(st, user, "mail") from authlib.integrations.starlette_client import OAuthError # noqa: WPS433 from . import gmail # noqa: WPS433 @@ -679,6 +686,88 @@ def mail_send(request: Request, order_id: int, payload: dict[str, Any] = Body(.. return JSONResponse({"ok": True, "message": f"메일을 보냈습니다 → {', '.join(to)}"}) +# ──────────────────────────────────────────────────────────── +# 입고 요청 메일 — 입고 담당 본인 Gmail(005). 입고 저장 뒤 미리보기 → [메일 발송], 받는 사람 = 옵션 → 물류센터 이메일. +# 본문 = 입고 상품 표 + 입고증 사진(본문 안 이미지, 가로 600px 이하 — store.mail_images). +# ──────────────────────────────────────────────────────────── +def _mail_receipt(request: Request, order_id: int, receipt_id: int) -> tuple[Any, dict[str, Any], dict[str, Any], dict[str, Any]]: + user = _user(request) + st = _store(request) + if st is None: + raise HTTPException(status_code=503, detail="입출고 관리 모듈이 설정되지 않았습니다.") + _require(st, user, "receive") + order = _order_or_404(st, order_id) + receipt = next((r for r in order["receipts"] if int(r["id"]) == receipt_id), None) + if receipt is None: + raise HTTPException(status_code=404, detail="입고 기록을 찾을 수 없습니다.") + return st, user, order, receipt + + +def _receipt_mail_parts(st: Any, user: dict[str, Any], order: dict[str, Any], + receipt: dict[str, Any]) -> tuple[dict[str, str], list[dict[str, Any]], int]: + images, skipped = store.mail_images(st.receipt_photo_data(int(receipt["id"]))) + mail = store.receipt_mail(order, receipt, images=images, skipped=skipped, + sender_name=str(user.get("name") or ""), sender_email=user.get("email", "")) + return mail, images, skipped + + +@router.get("/orders/{order_id}/receipts/{receipt_id}/mail") +def receipt_mail_preview(request: Request, order_id: int, receipt_id: int) -> JSONResponse: + """입고 요청 메일 미리보기 — 받는 사람(물류센터)·참조(기본 king@·bj@)·제목·본문(사진은 미리보기용 data: 로), 보낸 기록.""" + st, user, order, receipt = _mail_receipt(request, order_id, receipt_id) + from . import gmail # noqa: WPS433 + + conf = st.get_settings() + mail, images, skipped = _receipt_mail_parts(st, user, order, receipt) + tok = st.gmail_token(user.get("email", "")) + return JSONResponse({ + "kind": "receipt", "connected": tok is not None, "configured": gmail.configured(), "ready": st.settings_ready(), + "connect_url": f"/inout/gmail/connect?{urlencode({'next': f'/inout/orders/{order_id}?rmail={receipt_id}'})}", + "callback_url": _callback_url(request), + "from": user.get("email", ""), "to": conf[store.SETTING_LOGISTICS_EMAILS], "cc": conf[store.SETTING_RECEIPT_MAIL_CC], + "subject": mail["subject"], "html": store.inline_preview_html(mail["html"], images), + "photos": len(images), "photos_skipped": skipped, + "sent": [{"at": store.fmt_datetime(m["sent_at"]), "by": m["sent_by"], "to": m["to_addrs"]} for m in receipt["mails"]], + }) + + +@router.post("/orders/{order_id}/receipts/{receipt_id}/mail") +def receipt_mail_send(request: Request, order_id: int, receipt_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse: + """[메일 발송] — 사람이 누를 때만. 이미 보낸 입고는 resend=true 를 함께(실수로 두 번 보내지 않게).""" + st, user, order, receipt = _mail_receipt(request, order_id, receipt_id) + from . import gmail # noqa: WPS433 + + email = user.get("email", "") + try: + to = store.parse_emails(payload.get("to"), label="받는 사람", required=True) + cc = store.parse_emails(payload.get("cc"), label="참조") + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from None + if receipt["mails"] and not payload.get("resend"): + return JSONResponse({"ok": False, "resend_needed": True, + "message": f"이 입고는 이미 {len(receipt['mails'])}번 입고 요청 메일을 보냈습니다. 다시 보낼까요?"}, + status_code=409) + row = st.gmail_token(email) + if row is None: + return JSONResponse({"ok": False, "reconnect": True, "message": "Gmail 이 연결되지 않았습니다 — 먼저 [Gmail 연결]을 하세요."}, + status_code=409) + mail, images, _skipped = _receipt_mail_parts(st, user, order, receipt) + try: + refresh = gmail.decrypt_token(email, row["refresh_token_enc"]) + raw = gmail.build_message(sender_name=str(user.get("name") or ""), sender_email=email, to=to, cc=cc, + subject=mail["subject"], text=mail["text"], html=mail["html"], inline_images=images) + gid = gmail.send(refresh, raw) + except gmail.GmailNotConnected as exc: + st.delete_gmail_token(email) + return JSONResponse({"ok": False, "reconnect": True, "message": str(exc)}, status_code=409) + except gmail.GmailError as exc: + st.mark_gmail(email, error=str(exc)) + return JSONResponse({"ok": False, "message": str(exc)}, status_code=502) + st.add_receipt_mail(receipt_id, sent_by=email, to=to, cc=cc, subject=mail["subject"], gmail_id=gid) + st.mark_gmail(email) + return JSONResponse({"ok": True, "message": f"입고 요청 메일을 보냈습니다 → {', '.join(to)}"}) + + # ──────────────────────────────────────────────────────────── # 옵션 — 공장·발주 담당·입고 담당(ERP 관리자) # ──────────────────────────────────────────────────────────── @@ -710,6 +799,7 @@ def _options_ctx(request: Request, st: Any) -> dict[str, Any]: return {"products": products, "excluded": st.list_excluded(), "products_ready": st.products_ready(), "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(), "candidates": cands, "items_status": "연결됨" if reader is not None and reader.enabled else (reader.reason if reader else "없음")} @@ -759,6 +849,25 @@ async def settings_factory_save(request: Request) -> Any: return _options_done(request, "공장을 저장했습니다.") +@router.post("/settings/logistics") +async def settings_logistics_save(request: Request) -> Any: + """옵션 → 물류센터 — 입고 요청 메일 받는 주소(물류센터 입고 담당자)·참조 기본값(005).""" + got = _ctx(request) + if not isinstance(got, tuple): + return got + st, user = got + _require(st, user, "admin") + form = await request.form() + try: + st.save_settings({ + store.SETTING_LOGISTICS_EMAILS: store.clean_emails(form.get("logistics_emails"), label="물류센터 담당자 이메일"), + store.SETTING_RECEIPT_MAIL_CC: store.clean_emails(form.get("receipt_mail_cc"), label="참조"), + }, by=user.get("email", "")) + except ValueError as exc: + return _options_done(request, str(exc), ok=False) + return _options_done(request, "물류센터 이메일을 저장했습니다.") + + @router.post("/settings/factories/{factory_id}/delete") def settings_factory_delete(request: Request, factory_id: int) -> Any: got = _ctx(request) diff --git a/app/modules/inout/store.py b/app/modules/inout/store.py index f1d02e3..d806f01 100644 --- a/app/modules/inout/store.py +++ b/app/modules/inout/store.py @@ -473,3 +473,118 @@ def validate_photos(files: list[tuple[str, bytes]], *, existing: int = 0) -> lis if existing + len(out) > MAX_PHOTOS: raise ValueError(f"입고 한 건에 사진은 {MAX_PHOTOS}장까지입니다.") return out + + +# ════════════════════════════════════════════════════════════ +# 입고 요청 메일(2026-10-19, 마이그레이션 005) — 입고 담당이 입고를 저장한 뒤 물류센터 입고 담당자에게 +# "전산 등록 부탁" 메일(입고 담당 본인 Gmail). 받는 사람 = 옵션 → 물류센터 이메일, 참조 기본 = king@·bj@dbxcorp.co.kr. +# 본문 = 입고 상품 표(상품 이름·상품 코드·입고 수량·비고) + 입고증 사진을 본문 안 이미지(CID, 첨부 아님, 가로 600px 이하). +# ════════════════════════════════════════════════════════════ +SETTING_LOGISTICS_EMAILS = "logistics_emails" +SETTING_RECEIPT_MAIL_CC = "receipt_mail_cc" +SETTING_DEFAULTS = {SETTING_LOGISTICS_EMAILS: "", SETTING_RECEIPT_MAIL_CC: "king@dbxcorp.co.kr, bj@dbxcorp.co.kr"} +MAIL_IMAGE_MAX_W = 600 + + +def clean_emails(raw: Any, *, label: str) -> str: + """옵션 저장용 — 주소 검사 후 'a@x.com, b@y.com' 로 다시 씀(비우면 '').""" + return ", ".join(parse_emails(raw, label=label)) + + +def mail_images(photos: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], int]: + """입고증 사진 → 메일 본문용 JPEG(가로 최대 600px, 세로는 비율대로, 회전 정보 반영). + 반환 ([{cid, data, width, height}], 못 넣은 장수) — HEIC 등 서버가 못 여는 사진은 빼고 센다.""" + from io import BytesIO # noqa: WPS433 + + from PIL import Image, ImageOps # noqa: WPS433 + + out: list[dict[str, Any]] = [] + skipped = 0 + for ph in photos: + try: + im = Image.open(BytesIO(bytes(ph["data"]))) + if im.format == "JPEG": + im.draft("RGB", (MAIL_IMAGE_MAX_W * 2, MAIL_IMAGE_MAX_W * 2)) # 큰 JPEG 는 줄여서 읽기(빠름) + im = ImageOps.exif_transpose(im) + if im.mode not in ("RGB", "L"): + rgba = im.convert("RGBA") + bg = Image.new("RGB", rgba.size, (255, 255, 255)) + bg.paste(rgba, mask=rgba.split()[-1]) + im = bg + if im.width > MAIL_IMAGE_MAX_W: + im = im.resize((MAIL_IMAGE_MAX_W, max(1, round(im.height * MAIL_IMAGE_MAX_W / im.width))), Image.LANCZOS) + buf = BytesIO() + im.convert("RGB").save(buf, "JPEG", quality=85, optimize=True) + except Exception: # noqa: BLE001 — HEIC·깨진 파일은 본문에서 뺀다(입고 기록의 사진은 그대로) + skipped += 1 + continue + out.append({"cid": f"inout-photo-{ph['id']}@dbx", "data": buf.getvalue(), "width": im.width, "height": im.height}) + return out, skipped + + +def receipt_mail_subject(receipt_date: date) -> str: + d = receipt_date + return f"[입고 요청] {d.year}년 {d.month:02d}월 {d.day:02d}일({WEEKDAYS_KO[d.weekday()]}) 입고 요청 합니다." + + +def receipt_mail(order: dict[str, Any], receipt: dict[str, Any], *, images: list[dict[str, Any]], skipped: int = 0, + sender_name: str, sender_email: str) -> dict[str, str]: + """입고 1건 → 제목·글 본문·HTML 본문. 이미지는 (보낼 때 gmail.build_message 가 본문에 붙임). + 비고 = 그 발주 품목의 줄 메모. 값은 모두 escape.""" + memo_of = {int(ln["id"]): (ln.get("memo") or "") for ln in order["lines"]} + rows = [{"name": x["item_name"], "code": x["item_code"], "qty": int(x["qty"]), "note": memo_of.get(int(x["order_line_id"]), "")} + for x in receipt["lines"]] + total = sum(r["qty"] for r in rows) + who = sender_name or sender_email + when = fmt_date(receipt["receipt_date"]) + info = f"입고일 {when} · 발주번호 {order['order_no']} · 공장 {order['factory_name']}" + lead = "입고된 아래 리스트 상품을 전산 등록 부탁드립니다." + # 글 본문(HTML 을 못 보는 메일 프로그램용) + text = ["안녕하세요.", "", lead, "", info, "", "[입고 상품] 상품 이름 · 상품 코드 · 입고 수량 · 비고"] + text += [f"- {r['name']} · {r['code']} · {r['qty']:,}개" + (f" · {r['note']}" if r["note"] else "") for r in rows] + text.append(f"합계 {total:,}개") + if receipt.get("memo"): + text += ["", f"메모: {receipt['memo']}"] + if images or skipped: + text += ["", f"입고 인증 사진 {len(images)}장(본문 이미지)" + (f", 본문에 넣지 못한 사진 {skipped}장(HEIC 등)" if skipped else "")] + text += ["", f"입고 담당: {who} ({sender_email})"] + # HTML 본문 + e = _html.escape + td = "padding:6px 10px;border:1px solid #d9dce1;" + r_ = "text-align:right;white-space:nowrap;" + bg = "background:#f6f7f9;" + body_rows = "".join( + f'{e(r["name"])}{e(r["code"])}' + f'{r["qty"]:,}{e(r["note"])}' for r in rows) + imgs = "".join( + f'

입고 인증 사진 {i}

' + for i, im in enumerate(images, start=1)) + photo_block = "" + if images or skipped: + photo_block = (f'

입고 인증 사진 {len(images)}장

{imgs}' + + (f'

본문에 넣지 못한 사진 {skipped}장(HEIC 등) — ERP 입고 기록에서 볼 수 있습니다.

' if skipped else "")) + html = ( + '
' + f"

안녕하세요.
{e(lead)}

" + f'

{e(info)}

' + '' + f'' + f'{body_rows}' + f'' + f'
상품 이름상품 코드입고 수량비고
합계{total:,}
' + + (f'

메모: {e(str(receipt["memo"]))}

' if receipt.get("memo") else "") + + photo_block + + f'

입고 담당: {e(who)} ({e(sender_email)})

' + ) + return {"subject": receipt_mail_subject(receipt["receipt_date"]), "text": "\n".join(text), "html": html} + + +def inline_preview_html(html: str, images: list[dict[str, Any]]) -> str: + """미리보기 창용 — cid: 를 data: 로 바꿔 브라우저에서 바로 보이게(보내는 메일은 cid 그대로).""" + import base64 # noqa: WPS433 + + for im in images: + html = html.replace(f'src="cid:{_html.escape(im["cid"])}"', + f'src="data:image/jpeg;base64,{base64.b64encode(im["data"]).decode("ascii")}"') + return html diff --git a/app/modules/inout/templates/inout/_options_panel.html b/app/modules/inout/templates/inout/_options_panel.html index 0928649..42ac66a 100644 --- a/app/modules/inout/templates/inout/_options_panel.html +++ b/app/modules/inout/templates/inout/_options_panel.html @@ -5,6 +5,7 @@ +
@@ -126,4 +127,23 @@ {% endif %}
+ +

코드표(단품) 연결: {{ items_status }}

diff --git a/app/modules/inout/templates/inout/index.html b/app/modules/inout/templates/inout/index.html index 1861a7e..a6ef3da 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 %}
@@ -68,4 +68,4 @@
{% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/inout/templates/inout/order_detail.html b/app/modules/inout/templates/inout/order_detail.html index 32feac0..23856d5 100644 --- a/app/modules/inout/templates/inout/order_detail.html +++ b/app/modules/inout/templates/inout/order_detail.html @@ -1,6 +1,26 @@ {% extends "erp_base.html" %} {% from "inout/_macros.html" import status_badge, order_badge, progress, due, n, ymd, ymdhm %} -{% block head_extra %}{% endblock %} +{#- 메일 창(발주 메일 · 입고 요청 메일 같은 모양) — 열면 미리보기 GET, [메일 발송]을 눌러야 보낸다(inout.js initMail) -#} +{%- macro mail_dialog(id, title, open_url='', open_title='') -%} + +
+

{{ title }}

+ +
+ +

불러오는 중…

+ +
+{%- endmacro -%} +{% block head_extra %}{% endblock %} {% block content %} {% set active = order.status in ('open', 'partial') %} @@ -150,7 +170,7 @@ {% if order.receipts %}
- {% if photo_admin %}{% endif %} + {% if photo_admin %}{% endif %} {% for r in order.receipts %} @@ -174,6 +194,14 @@ {% elif not r.photos %}-{% endif %} + {% if photo_admin %} ")[1].split("")[0].split("2,000<", h) and self.assertIn(">500<", h) and self.assertIn(">2,500<", h) # 합계 + self.assertIn("흰 뚜껑", h) # 비고 = 발주 품목 줄 메모 + self.assertIn("<b>950ml</b>", h) and self.assertNotIn("950ml", h) + self.assertIn("박스 12개<파손 없음>", h) + self.assertIn('src="cid:inout-photo-1@dbx" width="600" height="450"', h) # 본문 안 이미지(첨부 아님) + self.assertLess(h.index("", ""]) + self.assertTrue(all(p.get_content_disposition() == "inline" and p.get_filename() is None for p in parts[1:])) + self.assertEqual(Image.open(io.BytesIO(parts[1].get_content())).size, (600, 450)) + self.assertEqual(list(msg.iter_attachments()), []) # 첨부 파일 없음 + plain = gmail.build_message(sender_name="K", sender_email="k@x.com", to=["a@x.com"], cc=[], subject="x", text="t", html="

h

") + self.assertEqual(email.message_from_bytes(plain, policy=policy.default).get_payload()[1].get_content_type(), "text/html") + + def test_clean_emails(self): + self.assertEqual(s.clean_emails("a@x.com;b@y.com a@x.com", label="x"), "a@x.com, b@y.com") + self.assertEqual(s.clean_emails("", label="x"), "") + with self.assertRaises(ValueError): + s.clean_emails("nope", label="물류센터") + + +class _Store: + """라우터가 부르는 것만 — 입고 1건(사진 1장)·설정·Gmail 연결.""" + + def __init__(self): + self.mails, self.saved, self.token = [], None, {"refresh_token_enc": "enc"} + self.settings = {"logistics_emails": "lg@x.com", "receipt_mail_cc": "king@dbxcorp.co.kr, bj@dbxcorp.co.kr"} + + def roles_of(self, email): + return {"receive"} + + def get_order(self, oid): + if oid != 7: + return None + return {**_order(), "receipts": [_receipt(mails=list(self.mails))]} + + def get_settings(self): + return dict(self.settings) + + def settings_ready(self): + return True + + def save_settings(self, values, *, by): + self.saved = (values, by) + + def receipt_photo_data(self, rid): + return [{"id": 5, "filename": "a.jpg", "content_type": "image/jpeg", "data": _jpeg(1000, 500)}] + + def gmail_token(self, email): + return self.token + + def mark_gmail(self, email, error=""): + pass + + def delete_gmail_token(self, email): + self.token = None + + def add_receipt_mail(self, rid, **kw): + self.mails.append({"sent_at": datetime(2026, 10, 19, 15, 0), "sent_by": kw["sent_by"], "to_addrs": ", ".join(kw["to"])}) + self.last = (rid, kw) + + +class ReceiptMailApiTests(unittest.TestCase): + def setUp(self): + import importlib + + from fastapi import FastAPI + from fastapi.testclient import TestClient + + self.api = importlib.import_module("app.modules.inout.router") + self.st = _Store() + app = FastAPI() + app.include_router(self.api.router) + app.state.inout_store = self.st + self.user = {"email": "wh@dbxcorp.co.kr", "name": "김물류", "role": "user"} + p1 = patch.object(self.api, "_user", lambda request: self.user) + p2 = patch.object(self.api, "_is_admin", lambda user: False) + p3 = patch.object(self.api, "_callback_url", lambda request: "https://erp/inout/gmail/callback") + for p in (p1, p2, p3): + p.start() + self.addCleanup(p.stop) + self.c = TestClient(app) + + def test_preview_defaults_and_photos_inline(self): + r = self.c.get("/inout/orders/7/receipts/3/mail") + self.assertEqual(r.status_code, 200, r.text) + d = r.json() + self.assertEqual((d["to"], d["cc"]), ("lg@x.com", "king@dbxcorp.co.kr, bj@dbxcorp.co.kr")) + self.assertEqual(d["subject"], "[입고 요청] 2026년 10월 19일(월) 입고 요청 합니다.") + self.assertTrue(d["connected"]) and self.assertEqual(d["photos"], 1) + self.assertIn('src="data:image/jpeg;base64,', d["html"]) and self.assertNotIn("cid:", d["html"]) + self.assertIn("rmail%3D3", d["connect_url"]) # 연결 뒤 이 입고 메일 창으로 돌아옴 + self.assertEqual(self.c.get("/inout/orders/7/receipts/99/mail").status_code, 404) + + def test_send_records_and_resend_guard(self): + sent = [] + + def fake_send(refresh, raw): + sent.append(email.message_from_bytes(raw, policy=policy.default)) + return "gm-1" + + with patch.object(gmail, "decrypt_token", lambda e, enc: "refresh"), patch.object(gmail, "send", fake_send): + r = self.c.post("/inout/orders/7/receipts/3/mail", json={"to": "lg@x.com", "cc": "king@dbxcorp.co.kr, bj@dbxcorp.co.kr"}) + self.assertEqual(r.status_code, 200, r.text) + self.assertEqual(self.st.last[0], 3) + self.assertEqual(self.st.last[1]["cc"], ["king@dbxcorp.co.kr", "bj@dbxcorp.co.kr"]) + msg = sent[0] + self.assertEqual(msg["To"], "lg@x.com") + related = msg.get_payload()[1] + self.assertEqual(related.get_content_type(), "multipart/related") + self.assertEqual(Image.open(io.BytesIO(related.get_payload()[1].get_content())).size, (600, 300)) + # 이미 보냄 → resend 없이는 409, resend=true 면 보냄 + r = self.c.post("/inout/orders/7/receipts/3/mail", json={"to": "lg@x.com"}) + self.assertEqual((r.status_code, r.json()["resend_needed"]), (409, True)) + r = self.c.post("/inout/orders/7/receipts/3/mail", json={"to": "lg@x.com", "resend": True}) + self.assertEqual(r.status_code, 200) and self.assertEqual(len(sent), 2) + self.assertEqual(self.c.post("/inout/orders/7/receipts/3/mail", json={"to": ""}).status_code, 400) + + def test_order_role_cannot_send_receipt_mail(self): + self.st.roles_of = lambda email: {"order"} + self.assertEqual(self.c.get("/inout/orders/7/receipts/3/mail").status_code, 403) + + def test_receive_role_may_connect_gmail(self): + p = self.api._perms(self.st, self.user) + self.assertEqual(self.api._require(self.st, self.user, "mail"), p) # 입고 담당도 Gmail 연결 + self.st.roles_of = lambda email: set() + with self.assertRaises(Exception): + self.api._require(self.st, self.user, "mail") + + +if __name__ == "__main__": + unittest.main()
입고일품목별 수량합계입고증입력
입고일품목별 수량합계입고증입력입고 요청 메일
{{ r.created_by }}
{{ ymdhm(r.created_at) }}
+ {% if r.mails %}{% set lm = r.mails[-1] %}보냄 {{ ymdhm(lm.sent_at) }} +
{{ lm.sent_by }}{% if r.mails|length > 1 %} · 모두 {{ r.mails|length }}번{% endif %}
{% endif %} + {% if perms.can_receive %} + {% elif not r.mails %}-{% endif %} +
@@ -205,23 +233,16 @@ {% if perms.can_order and not order.cancelled_at %} {# 발주 메일 — 열면 GET /inout/orders/{id}/mail 로 미리보기, [메일 발송]을 눌러야 보낸다(발주 담당 본인 Gmail) #} - -
-

발주 메일 보내기 · {{ order.order_no }}

- -
- -

불러오는 중…

-
- - - - -
-
+ {{ mail_dialog('io-mail', '발주 메일 보내기 · ' ~ order.order_no) }} + {% endif %} + {% if perms.can_receive and order.receipts %} + {# 입고 요청 메일(005) — 물류센터 입고 담당자에게 전산 등록 부탁(입고 담당 본인 Gmail). 입고 저장 뒤 ?rmail={입고 id} 면 바로 연다 #} + {% set open_r = order.receipts | selectattr('id', 'equalto', open_rmail) | list if open_rmail else [] %} + {% if open_r %} + {{ mail_dialog('io-rmail', '입고 요청 메일', '/inout/orders/' ~ order.id ~ '/receipts/' ~ open_r[0].id ~ '/mail', + '입고 요청 메일 · ' ~ ymd(open_r[0].receipt_date) ~ ' 입고 ' ~ n(open_r[0].total) ~ '개') }} + {% else %}{{ mail_dialog('io-rmail', '입고 요청 메일') }}{% endif %} {% endif %} {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/inout/templates/inout/order_form.html b/app/modules/inout/templates/inout/order_form.html index 5058f64..3a6a2ae 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 %}
@@ -80,4 +80,4 @@
{% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/inout/templates/inout/pending.html b/app/modules/inout/templates/inout/pending.html index 16556d9..833d28b 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 %}
@@ -88,4 +88,4 @@ {% endif %}
{% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/static/inout.css b/app/static/inout.css index 2e92ff3..2fe1088 100644 --- a/app/static/inout.css +++ b/app/static/inout.css @@ -286,3 +286,11 @@ .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; } + +/* 입고 요청 메일(005) — 입고 기록 칸 · 옵션 → 물류센터 */ +.io-rmail-cell { white-space: nowrap; } +.io-rmail-cell .io-rmail-btn { margin-top: 4px; } +.io-logi-form { display: grid; gap: 12px; max-width: 640px; } +.io-logi-field { display: grid; gap: 4px; } +.io-logi-field > span { font-weight: 600; } +.io-logi-field small { font-weight: 400; color: var(--color-midtone-gray, #777); } diff --git a/app/static/inout.js b/app/static/inout.js index 3a2aad5..e020822 100644 --- a/app/static/inout.js +++ b/app/static/inout.js @@ -4,7 +4,7 @@ · 발주서 화면: [남은 수량 모두 채우기], 이번 입고 합계 · 옵션 팝업(톱니): 담당자·공장 — 열 때 내용을 받고, 저장은 제자리 · 입고증 사진: 브라우저에서 줄여 올리기·미리보기·크게 보기, 입고 저장 전 초과 확인(사진이 사라지지 않게) - · 발주 메일: 미리보기 팝업 → [메일 발송](발주 담당 본인 Gmail), 처음엔 [Gmail 연결] + · 발주 메일·입고 요청 메일: 미리보기 팝업 → [메일 발송](보내는 사람 본인 Gmail), 처음엔 [Gmail 연결] · data-erp-confirm-btn: 버튼별 확인(formaction 이 있는 버튼 — 공용 data-erp-confirm 은 form.submit() 이라 누른 버튼이 사라짐) */ (function () { "use strict"; @@ -551,17 +551,34 @@ }); } - // ── 발주 메일(003) — 미리보기를 받아 보여 주고, [메일 발송]을 눌러야 보낸다 ── + // ── 메일 창 — 발주 메일(003)·입고 요청 메일(005) 공용. 미리보기를 받아 보여 주고, [메일 발송]을 눌러야 보낸다 ── + // 발주 메일: 머리 [발주 메일 보내기] → GET|POST /inout/orders/{id}/mail (발주 담당 본인 Gmail, 받는 사람 = 공장 이메일) + // 입고 요청 메일: 입고 저장 뒤 바로(?rmail=입고 id) 또는 입고 기록 줄 [보내기] → GET|POST …/receipts/{rid}/mail + // (입고 담당 본인 Gmail, 받는 사람 = 옵션 → 물류센터 이메일, 참조 기본 = 옵션 값, 본문에 입고증 사진) const mailBtn = document.getElementById("io-mail-btn"), mailDlg = document.getElementById("io-mail"); - if (mailBtn && mailDlg) initMail(mailBtn, mailDlg); + if (mailBtn && mailDlg) { + const om = initMail(mailDlg, { param: "mail", what: "발주 메일" }); + const url = "/inout/orders/" + mailBtn.dataset.order + "/mail"; + mailBtn.addEventListener("click", function () { om.open(url); }); + if (mailBtn.dataset.open === "1") om.open(url); + } + const rmailDlg = document.getElementById("io-rmail"); + if (rmailDlg) { + const rm = initMail(rmailDlg, { param: "rmail", what: "입고 요청 메일" }); + document.querySelectorAll(".io-rmail-btn").forEach(function (b) { + b.addEventListener("click", function () { rm.open(b.dataset.url, b.dataset.title); }); + }); + if (rmailDlg.dataset.openUrl) rm.open(rmailDlg.dataset.openUrl, rmailDlg.dataset.openTitle); + } - function initMail(btn, dlg) { - const body = document.getElementById("io-mail-body"), foot = document.getElementById("io-mail-foot"); - const msgEl = dlg.querySelector(".io-dlg-msg"), sendBtn = document.getElementById("io-mail-send"); - const base = "/inout/orders/" + btn.dataset.order + "/mail"; - let data = null, sent = false; + function initMail(dlg, cfg) { + const body = dlg.querySelector("[data-mail-body]"), foot = dlg.querySelector("[data-mail-foot]"); + const msgEl = dlg.querySelector(".io-dlg-msg"), sendBtn = dlg.querySelector("[data-mail-send]"); + const titleEl = dlg.querySelector("[data-mail-title]"); + let base = "", data = null, sent = false; function say(text, bad) { msgEl.textContent = text || ""; msgEl.hidden = !text; msgEl.classList.toggle("is-bad", !!bad); } function esc(s) { const d = document.createElement("div"); d.textContent = s == null ? "" : String(s); return d.innerHTML; } + function field(name) { return body.querySelector('[data-mail-field="' + name + '"]'); } async function load() { const res = await fetch(base, { headers: { Accept: "application/json" } }); data = await res.json(); @@ -569,7 +586,7 @@ if (!data.connected) { foot.hidden = true; body.innerHTML = '
' + - "

발주 메일은 내 Gmail(" + esc(data.from) + ")로 보냅니다. 처음 한 번만 Gmail 연결이 필요합니다.

" + + "

" + esc(cfg.what) + "은 내 Gmail(" + esc(data.from) + ")로 보냅니다. 처음 한 번만 Gmail 연결이 필요합니다.

" + "

구글 화면에서 같은 계정을 고르고 '메일 보내기' 권한을 허락하세요. 보내기 권한만 받으며, 메일함은 읽지 않습니다.

" + (data.configured ? "" : '

서버 설정(APP_ENCRYPTION_KEY·구글 OAuth)이 없어 연결할 수 없습니다 — 관리자에게 알려 주세요.

') + 'Gmail 연결' + @@ -580,29 +597,41 @@ return; } foot.hidden = false; + const receipt = data.kind === "receipt"; const sentList = (data.sent || []).map(function (m) { return "
  • " + esc(m.at) + " · " + esc(m.by) + " → " + esc(m.to) + "
  • "; }).join(""); + let hint = ""; + if (!data.to) { + hint = receipt ? "물류센터 담당자 이메일이 옵션에 없습니다 — 받는 사람을 직접 넣거나, 관리자가 옵션 → 물류센터에 넣어 두세요." + : (data.factory || "공장") + " 이메일이 옵션에 없습니다 — 받는 사람을 직접 넣거나, 관리자가 옵션 → 공장에 넣어 두세요."; + } + if (receipt && data.ready === false) hint += (hint ? " " : "") + "(DB 마이그레이션 005 전이라 보낸 기록이 남지 않습니다.)"; body.innerHTML = '
    ' + "" + - "" + - "" + + "" + + "" + "
    " + - (data.to ? "" : '

    ' + esc(data.factory) + " 이메일이 옵션에 없습니다 — 받는 사람을 직접 넣거나, 관리자가 옵션 → 공장에 넣어 두세요.

    ") + + (hint ? '

    ' + esc(hint) + "

    " : "") + + (receipt && data.photos_skipped ? '

    HEIC 등 본문에 넣지 못하는 입고증 사진 ' + esc(data.photos_skipped) + "장은 빠집니다(입고 기록에는 그대로).

    " : "") + (sentList ? '
    보낸 기록
      ' + sentList + "
    " : "") + ''; body.querySelector(".io-mail-preview").srcdoc = data.html; sendBtn.textContent = (data.sent || []).length ? "다시 발송" : "메일 발송"; } - async function open() { + async function open(url, title) { + base = url; + if (title && titleEl) titleEl.textContent = title; say(""); sent = false; if (!dlg.open) dlg.showModal(); dlg.focus({ preventScroll: true }); body.innerHTML = '

    불러오는 중…

    '; + foot.hidden = true; try { await load(); } catch (err) { body.innerHTML = '

    ' + esc(err.message) + "

    "; foot.hidden = true; } } async function send(resend) { - const to = document.getElementById("io-mail-to").value, cc = document.getElementById("io-mail-cc").value; + const to = field("to").value, cc = field("cc").value; sendBtn.disabled = true; say("보내는 중…"); try { @@ -623,9 +652,8 @@ say("보내지 못했습니다(연결 오류). 다시 눌러 주세요.", true); } finally { sendBtn.disabled = false; } } - btn.addEventListener("click", open); sendBtn.addEventListener("click", function () { send(false); }); - document.getElementById("io-gmail-disconnect").addEventListener("click", async function () { + dlg.querySelector("[data-gmail-disconnect]").addEventListener("click", async function () { if (!(await confirmMsg("Gmail 연결을 끊을까요? 다음에 보낼 때 다시 연결해야 합니다."))) return; await fetch("/inout/gmail/disconnect", { method: "POST" }); await load(); @@ -634,12 +662,12 @@ dlg.addEventListener("click", function (e) { if (e.target.closest("[data-close]")) dlg.close(); }); dlg.addEventListener("close", function () { const url = new URL(location.href); - const had = url.searchParams.has("mail"); - url.searchParams.delete("mail"); + const had = url.searchParams.has(cfg.param); + url.searchParams.delete(cfg.param); url.searchParams.delete("msg"); - if (sent) location.href = url.toString(); // 머리의 '발주 메일' 기록이 바뀌었다 + if (sent) location.href = url.toString(); // 보낸 기록(머리·입고 기록 칸)이 바뀌었다 else if (had) history.replaceState(null, "", url.toString()); }); - if (btn.dataset.open === "1") open(); + return { open: open }; } })(); diff --git a/docs/DATABASES.md b/docs/DATABASES.md index c4428ec..7aaaa18 100644 --- a/docs/DATABASES.md +++ b/docs/DATABASES.md @@ -12,7 +12,7 @@ | `malaysia_stock_db` | 말레이시아 창고 재고관리 — 창고/아이템/세트 BOM/입출고 이력/일일 재고조사 | | `cafe24_db` | 카페24 연동 — OAuth 토큰/상품 캐시/상세페이지 버전/예약/감사·API 로그 | | `performance_db` | 실적(쇼핑몰 통합 매출) — 쇼핑몰 설정/수수료율 이력/API 인증정보(암호문)/연결 상태/매출 사건/동기화 기록 | -| `inout_db` | 입출고 관리 — 공장/발주 담당·입고 담당/발주서·발주 품목/입고·입고 품목/상품 정보(단가·무게·은 함유량, 004) (2026-10-16, 앱 계정 `inout_app`, `INOUT_DB_URL`, 초기화 `scripts/sql/inout_db_init.sql`, 상세 `docs/INOUT_MODULE.md`) | +| `inout_db` | 입출고 관리 — 공장/발주 담당·입고 담당/발주서·발주 품목/입고·입고 품목/상품 정보(단가·무게·은 함유량, 004)/모듈 설정(물류센터 이메일)·입고 요청 메일 기록(005) (2026-10-16, 앱 계정 `inout_app`, `INOUT_DB_URL`, 초기화 `scripts/sql/inout_db_init.sql`, 상세 `docs/INOUT_MODULE.md`) | --- diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 6a7c390..d9b3c4a 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -287,6 +287,17 @@ curl -s http://127.0.0.1:8080/inout/health # {"status":"ok"} — DSN 그다음 ERP 관리자 화면에서 쓸 사람에게 **입출고 관리** 권한 → 입출고 관리 → 옵션에서 공장·발주 담당·입고 담당 지정. 백업: 매일 `docker exec postgres-db pg_dump -U postgres inout_db > /var/backups/postgres/inout_db_$(date +%F).sql`. +## 입출고 관리 물류센터 이메일·입고 요청 메일 마이그레이션 (inout_db 005) + +005는 표 2개만 추가한다 — `inout_settings`(모듈 설정: 물류센터 담당자 이메일·입고 요청 메일 참조, 참조 기본값 `king@dbxcorp.co.kr, bj@dbxcorp.co.kr` 한 줄 넣음)· +`inout_receipt_mails`(입고 요청 메일 보낸 기록, 입고를 지우면 함께). 다시 실행 가능, 기존 데이터 변경 없음, 새 환경변수 없음(Gmail 은 003 과 같은 연결). +미적용이어도 입고·발주는 그대로 — 입고 요청 메일 미리보기·발송은 되지만(받는 사람 직접 입력) 옵션 → 물류센터 저장과 보낸 기록만 안 됨. +적용 뒤 옵션(톱니) → **물류센터** 탭에 물류센터 담당자 이메일을 넣는다. 입고 담당도 처음 한 번 [Gmail 연결]이 필요하다. + +```bash +cd /opt/www/main && git pull && docker exec postgres-db pg_dump -U postgres inout_db > ~/inout_db_before_005_$(date +%Y%m%d%H%M).sql && docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d inout_db < scripts/sql/inout_db_005_receipt_mail.sql && docker compose up --build -d --no-deps web +``` + ## 입출고 관리 상품 정보 마이그레이션 (inout_db 004) 004는 표 2개(`inout_products` 상품 정보 — 단가·무게(개당 g)·은 함유량(%), `inout_products_excluded` 지운 단품)와 diff --git a/docs/INOUT_MODULE.md b/docs/INOUT_MODULE.md index a731e32..f92687e 100644 --- a/docs/INOUT_MODULE.md +++ b/docs/INOUT_MODULE.md @@ -65,7 +65,7 @@ cupang·malaysia 와 같은 DSN). 화면에서 코드·이름으로 검색(`GET | `/inout/pending` | 미입고 현황 — 요약 숫자, 제품별 합계, 발주별, 초과 입고 | | `/inout/orders/new`, `/{id}/edit` | 발주서 폼 — 공장·발주일·입고 예정일·메모, 제품 줄(검색 드롭다운·수량·**단가·금액**·줄 메모), 합계(수량·종·금액) | | `/inout/orders/{id}` | 발주서 — 품목별 발주·(발주 담당) **단가·금액·PP(g/개)·은(Ag)** ·입고·미입고·상태 + 합계 줄(금액·PP kg·은 g), **이번 입고** 칸(입고 담당) + [남은 수량 모두 채우기], 입고 기록, 종결·취소. 입고 담당만이면 이름·발주 수량만 | -| 톱니 → 옵션 팝업 | 관리자만. 탭 **담당자**(발주·입고 체크) · **공장**(이름·담당자·연락처·메모·순서·사용, 발주 기록 없을 때만 지우기) · **상품 정보**(6-3). 내용은 `GET /inout/settings?panel=1`, 저장은 팝업 안에서(`X-Inout-Options: 1` → JSON, 같은 탭 그대로 다시 그림), 바뀐 게 있으면 닫을 때 화면 새로고침. 예전 주소 `/inout/settings` = 목록으로 가서 팝업(`?options=1`) | +| 톱니 → 옵션 팝업 | 관리자만. 탭 **담당자**(발주·입고 체크) · **공장**(이름·담당자·연락처·메모·순서·사용, 발주 기록 없을 때만 지우기) · **상품 정보**(6-3) · **물류센터**(6-4). 내용은 `GET /inout/settings?panel=1`, 저장은 팝업 안에서(`X-Inout-Options: 1` → JSON, 같은 탭 그대로 다시 그림), 바뀐 게 있으면 닫을 때 화면 새로고침. 예전 주소 `/inout/settings` = 목록으로 가서 팝업(`?options=1`) | 화면은 서버 폼(POST → 303 + `?msg=` 안내). `static/inout.js` 는 입력 보조만(제품 검색 드롭다운 — `position: fixed` 로 body 에 붙여 표 가로 스크롤에 잘리지 않음, 줄 추가·삭제·합계, 남은 수량 채우기, 버튼별 확인 `data-erp-confirm-btn`). @@ -89,6 +89,8 @@ cupang·malaysia 와 같은 DSN). 화면에서 코드·이름으로 검색(`GET | `inout_products_excluded` | 상품 정보에서 지운 단품(004) — 다음 불러오기에서 빠진다 | | `inout_receipts` | 입고 1건(한 번 들어온 것) — 입고일·메모·입력자 | | `inout_receipt_lines` | 입고 품목별 수량 | +| `inout_settings` | 모듈 설정(005) — `logistics_emails`(물류센터 담당자 이메일)·`receipt_mail_cc`(입고 요청 메일 참조) | +| `inout_receipt_mails` | 입고 요청 메일 보낸 기록(005, 입고 1건마다, 입고 지우면 CASCADE) | 마이그레이션 `inout_db_002_factory_manager.sql`(2026-10-16): `manager` 열 추가, 예전 한 칸에 숫자 없이 이름만 있던 값은 담당자로 옮김(숫자가 있으면 연락처로 둠). 002 미적용이어도 발주서 화면은 열리고(담당자 = `to_jsonb(f)->>'manager'`), 공장 저장만 "002 필요" 안내. @@ -157,10 +159,33 @@ cupang·malaysia 와 같은 DSN). 화면에서 코드·이름으로 검색(`GET 칸 수가 홀수면 마지막 쌍은 빈 칸, **요청 사항**(메모, 길 수 있음)은 맨 아래 한 줄 전체(`colspan=3`). 글 본문(HTML 못 보는 메일 프로그램용)도 같은 값. 발주서 화면 표는 그대로. - 004 미적용이면 탭에 "마이그레이션 004 필요" 안내, 발주서는 예전처럼 코드표에서(`products_ready`). +## 6-4. 입고 요청 메일 — 물류센터 전산 등록 부탁(2026-10-19, 마이그레이션 005) + +- **왜**(사용자 요청): 물류에 들어온 입고를 물류센터 입고 담당자가 전산에 등록하도록, 입고 담당이 입고를 저장하면 메일로 알린다. +- **옵션 → 물류센터 탭**(관리자): 물류센터 담당자 이메일(받는 사람, 여러 개 쉼표)·입고 요청 메일 참조(기본 `king@dbxcorp.co.kr, bj@dbxcorp.co.kr` — 005 가 넣음). + `POST /inout/settings/logistics`, 주소 검사(`store.clean_emails`), `inout_settings` 키·값. 005 미적용이면 탭에 안내·저장 버튼 꺼짐. +- **흐름**: 입고 담당이 [입고 저장] → `/inout/orders/{id}?rmail={입고 id}` 로 돌아오며 **미리보기 팝업이 바로 뜬다**(발주 메일과 같은 창 모양, `inout.js initMail` 공용). + 사람이 **[메일 발송]**을 눌러야 보낸다. 입고 기록 표의 **입고 요청 메일** 칸 = 마지막 보낸 시각·사람 + [보내기 / 다시 보내기](입고 담당). + 이미 보낸 입고는 `resend: true` 확인(409 → "다시 보낼까요?"). +- **보내는 계정** = 누른 사람(입고 담당)의 Gmail — 발주 메일과 같은 연결(`inout_gmail_tokens`). Gmail 연결(`/inout/gmail/connect·callback`) 권한을 + 발주 담당만 → **발주 담당 또는 입고 담당**으로 넓혔다(`_require(…, "mail")`). 연결 후 돌아오는 곳 = 그 입고의 메일 창(`?rmail=`). +- **제목** `[입고 요청] 2026년 10월 19일(월) 입고 요청 합니다.` — 입고일, 월·일 두 자리(`store.receipt_mail_subject`). +- **본문**(`store.receipt_mail`) = 인사 · "입고된 아래 리스트 상품을 전산 등록 부탁드립니다." · 입고일·발주번호·공장 한 줄 · + 표 **상품 이름 · 상품 코드 · 입고 수량 · 비고**(비고 = 그 발주 품목의 줄 메모) + 합계 · 입고 메모 · **맨 아래 입고 인증 사진** · 입고 담당. + HTML + 글 본문, 값은 모두 escape. +- **사진 = 본문 안 이미지(첨부 아님)**: 보낼 때 `gmail.build_message(inline_images=)` 가 HTML 쪽을 `multipart/related` 로 만들고 사진을 + `Content-ID` + `Content-Disposition: inline`(파일 이름 없음)으로 붙인다 → ``. Gmail·Outlook 은 본문 안에 그린다 + (data: URI 는 Gmail 이 막아서 쓰지 않음). 크기는 서버가 **가로 최대 600px, 세로는 비율대로** JPEG(품질 85)로 다시 만든다(`store.mail_images` — + Pillow, EXIF 회전 반영, 투명 PNG 는 흰 바탕, 큰 JPEG 는 draft 로 빨리 읽음). img 에도 width·height 를 적는다. HEIC 등 서버가 못 여는 사진은 빼고 + "본문에 넣지 못한 사진 n장" 안내(입고 기록 사진은 그대로). 10장 × 600px ≈ 1MB 안팎이라 Gmail API 요청 크기 걱정 없음. +- **미리보기**(`GET …/receipts/{rid}/mail`)는 cid 를 data: 로 바꾼 HTML(`store.inline_preview_html`)을 sandbox iframe 에 — 보내는 메일은 cid 그대로. +- **권한**: 미리보기·발송 = 입고 담당(관리자 포함). 발주 담당만인 사람은 403. +- **005 미적용**: 미리보기·발송은 되고(받는 사람은 직접 입력, 참조는 기본값), 보낸 기록·옵션 저장만 안 됨(창에 안내). + ## 7. 테스트 ```bash -python -m pytest tests/test_inout_store.py tests/test_inout_mail_photo.py tests/test_inout_web.py # DB 없이(상태·검사·메일 본문·Gmail·사진) +python -m pytest tests/test_inout_store.py tests/test_inout_mail_photo.py tests/test_inout_receipt_mail.py tests/test_inout_web.py # DB 없이(상태·검사·메일 본문·Gmail·사진·입고 요청 메일) INOUT_TEST_DB_URL=postgresql://inout_app:@127.0.0.1:5432/inout_db \ python -m pytest tests/test_inout_db.py tests/test_inout_web.py # 로컬 테스트 DB(초기화 SQL 적용, 앱 계정 — 권한도 확인) ``` diff --git a/scripts/sql/inout_db_005_receipt_mail.sql b/scripts/sql/inout_db_005_receipt_mail.sql new file mode 100644 index 0000000..318575f --- /dev/null +++ b/scripts/sql/inout_db_005_receipt_mail.sql @@ -0,0 +1,45 @@ +-- ===================================================================== +-- inout_db 마이그레이션 005 — 물류센터 담당자 이메일 · 입고 요청 메일(2026-10-19) +-- ===================================================================== +-- 멱등(idempotent). 표 추가만, 기존 값 변경·삭제 없음. 운영: /opt/www/main 에서 기존 inout_db 에 적용(백업 먼저). +-- +-- 왜(사용자 요청): +-- ① 옵션에서 물류센터 입고 담당자 이메일을 등록한다(+ 입고 요청 메일 참조 기본값 — king@·bj@dbxcorp.co.kr). +-- ② 입고 담당이 입고를 저장하면 미리보기를 보고 [메일 발송]을 눌러 물류센터에 "입고 요청"(전산 등록 부탁) 메일을 +-- 입고 담당 본인 Gmail 로 보낸다(발주 메일과 같은 Gmail 연결). 본문 = 입고 상품 표 + 입고증 사진(본문 안 이미지). +-- 보낸 기록을 남긴다(다시 보낼 때 확인). +-- 되돌리기: 백업에서 복원(새 표만 생기므로 남아 있어도 이전 앱은 동작). +-- ===================================================================== +\set ON_ERROR_STOP on +BEGIN; + +-- ① 모듈 설정(키·값) — logistics_emails(물류센터 입고 담당 이메일, 쉼표) · receipt_mail_cc(입고 요청 메일 참조) +CREATE TABLE IF NOT EXISTS inout_settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL DEFAULT '', + updated_by TEXT NOT NULL DEFAULT '', + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +COMMENT ON TABLE inout_settings IS '입출고 — 모듈 설정(물류센터 이메일 등)'; +INSERT INTO inout_settings (key, value) VALUES ('receipt_mail_cc', 'king@dbxcorp.co.kr, bj@dbxcorp.co.kr') + ON CONFLICT (key) DO NOTHING; + +-- ② 입고 요청 메일 보낸 기록(입고 1건마다) +CREATE TABLE IF NOT EXISTS inout_receipt_mails ( + id BIGSERIAL PRIMARY KEY, + receipt_id BIGINT NOT NULL REFERENCES inout_receipts(id) ON DELETE CASCADE, + sent_by TEXT NOT NULL, + to_addrs TEXT NOT NULL, + cc_addrs TEXT NOT NULL DEFAULT '', + subject TEXT NOT NULL, + gmail_id TEXT NOT NULL DEFAULT '', + sent_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX IF NOT EXISTS idx_inout_receipt_mails_receipt ON inout_receipt_mails (receipt_id, sent_at); +COMMENT ON TABLE inout_receipt_mails IS '입출고 — 입고 요청 메일(물류센터) 보낸 기록'; + +GRANT SELECT, INSERT, UPDATE, DELETE ON inout_settings, inout_receipt_mails TO inout_app; +GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO inout_app; + +COMMIT; +SELECT 'inout_db 005 receipt mail ready' AS status; diff --git a/scripts/sql/inout_db_init.sql b/scripts/sql/inout_db_init.sql index 780d177..b2f0cd0 100644 --- a/scripts/sql/inout_db_init.sql +++ b/scripts/sql/inout_db_init.sql @@ -216,13 +216,40 @@ ALTER TABLE inout_order_lines ADD COLUMN IF NOT EXISTS unit_price NUMERIC(14,2) ALTER TABLE inout_order_lines ADD COLUMN IF NOT EXISTS weight_g NUMERIC(12,2) NULL; ALTER TABLE inout_order_lines ADD COLUMN IF NOT EXISTS silver_pct NUMERIC(9,4) NULL; +-- ════════════════════════════════════════════════════════════ +-- 7) 모듈 설정(물류센터 이메일·입고 요청 메일 참조) · 입고 요청 메일 기록 (= 마이그레이션 005) +-- ════════════════════════════════════════════════════════════ +CREATE TABLE IF NOT EXISTS inout_settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL DEFAULT '', + updated_by TEXT NOT NULL DEFAULT '', + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +COMMENT ON TABLE inout_settings IS '입출고 — 모듈 설정(물류센터 이메일 등)'; +INSERT INTO inout_settings (key, value) VALUES ('receipt_mail_cc', 'king@dbxcorp.co.kr, bj@dbxcorp.co.kr') + ON CONFLICT (key) DO NOTHING; + +CREATE TABLE IF NOT EXISTS inout_receipt_mails ( + id BIGSERIAL PRIMARY KEY, + receipt_id BIGINT NOT NULL REFERENCES inout_receipts(id) ON DELETE CASCADE, + sent_by TEXT NOT NULL, + to_addrs TEXT NOT NULL, + cc_addrs TEXT NOT NULL DEFAULT '', + subject TEXT NOT NULL, + gmail_id TEXT NOT NULL DEFAULT '', + sent_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX IF NOT EXISTS idx_inout_receipt_mails_receipt ON inout_receipt_mails (receipt_id, sent_at); +COMMENT ON TABLE inout_receipt_mails IS '입출고 — 입고 요청 메일(물류센터) 보낸 기록'; + -- ════════════════════════════════════════════════════════════ -- 권한 — 앱 계정은 읽기·쓰기만(스키마 변경 없음) -- ════════════════════════════════════════════════════════════ GRANT USAGE ON SCHEMA public TO inout_app; GRANT SELECT, INSERT, UPDATE, DELETE ON inout_factories, inout_roles, inout_orders, inout_order_lines, inout_receipts, inout_receipt_lines, - inout_gmail_tokens, inout_order_mails, inout_receipt_photos, inout_products, inout_products_excluded + inout_gmail_tokens, inout_order_mails, inout_receipt_photos, inout_products, inout_products_excluded, + inout_settings, inout_receipt_mails TO inout_app; GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO inout_app; diff --git a/tests/test_inout_db.py b/tests/test_inout_db.py index 48594a4..5a523bd 100644 --- a/tests/test_inout_db.py +++ b/tests/test_inout_db.py @@ -227,6 +227,36 @@ class InoutDbTests(unittest.TestCase): self.st.delete_gmail_token(me) self.assertIsNone(self.st.gmail_token(me)) + def test_logistics_settings_and_receipt_mail_log(self): + """005 — 물류센터 이메일·참조 설정(기본 참조 king@·bj@), 입고 사진 내용 읽기, 입고 요청 메일 기록(입고 지우면 함께).""" + from app.modules.inout import store + + if not self.st.settings_ready(): + self.skipTest("inout_db 005 미적용") + before = self.st.get_settings() + try: + self.assertEqual(before[store.SETTING_RECEIPT_MAIL_CC] or store.SETTING_DEFAULTS[store.SETTING_RECEIPT_MAIL_CC], + before[store.SETTING_RECEIPT_MAIL_CC]) + self.st.save_settings({store.SETTING_LOGISTICS_EMAILS: "lg@x.com, lg2@x.com", store.SETTING_RECEIPT_MAIL_CC: "c@x.com"}, + by="Admin@X") + got = self.st.get_settings() + self.assertEqual((got["logistics_emails"], got["receipt_mail_cc"]), ("lg@x.com, lg2@x.com", "c@x.com")) + o = self.order([("MT-R", 5)]) + ids = self.line_ids(o["id"]) + jpeg = b"\xff\xd8\xff\xe0" + b"1" * 50 + rid = self.st.add_receipt(o["id"], {ids["MT-R"]: "5"}, receipt_date="2026-10-19", memo="", confirm_over=False, by="w@x", + photos=store.validate_photos([("a.jpg", jpeg)]))["id"] + data = self.st.receipt_photo_data(rid) + self.assertEqual([(bytes(p["data"]), p["content_type"]) for p in data], [(jpeg, "image/jpeg")]) + self.assertEqual(self.st.get_order(o["id"])["receipts"][0]["mails"], []) + self.st.add_receipt_mail(rid, sent_by="W@X.com", to=["lg@x.com"], cc=["c@x.com"], subject="[입고 요청] x", gmail_id="g1") + r = self.st.get_order(o["id"])["receipts"][0] + self.assertEqual([(m["sent_by"], m["to_addrs"], m["cc_addrs"], m["gmail_id"]) for m in r["mails"]], + [("w@x.com", "lg@x.com", "c@x.com", "g1")]) + self.st.delete_receipt(o["id"], rid, by="w@x") # 입고를 지우면 메일 기록도 함께(CASCADE) + self.assertEqual(self.st.get_order(o["id"])["receipts"], []) + finally: + self.st.save_settings({k: before[k] for k in store.SETTING_DEFAULTS}, by="test") def test_times_are_kst(self): """TIMESTAMPTZ 는 한국 시각으로 읽힌다(화면·메일에 찍는 입력·보낸 시각) — DB 서버 시간대와 무관.""" diff --git a/tests/test_inout_receipt_mail.py b/tests/test_inout_receipt_mail.py new file mode 100644 index 0000000..7202d95 --- /dev/null +++ b/tests/test_inout_receipt_mail.py @@ -0,0 +1,230 @@ +"""입출고 005 — 입고 요청 메일(물류센터): 제목·본문 표·본문 안 사진(가로 600px, CID)·옵션 저장·미리보기/발송 API. DB·구글 없이.""" +import email +import io +import unittest +from datetime import date, datetime +from email import policy +from unittest.mock import patch + +from PIL import Image + +from app.modules.inout import gmail +from app.modules.inout import store as s + + +def _jpeg(w, h, color=(200, 30, 30)): + buf = io.BytesIO() + Image.new("RGB", (w, h), color).save(buf, "JPEG") + return buf.getvalue() + + +def _png_alpha(w, h): + buf = io.BytesIO() + Image.new("RGBA", (w, h), (0, 0, 255, 128)).save(buf, "PNG") + return buf.getvalue() + + +HEIC = b"\x00\x00\x00\x18ftypheic" + b"0" * 64 + + +def _order(): + return {"id": 7, "order_no": "PO-261019-01", "factory_name": "엘리화학", "cancelled_at": None, + "lines": [{"id": 11, "item_code": "MW-0320", "item_name": "미라클 통 황토 320ml", "qty": 5000, "memo": "흰 뚜껑"}, + {"id": 12, "item_code": "MW-0950", "item_name": "950ml", "qty": 10000, "memo": ""}]} + + +def _receipt(**over): + r = {"id": 3, "receipt_date": date(2026, 10, 19), "memo": "박스 12개<파손 없음>", "mails": [], + "lines": [{"order_line_id": 11, "item_code": "MW-0320", "item_name": "미라클 통 황토 320ml", "qty": 2000}, + {"order_line_id": 12, "item_code": "MW-0950", "item_name": "950ml", "qty": 500}]} + r.update(over) + return r + + +class ReceiptMailTests(unittest.TestCase): + def test_subject_format(self): + self.assertEqual(s.receipt_mail_subject(date(2026, 10, 19)), "[입고 요청] 2026년 10월 19일(월) 입고 요청 합니다.") + self.assertEqual(s.receipt_mail_subject(date(2026, 3, 1)), "[입고 요청] 2026년 03월 01일(일) 입고 요청 합니다.") + + def test_mail_images_resize_to_600_keep_ratio(self): + photos = [{"id": 1, "data": _jpeg(2000, 1500)}, {"id": 2, "data": _jpeg(400, 900)}, + {"id": 3, "data": _png_alpha(1200, 300)}, {"id": 4, "data": HEIC}] + imgs, skipped = s.mail_images(photos) + self.assertEqual(skipped, 1) # HEIC 은 서버가 못 연다 → 뺌 + self.assertEqual([(i["width"], i["height"]) for i in imgs], [(600, 450), (400, 900), (600, 150)]) + self.assertEqual([i["cid"] for i in imgs], ["inout-photo-1@dbx", "inout-photo-2@dbx", "inout-photo-3@dbx"]) + for i in imgs: + im = Image.open(io.BytesIO(i["data"])) + self.assertEqual((im.format, im.size), ("JPEG", (i["width"], i["height"]))) + + def test_mail_images_respects_exif_rotation(self): + im = Image.new("RGB", (1600, 1200), (10, 200, 10)) + exif = im.getexif() + exif[0x0112] = 6 # 시계 방향 90° — 휴대폰 세로 사진 + buf = io.BytesIO() + im.save(buf, "JPEG", exif=exif.tobytes()) + imgs, _ = s.mail_images([{"id": 9, "data": buf.getvalue()}]) + self.assertEqual((imgs[0]["width"], imgs[0]["height"]), (600, 800)) + + def test_body_table_photos_and_escaping(self): + imgs, _ = s.mail_images([{"id": 1, "data": _jpeg(2000, 1500)}]) + m = s.receipt_mail(_order(), _receipt(), images=imgs, skipped=1, sender_name="김물류", sender_email="wh@dbxcorp.co.kr") + self.assertEqual(m["subject"], "[입고 요청] 2026년 10월 19일(월) 입고 요청 합니다.") + h = m["html"] + self.assertIn("입고된 아래 리스트 상품을 전산 등록 부탁드립니다.", h) + heads = [x.split("")[0].split(">")[-1] for x in h.split("