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:
+195
-10
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user