feat(vacation): 휴가 옵션(승인자·승인 통보자) · 제출·승인·반려 메일(처리한 사람 본인 Gmail)

- /vacation/options(달력 [옵션], 수정 = ERP 관리자): 휴가 승인자(여러 명)·휴가 승인 통보자 — vacation_options(마이그레이션 001)
- 승인·반려 = 관리자 + 옵션 승인자(지정 시 그 사람만), 비우면 예전처럼 vacation_approver 권한자
- 메일(notify.py, 응답 뒤 백그라운드): 제출 = 승인자+통보자, 승인·반려 = 승인자+통보자+신청자
  보내는 사람 = 그 일을 한 사람 본인 Gmail(입출고와 같은 연결·같은 구글 콜백, _gmail_callback_vacation),
  없거나 실패하면 회사 SMTP(이름·Reply-To = 그 사람, app/mail.py reply_to 추가)
- vacation_mail_log → 상세 화면 "메일" 줄, 휴가 화면 셸 오른쪽 넘침(border-box) 수정
- 테스트: test_vacation_options_mail.py(규칙·내용·Gmail→SMTP·실제 앱 권한·콜백), test_vacation_db.py(실제 PG)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-26 14:35:44 +09:00
parent 2cba5596a9
commit 09f6a2ee6f
19 changed files with 1120 additions and 15 deletions
+17
View File
@@ -5,3 +5,20 @@
- 월간 달력(구글식 bar) / 연차·반차 신청 / 승인 워크플로 / 공휴일·연차 설정.
- 권한키 `vacation`(사용)·`vacation_approver`(승인).
## 휴가 옵션 · 휴가 메일 (2026-10-27, 마이그레이션 `vacation_db_001_options_mail.sql`)
- **옵션** `/vacation/options`(달력 위 [옵션], 누구나 보기 · **수정 = ERP 관리자**): 휴가 승인자(여러 명) · 휴가 승인 통보자.
`vacation_options` 키 `approval` = `{"approvers": [...], "notifiers": [...]}`(`db.get_options`·`save_options`, 휴가 모듈 사용자만 고를 수 있음).
- **승인·반려 권한**(`router._is_approver`) = ERP 관리자 + 옵션 승인자(지정했으면 그 사람만), 승인자를 비우면 예전처럼 `vacation_approver` 권한자.
승인 대기 버튼·상세 조회·`_require_approver` 모두 이 한 곳.
- **메일**(`notify.py`, 응답 뒤 BackgroundTasks — 실패해도 휴가 처리는 그대로): 제출 = 승인자 + 통보자, 승인·반려 = 승인자 + 통보자 + 신청자
(승인자 미지정이면 `vacation_approver` 칩을 켠 사람 — 관리자는 자동으로 안 넣음, 중복 한 번). 제목 `[휴가 승인] 이름 · 종류 기간 (N일)`,
본문 표 + [휴가 신청 보기] 링크(`PUBLIC_BASE_URL`). 사유·반려 사유는 escape.
- **보내는 사람 = 그 일을 한 사람 본인 Gmail**(제출 = 신청자, 승인·반려 = 처리한 승인자) — **입출고와 같은 Gmail 연결**(inout_db `inout_gmail_tokens`,
gmail.send 만, 한 사람 = 연결 하나). 옵션 화면 [Gmail 연결] → `/vacation/gmail/connect`(세션 `_gmail_origin=vacation`) → 구글 →
**입출고 콜백 `/inout/gmail/callback` 이 휴가 권한으로 처리**(`inout.router._gmail_callback_vacation` — 구글 클라우드 리디렉션 주소 추가 없음) → 옵션으로.
연결이 없거나 끊김·Gmail 실패면 회사 SMTP(`app/mail.py`, 보낸 사람 이름 = "이름 (DBX ERP)"·Reply-To = 그 사람). 끊긴 토큰은 지움.
- **기록** `vacation_mail_log`(이벤트·보낸 사람·gmail|smtp·받는 사람·제목·성공·오류, 본문·토큰은 안 남김) → 상세 화면 "메일" 줄.
- 001 미적용이면 옵션 없음(예전 권한 규칙)·저장 503·기록 없음, 메일은 그대로 나감. 화면 `.erp-page:has(> .vac)` border-box(셸 오른쪽 48px 넘침).
- 테스트 `tests/test_vacation_options_mail.py`(규칙·내용·Gmail→SMTP·실제 앱 권한·콜백 분기), `tests/test_vacation_db.py`(실제 PG, `VACATION_TEST_DB_URL`).
+78
View File
@@ -27,6 +27,16 @@ from app.timezone import KST
from .store import EDITABLE_STATUSES, STATUSES, VACATION_TYPES, compute_days, normalize_half
def _email_list(value: Any) -> list[str]:
"""이메일 목록 정리 — 소문자·공백 제거·@ 있는 것만·중복 제거(순서 유지)."""
out: list[str] = []
for v in value or []:
e = str(v or "").strip().lower()
if "@" in e and e not in out:
out.append(e)
return out
class VacationDBStore:
def __init__(self, dsn: str, *, min_size: int = 1, max_size: int = 5):
self._pool = ConnectionPool(
@@ -41,6 +51,74 @@ class VacationDBStore:
def close(self) -> None:
self._pool.close()
# ════════════════════════════════════════════════════════════
# 옵션 · 메일 기록 (마이그레이션 001, 2026-10-27) — 테이블이 없으면 옵션 없음·기록 없음
# ════════════════════════════════════════════════════════════
OPTION_KEY = "approval"
def options_ready(self) -> bool:
with self._pool.connection() as conn:
row = conn.execute("SELECT to_regclass('public.vacation_options') AS r").fetchone()
return bool(row and row["r"])
def get_options(self) -> dict[str, Any]:
"""{"approvers": [이메일], "notifiers": [이메일], "updated_by", "updated_at", "ready": 001 적용 여부}."""
out: dict[str, Any] = {"approvers": [], "notifiers": [], "updated_by": "", "updated_at": "", "ready": False}
if not self.options_ready():
return out
out["ready"] = True
with self._pool.connection() as conn:
row = conn.execute("SELECT value, updated_by, updated_at FROM vacation_options WHERE key = %s",
(self.OPTION_KEY,)).fetchone()
if row:
value = row["value"] if isinstance(row["value"], dict) else {}
out["approvers"] = _email_list(value.get("approvers"))
out["notifiers"] = _email_list(value.get("notifiers"))
out["updated_by"] = row["updated_by"] or ""
if isinstance(row["updated_at"], datetime):
out["updated_at"] = row["updated_at"].astimezone(KST).isoformat(timespec="seconds")
return out
def save_options(self, *, approvers: list[str], notifiers: list[str], by: str) -> dict[str, Any]:
if not self.options_ready():
raise RuntimeError("휴가 옵션은 vacation_db_001 마이그레이션 뒤에 저장할 수 있습니다.")
from psycopg.types.json import Jsonb # noqa: WPS433
value = {"approvers": _email_list(approvers), "notifiers": _email_list(notifiers)}
with self._pool.connection() as conn:
conn.execute(
"INSERT INTO vacation_options (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()",
(self.OPTION_KEY, Jsonb(value), (by or "").lower().strip()),
)
return self.get_options()
def add_mail_log(self, *, request_id: str, event: str, sender: str, via: str, recipients: list[str],
subject: str, ok: bool, error: str = "") -> None:
if not self.options_ready():
return
with self._pool.connection() as conn:
conn.execute(
"INSERT INTO vacation_mail_log (request_id, event, sender, via, recipients, subject, ok, error) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
(request_id, event, (sender or "").lower(), via, ", ".join(recipients)[:2000], (subject or "")[:300],
bool(ok), (error or "")[:500]),
)
def list_mail_log(self, *, request_id: str) -> list[dict[str, Any]]:
if not self.options_ready():
return []
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT * FROM vacation_mail_log WHERE request_id = %s ORDER BY sent_at, id", (request_id,)).fetchall()
out = []
for r in rows:
d = dict(r)
if isinstance(d.get("sent_at"), datetime):
d["sent_at"] = d["sent_at"].astimezone(KST).isoformat(timespec="seconds")
out.append(d)
return out
# ════════════════════════════════════════════════════════════
# 공휴일 (vacation_holidays) — holiday provider
# ════════════════════════════════════════════════════════════
+196
View File
@@ -0,0 +1,196 @@
"""휴가 메일(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'<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 = {"submitted": "#1a56db", "approved": "#0f8a3a", "rejected": "#c22b10"}[event]
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(EVENT_LEAD[event])}</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} (테스트·로그용)."""
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
+195 -10
View File
@@ -2,7 +2,9 @@
- 경로: /vacation
- 권한: 로그인 + `vacation` 모듈 권한 (관리자는 항상 통과). 서버 측 검사.
승인/반려는 `vacation_approver` 또는 admin.
승인/반려 = admin + (휴가 옵션에 승인자를 지정했으면 그 사람들, 아니면 `vacation_approver` 권한자) — 2026-10-27.
- 휴가 옵션(`/vacation/options`, 수정은 admin): 승인자·승인 통보자. 제출·승인·반려 메일은 `notify.py`
(처리한 사람 본인 Gmail — 입출고와 같은 Gmail 연결, 없으면 회사 SMTP).
- 데이터: VacationDBStore (vacation_db / PostgreSQL) 전용.
VACATION_DB_URL 미설정 시 store 가 None 이며, 각 페이지는 "설정 필요" 안내를 보여준다.
"""
@@ -14,7 +16,7 @@ import io
from datetime import date
from typing import Any
from fastapi import APIRouter, Depends, Form, HTTPException, Request
from fastapi import APIRouter, BackgroundTasks, Depends, Form, HTTPException, Request
from fastapi.responses import (
HTMLResponse,
JSONResponse,
@@ -50,20 +52,62 @@ def _require_user(request: Request) -> dict[str, Any]:
def _require_approver(request: Request) -> dict[str, Any]:
from app.main import get_current_user_record # noqa: WPS433
from app.store import has_module, is_admin # noqa: WPS433
user = get_current_user_record(request)
if user is None:
raise HTTPException(status_code=401, detail="로그인이 필요합니다.")
if not (is_admin(user) or has_module(user, "vacation_approver")):
raise HTTPException(status_code=403, detail="휴가 승인자 권한이 필요합니다.")
if not _is_approver(request, user):
raise HTTPException(status_code=403, detail="휴가 승인자만 승인·반려할 수 있습니다(휴가 → 옵션에서 지정).")
return user
def _options(request: Request) -> dict[str, Any]:
"""휴가 옵션(승인자·통보자, 마이그레이션 001). DB·001 이 없으면 빈 옵션."""
st = _store(request)
if st is None:
return {"approvers": [], "notifiers": [], "ready": False}
try:
return st.get_options()
except Exception: # noqa: BLE001 — 옵션 조회 실패가 휴가 화면을 막지 않게(예전 규칙으로)
return {"approvers": [], "notifiers": [], "ready": False}
def _is_approver(request: Request, user: dict[str, Any]) -> bool:
"""승인·반려할 수 있나 — ERP 관리자 + 옵션의 승인자(지정했으면), 아니면 예전처럼 vacation_approver 권한자."""
from app.store import has_module, is_admin # noqa: WPS433
return is_admin(user) or has_module(user, "vacation_approver")
if is_admin(user):
return True
chosen = _options(request).get("approvers") or []
if chosen:
return str(user.get("email") or "").strip().lower() in chosen
return has_module(user, "vacation_approver")
def _vacation_users() -> list[dict[str, Any]]:
"""휴가 모듈을 쓰는 등록 사용자(옵션 후보·메일 이름) — 이름 순."""
from app.main import user_store # noqa: WPS433
from app.store import has_module # noqa: WPS433
out = [u for u in user_store.list_all() if has_module(u, "vacation")]
out.sort(key=lambda u: (u.get("name") or u["email"]).lower())
return out
def _notify(bg: BackgroundTasks, request: Request, event: str, req: dict[str, Any] | None,
actor: dict[str, Any]) -> None:
"""제출·승인·반려 메일을 응답 뒤 백그라운드로(notify.deliver — 받는 사람·보내는 사람 규칙은 그쪽)."""
from app.main import env # noqa: WPS433
from . import notify # noqa: WPS433
st = _store(request)
if st is None or not req:
return
base = (env("PUBLIC_BASE_URL") or str(request.base_url)).rstrip("/")
inout_store = getattr(request.app.state, "inout_store", None)
bg.add_task(notify.deliver, st, inout_store, event=event, req=req, actor=dict(actor),
users=_vacation_users(), link=f"{base}/vacation/{req['id']}")
def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLResponse:
@@ -344,6 +388,7 @@ def _payload_from_form(
@router.post("/new")
def create(
request: Request,
bg: BackgroundTasks,
vacation_type: str = Form(...),
start_date: str = Form(...),
end_date: str = Form(""),
@@ -369,6 +414,8 @@ def create(
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
if status == "제출":
_notify(bg, request, "submitted", req, user)
return RedirectResponse(url=f"/vacation/{req['id']}", status_code=303)
@@ -614,6 +661,129 @@ def health() -> dict[str, str]:
return {"status": "ok", "module": "vacation"}
# ────────────────────────────────────────────────────────────
# 휴가 옵션(2026-10-27) — 승인자·승인 통보자(수정 = ERP 관리자), 내 Gmail 연결(누구나 — 내가 보내는 휴가 메일)
# ────────────────────────────────────────────────────────────
def _gmail_state(request: Request, user: dict[str, Any]) -> dict[str, Any]:
from app import mail as smtp # noqa: WPS433
from app.modules.inout import gmail # noqa: WPS433
inout_store = getattr(request.app.state, "inout_store", None)
connected = False
if inout_store is not None:
try:
connected = inout_store.gmail_token(user["email"]) is not None
except Exception: # noqa: BLE001
connected = False
return {"available": inout_store is not None and gmail.configured(), "connected": connected,
"smtp": smtp.mail_enabled()}
@router.get("/options", response_class=HTMLResponse)
def options_page(request: Request) -> HTMLResponse:
from app.main import build_erp_nav, render_template # noqa: WPS433
from app.store import is_admin # noqa: WPS433
from . import notify # noqa: WPS433
guard = _guard(request)
if not isinstance(guard, tuple):
return guard
store, user = guard
opts = _options(request)
users = _vacation_users()
return render_template(
request,
"vacation/options.html",
{
"user": user,
"is_admin": is_admin(user),
"is_approver": _is_approver(request, user),
"nav_items": build_erp_nav(user, active="vacation"),
"page_title": "휴가 — 옵션",
"page_subtitle": "승인자 · 승인 통보자 · 메일",
"options": opts,
"candidates": [{"email": u["email"], "name": u.get("name") or u["email"].split("@")[0],
"picture": u.get("picture") or ""} for u in users],
"effective_approvers": notify.approver_emails(opts, users),
"gmail": _gmail_state(request, user),
"msg": request.query_params.get("msg", ""),
},
)
@router.post("/options")
def options_save(
request: Request,
approvers: list[str] = Form(default=[]),
notifiers: list[str] = Form(default=[]),
user: dict[str, Any] = Depends(_require_user),
) -> RedirectResponse:
from urllib.parse import urlencode # noqa: WPS433
from app.store import is_admin # noqa: WPS433
if not is_admin(user):
raise HTTPException(status_code=403, detail="휴가 옵션은 ERP 관리자만 바꿀 수 있습니다.")
store = _store(request)
if store is None:
raise HTTPException(status_code=503, detail="vacation_db 미설정")
allowed = {u["email"].lower() for u in _vacation_users()}
bad = [e for e in approvers + notifiers if e.strip().lower() not in allowed]
if bad:
raise HTTPException(status_code=400, detail="휴가 모듈 사용자만 고를 수 있습니다: " + ", ".join(bad))
try:
store.save_options(approvers=approvers, notifiers=notifiers, by=user["email"])
except RuntimeError as exc:
raise HTTPException(status_code=503, detail=str(exc))
return RedirectResponse(url="/vacation/options?" + urlencode({"msg": "옵션을 저장했습니다."}), status_code=303)
@router.get("/gmail/connect")
async def gmail_connect(request: Request) -> Any:
"""내 Gmail 연결 — 입출고와 같은 연결(같은 OAuth 클라이언트·같은 구글 리디렉션 주소 /inout/gmail/callback).
콜백은 세션 표시(_gmail_origin=vacation)를 보고 휴가 권한으로 처리한 뒤 휴가 옵션으로 돌아온다."""
from urllib.parse import urlencode # noqa: WPS433
from app.main import ALLOWED_DOMAIN, public_url_for # noqa: WPS433
from app.modules.inout import gmail # noqa: WPS433
user = _require_user(request)
if getattr(request.app.state, "inout_store", None) is None:
return RedirectResponse(url="/vacation/options?" + urlencode(
{"msg": "Gmail 연결 저장소(입출고 DB)가 설정되지 않아 연결할 수 없습니다 — 회사 메일로 보냅니다."}), status_code=303)
try:
client = gmail.oauth_client()
except gmail.GmailError as exc:
return RedirectResponse(url="/vacation/options?" + urlencode({"msg": str(exc)}), status_code=303)
request.session["_gmail_origin"] = "vacation"
request.session["_vacation_gmail_next"] = "/vacation/options"
return await client.authorize_redirect(
request, public_url_for(request, "inout_gmail_callback"),
access_type="offline", prompt="consent", include_granted_scopes="true",
login_hint=user.get("email", ""), hd=ALLOWED_DOMAIN)
@router.post("/gmail/disconnect")
def gmail_disconnect(request: Request) -> RedirectResponse:
from urllib.parse import urlencode # noqa: WPS433
from app.modules.inout import gmail # noqa: WPS433
user = _require_user(request)
inout_store = getattr(request.app.state, "inout_store", None)
if inout_store is not None:
row = inout_store.gmail_token(user["email"])
if row:
try:
gmail.revoke(gmail.decrypt_token(user["email"], row["refresh_token_enc"]))
except (gmail.GmailError, gmail.GmailNotConnected):
pass
inout_store.delete_gmail_token(user["email"])
return RedirectResponse(url="/vacation/options?" + urlencode(
{"msg": "Gmail 연결을 끊었습니다(입출고 발주 메일도 함께) — 이제 회사 메일로 보냅니다."}), status_code=303)
@router.get("/{request_id}", response_class=HTMLResponse)
def detail(request: Request, request_id: str) -> HTMLResponse:
from app.main import build_erp_nav, render_template # noqa: WPS433
@@ -652,10 +822,20 @@ def detail(request: Request, request_id: str) -> HTMLResponse:
"req": req,
"half_labels": HALF_LABELS,
"can_edit": is_owner and req["status"] in ("작성중", "반려"),
"mail_log": _mail_log(store, request_id),
"event_words": {"submitted": "제출", "approved": "승인", "rejected": "반려"},
},
)
def _mail_log(store: Any, request_id: str) -> list[dict[str, Any]]:
"""그 신청의 휴가 메일 기록(001) — 실패해도 상세 화면은 그대로."""
try:
return store.list_mail_log(request_id=request_id)
except Exception: # noqa: BLE001
return []
@router.get("/{request_id}/edit", response_class=HTMLResponse)
def edit_form(request: Request, request_id: str) -> HTMLResponse:
from app.main import render_template # noqa: WPS433
@@ -700,6 +880,7 @@ def edit_form(request: Request, request_id: str) -> HTMLResponse:
@router.post("/{request_id}/edit")
def update(
request: Request,
bg: BackgroundTasks,
request_id: str,
vacation_type: str = Form(...),
start_date: str = Form(...),
@@ -719,7 +900,7 @@ def update(
try:
store.update_request(request_id=request_id, owner=user["email"], payload=payload)
if action == "submit":
store.submit(request_id=request_id, owner=user["email"])
_notify(bg, request, "submitted", store.submit(request_id=request_id, owner=user["email"]), user)
except KeyError:
raise HTTPException(status_code=404, detail="휴가 신청을 찾을 수 없습니다.")
except PermissionError as exc:
@@ -733,13 +914,14 @@ def update(
def submit(
request: Request,
request_id: str,
bg: BackgroundTasks,
user: dict[str, Any] = Depends(_require_user),
) -> RedirectResponse:
store = _store(request)
if store is None:
raise HTTPException(status_code=503, detail="vacation_db 미설정")
try:
store.submit(request_id=request_id, owner=user["email"])
_notify(bg, request, "submitted", store.submit(request_id=request_id, owner=user["email"]), user)
except ValueError as exc:
raise HTTPException(status_code=409, detail=str(exc))
return RedirectResponse(url=f"/vacation/{request_id}", status_code=303)
@@ -749,13 +931,14 @@ def submit(
def approve(
request: Request,
request_id: str,
bg: BackgroundTasks,
user: dict[str, Any] = Depends(_require_approver),
) -> RedirectResponse:
store = _store(request)
if store is None:
raise HTTPException(status_code=503, detail="vacation_db 미설정")
try:
store.approve(request_id=request_id, approver_email=user["email"])
_notify(bg, request, "approved", store.approve(request_id=request_id, approver_email=user["email"]), user)
except ValueError as exc:
raise HTTPException(status_code=409, detail=str(exc))
return RedirectResponse(url=f"/vacation/{request_id}", status_code=303)
@@ -765,6 +948,7 @@ def approve(
def reject(
request: Request,
request_id: str,
bg: BackgroundTasks,
reject_reason: str = Form(...),
user: dict[str, Any] = Depends(_require_approver),
) -> RedirectResponse:
@@ -772,9 +956,10 @@ def reject(
if store is None:
raise HTTPException(status_code=503, detail="vacation_db 미설정")
try:
store.reject(
done = store.reject(
request_id=request_id, approver_email=user["email"], reason=reject_reason
)
_notify(bg, request, "rejected", done, user)
except ValueError as exc:
raise HTTPException(status_code=409, detail=str(exc))
return RedirectResponse(url=f"/vacation/{request_id}", status_code=303)
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20260530j" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027a" />{% endblock %}
{% block content %}
<section class="vac">
@@ -56,6 +56,24 @@
</div>
{% endif %}
{#- 휴가 메일 기록(2026-10-27, 001) — 제출·승인·반려 때 보낸 메일(받는 사람·보낸 사람·방법·결과) -#}
{% if mail_log %}
<div class="vac-detail-block vac-mail-log">
<div class="vac-detail-label">메일</div>
<ul>
{% for m in mail_log %}
<li class="{{ 'is-ok' if m.ok else 'is-fail' }}">
<span class="vac-mail-when">{{ m.sent_at[5:16] | replace('T', ' ') }}</span>
<b>{{ event_words.get(m.event, m.event) }}</b>
{{ '보냄' if m.ok else '못 보냄' }}
<span class="erp-muted">— {{ m.sender }}{% if m.via %} ({{ 'Gmail' if m.via == 'gmail' else '회사 메일' }}){% endif %} → {{ m.recipients or '받는 사람 없음' }}</span>
{% if m.error %}<span class="vac-mail-err">{{ m.error }}</span>{% endif %}
</li>
{% endfor %}
</ul>
</div>
{% endif %}
<div class="erp-page-actions vac-detail-actions">
<a class="erp-btn erp-btn-primary" href="/vacation/">◀◀ 달력</a>
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20260530i" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027a" />{% endblock %}
{% block content %}
<section class="vac">
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20260530i" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027a" />{% endblock %}
{% block content %}
<section class="vac">
@@ -18,6 +18,8 @@
{% if is_admin %}
<a class="erp-btn erp-btn-outline" href="/vacation/settings?year={{ year }}">설정</a>
{% endif %}
{#- 옵션(2026-10-27) — 승인자·승인 통보자(수정 = 관리자) · 내 Gmail 연결(누구나) -#}
<a class="erp-btn erp-btn-outline" href="/vacation/options">옵션</a>
</div>
<div class="vac-balance">
<span class="vac-bal-item">총 <strong>{{ balance.total_days }}</strong></span>
@@ -0,0 +1,87 @@
{% extends "erp_base.html" %}
{#- 휴가 옵션(2026-10-27) — 승인자·승인 통보자(수정 = ERP 관리자, 나머지는 보기만) + 내 Gmail 연결(누구나).
메일: 제출 = 승인자·통보자, 승인·반려 = 승인자·통보자·신청자. 보내는 사람 = 처리한 사람 본인 Gmail(없으면 회사 메일). -#}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027a" />{% endblock %}
{% block content %}
<section class="vac vac-options">
<div class="vac-actions">
<div class="vac-actions-main">
<a class="erp-btn erp-btn-outline" href="/vacation/">◀ 달력</a>
</div>
</div>
{% if msg %}<p class="vac-opt-msg" role="status">{{ msg }}</p>{% endif %}
{% if not options.ready %}
<p class="vac-opt-msg is-warn" role="alert">옵션 저장소가 아직 없습니다 — 관리자가 <code>scripts/sql/vacation_db_001_options_mail.sql</code> 을 적용하면 저장할 수 있습니다.
그 전에는 예전처럼 <b>휴가 승인자 권한</b>을 가진 사람이 승인하고, 메일 기록은 남지 않습니다.</p>
{% endif %}
<form method="post" action="/vacation/options" class="vac-opt-grid">
{% for key, title, hint in (
('approvers', '휴가 승인자', '제출된 휴가를 승인·반려합니다(여러 명이면 누구든 한 명). 비워 두면 관리자 화면의 "휴가 승인" 권한자가 승인합니다. ERP 관리자는 늘 승인할 수 있습니다.'),
('notifiers', '휴가 승인 통보자', '휴가가 제출·승인·반려될 때마다 메일을 받습니다(승인 권한은 없음).')) %}
{% set chosen = options[key] %}
<div class="erp-card vac-opt-card">
<div class="vac-card-head"><h2>{{ title }} <span class="erp-muted vac-opt-count">{{ chosen | length }}명</span></h2></div>
<p class="erp-muted vac-opt-hint">{{ hint }}</p>
{% if key == 'approvers' and not chosen %}
<p class="vac-opt-now">지금 승인자(권한자): {% if effective_approvers %}{{ effective_approvers | join(', ') }}{% else %}없음 — ERP 관리자만{% endif %}</p>
{% endif %}
<ul class="vac-opt-people">
{% for c in candidates %}
<li>
<label class="vac-opt-person{% if c.email in chosen %} is-on{% endif %}">
<input type="checkbox" name="{{ key }}" value="{{ c.email }}"{% if c.email in chosen %} checked{% endif %}{% if not is_admin or not options.ready %} disabled{% endif %} />
{% if c.picture %}<img class="vac-opt-face" src="{{ c.picture }}" alt="" referrerpolicy="no-referrer" />
{% else %}<span class="vac-opt-face is-ini">{{ c.name[:1] }}</span>{% endif %}
<span class="vac-opt-name">{{ c.name }}</span>
<span class="erp-muted vac-opt-mail">{{ c.email }}</span>
</label>
</li>
{% else %}
<li class="erp-muted">휴가 모듈 권한이 있는 사용자가 없습니다.</li>
{% endfor %}
</ul>
</div>
{% endfor %}
<div class="vac-opt-save">
{% if is_admin and options.ready %}
<button type="submit" class="erp-btn erp-btn-primary">저장</button>
{% if options.updated_by %}<span class="erp-muted">마지막 저장 {{ options.updated_by }} · {{ options.updated_at[:16] | replace('T', ' ') }}</span>{% endif %}
{% elif not is_admin %}
<span class="erp-muted">승인자·통보자는 ERP 관리자만 바꿀 수 있습니다.</span>
{% endif %}
</div>
</form>
<div class="erp-card vac-opt-card vac-opt-mailcard">
<div class="vac-card-head"><h2>메일</h2></div>
<ul class="vac-opt-rules">
<li><b>제출</b> → 승인자 · 통보자</li>
<li><b>승인 · 반려</b> → 승인자 · 통보자 · 신청자</li>
<li>보내는 사람 = 그 일을 한 사람(제출 = 신청자, 승인·반려 = 처리한 승인자)의 <b>본인 Gmail</b>.
Gmail 을 연결하지 않았으면 회사 알림 메일로 보내고 보낸 사람 이름·답장 주소를 그 사람으로 합니다.</li>
</ul>
<div class="vac-opt-gmail">
<span class="vac-opt-gmail-state{% if gmail.connected %} is-on{% endif %}">
내 Gmail({{ user.email }}) — {% if gmail.connected %}연결됨{% else %}연결 안 됨{% endif %}</span>
{% if gmail.connected %}
<form method="post" action="/vacation/gmail/disconnect" class="vac-inline-form"
onsubmit="return confirm('Gmail 연결을 끊을까요? 입출고 발주 메일 연결도 함께 끊깁니다.');">
<button type="submit" class="erp-btn erp-btn-outline">연결 끊기</button>
</form>
{% elif gmail.available %}
<a class="erp-btn erp-btn-primary" href="/vacation/gmail/connect">Gmail 연결</a>
{% else %}
<span class="erp-muted">Gmail 연결을 쓸 수 없는 서버입니다(입출고 DB·구글 OAuth·APP_ENCRYPTION_KEY 필요) — 회사 메일로 보냅니다.</span>
{% endif %}
</div>
<p class="erp-muted vac-opt-hint">입출고 발주 메일과 같은 연결입니다(한 번 연결하면 두 곳 모두). 메일 보내기 권한(gmail.send)만 받습니다.
{% if not gmail.smtp %}<br>회사 알림 메일(SMTP)이 설정되지 않아 Gmail 을 연결하지 않은 사람의 메일은 나가지 않습니다.{% endif %}</p>
</div>
</section>
{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20260530i" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027a" />{% endblock %}
{% block content %}
<section class="vac">
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20260530i" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027a" />{% endblock %}
{% block content %}
<section class="vac">