Files
dbx-main/app/modules/vacation/notify.py
T

227 lines
12 KiB
Python

"""휴가 메일(2026-10-27) — 제출·승인·반려 때 보낸다.
받는 사람(중복은 한 번):
제출 = 승인자 + 승인 통보자
승인 = 승인자 + 승인 통보자 + 신청자
반려 = 승인자 + 승인 통보자 + 신청자
협의 완료(협의자 모두 승인) = 승인자 + 승인 통보자 + 신청자
승인자 = 휴가 옵션의 승인자(없으면 vacation_approver 권한자 — ERP 관리자는 자동으로 넣지 않는다).
협의자(2026-11-02)가 있으면 제출 때 협의자마다 따로 한 통 — 자기 협의 내용만. 그 밖의 메일은 협의자 전체와 협의 내용을 싣는다.
보내는 사람 = 그 일을 한 사람(제출 = 신청자, 승인·반려 = 처리한 승인자)의 **본인 Gmail** — 입출고 발주 메일과 같은
Gmail 연결(inout_db `inout_gmail_tokens`, gmail.send 만, 사람마다 한 번 연결). 연결이 없거나 끊겼거나 Gmail 이 실패하면
회사 알림 메일(SMTP, app/mail.py)로 보내고 보낸 사람 이름·답장 주소를 그 사람으로 한다.
라우터가 요청을 끝낸 뒤 백그라운드(BackgroundTasks)로 부른다 — 메일이 실패해도 휴가 처리는 그대로, 결과는 vacation_mail_log.
"""
from __future__ import annotations
import logging
from datetime import date
from html import escape
from typing import Any, Iterable
from .store import HALF_LABELS
logger = logging.getLogger("app.vacation.notify")
EVENTS = ("submitted", "approved", "rejected", "consulted")
EVENT_WORD = {"submitted": "제출", "approved": "승인", "rejected": "반려", "consult_request": "협의 요청", "consulted": "협의 완료"}
EVENT_LEAD = {
"submitted": "휴가 신청이 제출되었습니다. 확인 후 승인해 주세요.",
"approved": "휴가가 승인되었습니다.",
"rejected": "휴가가 반려되었습니다.",
"consult_request": "휴가 협의 요청이 왔습니다. 내용을 확인하고 ERP 휴가 메뉴에서 협의 결재를 진행해 주세요.",
"consulted": "협의가 모두 끝났습니다. 확인 후 승인해 주세요.",
}
LEAD_WITH_CONSULTS = "휴가 신청이 제출되었습니다. 협의자가 모두 승인하면 결재할 수 있습니다."
_WEEKDAYS = "월화수목금토일"
def _norm(e: Any) -> str:
return str(e or "").strip().lower()
def _uniq(emails: Iterable[str]) -> list[str]:
out: list[str] = []
for e in emails:
e = _norm(e)
if "@" in e and e not in out:
out.append(e)
return out
def approver_emails(options: dict[str, Any], users: list[dict[str, Any]]) -> list[str]:
"""지금 승인자 — 옵션에 지정했으면 그 사람들, 아니면 vacation_approver 권한(칩)을 켠 사용자."""
chosen = _uniq(options.get("approvers") or [])
if chosen:
return chosen
return _uniq(u.get("email") for u in users if (u.get("modules") or {}).get("vacation_approver"))
def recipients(event: str, req: dict[str, Any], options: dict[str, Any], users: list[dict[str, Any]]) -> list[str]:
people = approver_emails(options, users) + _uniq(options.get("notifiers") or [])
if event in ("approved", "rejected", "consulted"):
people.append(req.get("owner") or "")
return _uniq(people)
def _md(iso: str) -> str:
try:
d = date.fromisoformat(str(iso)[:10])
except ValueError:
return str(iso or "")
return f"{d.month}/{d.day}({_WEEKDAYS[d.weekday()]})"
def period_text(req: dict[str, Any]) -> str:
s, e = req.get("start_date") or "", req.get("end_date") or ""
sh, eh = req.get("start_half") or "full", req.get("end_half") or "full"
if s == e:
return _md(s) + (f" {HALF_LABELS.get(sh, '')}" if sh != "full" else "")
a = _md(s) + (f" {HALF_LABELS.get(sh, '')}" if sh != "full" else "")
b = _md(e) + (f" {HALF_LABELS.get(eh, '')}" if eh != "full" else "")
return f"{a} ~ {b}"
def _days(v: Any) -> str:
try:
f = float(v)
except (TypeError, ValueError):
return str(v or "")
return str(int(f)) if f == int(f) else f"{f:g}"
def build(event: str, req: dict[str, Any], *, actor_name: str, actor_email: str, link: str,
name_of: Any = None, consult: dict[str, Any] | None = None) -> dict[str, str]:
"""제목·글·HTML. 사용자 글(사유·반려 사유·이름)은 HTML 에서 늘 escape.
협의 요청(consult_request)은 받는 협의자 한 명 몫(consult)만, 나머지 메일은 협의자 전체(req["consults"])와 협의 내용을 싣는다."""
name_of = name_of or (lambda e: e)
owner = req.get("owner_name") or name_of(req.get("owner") or "")
word = EVENT_WORD[event]
consults = req.get("consults") or []
subject = f"[휴가 {word}] {owner} · {req.get('vacation_type', '')} {period_text(req)} ({_days(req.get('days'))}일)"
rows = [("신청자", f"{owner} ({req.get('owner', '')})"), ("종류", req.get("vacation_type") or ""),
("기간", period_text(req)), ("일수", f"{_days(req.get('days'))}일"), ("사유", req.get("reason") or "-")]
if event == "consult_request":
rows += [("상태", "협의 대기"), ("협의 내용", (consult or {}).get("message") or "-")]
elif event == "consulted":
rows.append(("상태", "협의 완료 — 승인 대기"))
elif event == "submitted":
rows.append(("상태", "협의 진행 중" if consults else "제출 — 승인 대기"))
else:
rows.append(("상태", word))
rows.append((f"{word}자", f"{actor_name} ({actor_email})"))
if event == "rejected":
rows.append(("반려 사유", req.get("reject_reason") or "-"))
if event != "consult_request":
rows += [(f"협의자 {c.get('name') or name_of(c.get('email') or '')}",
f"{c.get('state') or '대기'} — {c.get('message') or '협의 내용 없음'}") for c in consults]
lead = LEAD_WITH_CONSULTS if event == "submitted" and consults else EVENT_LEAD[event]
text = "\n".join([lead, ""] + [f"{k}: {v}" for k, v in rows] + ["", f"휴가 신청 보기: {link}"])
tr = "".join(
f'<tr><th style="text-align:left;padding:6px 12px 6px 0;color:#666;font-weight:600;white-space:nowrap;vertical-align:top">'
f'{escape(k)}</th><td style="padding:6px 0;white-space:pre-wrap">{escape(str(v))}</td></tr>' for k, v in rows)
color = {"approved": "#0f8a3a", "rejected": "#c22b10"}.get(event, "#1a56db")
html = (
'<div style="font-family:Pretendard,\'Malgun Gothic\',sans-serif;font-size:14px;color:#111;line-height:1.5">'
f'<p style="margin:0 0 12px;font-size:16px;font-weight:700;color:{color}">{escape(lead)}</p>'
f'<table style="border-collapse:collapse;margin:0 0 16px">{tr}</table>'
f'<p style="margin:0"><a href="{escape(link, quote=True)}" style="display:inline-block;padding:8px 14px;border-radius:6px;'
f'background:{color};color:#fff;text-decoration:none;font-weight:600">휴가 신청 보기</a></p>'
'<p style="margin:16px 0 0;color:#999;font-size:12px">DBX ERP 휴가 관리에서 보낸 메일입니다.</p></div>'
)
return {"subject": subject, "text": text, "html": html}
def _send_gmail(inout_store: Any, *, email: str, name: str, to: list[str], mail: dict[str, str]) -> tuple[bool, str]:
"""본인 Gmail 로 — (보냄, 못 보낸 까닭). 연결이 없으면 (False, '')."""
if inout_store is None:
return False, ""
try:
row = inout_store.gmail_token(email)
except Exception as exc: # noqa: BLE001 — 입출고 DB 장애여도 SMTP 로 대신
return False, f"Gmail 연결 조회 실패({type(exc).__name__})"
if not row:
return False, ""
from app.modules.inout import gmail # noqa: WPS433
try:
refresh = gmail.decrypt_token(email, row["refresh_token_enc"])
raw = gmail.build_message(sender_name=name, sender_email=email, to=to, cc=[], subject=mail["subject"],
text=mail["text"], html=mail["html"])
gmail.send(refresh, raw)
except gmail.GmailNotConnected as exc:
try:
inout_store.delete_gmail_token(email)
except Exception: # noqa: BLE001
pass
return False, str(exc)
except gmail.GmailError as exc:
try:
inout_store.mark_gmail(email, error=str(exc))
except Exception: # noqa: BLE001
pass
return False, str(exc)
try:
inout_store.mark_gmail(email)
except Exception: # noqa: BLE001
pass
return True, ""
def deliver(store: Any, inout_store: Any, *, event: str, req: dict[str, Any], actor: dict[str, Any],
users: list[dict[str, Any]], link: str) -> dict[str, Any]:
"""받는 사람을 정해 한 통 보내고 기록한다. 제출이면 협의자마다 자기 몫 협의 요청도 따로 한 통씩.
반환 {ok, via, to, error} (테스트·로그용, 협의 요청 제외)."""
if event not in EVENTS:
raise ValueError(event)
try:
options = store.get_options()
except Exception: # noqa: BLE001 — 001 미적용 등: 옵션 없음
options = {"approvers": [], "notifiers": []}
to = recipients(event, req, options, users)
names = {_norm(u.get("email")): u.get("name") or "" for u in users}
email = _norm(actor.get("email"))
name = actor.get("name") or names.get(email) or email.split("@")[0]
def name_of(e: Any) -> str:
return names.get(_norm(e)) or str(e).split("@")[0]
if event == "submitted":
for c in req.get("consults") or []:
mail = build("consult_request", req, actor_name=name, actor_email=email, link=link, name_of=name_of, consult=c)
_send_and_log(store, inout_store, "consult_request", req, _uniq([c.get("email")]), mail, email, name)
result: dict[str, Any] = {"ok": False, "via": "", "to": to, "error": ""}
if not to:
result["error"] = "받는 사람 없음(승인자·통보자 미지정)"
logger.info("휴가 메일 받는 사람 없음 — %s %s", event, req.get("id"))
return result
mail = build(event, req, actor_name=name, actor_email=email, link=link, name_of=name_of)
return _send_and_log(store, inout_store, event, req, to, mail, email, name)
def _send_and_log(store: Any, inout_store: Any, event: str, req: dict[str, Any], to: list[str], mail: dict[str, str],
email: str, name: str) -> dict[str, Any]:
"""한 통 보내기 — 본인 Gmail, 안 되면 회사 SMTP. 결과는 vacation_mail_log 에."""
from app import mail as smtp # noqa: WPS433
result: dict[str, Any] = {"ok": False, "via": "", "to": to, "error": ""}
ok, gmail_err = _send_gmail(inout_store, email=email, name=name, to=to, mail=mail)
if ok:
result.update(ok=True, via="gmail")
else:
sent = smtp.send_email(to=to, subject=mail["subject"], body=mail["text"], html=mail["html"],
from_name=f"{name} (DBX ERP)", reply_to=email)
if sent:
err = f"Gmail 실패 → 회사 메일로 보냄: {gmail_err}" if gmail_err else ""
else:
smtp_err = "회사 알림 메일(SMTP) " + ("발송 실패" if smtp.mail_enabled() else "미설정")
err = f"{gmail_err} · {smtp_err}" if gmail_err else smtp_err
result.update(ok=bool(sent), via="smtp", error=err)
try:
store.add_mail_log(request_id=str(req.get("id") or ""), event=event, sender=email, via=result["via"],
recipients=to, subject=mail["subject"], ok=result["ok"], error=result["error"])
except Exception: # noqa: BLE001 — 기록 실패가 메일·휴가 처리를 막지 않게
logger.warning("휴가 메일 기록 실패 — %s %s", event, req.get("id"))
return result