feat(inout): 물류센터 이메일 옵션 · 입고 저장 뒤 입고 요청 메일(Gmail, 본문 안 사진 600px)

- 옵션 → 물류센터 탭: 물류센터 담당자 이메일·입고 요청 메일 참조(기본 king@·bj@dbxcorp.co.kr)
- 입고 저장 → 미리보기 팝업 바로 → [메일 발송](입고 담당 본인 Gmail), 입고 기록 줄 보내기/다시 보내기
- 제목 "[입고 요청] yyyy년 mm월 dd일(요일) 입고 요청 합니다.", 본문 = 전산 등록 부탁 + 상품 이름·코드·입고 수량·비고 표
- 입고증 사진은 첨부가 아니라 본문 안 이미지(CID multipart/related), 가로 최대 600px·비율 유지로 줄임
- Gmail 연결 권한을 발주 담당 → 발주·입고 담당으로
- 마이그레이션 inout_db 005(inout_settings·inout_receipt_mails), 초기화 SQL 에도 반영

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-19 13:33:46 +09:00
parent b95d3909a4
commit 08fe894d1b
19 changed files with 794 additions and 53 deletions
+112 -3
View File
@@ -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)