"""휴가 메일(2026-10-27) — 제출·승인·반려 때 보낸다. 받는 사람(중복은 한 번): 제출 = 승인자 + 승인 통보자 승인 = 승인자 + 승인 통보자 + 신청자 반려 = 승인자 + 승인 통보자 + 신청자 승인자 = 휴가 옵션의 승인자(없으면 vacation_approver 권한자 — ERP 관리자는 자동으로 넣지 않는다). 보내는 사람 = 그 일을 한 사람(제출 = 신청자, 승인·반려 = 처리한 승인자)의 **본인 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") EVENT_WORD = {"submitted": "제출", "approved": "승인", "rejected": "반려"} EVENT_LEAD = { "submitted": "휴가 신청이 제출되었습니다. 확인 후 승인해 주세요.", "approved": "휴가가 승인되었습니다.", "rejected": "휴가가 반려되었습니다.", } _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"): 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) -> dict[str, str]: """제목·글·HTML. 사용자 글(사유·반려 사유·이름)은 HTML 에서 늘 escape.""" name_of = name_of or (lambda e: e) owner = req.get("owner_name") or name_of(req.get("owner") or "") word = EVENT_WORD[event] 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 == "submitted": rows.append(("상태", "제출 — 승인 대기")) else: rows.append(("상태", word)) rows.append((f"{word}자", f"{actor_name} ({actor_email})")) if event == "rejected": rows.append(("반려 사유", req.get("reject_reason") or "-")) text = "\n".join([EVENT_LEAD[event], ""] + [f"{k}: {v}" for k, v in rows] + ["", f"휴가 신청 보기: {link}"]) tr = "".join( f'' f'{escape(k)}{escape(str(v))}' for k, v in rows) color = {"submitted": "#1a56db", "approved": "#0f8a3a", "rejected": "#c22b10"}[event] html = ( '
' f'

{escape(EVENT_LEAD[event])}

' f'{tr}
' f'

휴가 신청 보기

' '

DBX ERP 휴가 관리에서 보낸 메일입니다.

' ) 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} (테스트·로그용).""" from app import mail as smtp # noqa: WPS433 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] 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=lambda e: names.get(_norm(e)) or str(e).split("@")[0]) 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