feat(휴가): 협의자 결재·신청 화면 개편(라디오·붙박이 달력·결재 라인)·내 신청 내역
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+169
-23
@@ -3,6 +3,7 @@
|
||||
- 경로: /vacation
|
||||
- 권한: 로그인 + `vacation` 모듈 권한 (관리자는 항상 통과). 서버 측 검사.
|
||||
승인/반려 = admin + (휴가 옵션에 승인자를 지정했으면 그 사람들, 아니면 `vacation_approver` 권한자) — 2026-10-27.
|
||||
- 협의자(2026-11-02, 마이그레이션 003): 신청자가 지정(복수) → 모두 승인해야 결재자에게 넘어감(상태 협의중 → 제출). 협의자는 휴가 권한이 없어도 자기 신청은 볼 수 있다.
|
||||
- 휴가 옵션(`/vacation/options`, 수정 = admin·승인자·통보자): 승인자·승인 통보자·잔여 연차. 공휴일 = 국경일 표(설정 화면 없음). 제출·승인·반려 메일은 `notify.py`
|
||||
(처리한 사람 본인 Gmail — 입출고와 같은 Gmail 연결, 없으면 회사 SMTP).
|
||||
- 데이터: VacationDBStore (vacation_db / PostgreSQL) 전용.
|
||||
@@ -61,6 +62,16 @@ def _require_approver(request: Request) -> dict[str, Any]:
|
||||
return user
|
||||
|
||||
|
||||
def _require_login(request: Request) -> dict[str, Any]:
|
||||
"""로그인만 — 협의 결재처럼 휴가 모듈 권한이 없어도 되는 곳(협의자 여부는 저장소가 확인)."""
|
||||
from app.main import get_current_user_record # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="로그인이 필요합니다.")
|
||||
return user
|
||||
|
||||
|
||||
def _options(request: Request) -> dict[str, Any]:
|
||||
"""휴가 옵션(승인자·통보자, 마이그레이션 001). DB·001 이 없으면 빈 옵션."""
|
||||
st = _store(request)
|
||||
@@ -111,6 +122,38 @@ def _vacation_users() -> list[dict[str, Any]]:
|
||||
return out
|
||||
|
||||
|
||||
def _people() -> dict[str, dict[str, str]]:
|
||||
"""전체 구성원(휴가 권한과 무관) {이메일: 이메일·이름·사진} — 협의자 후보·결재 라인 아이콘. 이름 순."""
|
||||
from app.main import user_store # noqa: WPS433
|
||||
|
||||
rows = [{"email": u["email"].lower(), "name": u.get("name") or u["email"].split("@")[0], "picture": u.get("picture") or ""}
|
||||
for u in user_store.list_all()]
|
||||
rows.sort(key=lambda p: p["name"].lower())
|
||||
return {p["email"]: p for p in rows}
|
||||
|
||||
|
||||
def _form_consults(store: Any, owner: str, emails: list[str], messages: list[str], no_consult: str, action: str) -> list[dict[str, Any]] | None:
|
||||
"""폼의 협의자 줄 → [{email, name, message}]. 003 전이면 None(협의자 없음). 제출인데 협의자도 "협의자 없음"도 없으면 400."""
|
||||
if not store.consults_ready():
|
||||
return None
|
||||
if no_consult:
|
||||
return []
|
||||
if len(emails) != len(messages):
|
||||
raise HTTPException(status_code=400, detail="협의자 칸이 맞지 않습니다.")
|
||||
known = _people()
|
||||
out: dict[str, dict[str, Any]] = {}
|
||||
for raw, message in zip(emails, messages):
|
||||
email = raw.strip().lower()
|
||||
if email == owner.lower():
|
||||
continue
|
||||
if email not in known:
|
||||
raise HTTPException(status_code=400, detail=f"등록된 구성원만 협의자로 고를 수 있습니다: {email}")
|
||||
out[email] = {"email": email, "name": known[email]["name"], "message": message.strip()[:2000]}
|
||||
if action == "submit" and not out:
|
||||
raise HTTPException(status_code=400, detail="협의자를 고르거나 '협의자 없음'을 체크하세요.")
|
||||
return list(out.values())
|
||||
|
||||
|
||||
def _notify(bg: BackgroundTasks, request: Request, event: str, req: dict[str, Any] | None,
|
||||
actor: dict[str, Any]) -> None:
|
||||
"""제출·승인·반려 메일을 응답 뒤 백그라운드로(notify.deliver — 받는 사람·보내는 사람 규칙은 그쪽)."""
|
||||
@@ -121,6 +164,10 @@ def _notify(bg: BackgroundTasks, request: Request, event: str, req: dict[str, An
|
||||
st = _store(request)
|
||||
if st is None or not req:
|
||||
return
|
||||
try:
|
||||
req = {**req, "consults": st.list_consults(request_id=req["id"])}
|
||||
except Exception: # noqa: BLE001 — 협의자 조회 실패가 처리 결과를 뒤집지 않게(메일만 협의 내용 없이)
|
||||
req = {**req, "consults": []}
|
||||
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),
|
||||
@@ -147,23 +194,26 @@ def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLRespons
|
||||
|
||||
|
||||
def _guard(
|
||||
request: Request,
|
||||
request: Request, consult_of: str = "",
|
||||
) -> tuple[Any, dict[str, Any]] | HTMLResponse | RedirectResponse:
|
||||
"""로그인+권한+store 점검. 페이지 핸들러 진입부에서 사용."""
|
||||
"""로그인+권한+store 점검. 페이지 핸들러 진입부에서 사용.
|
||||
consult_of = 신청 id — 휴가 권한이 없어도 그 신청의 협의자면 통과(메일 링크로 들어와 협의 결재)."""
|
||||
from app.main import get_current_user_record, render_template # noqa: WPS433
|
||||
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
return login_redirect(request)
|
||||
if not has_module(user, "vacation"):
|
||||
store = _store(request)
|
||||
allowed = has_module(user, "vacation") or (store is not None and consult_of and any(
|
||||
c["email"] == user["email"].lower() for c in store.list_consults(request_id=consult_of)))
|
||||
if not allowed:
|
||||
return render_template(
|
||||
request,
|
||||
"denied.html",
|
||||
{"reason": "휴가 관리 모듈 접근 권한이 없습니다.", "is_admin": is_admin(user)},
|
||||
status_code=403,
|
||||
)
|
||||
store = _store(request)
|
||||
if store is None:
|
||||
return _render_config_needed(request, user)
|
||||
return store, user
|
||||
@@ -184,6 +234,7 @@ def _ym(request: Request) -> tuple[int, int]:
|
||||
# 상태별 bar 스타일 클래스 (CSS 와 매핑)
|
||||
_STATUS_CLASS = {
|
||||
"작성중": "vac-bar-draft",
|
||||
"협의중": "vac-bar-submit",
|
||||
"제출": "vac-bar-submit",
|
||||
"승인": "vac-bar-approve",
|
||||
"반려": "vac-bar-reject",
|
||||
@@ -323,6 +374,7 @@ def index(request: Request) -> HTMLResponse:
|
||||
"is_admin": is_admin(user),
|
||||
"is_approver": is_approver,
|
||||
"pending_count": pending_count,
|
||||
"consult_count": len(store.my_consults(email=user["email"])),
|
||||
"nav_items": build_erp_nav(user, active="vacation"),
|
||||
"page_title": "휴가 관리",
|
||||
"page_subtitle": f"{year}년 {month}월 휴가 달력",
|
||||
@@ -344,11 +396,29 @@ def index(request: Request) -> HTMLResponse:
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 휴가 신청 — 등록 / 수정 / 상세
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _form_context(request: Request, user: dict[str, Any]) -> dict[str, Any]:
|
||||
def _approval_line(request: Request, people: dict[str, dict[str, str]]) -> dict[str, list[dict[str, str]]]:
|
||||
"""옵션에 세팅된 결재자·통보자(아이콘 + 이름) — 신청 화면·상세의 결재 라인."""
|
||||
from . import notify # noqa: WPS433
|
||||
|
||||
opts = _options(request)
|
||||
|
||||
def who(emails: list[str]) -> list[dict[str, str]]:
|
||||
return [people.get(e) or {"email": e, "name": e.split("@")[0], "picture": ""} for e in emails]
|
||||
|
||||
return {"approvers": who(notify.approver_emails(opts, _vacation_users())), "notifiers": who(opts.get("notifiers") or [])}
|
||||
|
||||
|
||||
def _form_context(request: Request, user: dict[str, Any], req: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
from app.main import build_erp_nav # noqa: WPS433
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
people = _people()
|
||||
st = _store(request)
|
||||
return {
|
||||
"members": [p for e, p in people.items() if e != user["email"].lower()],
|
||||
"consult_ready": bool(st is not None and st.consults_ready()),
|
||||
"consult_chosen": {c["email"]: c["message"] for c in st.list_consults(request_id=req["id"])} if req and st is not None else {},
|
||||
"line": _approval_line(request, people),
|
||||
"user": user,
|
||||
"is_admin": is_admin(user),
|
||||
"is_approver": _is_approver(request, user),
|
||||
@@ -422,6 +492,9 @@ def create(
|
||||
end_half: str = Form("full"),
|
||||
reason: str = Form(""),
|
||||
action: str = Form("submit"), # "draft" | "submit"
|
||||
consult_email: list[str] = Form(default=[]),
|
||||
consult_message: list[str] = Form(default=[]),
|
||||
no_consult: str = Form(""),
|
||||
user: dict[str, Any] = Depends(_require_user),
|
||||
) -> RedirectResponse:
|
||||
store = _store(request)
|
||||
@@ -431,12 +504,14 @@ def create(
|
||||
payload = _payload_from_form(
|
||||
vacation_type, start_date, end_date, start_half, end_half, reason
|
||||
)
|
||||
consults = _form_consults(store, user["email"], consult_email, consult_message, no_consult, action)
|
||||
try:
|
||||
req = store.create_request(
|
||||
owner=user["email"],
|
||||
owner_name=user.get("name") or user["email"],
|
||||
payload=payload,
|
||||
status=status,
|
||||
consults=consults,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
@@ -454,26 +529,57 @@ def pending_page(request: Request) -> HTMLResponse:
|
||||
if not isinstance(guard, tuple):
|
||||
return guard
|
||||
store, user = guard
|
||||
if not _is_approver(request, user):
|
||||
return render_template(
|
||||
request,
|
||||
"denied.html",
|
||||
{"reason": "휴가 승인자 권한이 없습니다.", "is_admin": is_admin(user)},
|
||||
status_code=403,
|
||||
)
|
||||
pending = store.list_pending()
|
||||
is_approver = _is_approver(request, user)
|
||||
pending = store.list_pending() if is_approver else []
|
||||
consults = store.my_consults(email=user["email"])
|
||||
by_req = store.consults_for([r["id"] for r in pending])
|
||||
for r in pending:
|
||||
r["consults"] = by_req.get(r["id"], [])
|
||||
return render_template(
|
||||
request,
|
||||
"vacation/pending.html",
|
||||
{
|
||||
"user": user,
|
||||
"is_admin": is_admin(user),
|
||||
"is_approver": True,
|
||||
"is_approver": is_approver,
|
||||
"nav_items": build_erp_nav(user, active="vacation"),
|
||||
"page_title": "휴가 — 승인 대기",
|
||||
"page_subtitle": f"제출 상태 {len(pending)}건",
|
||||
"page_title": "휴가 — 결재 대기",
|
||||
"page_subtitle": f"협의 {len(consults)}건" + (f" · 승인 {len(pending)}건" if is_approver else ""),
|
||||
"items": pending,
|
||||
"consult_items": consults,
|
||||
"half_labels": HALF_LABELS,
|
||||
"people": _people(),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.get("/mine", response_class=HTMLResponse)
|
||||
def mine_page(request: Request) -> HTMLResponse:
|
||||
"""내 휴가 신청 내역 — 협의·결재 진행 상황(2026-11-02)."""
|
||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
guard = _guard(request)
|
||||
if not isinstance(guard, tuple):
|
||||
return guard
|
||||
store, user = guard
|
||||
items = store.list_for(user["email"])
|
||||
by_req = store.consults_for([r["id"] for r in items])
|
||||
for r in items:
|
||||
r["consults"] = by_req.get(r["id"], [])
|
||||
return render_template(
|
||||
request,
|
||||
"vacation/mine.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": f"{len(items)}건",
|
||||
"items": items,
|
||||
"half_labels": HALF_LABELS,
|
||||
"people": _people(),
|
||||
},
|
||||
)
|
||||
|
||||
@@ -776,7 +882,7 @@ def detail(request: Request, request_id: str) -> HTMLResponse:
|
||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
guard = _guard(request)
|
||||
guard = _guard(request, consult_of=request_id)
|
||||
if not isinstance(guard, tuple):
|
||||
return guard
|
||||
store, user = guard
|
||||
@@ -787,14 +893,20 @@ def detail(request: Request, request_id: str) -> HTMLResponse:
|
||||
{"reason": "휴가 신청을 찾을 수 없습니다.", "is_admin": is_admin(user)},
|
||||
status_code=404,
|
||||
)
|
||||
email = user["email"].lower()
|
||||
is_owner = req["owner"] == user["email"]
|
||||
is_approver = _is_approver(request, user)
|
||||
if not (is_owner or is_approver):
|
||||
consults = store.list_consults(request_id=request_id)
|
||||
mine = next((c for c in consults if c["email"] == email), None)
|
||||
see_all = is_owner or is_approver or email in (_options(request).get("notifiers") or [])
|
||||
if not (see_all or mine):
|
||||
return render_template(
|
||||
request, "denied.html",
|
||||
{"reason": "본인 또는 승인자만 조회할 수 있습니다.", "is_admin": is_admin(user)},
|
||||
{"reason": "본인·승인자·통보자·협의자만 조회할 수 있습니다.", "is_admin": is_admin(user)},
|
||||
status_code=403,
|
||||
)
|
||||
req["consults"] = consults if see_all else [mine] # 협의자는 자기 몫 협의 내용만
|
||||
people = _people()
|
||||
return render_template(
|
||||
request,
|
||||
"vacation/detail.html",
|
||||
@@ -809,8 +921,11 @@ 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": "반려"},
|
||||
"can_consult": bool(mine and mine["state"] == "대기" and req["status"] == "협의중"),
|
||||
"people": people,
|
||||
"line": _approval_line(request, people),
|
||||
"mail_log": _mail_log(store, request_id) if see_all else [],
|
||||
"event_words": {"submitted": "제출", "approved": "승인", "rejected": "반려", "consult_request": "협의 요청", "consulted": "협의 완료"},
|
||||
},
|
||||
)
|
||||
|
||||
@@ -851,7 +966,7 @@ def edit_form(request: Request, request_id: str) -> HTMLResponse:
|
||||
{"reason": f"{req['status']} 상태에서는 수정할 수 없습니다.", "is_admin": is_admin(user)},
|
||||
status_code=409,
|
||||
)
|
||||
ctx = _form_context(request, user)
|
||||
ctx = _form_context(request, user, req)
|
||||
ctx.update(
|
||||
{
|
||||
"page_title": "휴가 신청 수정",
|
||||
@@ -876,6 +991,9 @@ def update(
|
||||
end_half: str = Form("full"),
|
||||
reason: str = Form(""),
|
||||
action: str = Form("save"), # "save" | "submit"
|
||||
consult_email: list[str] = Form(default=[]),
|
||||
consult_message: list[str] = Form(default=[]),
|
||||
no_consult: str = Form(""),
|
||||
user: dict[str, Any] = Depends(_require_user),
|
||||
) -> RedirectResponse:
|
||||
store = _store(request)
|
||||
@@ -884,8 +1002,9 @@ def update(
|
||||
payload = _payload_from_form(
|
||||
vacation_type, start_date, end_date, start_half, end_half, reason
|
||||
)
|
||||
consults = _form_consults(store, user["email"], consult_email, consult_message, no_consult, action)
|
||||
try:
|
||||
store.update_request(request_id=request_id, owner=user["email"], payload=payload)
|
||||
store.update_request(request_id=request_id, owner=user["email"], payload=payload, consults=consults)
|
||||
if action == "submit":
|
||||
_notify(bg, request, "submitted", store.submit(request_id=request_id, owner=user["email"]), user)
|
||||
except KeyError:
|
||||
@@ -914,6 +1033,33 @@ def submit(
|
||||
return RedirectResponse(url=f"/vacation/{request_id}", status_code=303)
|
||||
|
||||
|
||||
@router.post("/{request_id}/consult")
|
||||
def consult_decide(
|
||||
request: Request,
|
||||
request_id: str,
|
||||
bg: BackgroundTasks,
|
||||
decision: str = Form(...), # "approve" | "reject"
|
||||
reject_reason: str = Form(""),
|
||||
user: dict[str, Any] = Depends(_require_login),
|
||||
) -> RedirectResponse:
|
||||
"""협의 결재 — 모두 승인하면 제출(결재자 승인 대기)로, 한 명이 반려하면 신청도 반려."""
|
||||
store = _store(request)
|
||||
if store is None:
|
||||
raise HTTPException(status_code=503, detail="vacation_db 미설정")
|
||||
try:
|
||||
req, event = store.decide_consult(request_id=request_id, email=user["email"], approve=decision == "approve",
|
||||
reason=reject_reason)
|
||||
except KeyError:
|
||||
raise HTTPException(status_code=404, detail="휴가 신청을 찾을 수 없습니다.")
|
||||
except PermissionError as exc:
|
||||
raise HTTPException(status_code=403, detail=str(exc))
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc))
|
||||
if event:
|
||||
_notify(bg, request, event, req, user)
|
||||
return RedirectResponse(url=f"/vacation/{request_id}", status_code=303)
|
||||
|
||||
|
||||
@router.post("/{request_id}/approve")
|
||||
def approve(
|
||||
request: Request,
|
||||
|
||||
Reference in New Issue
Block a user