8c805fdd9c
- 새 모듈 app/modules/outreach(권한키 outreach, outreach_db — scripts/sql/outreach_db_init.sql, OUTREACH_DB_URL)
- 리스트 붙여넣기(주소, 이름) → 주소를 보고 메일/DM 판별(store.detect: 이메일·@계정·instagram.com·ig.me·계정명) → 미리보기 → 추가
- 메일 = 고른 줄을 한 UPDATE 로 발송중(두 번 눌러도 한 번) → 백그라운드로 본인 Gmail 한 사람에 한 통(입출고·휴가와 같은 Gmail 연결),
설정 사진 본문 아래(cid), 보냄/실패·기록. 인스타 = 이름 넣은 문구 복사 + ig.me DM 창 → [보냄] 기록(공식 API 는 첫 DM 불가)
- 설정: 제목·본문 기본 = 미라네주방 공동구매 제안 문구, {이름}·**굵게**, 보내는 이름·끝 문구·(광고) 표시, 사진 10장
- 입출고 Gmail 콜백을 모듈 공용으로(_GMAIL_ORIGINS — vacation·outreach)
- 테스트: 판별·본문·발송(가짜 Gmail)·실제 앱·실제 PG(동시 claim 4번 = 1번)·브라우저
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1000 lines
40 KiB
Python
1000 lines
40 KiB
Python
"""휴가 관리 모듈 라우터.
|
|
|
|
- 경로: /vacation
|
|
- 권한: 로그인 + `vacation` 모듈 권한 (관리자는 항상 통과). 서버 측 검사.
|
|
승인/반려 = admin + (휴가 옵션에 승인자를 지정했으면 그 사람들, 아니면 `vacation_approver` 권한자) — 2026-10-27.
|
|
- 휴가 옵션(`/vacation/options`, 수정 = admin·승인자·통보자): 승인자·승인 통보자·잔여 연차. 공휴일 = 국경일 표(설정 화면 없음). 제출·승인·반려 메일은 `notify.py`
|
|
(처리한 사람 본인 Gmail — 입출고와 같은 Gmail 연결, 없으면 회사 SMTP).
|
|
- 데이터: VacationDBStore (vacation_db / PostgreSQL) 전용.
|
|
VACATION_DB_URL 미설정 시 store 가 None 이며, 각 페이지는 "설정 필요" 안내를 보여준다.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import calendar as _calendar
|
|
import io
|
|
from datetime import date
|
|
from typing import Any
|
|
|
|
from fastapi import APIRouter, BackgroundTasks, Depends, Form, HTTPException, Request
|
|
from fastapi.responses import (
|
|
HTMLResponse,
|
|
JSONResponse,
|
|
RedirectResponse,
|
|
StreamingResponse,
|
|
)
|
|
|
|
from app.timezone import now_kst, today_kst
|
|
|
|
from .store import HALF_LABELS, HALVES, SYSTEM_START_YEAR, VACATION_TYPES
|
|
|
|
router = APIRouter(prefix="/vacation", tags=["vacation"])
|
|
|
|
|
|
# ────────────────────────────────────────────────────────────
|
|
# 공용 헬퍼
|
|
# ────────────────────────────────────────────────────────────
|
|
def _store(request: Request) -> Any:
|
|
return getattr(request.app.state, "vacation_store", None)
|
|
|
|
|
|
def _require_user(request: Request) -> dict[str, Any]:
|
|
from app.main import get_current_user_record # noqa: WPS433
|
|
from app.store import has_module # noqa: WPS433
|
|
|
|
user = get_current_user_record(request)
|
|
if user is None:
|
|
raise HTTPException(status_code=401, detail="로그인이 필요합니다.")
|
|
if not has_module(user, "vacation"):
|
|
raise HTTPException(status_code=403, detail="휴가 관리 모듈 권한이 없습니다.")
|
|
return user
|
|
|
|
|
|
def _require_approver(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="로그인이 필요합니다.")
|
|
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
|
|
|
|
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 _can_edit_options(request: Request, user: dict[str, Any], opts: dict[str, Any] | None = None,
|
|
users: list[dict[str, Any]] | None = None) -> bool:
|
|
"""휴가 옵션(승인자·통보자·잔여 연차) 수정 — ERP 관리자(수퍼관리자 포함) + 지금 승인자(옵션 지정, 없으면 휴가 승인 권한자)
|
|
+ 승인 통보자(2026-10-27, 예전엔 관리자만)."""
|
|
from app.store import is_admin # noqa: WPS433
|
|
|
|
from . import notify # noqa: WPS433
|
|
|
|
if is_admin(user):
|
|
return True
|
|
opts = opts if opts is not None else _options(request)
|
|
email = str(user.get("email") or "").strip().lower()
|
|
if email in (opts.get("notifiers") or []):
|
|
return True
|
|
return email in notify.approver_emails(opts, users if users is not None else _vacation_users())
|
|
|
|
|
|
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:
|
|
from app.main import build_erp_nav, render_template # noqa: WPS433
|
|
from app.store import is_admin # noqa: WPS433
|
|
|
|
return render_template(
|
|
request,
|
|
"denied.html",
|
|
{
|
|
"reason": "휴가 관리 모듈이 아직 설정되지 않았습니다. "
|
|
"VACATION_DB_URL 환경변수를 설정하고 scripts/sql/vacation_db_init.sql 로 "
|
|
"vacation_db 를 초기화한 뒤 컨테이너를 재기동하세요.",
|
|
"user": user,
|
|
"is_admin": is_admin(user),
|
|
"nav_items": build_erp_nav(user, active="vacation"),
|
|
},
|
|
status_code=503,
|
|
)
|
|
|
|
|
|
def _guard(
|
|
request: Request,
|
|
) -> tuple[Any, dict[str, Any]] | HTMLResponse | RedirectResponse:
|
|
"""로그인+권한+store 점검. 페이지 핸들러 진입부에서 사용."""
|
|
from app.main import get_current_user_record, render_template # noqa: WPS433
|
|
from app.store import has_module, is_admin # noqa: WPS433
|
|
|
|
user = get_current_user_record(request)
|
|
if user is None:
|
|
return RedirectResponse(url="/login", status_code=303)
|
|
if not has_module(user, "vacation"):
|
|
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
|
|
|
|
|
|
def _ym(request: Request) -> tuple[int, int]:
|
|
today = today_kst()
|
|
try:
|
|
year = int(request.query_params.get("year") or today.year)
|
|
month = int(request.query_params.get("month") or today.month)
|
|
except ValueError:
|
|
year, month = today.year, today.month
|
|
if not (1 <= month <= 12):
|
|
year, month = today.year, today.month
|
|
return year, month
|
|
|
|
|
|
# 상태별 bar 스타일 클래스 (CSS 와 매핑)
|
|
_STATUS_CLASS = {
|
|
"작성중": "vac-bar-draft",
|
|
"제출": "vac-bar-submit",
|
|
"승인": "vac-bar-approve",
|
|
"반려": "vac-bar-reject",
|
|
"취소": "vac-bar-cancel",
|
|
}
|
|
|
|
|
|
def _assign_lanes(bars: list[dict[str, Any]]) -> int:
|
|
"""주(week) 내 bar 들에 겹치지 않는 lane(행) 번호를 그리디 배정.
|
|
|
|
bars 는 같은 주의 segment 들. 각 bar 에 'lane' 키를 추가하고, 사용된 lane 수를 반환.
|
|
"""
|
|
bars.sort(key=lambda b: (b["start_col"], -b["span"]))
|
|
lane_end: list[int] = [] # lane 별 마지막 점유 col(포함)
|
|
for b in bars:
|
|
placed = False
|
|
for li, end_col in enumerate(lane_end):
|
|
if b["start_col"] > end_col:
|
|
b["lane"] = li
|
|
lane_end[li] = b["start_col"] + b["span"] - 1
|
|
placed = True
|
|
break
|
|
if not placed:
|
|
b["lane"] = len(lane_end)
|
|
lane_end.append(b["start_col"] + b["span"] - 1)
|
|
return len(lane_end)
|
|
|
|
|
|
def _build_calendar(
|
|
store: Any, year: int, month: int, sel: str
|
|
) -> dict[str, Any]:
|
|
"""월간 달력 데이터 + bar lane 레이아웃 계산."""
|
|
cal = _calendar.Calendar(firstweekday=6) # 일요일 시작
|
|
weeks_dates = cal.monthdatescalendar(year, month)
|
|
range_start = weeks_dates[0][0]
|
|
range_end = weeks_dates[-1][-1]
|
|
|
|
# 쉬는 날 = 대한민국 국경일·대체공휴일(db.holiday_map) — 빨강 + 날짜 밑 이름(2026-10-27)
|
|
holiday_names = store.holiday_map(
|
|
date_from=range_start.isoformat(), date_to=range_end.isoformat()
|
|
)
|
|
requests = store.list_overlapping(
|
|
date_from=range_start.isoformat(), date_to=range_end.isoformat()
|
|
)
|
|
|
|
today = today_kst()
|
|
weeks: list[dict[str, Any]] = []
|
|
for week in weeks_dates:
|
|
w_start, w_end = week[0], week[-1]
|
|
days = [
|
|
{
|
|
"date": d.isoformat(),
|
|
"day": d.day,
|
|
"in_month": d.month == month,
|
|
"is_today": d == today,
|
|
"is_selected": d.isoformat() == sel,
|
|
"is_sunday": d.weekday() == 6,
|
|
"is_saturday": d.weekday() == 5,
|
|
"is_holiday": d.isoformat() in holiday_names,
|
|
"holiday_name": holiday_names.get(d.isoformat(), ""),
|
|
}
|
|
for d in week
|
|
]
|
|
# 이 주에 걸치는 bar segment
|
|
bars: list[dict[str, Any]] = []
|
|
for r in requests:
|
|
rs = date.fromisoformat(r["start_date"])
|
|
re_ = date.fromisoformat(r["end_date"])
|
|
if re_ < w_start or rs > w_end:
|
|
continue
|
|
seg_start = max(rs, w_start)
|
|
seg_end = min(re_, w_end)
|
|
start_col = (seg_start - w_start).days # 0..6
|
|
span = (seg_end - seg_start).days + 1
|
|
label = f"{r.get('owner_name') or r.get('owner')} {r['vacation_type']}"
|
|
bars.append(
|
|
{
|
|
"id": r["id"],
|
|
"label": label,
|
|
"status": r["status"],
|
|
"status_class": _STATUS_CLASS.get(r["status"], "vac-bar-draft"),
|
|
"start_col": start_col,
|
|
"span": span,
|
|
"continues_left": rs < w_start,
|
|
"continues_right": re_ > w_end,
|
|
"days": r["days"],
|
|
}
|
|
)
|
|
lane_count = _assign_lanes(bars)
|
|
weeks.append({"days": days, "bars": bars, "lane_count": lane_count})
|
|
|
|
return {"weeks": weeks, "requests": requests, "sel_date": sel}
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# 메인 — 월간 달력 + 선택일 휴가 리스트
|
|
# ════════════════════════════════════════════════════════════
|
|
@router.get("/", response_class=HTMLResponse)
|
|
def index(request: Request) -> HTMLResponse:
|
|
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
|
|
|
|
year, month = _ym(request)
|
|
sel = request.query_params.get("date") or ""
|
|
today = today_kst()
|
|
if not sel:
|
|
sel = (
|
|
today.isoformat()
|
|
if (today.year == year and today.month == month)
|
|
else f"{year:04d}-{month:02d}-01"
|
|
)
|
|
|
|
caldata = _build_calendar(store, year, month, sel)
|
|
sel_requests = [
|
|
r
|
|
for r in caldata["requests"]
|
|
if r["start_date"] <= sel <= r["end_date"]
|
|
]
|
|
|
|
prev_y, prev_m = (year - 1, 12) if month == 1 else (year, month - 1)
|
|
next_y, next_m = (year + 1, 1) if month == 12 else (year, month + 1)
|
|
|
|
summary = store.balance_summary(user_email=user["email"]) # 입사일 기준 — 오늘 쓸 수 있는 연차(달력의 해와 무관)
|
|
is_approver = _is_approver(request, user)
|
|
pending_count = len(store.list_pending()) if is_approver else 0
|
|
|
|
return render_template(
|
|
request,
|
|
"vacation/index.html",
|
|
{
|
|
"user": user,
|
|
"is_admin": is_admin(user),
|
|
"is_approver": is_approver,
|
|
"pending_count": pending_count,
|
|
"nav_items": build_erp_nav(user, active="vacation"),
|
|
"page_title": "휴가 관리",
|
|
"page_subtitle": f"{year}년 {month}월 휴가 달력",
|
|
"year": year,
|
|
"month": month,
|
|
"prev_y": prev_y, "prev_m": prev_m,
|
|
"next_y": next_y, "next_m": next_m,
|
|
"today": today.isoformat(),
|
|
"weekdays": ["일", "월", "화", "수", "목", "금", "토"],
|
|
"weeks": caldata["weeks"],
|
|
"selected_date": sel,
|
|
"sel_requests": sel_requests,
|
|
"balance": summary,
|
|
"half_labels": HALF_LABELS,
|
|
},
|
|
)
|
|
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# 휴가 신청 — 등록 / 수정 / 상세
|
|
# ════════════════════════════════════════════════════════════
|
|
def _form_context(request: Request, user: dict[str, Any]) -> dict[str, Any]:
|
|
from app.main import build_erp_nav # noqa: WPS433
|
|
from app.store import is_admin # noqa: WPS433
|
|
|
|
return {
|
|
"user": user,
|
|
"is_admin": is_admin(user),
|
|
"is_approver": _is_approver(request, user),
|
|
"nav_items": build_erp_nav(user, active="vacation"),
|
|
"vacation_types": list(VACATION_TYPES),
|
|
"halves": list(HALVES),
|
|
"half_labels": HALF_LABELS,
|
|
"holidays": _red_holidays(request),
|
|
}
|
|
|
|
|
|
def _red_holidays(request: Request) -> dict[str, str]:
|
|
"""날짜 팝업 공휴일(빨강·이름) — 국경일·대체공휴일, 작년~내년. 일수 계산과 같은 표(db.holiday_map)."""
|
|
st = _store(request)
|
|
if st is None:
|
|
return {}
|
|
year = today_kst().year
|
|
try:
|
|
return st.holiday_map(date_from=f"{year - 1}-01-01", date_to=f"{year + 1}-12-31")
|
|
except Exception: # noqa: BLE001 — 공휴일 표시가 신청 화면을 막지 않게
|
|
return {}
|
|
|
|
|
|
@router.get("/new", response_class=HTMLResponse)
|
|
def new_form(request: Request) -> HTMLResponse:
|
|
from app.main import render_template # noqa: WPS433
|
|
|
|
guard = _guard(request)
|
|
if not isinstance(guard, tuple):
|
|
return guard
|
|
_store_obj, user = guard
|
|
ctx = _form_context(request, user)
|
|
ctx.update(
|
|
{
|
|
"page_title": "휴가 신청",
|
|
"page_subtitle": "휴가 종류 · 기간 · 사유 입력",
|
|
"mode": "new",
|
|
"req": None,
|
|
"default_date": today_kst().isoformat(),
|
|
}
|
|
)
|
|
return render_template(request, "vacation/form.html", ctx)
|
|
|
|
|
|
def _payload_from_form(
|
|
vacation_type: str,
|
|
start_date: str,
|
|
end_date: str,
|
|
start_half: str,
|
|
end_half: str,
|
|
reason: str,
|
|
) -> dict[str, Any]:
|
|
return {
|
|
"vacation_type": vacation_type,
|
|
"start_date": start_date,
|
|
"end_date": end_date or start_date,
|
|
"start_half": start_half,
|
|
"end_half": end_half,
|
|
"reason": reason,
|
|
}
|
|
|
|
|
|
@router.post("/new")
|
|
def create(
|
|
request: Request,
|
|
bg: BackgroundTasks,
|
|
vacation_type: str = Form(...),
|
|
start_date: str = Form(...),
|
|
end_date: str = Form(""),
|
|
start_half: str = Form("full"),
|
|
end_half: str = Form("full"),
|
|
reason: str = Form(""),
|
|
action: str = Form("submit"), # "draft" | "submit"
|
|
user: dict[str, Any] = Depends(_require_user),
|
|
) -> RedirectResponse:
|
|
store = _store(request)
|
|
if store is None:
|
|
raise HTTPException(status_code=503, detail="vacation_db 미설정")
|
|
status = "작성중" if action == "draft" else "제출"
|
|
payload = _payload_from_form(
|
|
vacation_type, start_date, end_date, start_half, end_half, reason
|
|
)
|
|
try:
|
|
req = store.create_request(
|
|
owner=user["email"],
|
|
owner_name=user.get("name") or user["email"],
|
|
payload=payload,
|
|
status=status,
|
|
)
|
|
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)
|
|
|
|
|
|
@router.get("/pending", response_class=HTMLResponse)
|
|
def pending_page(request: Request) -> HTMLResponse:
|
|
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
|
|
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()
|
|
return render_template(
|
|
request,
|
|
"vacation/pending.html",
|
|
{
|
|
"user": user,
|
|
"is_admin": is_admin(user),
|
|
"is_approver": True,
|
|
"nav_items": build_erp_nav(user, active="vacation"),
|
|
"page_title": "휴가 — 승인 대기",
|
|
"page_subtitle": f"제출 상태 {len(pending)}건",
|
|
"items": pending,
|
|
"half_labels": HALF_LABELS,
|
|
},
|
|
)
|
|
|
|
|
|
@router.get("/settings")
|
|
def settings_page(request: Request) -> RedirectResponse:
|
|
"""예전 설정 화면(공휴일·잔여 연차) — 2026-10-27 없앴다(공휴일 = 국경일 표, 잔여 연차 = 옵션). 예전 주소는 옵션으로."""
|
|
return RedirectResponse(url="/vacation/options", status_code=303)
|
|
|
|
|
|
@router.post("/options/balances")
|
|
async def balances_save(request: Request) -> RedirectResponse:
|
|
"""잔여 연차 한꺼번에(옵션 — ERP 관리자·휴가 승인자·승인 통보자) — 참여자 줄마다 email·hire·total·prior·memo(2026-10-27).
|
|
hire = 입사일(빈 칸 = 지움), total = 연차 직접 입력(빈 칸 = 입사일 기준 법정 연차), prior = 시스템 전에 그해 쓴 연차(빈 칸 = 0)."""
|
|
from urllib.parse import urlencode # noqa: WPS433
|
|
|
|
user = _require_user(request)
|
|
if not _can_edit_options(request, user):
|
|
raise HTTPException(status_code=403, detail="잔여 연차는 ERP 관리자·휴가 승인자·승인 통보자만 등록할 수 있습니다.")
|
|
store = _store(request)
|
|
if store is None:
|
|
raise HTTPException(status_code=503, detail="vacation_db 미설정")
|
|
form = await request.form()
|
|
emails, memos = form.getlist("email"), form.getlist("memo")
|
|
totals, priors, hires = form.getlist("total"), form.getlist("prior"), form.getlist("hire")
|
|
if not (len(emails) == len(totals) == len(memos) == len(priors) == len(hires)):
|
|
raise HTTPException(status_code=400, detail="잔여 연차 칸이 맞지 않습니다.")
|
|
|
|
def num(v: Any, label: str, email: str) -> float | None:
|
|
v = str(v).strip()
|
|
if not v:
|
|
return None
|
|
try:
|
|
return float(v)
|
|
except ValueError:
|
|
raise HTTPException(status_code=400, detail=f"{label}이(가) 숫자가 아닙니다: {email}")
|
|
|
|
rows = [{"user_email": email, "total_days": num(total, "연차 일수", email), "prior_used": num(prior, "시스템 전 사용", email),
|
|
"memo": memo, "hire_date": str(hire).strip()}
|
|
for email, total, prior, memo, hire in zip(emails, totals, priors, memos, hires)]
|
|
from starlette.concurrency import run_in_threadpool # noqa: WPS433 — 폼 배열을 읽으려 async, DB 는 동기라 스레드에서
|
|
|
|
try:
|
|
n = await run_in_threadpool(store.save_balances, rows=rows, by=user["email"])
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc))
|
|
return RedirectResponse(url="/vacation/options?" + urlencode({"msg": f"잔여 연차 {n}명을 저장했습니다."})
|
|
+ "#balances", status_code=303)
|
|
|
|
|
|
def _balance_rows(store: Any, as_of: date) -> list[dict[str, Any]]:
|
|
"""옵션 잔여 연차 표 — 참여자(휴가 모듈 사용자) 전원 + 예전에 등록됐지만 지금 권한이 없는 사람(2026-10-27 입사일 기준).
|
|
줄마다 입사일·근속·이번 연차 기간·생기는 연차(법정, 오늘까지/앞으로)·직접 입력·시스템 전 사용·사용·지금 잔여·먼저 소멸할 잔여·메모
|
|
(db.balance_summary → store.leave_status 한 곳)."""
|
|
users = _vacation_users()
|
|
registered = {b["user_email"] for y in (as_of.year - 1, as_of.year) for b in store.list_balances(year=y)}
|
|
hires = store.hire_dates()
|
|
rows = []
|
|
people = [(u["email"].lower(), u.get("name") or u["email"].split("@")[0], u.get("picture") or "", True) for u in users]
|
|
known = {p[0] for p in people}
|
|
people += [(e, e.split("@")[0], "", False) for e in sorted(registered | set(hires)) if e not in known]
|
|
for email, name, picture, active in people:
|
|
s = store.balance_summary(user_email=email, as_of=as_of, hire_date=hires.get(email))
|
|
counted = s["has_hire"] or s["manual_total"] is not None
|
|
rows.append({"email": email, "name": name, "picture": picture, "active": active,
|
|
"hire_date": s["hire_date"], "service_years": s["service_years"],
|
|
"period_start": s["period_start"], "period_end": s["period_end"],
|
|
"granted": s["granted"], "granted_so_far": s["granted_so_far"], "upcoming": s["upcoming"],
|
|
"grants_tip": ", ".join(f"{g['date'][2:]} {g['label']} {g['days']:g}일(~{g['expires'][2:]})" for g in s["grants"]),
|
|
"total": s["manual_total"], "prior": s["prior_used"], "used": s["used"],
|
|
"available": s["available"] if counted else None, "expiring": s["expiring"], "memo": s["memo"]})
|
|
return rows
|
|
|
|
|
|
@router.get("/api/calendar")
|
|
def api_calendar(
|
|
request: Request, user: dict[str, Any] = Depends(_require_user)
|
|
) -> JSONResponse:
|
|
"""달력 비동기 데이터(JSON). year/month 쿼리."""
|
|
store = _store(request)
|
|
if store is None:
|
|
raise HTTPException(status_code=503, detail="vacation_db 미설정")
|
|
year, month = _ym(request)
|
|
sel = request.query_params.get("date") or f"{year:04d}-{month:02d}-01"
|
|
caldata = _build_calendar(store, year, month, sel)
|
|
return JSONResponse(
|
|
{
|
|
"year": year,
|
|
"month": month,
|
|
"weeks": caldata["weeks"],
|
|
"requests": caldata["requests"],
|
|
}
|
|
)
|
|
|
|
|
|
@router.get("/export.xlsx")
|
|
def export_xlsx(
|
|
request: Request, user: dict[str, Any] = Depends(_require_user)
|
|
) -> StreamingResponse:
|
|
from openpyxl import Workbook # 지연 import
|
|
|
|
store = _store(request)
|
|
if store is None:
|
|
raise HTTPException(status_code=503, detail="vacation_db 미설정")
|
|
|
|
today = today_kst()
|
|
try:
|
|
year = int(request.query_params.get("year") or today.year)
|
|
month = int(request.query_params.get("month") or 0)
|
|
except ValueError:
|
|
year, month = today.year, 0
|
|
|
|
if 1 <= month <= 12:
|
|
last = _calendar.monthrange(year, month)[1]
|
|
date_from = f"{year:04d}-{month:02d}-01"
|
|
date_to = f"{year:04d}-{month:02d}-{last:02d}"
|
|
else:
|
|
date_from = f"{year:04d}-01-01"
|
|
date_to = f"{year:04d}-12-31"
|
|
|
|
rows = store.list_for_export(date_from=date_from, date_to=date_to)
|
|
|
|
wb = Workbook()
|
|
ws = wb.active
|
|
ws.title = "vacation"
|
|
header = [
|
|
"신청자", "휴가종류", "시작일", "종료일", "시작구분", "종료구분",
|
|
"사용일수", "상태", "승인자", "승인/반려일", "사유", "반려사유",
|
|
]
|
|
ws.append(header)
|
|
for r in rows:
|
|
ws.append([
|
|
r.get("owner_name") or r.get("owner", ""),
|
|
r.get("vacation_type", ""),
|
|
r.get("start_date", ""),
|
|
r.get("end_date", ""),
|
|
HALF_LABELS.get(r.get("start_half", "full"), ""),
|
|
HALF_LABELS.get(r.get("end_half", "full"), ""),
|
|
r.get("days", 0),
|
|
r.get("status", ""),
|
|
r.get("approver_email", "") or "",
|
|
r.get("decided_at", "") or "",
|
|
r.get("reason", "") or "",
|
|
r.get("reject_reason", "") or "",
|
|
])
|
|
widths = [24, 10, 12, 12, 8, 8, 8, 8, 24, 22, 30, 30]
|
|
for col, w in enumerate(widths, start=1):
|
|
ws.column_dimensions[ws.cell(row=1, column=col).column_letter].width = w
|
|
|
|
buf = io.BytesIO()
|
|
wb.save(buf)
|
|
buf.seek(0)
|
|
scope = f"{year}{('%02d' % month) if (1 <= month <= 12) else ''}"
|
|
fname = f"vacation_{scope}_{now_kst().strftime('%Y%m%d_%H%M%S')}.xlsx"
|
|
return StreamingResponse(
|
|
buf,
|
|
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
headers={"Content-Disposition": f'attachment; filename="{fname}"'},
|
|
)
|
|
|
|
|
|
@router.get("/health")
|
|
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()
|
|
can_edit = _can_edit_options(request, user, opts, users)
|
|
today = today_kst()
|
|
bal_rows = _balance_rows(store, today) if can_edit else []
|
|
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", ""),
|
|
"bal_today": today.isoformat(),
|
|
# "시스템 전 사용"(도입 해 2026 에 이미 쓴 연차) 칸 — 도입 다음 해까지, 또는 값이 남아 있으면
|
|
"bal_prior_col": today.year <= SYSTEM_START_YEAR + 1 or any(r["prior"] for r in bal_rows),
|
|
"system_start_year": SYSTEM_START_YEAR,
|
|
"hire_ready": store.hire_ready() if can_edit else False,
|
|
"can_edit": can_edit,
|
|
"bal_rows": bal_rows,
|
|
},
|
|
)
|
|
|
|
|
|
@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
|
|
|
|
if not _can_edit_options(request, 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["_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
|
|
from app.store import is_admin # noqa: WPS433
|
|
|
|
guard = _guard(request)
|
|
if not isinstance(guard, tuple):
|
|
return guard
|
|
store, user = guard
|
|
req = store.get_request(request_id=request_id)
|
|
if not req:
|
|
return render_template(
|
|
request, "denied.html",
|
|
{"reason": "휴가 신청을 찾을 수 없습니다.", "is_admin": is_admin(user)},
|
|
status_code=404,
|
|
)
|
|
is_owner = req["owner"] == user["email"]
|
|
is_approver = _is_approver(request, user)
|
|
if not (is_owner or is_approver):
|
|
return render_template(
|
|
request, "denied.html",
|
|
{"reason": "본인 또는 승인자만 조회할 수 있습니다.", "is_admin": is_admin(user)},
|
|
status_code=403,
|
|
)
|
|
return render_template(
|
|
request,
|
|
"vacation/detail.html",
|
|
{
|
|
"user": user,
|
|
"is_admin": is_admin(user),
|
|
"is_approver": is_approver,
|
|
"is_owner": is_owner,
|
|
"nav_items": build_erp_nav(user, active="vacation"),
|
|
"page_title": "휴가 상세",
|
|
"page_subtitle": f"{req['start_date']} · {req['vacation_type']}",
|
|
"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
|
|
from app.store import is_admin # noqa: WPS433
|
|
|
|
guard = _guard(request)
|
|
if not isinstance(guard, tuple):
|
|
return guard
|
|
store, user = guard
|
|
req = store.get_request(request_id=request_id)
|
|
if not req:
|
|
return render_template(
|
|
request, "denied.html",
|
|
{"reason": "휴가 신청을 찾을 수 없습니다.", "is_admin": is_admin(user)},
|
|
status_code=404,
|
|
)
|
|
if req["owner"] != user["email"]:
|
|
return render_template(
|
|
request, "denied.html",
|
|
{"reason": "본인 신청만 수정할 수 있습니다.", "is_admin": is_admin(user)},
|
|
status_code=403,
|
|
)
|
|
if req["status"] not in ("작성중", "반려"):
|
|
return render_template(
|
|
request, "denied.html",
|
|
{"reason": f"{req['status']} 상태에서는 수정할 수 없습니다.", "is_admin": is_admin(user)},
|
|
status_code=409,
|
|
)
|
|
ctx = _form_context(request, user)
|
|
ctx.update(
|
|
{
|
|
"page_title": "휴가 신청 수정",
|
|
"page_subtitle": "작성중/반려 상태만 수정 가능",
|
|
"mode": "edit",
|
|
"req": req,
|
|
"default_date": req["start_date"],
|
|
}
|
|
)
|
|
return render_template(request, "vacation/form.html", ctx)
|
|
|
|
|
|
@router.post("/{request_id}/edit")
|
|
def update(
|
|
request: Request,
|
|
bg: BackgroundTasks,
|
|
request_id: str,
|
|
vacation_type: str = Form(...),
|
|
start_date: str = Form(...),
|
|
end_date: str = Form(""),
|
|
start_half: str = Form("full"),
|
|
end_half: str = Form("full"),
|
|
reason: str = Form(""),
|
|
action: str = Form("save"), # "save" | "submit"
|
|
user: dict[str, Any] = Depends(_require_user),
|
|
) -> RedirectResponse:
|
|
store = _store(request)
|
|
if store is None:
|
|
raise HTTPException(status_code=503, detail="vacation_db 미설정")
|
|
payload = _payload_from_form(
|
|
vacation_type, start_date, end_date, start_half, end_half, reason
|
|
)
|
|
try:
|
|
store.update_request(request_id=request_id, owner=user["email"], payload=payload)
|
|
if action == "submit":
|
|
_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:
|
|
raise HTTPException(status_code=403, detail=str(exc))
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc))
|
|
return RedirectResponse(url=f"/vacation/{request_id}", status_code=303)
|
|
|
|
|
|
@router.post("/{request_id}/submit")
|
|
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:
|
|
_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)
|
|
|
|
|
|
@router.post("/{request_id}/approve")
|
|
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:
|
|
_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)
|
|
|
|
|
|
@router.post("/{request_id}/reject")
|
|
def reject(
|
|
request: Request,
|
|
request_id: str,
|
|
bg: BackgroundTasks,
|
|
reject_reason: str = Form(...),
|
|
user: dict[str, Any] = Depends(_require_approver),
|
|
) -> RedirectResponse:
|
|
store = _store(request)
|
|
if store is None:
|
|
raise HTTPException(status_code=503, detail="vacation_db 미설정")
|
|
try:
|
|
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)
|
|
|
|
|
|
@router.post("/{request_id}/cancel")
|
|
def cancel(
|
|
request: Request,
|
|
request_id: str,
|
|
user: dict[str, Any] = Depends(_require_user),
|
|
) -> RedirectResponse:
|
|
from app.store import is_admin # noqa: WPS433
|
|
|
|
store = _store(request)
|
|
if store is None:
|
|
raise HTTPException(status_code=503, detail="vacation_db 미설정")
|
|
try:
|
|
store.cancel(
|
|
request_id=request_id, user_email=user["email"], is_admin=is_admin(user)
|
|
)
|
|
except KeyError:
|
|
raise HTTPException(status_code=404, detail="휴가 신청을 찾을 수 없습니다.")
|
|
except PermissionError as exc:
|
|
raise HTTPException(status_code=403, detail=str(exc))
|
|
return RedirectResponse(url=f"/vacation/{request_id}", status_code=303)
|
|
|
|
|
|
@router.post("/{request_id}/delete")
|
|
def delete(
|
|
request: Request,
|
|
request_id: str,
|
|
user: dict[str, Any] = Depends(_require_user),
|
|
) -> RedirectResponse:
|
|
"""완전 삭제 — 승인 전(작성중/제출/반려)만. 달력으로 복귀."""
|
|
from app.store import is_admin # noqa: WPS433
|
|
|
|
store = _store(request)
|
|
if store is None:
|
|
raise HTTPException(status_code=503, detail="vacation_db 미설정")
|
|
try:
|
|
store.hard_delete(
|
|
request_id=request_id, user_email=user["email"], is_admin=is_admin(user)
|
|
)
|
|
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))
|
|
return RedirectResponse(url="/vacation/", status_code=303)
|