From 09f6a2ee6f3c408b637a9c14f52c9490cb63b8bb Mon Sep 17 00:00:00 2001 From: king Date: Mon, 26 Oct 2026 14:35:44 +0900 Subject: [PATCH] =?UTF-8?q?feat(vacation):=20=ED=9C=B4=EA=B0=80=20?= =?UTF-8?q?=EC=98=B5=EC=85=98(=EC=8A=B9=EC=9D=B8=EC=9E=90=C2=B7=EC=8A=B9?= =?UTF-8?q?=EC=9D=B8=20=ED=86=B5=EB=B3=B4=EC=9E=90)=20=C2=B7=20=EC=A0=9C?= =?UTF-8?q?=EC=B6=9C=C2=B7=EC=8A=B9=EC=9D=B8=C2=B7=EB=B0=98=EB=A0=A4=20?= =?UTF-8?q?=EB=A9=94=EC=9D=BC(=EC=B2=98=EB=A6=AC=ED=95=9C=20=EC=82=AC?= =?UTF-8?q?=EB=9E=8C=20=EB=B3=B8=EC=9D=B8=20Gmail)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - /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 --- CLAUDE.md | 1 + app/mail.py | 5 + app/modules/inout/CLAUDE.md | 2 + app/modules/inout/router.py | 40 +++ app/modules/vacation/CLAUDE.md | 17 + app/modules/vacation/db.py | 78 +++++ app/modules/vacation/notify.py | 196 +++++++++++ app/modules/vacation/router.py | 205 ++++++++++- .../vacation/templates/vacation/detail.html | 20 +- .../vacation/templates/vacation/form.html | 2 +- .../vacation/templates/vacation/index.html | 4 +- .../vacation/templates/vacation/options.html | 87 +++++ .../vacation/templates/vacation/pending.html | 2 +- .../vacation/templates/vacation/settings.html | 2 +- app/static/vacation.css | 32 ++ docs/DATABASES.md | 8 + scripts/sql/vacation_db_001_options_mail.sql | 37 ++ tests/test_vacation_db.py | 75 ++++ tests/test_vacation_options_mail.py | 322 ++++++++++++++++++ 19 files changed, 1120 insertions(+), 15 deletions(-) create mode 100644 app/modules/vacation/notify.py create mode 100644 app/modules/vacation/templates/vacation/options.html create mode 100644 scripts/sql/vacation_db_001_options_mail.sql create mode 100644 tests/test_vacation_db.py create mode 100644 tests/test_vacation_options_mail.py diff --git a/CLAUDE.md b/CLAUDE.md index 4185379..80cc81e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -59,6 +59,7 @@ - `performance_store` 매출: 실적 → 프로젝트 주간 회의록 머리 카드(읽기 전용). - `ProjectStore.pool`(`project_db`): 프로젝트 + 긴급 공지. - `APP_ENCRYPTION_KEY`: 실적(쇼핑몰·광고 인증) + 입출고(Gmail 토큰). +- 입출고 Gmail 연결(`inout_gmail_tokens`·`/inout/gmail/callback`): 입출고 발주 메일 + 휴가 메일(`vacation/notify.py`, 처리한 사람 본인 Gmail). - `app/integrations/google_sheets.py`(쿠팡) · `google_slides.py`(프로젝트 회의록 보드). - `app/mail.py`: 프로젝트 알림 메일. - ERP 모든 화면 스크립트: `erp-notice.js`(공지) · `erp-overdue.js`(프로젝트 마감 알림). diff --git a/app/mail.py b/app/mail.py index 4ffd446..9f56faa 100644 --- a/app/mail.py +++ b/app/mail.py @@ -44,9 +44,12 @@ def send_email( body: str, html: str | None = None, from_name: str = "DBX ERP", + reply_to: str = "", ) -> bool: """단순 텍스트(+선택 HTML) 메일 1건 발송. + reply_to — 받는 사람이 [답장]하면 갈 주소(예: 휴가 메일 = 처리한 사람, 2026-10-27). 보내는 주소는 늘 SMTP_FROM. + 반환: 성공 True / 비활성·실패 False. 예외를 밖으로 던지지 않는다. """ host = _env("SMTP_HOST") @@ -71,6 +74,8 @@ def send_email( msg["Subject"] = subject msg["From"] = formataddr((from_name, sender)) msg["To"] = ", ".join(recipients) + if reply_to and "@" in reply_to: + msg["Reply-To"] = formataddr((from_name, reply_to.strip())) msg.set_content(body) if html: msg.add_alternative(html, subtype="html") diff --git a/app/modules/inout/CLAUDE.md b/app/modules/inout/CLAUDE.md index c48f67f..a010b56 100644 --- a/app/modules/inout/CLAUDE.md +++ b/app/modules/inout/CLAUDE.md @@ -29,6 +29,8 @@ - 새 발주서 저장 → 미리보기 팝업(받는 사람 = 공장 이메일, 요약 표 본문) → 사람이 [메일 발송]을 눌러야 보냄. - **발주 담당 본인 Gmail**(Gmail API `gmail.send`, 사람마다 [Gmail 연결] 1회 — 고른 구글 계정 = ERP 계정 확인). 갱신 토큰은 `APP_ENCRYPTION_KEY` AES-GCM 암호문(`gmail.py`). + **휴가 모듈도 같은 연결을 쓴다**(2026-10-27) — 휴가 옵션 [Gmail 연결]은 세션 `_gmail_origin=vacation` 을 달고 같은 콜백(`/inout/gmail/callback`)으로 돌아오며, + 콜백이 `_gmail_callback_vacation`(휴가 권한 확인, 휴가 옵션으로 복귀)으로 넘긴다. 토큰 표·끊기는 공용 — 바꾸면 휴가 메일(`vacation/notify.py`)도 확인. - 보낸 기록·재발송 확인. - **입고 담당 발주 알림 자동 발송**(2026-10-19): 발주 메일이 나가면 같은 Gmail 로 옵션 → 담당자의 입고 담당들에게 따로 보냄 — 제목은 발주 메일과 같고 내용은 발주번호·발주일·제품 코드·제품명·수량만(`store.order_notice_mail`, `router._send_order_notice`). 실패해도 공장 메일은 그대로(안내만), 미리보기 창에 받을 사람 안내. - **참조 기본값 `king@dbxcorp.co.kr`**(2026-10-19) — 미리보기 참조 칸에 미리 들어감, 옵션 → 공장 탭 "발주 메일 참조"에서 고침(`inout_settings` `order_mail_cc`, 행이 없으면 기본값 — 저장만 005 필요). diff --git a/app/modules/inout/router.py b/app/modules/inout/router.py index 2965b3f..67e04e7 100644 --- a/app/modules/inout/router.py +++ b/app/modules/inout/router.py @@ -577,6 +577,7 @@ async def gmail_connect(request: Request, next: str = "/inout/") -> Any: # noqa except gmail.GmailError as exc: return _redirect(_safe_next(next), str(exc)) request.session["_inout_gmail_next"] = _safe_next(next) + request.session.pop("_gmail_origin", None) # 휴가 옵션에서 시작한 연결 표시가 남아 있으면 지움 return await client.authorize_redirect( request, public_url_for(request, "inout_gmail_callback"), access_type="offline", prompt="consent", include_granted_scopes="true", @@ -585,6 +586,8 @@ async def gmail_connect(request: Request, next: str = "/inout/") -> Any: # noqa @router.get("/gmail/callback", name="inout_gmail_callback") async def gmail_callback(request: Request) -> Any: + if request.session.get("_gmail_origin") == "vacation": + return await _gmail_callback_vacation(request) got = _ctx(request) if not isinstance(got, tuple): return got @@ -608,6 +611,43 @@ async def gmail_callback(request: Request) -> Any: return _redirect(nxt, "Gmail 을 연결했습니다 — 이제 [메일 발송]으로 보낼 수 있습니다.") +async def _gmail_callback_vacation(request: Request) -> Any: + """휴가 옵션 [Gmail 연결](2026-10-27) — 같은 구글 리디렉션 주소를 함께 쓰므로 여기로 돌아온다(구글 클라우드 설정 추가 없음). + 입출고 담당 권한 대신 휴가 모듈 권한을 보고, 토큰은 입출고와 같은 inout_gmail_tokens 에(한 사람 = 연결 하나, 두 모듈이 같이 씀).""" + from urllib.parse import quote # noqa: WPS433 + + from authlib.integrations.starlette_client import OAuthError # noqa: WPS433 + + from app.main import get_current_user_record # noqa: WPS433 + from app.store import has_module # noqa: WPS433 + + from . import gmail # noqa: WPS433 + + request.session.pop("_gmail_origin", None) + nxt = str(request.session.pop("_vacation_gmail_next", "") or "") + if not nxt.startswith("/vacation/") or "//" in nxt or "\\" in nxt: + nxt = "/vacation/options" + user = get_current_user_record(request) + if user is None: + return RedirectResponse(url="/login?next=" + quote(nxt, safe=""), status_code=303) + if not has_module(user, "vacation"): + raise HTTPException(status_code=403, detail="휴가 관리 모듈 권한이 없습니다.") + st = _store(request) + if st is None: + return _redirect(nxt, "Gmail 연결 저장소(입출고 DB)가 설정되지 않아 연결할 수 없습니다.") + email = user.get("email", "") + try: + token = await gmail.oauth_client().authorize_access_token(request) + refresh, scopes = gmail.check_grant(token, expected_email=email) + st.save_gmail_token(email, refresh_token_enc=gmail.encrypt_token(email, refresh), scopes=scopes) + except OAuthError as exc: + msg = "Gmail 연결을 취소했습니다." if exc.error == "access_denied" else f"Gmail 연결 실패({exc.error})" + return _redirect(nxt, msg) + except (gmail.GmailError, ValueError) as exc: + return _redirect(nxt, str(exc)) + return _redirect(nxt, "Gmail 을 연결했습니다 — 이제 휴가 메일이 내 Gmail 로 나갑니다.") + + @router.post("/gmail/disconnect") def gmail_disconnect(request: Request) -> JSONResponse: user = _user(request) diff --git a/app/modules/vacation/CLAUDE.md b/app/modules/vacation/CLAUDE.md index 853237f..661319b 100644 --- a/app/modules/vacation/CLAUDE.md +++ b/app/modules/vacation/CLAUDE.md @@ -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`). diff --git a/app/modules/vacation/db.py b/app/modules/vacation/db.py index 1f812dd..6a59708 100644 --- a/app/modules/vacation/db.py +++ b/app/modules/vacation/db.py @@ -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 # ════════════════════════════════════════════════════════════ diff --git a/app/modules/vacation/notify.py b/app/modules/vacation/notify.py new file mode 100644 index 0000000..49fa0f6 --- /dev/null +++ b/app/modules/vacation/notify.py @@ -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'' + f'{escape(k)}{escape(str(v))}' for k, v in rows) + color = {"submitted": "#1a56db", "approved": "#0f8a3a", "rejected": "#c22b10"}[event] + html = ( + '
' + f'

{escape(EVENT_LEAD[event])}

' + f'{tr}
' + f'

휴가 신청 보기

' + '

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

' + ) + return {"subject": subject, "text": text, "html": html} + + +def _send_gmail(inout_store: Any, *, email: str, name: str, to: list[str], mail: dict[str, str]) -> tuple[bool, str]: + """본인 Gmail 로 — (보냄, 못 보낸 까닭). 연결이 없으면 (False, '').""" + if inout_store is None: + return False, "" + try: + row = inout_store.gmail_token(email) + except Exception as exc: # noqa: BLE001 — 입출고 DB 장애여도 SMTP 로 대신 + return False, f"Gmail 연결 조회 실패({type(exc).__name__})" + if not row: + return False, "" + from app.modules.inout import gmail # noqa: WPS433 + + try: + refresh = gmail.decrypt_token(email, row["refresh_token_enc"]) + raw = gmail.build_message(sender_name=name, sender_email=email, to=to, cc=[], subject=mail["subject"], + text=mail["text"], html=mail["html"]) + gmail.send(refresh, raw) + except gmail.GmailNotConnected as exc: + try: + inout_store.delete_gmail_token(email) + except Exception: # noqa: BLE001 + pass + return False, str(exc) + except gmail.GmailError as exc: + try: + inout_store.mark_gmail(email, error=str(exc)) + except Exception: # noqa: BLE001 + pass + return False, str(exc) + try: + inout_store.mark_gmail(email) + except Exception: # noqa: BLE001 + pass + return True, "" + + +def deliver(store: Any, inout_store: Any, *, event: str, req: dict[str, Any], actor: dict[str, Any], + users: list[dict[str, Any]], link: str) -> dict[str, Any]: + """받는 사람을 정해 한 통 보내고 기록한다. 반환 {ok, via, to, error} (테스트·로그용).""" + from app import mail as smtp # noqa: WPS433 + + if event not in EVENTS: + raise ValueError(event) + try: + options = store.get_options() + except Exception: # noqa: BLE001 — 001 미적용 등: 옵션 없음 + options = {"approvers": [], "notifiers": []} + to = recipients(event, req, options, users) + names = {_norm(u.get("email")): u.get("name") or "" for u in users} + email = _norm(actor.get("email")) + name = actor.get("name") or names.get(email) or email.split("@")[0] + result: dict[str, Any] = {"ok": False, "via": "", "to": to, "error": ""} + if not to: + result["error"] = "받는 사람 없음(승인자·통보자 미지정)" + logger.info("휴가 메일 받는 사람 없음 — %s %s", event, req.get("id")) + return result + mail = build(event, req, actor_name=name, actor_email=email, link=link, + name_of=lambda e: names.get(_norm(e)) or str(e).split("@")[0]) + ok, gmail_err = _send_gmail(inout_store, email=email, name=name, to=to, mail=mail) + if ok: + result.update(ok=True, via="gmail") + else: + sent = smtp.send_email(to=to, subject=mail["subject"], body=mail["text"], html=mail["html"], + from_name=f"{name} (DBX ERP)", reply_to=email) + if sent: + err = f"Gmail 실패 → 회사 메일로 보냄: {gmail_err}" if gmail_err else "" + else: + smtp_err = "회사 알림 메일(SMTP) " + ("발송 실패" if smtp.mail_enabled() else "미설정") + err = f"{gmail_err} · {smtp_err}" if gmail_err else smtp_err + result.update(ok=bool(sent), via="smtp", error=err) + try: + store.add_mail_log(request_id=str(req.get("id") or ""), event=event, sender=email, via=result["via"], + recipients=to, subject=mail["subject"], ok=result["ok"], error=result["error"]) + except Exception: # noqa: BLE001 — 기록 실패가 메일·휴가 처리를 막지 않게 + logger.warning("휴가 메일 기록 실패 — %s %s", event, req.get("id")) + return result diff --git a/app/modules/vacation/router.py b/app/modules/vacation/router.py index cc04e8e..934b8eb 100644 --- a/app/modules/vacation/router.py +++ b/app/modules/vacation/router.py @@ -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) diff --git a/app/modules/vacation/templates/vacation/detail.html b/app/modules/vacation/templates/vacation/detail.html index 1dbc25e..7b0856f 100644 --- a/app/modules/vacation/templates/vacation/detail.html +++ b/app/modules/vacation/templates/vacation/detail.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
@@ -56,6 +56,24 @@ {% endif %} + {#- 휴가 메일 기록(2026-10-27, 001) — 제출·승인·반려 때 보낸 메일(받는 사람·보낸 사람·방법·결과) -#} + {% if mail_log %} +
+
메일
+
    + {% for m in mail_log %} +
  • + {{ m.sent_at[5:16] | replace('T', ' ') }} + {{ event_words.get(m.event, m.event) }} + {{ '보냄' if m.ok else '못 보냄' }} + — {{ m.sender }}{% if m.via %} ({{ 'Gmail' if m.via == 'gmail' else '회사 메일' }}){% endif %} → {{ m.recipients or '받는 사람 없음' }} + {% if m.error %}{{ m.error }}{% endif %} +
  • + {% endfor %} +
+
+ {% endif %} +
◀◀ 달력 diff --git a/app/modules/vacation/templates/vacation/form.html b/app/modules/vacation/templates/vacation/form.html index 12ea7cf..118816c 100644 --- a/app/modules/vacation/templates/vacation/form.html +++ b/app/modules/vacation/templates/vacation/form.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
diff --git a/app/modules/vacation/templates/vacation/index.html b/app/modules/vacation/templates/vacation/index.html index b6f6912..0e327b4 100644 --- a/app/modules/vacation/templates/vacation/index.html +++ b/app/modules/vacation/templates/vacation/index.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
@@ -18,6 +18,8 @@ {% if is_admin %} 설정 {% endif %} + {#- 옵션(2026-10-27) — 승인자·승인 통보자(수정 = 관리자) · 내 Gmail 연결(누구나) -#} + 옵션
총 {{ balance.total_days }} diff --git a/app/modules/vacation/templates/vacation/options.html b/app/modules/vacation/templates/vacation/options.html new file mode 100644 index 0000000..3d5ddc5 --- /dev/null +++ b/app/modules/vacation/templates/vacation/options.html @@ -0,0 +1,87 @@ +{% extends "erp_base.html" %} + +{#- 휴가 옵션(2026-10-27) — 승인자·승인 통보자(수정 = ERP 관리자, 나머지는 보기만) + 내 Gmail 연결(누구나). + 메일: 제출 = 승인자·통보자, 승인·반려 = 승인자·통보자·신청자. 보내는 사람 = 처리한 사람 본인 Gmail(없으면 회사 메일). -#} +{% block head_extra %}{% endblock %} + +{% block content %} +
+ +
+ +
+ + {% if msg %}

{{ msg }}

{% endif %} + {% if not options.ready %} + + {% endif %} + +
+ {% for key, title, hint in ( + ('approvers', '휴가 승인자', '제출된 휴가를 승인·반려합니다(여러 명이면 누구든 한 명). 비워 두면 관리자 화면의 "휴가 승인" 권한자가 승인합니다. ERP 관리자는 늘 승인할 수 있습니다.'), + ('notifiers', '휴가 승인 통보자', '휴가가 제출·승인·반려될 때마다 메일을 받습니다(승인 권한은 없음).')) %} + {% set chosen = options[key] %} +
+

{{ title }} {{ chosen | length }}명

+

{{ hint }}

+ {% if key == 'approvers' and not chosen %} +

지금 승인자(권한자): {% if effective_approvers %}{{ effective_approvers | join(', ') }}{% else %}없음 — ERP 관리자만{% endif %}

+ {% endif %} +
    + {% for c in candidates %} +
  • + +
  • + {% else %} +
  • 휴가 모듈 권한이 있는 사용자가 없습니다.
  • + {% endfor %} +
+
+ {% endfor %} +
+ {% if is_admin and options.ready %} + + {% if options.updated_by %}마지막 저장 {{ options.updated_by }} · {{ options.updated_at[:16] | replace('T', ' ') }}{% endif %} + {% elif not is_admin %} + 승인자·통보자는 ERP 관리자만 바꿀 수 있습니다. + {% endif %} +
+
+ +
+

메일

+
    +
  • 제출 → 승인자 · 통보자
  • +
  • 승인 · 반려 → 승인자 · 통보자 · 신청자
  • +
  • 보내는 사람 = 그 일을 한 사람(제출 = 신청자, 승인·반려 = 처리한 승인자)의 본인 Gmail. + Gmail 을 연결하지 않았으면 회사 알림 메일로 보내고 보낸 사람 이름·답장 주소를 그 사람으로 합니다.
  • +
+
+ + 내 Gmail({{ user.email }}) — {% if gmail.connected %}연결됨{% else %}연결 안 됨{% endif %} + {% if gmail.connected %} +
+ +
+ {% elif gmail.available %} + Gmail 연결 + {% else %} + Gmail 연결을 쓸 수 없는 서버입니다(입출고 DB·구글 OAuth·APP_ENCRYPTION_KEY 필요) — 회사 메일로 보냅니다. + {% endif %} +
+

입출고 발주 메일과 같은 연결입니다(한 번 연결하면 두 곳 모두). 메일 보내기 권한(gmail.send)만 받습니다. + {% if not gmail.smtp %}
회사 알림 메일(SMTP)이 설정되지 않아 Gmail 을 연결하지 않은 사람의 메일은 나가지 않습니다.{% endif %}

+
+ +
+{% endblock %} diff --git a/app/modules/vacation/templates/vacation/pending.html b/app/modules/vacation/templates/vacation/pending.html index d7ac6d3..ae1b19f 100644 --- a/app/modules/vacation/templates/vacation/pending.html +++ b/app/modules/vacation/templates/vacation/pending.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
diff --git a/app/modules/vacation/templates/vacation/settings.html b/app/modules/vacation/templates/vacation/settings.html index 2ce5384..fd63a56 100644 --- a/app/modules/vacation/templates/vacation/settings.html +++ b/app/modules/vacation/templates/vacation/settings.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
diff --git a/app/static/vacation.css b/app/static/vacation.css index c0d5dd8..334c499 100644 --- a/app/static/vacation.css +++ b/app/static/vacation.css @@ -13,6 +13,8 @@ } .vac { display: flex; flex-direction: column; gap: 16px; } +/* 셸 .erp-page 는 width:100% + 좌우 여백이라 오른쪽이 48px 넘쳐 잘린다 — 실적처럼 border-box(2026-10-27) */ +.erp-page:has(> .vac) { box-sizing: border-box; } /* 검정 배경 버튼 글자 흰색 강제 */ .vac .erp-btn-primary { color: #fff !important; } @@ -217,3 +219,33 @@ .vac-check { display: flex; align-items: center; gap: 6px; font-size: 13px; } .vac-set-scroll { max-height: 420px; overflow: auto; } .vac-set-note { font-size: 12px; margin-top: 8px; } + +/* ── 휴가 옵션(2026-10-27) — 승인자·승인 통보자 · 메일 ── */ +.vac-opt-msg { margin: 0 0 12px; padding: 8px 12px; border-radius: 8px; background: #eef6ff; color: #1a4fa0; font-size: 13px; } +.vac-opt-msg.is-warn { background: #fff7e6; color: #8a5a00; } +.vac-opt-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; align-items: start; } +.vac-opt-card { padding: 16px; } +.vac-opt-count { font-size: 12px; font-weight: 500; margin-left: 4px; } +.vac-opt-hint { margin: 4px 0 10px; font-size: 12px; line-height: 1.5; } +.vac-opt-now { margin: 0 0 10px; font-size: 12px; color: var(--vac-muted); } +.vac-opt-people { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; max-height: 420px; overflow-y: auto; } +.vac-opt-person { display: flex; align-items: center; gap: 8px; padding: 6px 8px; border-radius: 8px; border: 1px solid transparent; cursor: pointer; } +.vac-opt-person:hover { background: #f6f7f9; } +.vac-opt-person.is-on, .vac-opt-person:has(input:checked) { border-color: #c7d2fe; background: #f0f3ff; } +.vac-opt-person input:disabled + * { opacity: 1; } +.vac-opt-face { width: 24px; height: 24px; border-radius: 50%; object-fit: cover; flex: none; } +.vac-opt-face.is-ini { display: inline-flex; align-items: center; justify-content: center; background: #e5e7eb; color: #374151; font-size: 12px; font-weight: 700; } +.vac-opt-name { font-weight: 600; } +.vac-opt-mail { font-size: 12px; margin-left: auto; } +.vac-opt-save { grid-column: 1 / -1; display: flex; align-items: center; gap: 12px; } +.vac-opt-mailcard { margin-top: 16px; } +.vac-opt-rules { margin: 4px 0 12px; padding-left: 18px; font-size: 13px; line-height: 1.7; } +.vac-opt-gmail { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; } +.vac-opt-gmail-state { font-weight: 600; color: var(--vac-muted); } +.vac-opt-gmail-state.is-on { color: #0f8a3a; } +@media (max-width: 900px) { .vac-opt-grid { grid-template-columns: 1fr; } } +/* 상세 — 휴가 메일 기록 */ +.vac-mail-log ul { list-style: none; margin: 4px 0 0; padding: 0; display: flex; flex-direction: column; gap: 4px; font-size: 13px; } +.vac-mail-log li.is-fail b { color: #c22b10; } +.vac-mail-when { color: var(--vac-muted); margin-right: 6px; font-variant-numeric: tabular-nums; } +.vac-mail-err { display: block; margin-left: 2px; color: #c22b10; font-size: 12px; } diff --git a/docs/DATABASES.md b/docs/DATABASES.md index 7aaaa18..60e817a 100644 --- a/docs/DATABASES.md +++ b/docs/DATABASES.md @@ -257,6 +257,14 @@ DDL: `scripts/sql/vacation_db_init.sql` (멱등). DB·역할(`vacation_app`)· 권한: `vacation`(접근) / `vacation_approver`(승인·반려). admin 은 항상 통과. 공휴일·연차 설정은 admin 전용. +**마이그레이션 001**(`scripts/sql/vacation_db_001_options_mail.sql`, 2026-10-27, 테이블만 추가·멱등): +`vacation_options`(키 `approval` = 휴가 승인자·승인 통보자 JSONB — 승인자를 지정하면 그 사람들 + admin 만 승인·반려) · +`vacation_mail_log`(제출·승인·반려 메일 기록 — 보낸 사람·gmail|smtp·받는 사람·성공·오류). 미적용이면 옵션 없음·기록 없음으로 동작. + +```bash +docker exec -i postgres-db psql -U postgres -d vacation_db -v ON_ERROR_STOP=1 < scripts/sql/vacation_db_001_options_mail.sql +``` + ### 운영 서버 초기화 (1회, 사용자 승인 후) ```bash diff --git a/scripts/sql/vacation_db_001_options_mail.sql b/scripts/sql/vacation_db_001_options_mail.sql new file mode 100644 index 0000000..0e5224c --- /dev/null +++ b/scripts/sql/vacation_db_001_options_mail.sql @@ -0,0 +1,37 @@ +-- ════════════════════════════════════════════════════════════ +-- vacation_db 001 — 휴가 옵션(승인자·승인 통보자) + 휴가 메일 기록 (2026-10-27) +-- ════════════════════════════════════════════════════════════ +-- · vacation_options: 키 하나 = 값(JSONB). 지금은 'approval' = {"approvers": [...], "notifiers": [...]} 하나. +-- 승인자를 지정하면 그 사람들(+ ERP 관리자)만 승인·반려, 비어 있으면 예전처럼 vacation_approver 권한자. +-- · vacation_mail_log: 제출·승인·반려 메일 한 통마다 한 줄(받는 사람·보낸 사람·방법 gmail|smtp·성공 여부·오류). +-- 메일 본문·토큰은 남기지 않는다. +-- 적용(운영, superuser, 1회 — 여러 번 돌려도 안전, 테이블만 추가): +-- docker exec -i postgres-db psql -U postgres -d vacation_db -v ON_ERROR_STOP=1 < scripts/sql/vacation_db_001_options_mail.sql +-- 되돌리기: DROP TABLE vacation_mail_log, vacation_options; (앱은 테이블이 없으면 옵션 없음·기록 없음으로 동작) +\set ON_ERROR_STOP on + +CREATE TABLE IF NOT EXISTS vacation_options ( + key TEXT PRIMARY KEY, + value JSONB NOT NULL DEFAULT '{}'::jsonb, + updated_by TEXT NOT NULL DEFAULT '', + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE IF NOT EXISTS vacation_mail_log ( + id BIGSERIAL PRIMARY KEY, + request_id TEXT NOT NULL, + event TEXT NOT NULL CHECK (event IN ('submitted', 'approved', 'rejected')), + sender TEXT NOT NULL DEFAULT '', + via TEXT NOT NULL DEFAULT '' CHECK (via IN ('', 'gmail', 'smtp')), + recipients TEXT NOT NULL DEFAULT '', + subject TEXT NOT NULL DEFAULT '', + ok BOOLEAN NOT NULL DEFAULT FALSE, + error TEXT NOT NULL DEFAULT '', + sent_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX IF NOT EXISTS idx_vacation_mail_log_request ON vacation_mail_log (request_id, sent_at); + +GRANT SELECT, INSERT, UPDATE, DELETE ON vacation_options, vacation_mail_log TO vacation_app; +GRANT USAGE, SELECT ON SEQUENCE vacation_mail_log_id_seq TO vacation_app; + +SELECT 'vacation_db 001 ready' AS status; diff --git a/tests/test_vacation_db.py b/tests/test_vacation_db.py new file mode 100644 index 0000000..4275ad3 --- /dev/null +++ b/tests/test_vacation_db.py @@ -0,0 +1,75 @@ +"""휴가 DB(vacation_db) — 옵션·메일 기록(마이그레이션 001, 2026-10-27) 실제 PostgreSQL 확인. + +VACATION_TEST_DB_URL 이 localhost/127.0.0.1 일 때만 돈다(아니면 skip). 앱 계정(vacation_app)으로 접속해 권한(GRANT)까지 본다. + psql … -v app_password=… -f scripts/sql/vacation_db_init.sql + psql … -d vacation_db -f scripts/sql/vacation_db_001_options_mail.sql + VACATION_TEST_DB_URL=postgresql://vacation_app:@localhost:55432/vacation_db python -m pytest tests/test_vacation_db.py +""" +import os +import sys +import unittest +import uuid +from pathlib import Path +from unittest.mock import patch +from urllib.parse import urlparse + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +DSN = os.getenv("VACATION_TEST_DB_URL", "") +ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1") + + +@unittest.skipUnless(ENABLED, "VACATION_TEST_DB_URL(localhost) 미설정") +class VacationOptionsDBTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + from app.modules.vacation.db import VacationDBStore + + cls.st = VacationDBStore(DSN) + + @classmethod + def tearDownClass(cls): + cls.st.close() + + def test_options_roundtrip(self): + self.assertTrue(self.st.options_ready()) + saved = self.st.save_options(approvers=[" Lee@Test.local", "lee@test.local", "boss@test.local", "x"], + notifiers=["HR@test.local"], by="Admin@Test.local") + self.assertEqual(saved["approvers"], ["lee@test.local", "boss@test.local"]) # 소문자·중복·@ 없는 값 정리 + self.assertEqual(saved["notifiers"], ["hr@test.local"]) + self.assertEqual(saved["updated_by"], "admin@test.local") + self.assertTrue(saved["ready"] and saved["updated_at"]) + again = self.st.save_options(approvers=[], notifiers=[], by="admin@test.local") # 덮어쓰기(키 하나) + self.assertEqual((again["approvers"], again["notifiers"]), ([], [])) + + def test_submit_approve_mail_log_end_to_end(self): + """신청 → 제출 → 승인을 실제 DB 로, 메일은 가짜 SMTP — 기록이 상세 화면용 목록으로 나온다.""" + from app.modules.vacation import notify + + self.st.save_options(approvers=["lee@test.local"], notifiers=["hr@test.local"], by="admin@test.local") + owner = f"kim-{uuid.uuid4().hex[:6]}@test.local" + req = self.st.create_request(owner=owner, owner_name="김철수", status="작성중", + payload={"vacation_type": "연차", "start_date": "2026-11-02", "end_date": "2026-11-03", + "start_half": "full", "end_half": "full", "reason": "가족 행사"}) + sub = self.st.submit(request_id=req["id"], owner=owner) + done = self.st.approve(request_id=req["id"], approver_email="lee@test.local") + users = [{"email": "lee@test.local", "name": "이팀장", "modules": {"vacation": True}}] + with patch("app.mail.send_email", return_value=True) as smtp, patch("app.mail.mail_enabled", return_value=True): + r1 = notify.deliver(self.st, None, event="submitted", req=sub, actor={"email": owner, "name": "김철수"}, + users=users, link="https://erp.test/vacation/" + req["id"]) + r2 = notify.deliver(self.st, None, event="approved", req=done, actor={"email": "lee@test.local", "name": "이팀장"}, + users=users, link="https://erp.test/vacation/" + req["id"]) + self.assertTrue(r1["ok"] and r2["ok"]) + self.assertEqual(smtp.call_args_list[1].kwargs["to"], ["lee@test.local", "hr@test.local", owner]) + log = self.st.list_mail_log(request_id=req["id"]) + self.assertEqual([(m["event"], m["via"], m["ok"]) for m in log], [("submitted", "smtp", True), ("approved", "smtp", True)]) + self.assertEqual(log[0]["sender"], owner) + self.assertEqual(log[1]["recipients"], f"lee@test.local, hr@test.local, {owner}") + self.assertIn("[휴가 승인] 김철수 · 연차", log[1]["subject"]) + self.st.hard_delete(request_id=req["id"], user_email=owner, is_admin=True) + self.st.save_options(approvers=[], notifiers=[], by="admin@test.local") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_vacation_options_mail.py b/tests/test_vacation_options_mail.py new file mode 100644 index 0000000..768ae15 --- /dev/null +++ b/tests/test_vacation_options_mail.py @@ -0,0 +1,322 @@ +"""휴가 옵션(승인자·승인 통보자)·휴가 메일(2026-10-27). + +1) notify — 받는 사람 규칙(제출 = 승인자+통보자, 승인·반려 = +신청자, 승인자 미지정이면 vacation_approver 권한자), + 메일 내용(escape), 보내는 사람 = 처리한 사람 본인 Gmail → 없거나 실패하면 회사 SMTP(이름·답장 = 그 사람), 기록. +2) 실제 앱(격리된 하위 프로세스, 가짜 휴가 저장소): 옵션 화면·저장 권한(관리자만), 승인자 지정 시 그 사람만 승인·반려, + 제출·승인·반려 뒤 메일 작업 예약, Gmail 연결 저장소 없을 때 안내. +DB·메일 서버·구글은 쓰지 않는다. +""" +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +from app.modules.vacation import notify # noqa: E402 + +REQ = {"id": "r1", "owner": "kim@test.local", "owner_name": "김철수", "vacation_type": "연차", + "start_date": "2026-10-27", "end_date": "2026-10-28", "start_half": "full", "end_half": "pm", + "days": 1.5, "reason": "가족 행사", "status": "제출", "reject_reason": ""} +USERS = [ + {"email": "boss@test.local", "name": "사장", "modules": {"vacation": True, "vacation_approver": True}}, + {"email": "lee@test.local", "name": "이팀장", "modules": {"vacation": True}}, + {"email": "kim@test.local", "name": "김철수", "modules": {"vacation": True}}, + {"email": "admin@test.local", "name": "관리자", "role": "admin", "modules": {"vacation": True}}, +] + + +class FakeStore: + def __init__(self, approvers=(), notifiers=()): + self.opts = {"approvers": list(approvers), "notifiers": list(notifiers), "ready": True} + self.logs = [] + + def get_options(self): + return dict(self.opts) + + def add_mail_log(self, **kw): + self.logs.append(kw) + + +class FakeInout: + def __init__(self, tokens=()): + self.tokens = {t: {"refresh_token_enc": "enc-" + t} for t in tokens} + self.deleted, self.marked = [], [] + + def gmail_token(self, email): + return self.tokens.get(email) + + def delete_gmail_token(self, email): + self.deleted.append(email) + self.tokens.pop(email, None) + + def mark_gmail(self, email, error=""): + self.marked.append((email, error)) + + +class RecipientTests(unittest.TestCase): + def test_rules_per_event(self): + opts = {"approvers": ["lee@test.local", "boss@test.local"], "notifiers": ["hr@test.local", "LEE@test.local"]} + self.assertEqual(notify.recipients("submitted", REQ, opts, USERS), ["lee@test.local", "boss@test.local", "hr@test.local"]) + for ev in ("approved", "rejected"): + self.assertEqual(notify.recipients(ev, REQ, opts, USERS), + ["lee@test.local", "boss@test.local", "hr@test.local", "kim@test.local"]) + + def test_no_chosen_approver_falls_back_to_permission_holders(self): + """승인자를 비워 두면 vacation_approver 칩을 켠 사람(관리자는 자동으로 넣지 않음).""" + self.assertEqual(notify.approver_emails({"approvers": []}, USERS), ["boss@test.local"]) + self.assertEqual(notify.recipients("submitted", REQ, {"approvers": [], "notifiers": []}, USERS), ["boss@test.local"]) + + +class ContentTests(unittest.TestCase): + def test_subject_period_and_escape(self): + m = notify.build("rejected", dict(REQ, reject_reason="일정 <겹침>"), actor_name="이팀장", actor_email="lee@test.local", + link="https://erp.test/vacation/r1") + self.assertEqual(m["subject"], "[휴가 반려] 김철수 · 연차 10/27(화) ~ 10/28(수) 오후 (1.5일)") + self.assertIn("<b>가족</b> 행사", m["html"]) + self.assertNotIn("가족", m["html"]) + self.assertIn("일정 <겹침>", m["html"]) + self.assertIn("반려자: 이팀장 (lee@test.local)", m["text"]) + self.assertIn("https://erp.test/vacation/r1", m["text"]) + one = notify.build("submitted", dict(REQ, end_date="2026-10-27", start_half="am", days=0.5), + actor_name="김철수", actor_email="kim@test.local", link="x") + self.assertEqual(one["subject"], "[휴가 제출] 김철수 · 연차 10/27(화) 오전 (0.5일)") + self.assertIn("제출 — 승인 대기", one["text"]) + + +class DeliverTests(unittest.TestCase): + ACTOR = {"email": "lee@test.local", "name": "이팀장"} + + def _run(self, store, inout, *, smtp_ok=True, gmail_exc=None): + sent_gmail, sent_smtp = [], [] + from app.modules.inout import gmail + + def fake_send(refresh, raw): + if gmail_exc: + raise gmail_exc + sent_gmail.append((refresh, raw)) + return "gid" + + def fake_smtp(**kw): + sent_smtp.append(kw) + return smtp_ok + + with patch.object(gmail, "decrypt_token", side_effect=lambda e, enc: "refresh:" + e), \ + patch.object(gmail, "send", side_effect=fake_send), \ + patch("app.mail.send_email", side_effect=fake_smtp), \ + patch("app.mail.mail_enabled", return_value=True): + res = notify.deliver(store, inout, event="approved", req=REQ, actor=self.ACTOR, users=USERS, + link="https://erp.test/vacation/r1") + return res, sent_gmail, sent_smtp + + def test_gmail_of_actor(self): + store, inout = FakeStore(["lee@test.local"], ["hr@test.local"]), FakeInout(["lee@test.local"]) + res, g, s = self._run(store, inout) + self.assertEqual((res["ok"], res["via"]), (True, "gmail")) + self.assertEqual(len(g), 1) + self.assertEqual(s, []) + raw = g[0][1].decode("utf-8", "replace") + self.assertEqual(g[0][0], "refresh:lee@test.local") + self.assertIn("lee@test.local", raw.split("To:")[0]) # From = 승인자 본인 + self.assertEqual(store.logs[0]["via"], "gmail") + self.assertEqual(store.logs[0]["recipients"], ["lee@test.local", "hr@test.local", "kim@test.local"]) + self.assertTrue(store.logs[0]["ok"]) + + def test_no_gmail_falls_back_to_smtp_with_reply_to(self): + store, inout = FakeStore(["lee@test.local"], ["hr@test.local"]), FakeInout() + res, g, s = self._run(store, inout) + self.assertEqual((res["ok"], res["via"], res["error"]), (True, "smtp", "")) + self.assertEqual(g, []) + self.assertEqual(s[0]["reply_to"], "lee@test.local") + self.assertEqual(s[0]["from_name"], "이팀장 (DBX ERP)") + self.assertEqual(s[0]["to"], ["lee@test.local", "hr@test.local", "kim@test.local"]) + + def test_broken_gmail_drops_token_and_uses_smtp(self): + from app.modules.inout import gmail + + store, inout = FakeStore(["lee@test.local"]), FakeInout(["lee@test.local"]) + res, g, s = self._run(store, inout, gmail_exc=gmail.GmailNotConnected("연결이 끊겼습니다")) + self.assertEqual((res["ok"], res["via"]), (True, "smtp")) + self.assertEqual(inout.deleted, ["lee@test.local"]) + self.assertIn("Gmail 실패 → 회사 메일로 보냄", res["error"]) + self.assertEqual(len(s), 1) + + def test_all_fail_is_logged_not_raised(self): + store = FakeStore(["lee@test.local"]) + res, g, s = self._run(store, None, smtp_ok=False) + self.assertFalse(res["ok"]) + self.assertFalse(store.logs[0]["ok"]) + self.assertIn("SMTP", store.logs[0]["error"]) + + def test_nobody_to_send(self): + store = FakeStore() + with patch("app.mail.send_email") as smtp: + res = notify.deliver(store, None, event="submitted", req=REQ, actor={"email": "kim@test.local"}, + users=[u for u in USERS if u["email"] != "boss@test.local"], link="x") + smtp.assert_not_called() + self.assertFalse(res["ok"]) + self.assertEqual(store.logs, []) + + +# ── 실제 앱 ───────────────────────────────────────────── +PRELUDE = ''' +from unittest.mock import patch +from fastapi.testclient import TestClient +import app.main as main +from app.modules.vacation import notify + +def U(email, role="user", approver=False): + return {"email": email, "name": email.split("@")[0], "role": role, "is_super_admin": False, + "modules": {"vacation": True, "vacation_approver": approver}} + +who = {"u": None} +admin, lee, chip, kim = U("admin@test.local", role="admin"), U("lee@test.local"), U("chip@test.local", approver=True), U("kim@test.local") +users = [admin, lee, chip, kim] +sent = [] + +class Store: + def __init__(self): + self.opts = {"approvers": [], "notifiers": [], "ready": True, "updated_by": "", "updated_at": ""} + self.req = {"id": "r1", "owner": "kim@test.local", "owner_name": "kim", "vacation_type": "연차", + "start_date": "2026-10-27", "end_date": "2026-10-27", "start_half": "full", "end_half": "full", + "days": 1, "reason": "", "status": "제출", "reject_reason": "", "approver_email": None} + def get_options(self): + return dict(self.opts) + def save_options(self, approvers, notifiers, by): + self.opts.update(approvers=[a.lower() for a in approvers], notifiers=[n.lower() for n in notifiers], updated_by=by) + return self.get_options() + def submit(self, request_id, owner): + self.req["status"] = "제출"; return dict(self.req) + def approve(self, request_id, approver_email): + self.req.update(status="승인", approver_email=approver_email); return dict(self.req) + def reject(self, request_id, approver_email, reason): + self.req.update(status="반려", reject_reason=reason); return dict(self.req) + def list_mail_log(self, request_id): + return [] + +st = Store() + +def run(body): + main.app.state.vacation_store = st + main.app.state.inout_store = None + with patch.object(main, "get_current_user_record", side_effect=lambda r: who["u"]), \\ + patch.object(main, "get_session_user", side_effect=lambda r: who["u"]), \\ + patch.object(main.user_store, "get", side_effect=lambda e: who["u"]), \\ + patch.object(main.user_store, "list_all", side_effect=lambda: users), \\ + patch.object(notify, "deliver", side_effect=lambda *a, **kw: sent.append((kw["event"], kw["actor"]["email"], kw["link"]))): + body(TestClient(main.app, follow_redirects=False)) +''' + + +def _run(code: str) -> subprocess.CompletedProcess: + env = dict(os.environ) + for key in ("ASSET", "CAFE24", "CUPANG", "VACATION", "PROJECT", "DISPATCH", "PERFORMANCE", "MALAYSIA_STOCK", + "ITEMCODE", "EXPENSE", "INOUT"): + env[key + "_DB_URL"] = "" + env.update(SESSION_SECRET_KEY="local-vacation-test-only", SESSION_COOKIE_SECURE="false", PERFORMANCE_AUTO_SYNC="false", + PUBLIC_BASE_URL="https://erp.test") + with tempfile.TemporaryDirectory(prefix="vacation-web-") as directory: + env["DATA_DIR"] = directory + return subprocess.run([sys.executable, "-c", PRELUDE + code], cwd=ROOT, env=env, capture_output=True, + text=True, encoding="utf-8", timeout=90) + + +class VacationWebTests(unittest.TestCase): + def test_options_and_approver_rules_and_mail_hooks(self): + res = _run(''' +def body(c): + # 옵션 화면 — 누구나 보기, 일반 사용자는 체크 잠김·저장 버튼 없음 + who["u"] = kim + r = c.get("/vacation/options") + assert r.status_code == 200, r.status_code + assert "휴가 승인자" in r.text and "휴가 승인 통보자" in r.text and "ERP 관리자만 바꿀 수 있습니다" in r.text + assert 'value="lee@test.local" disabled' in r.text and ">저장" not in r.text + assert "Gmail 연결을 쓸 수 없는 서버" in r.text # 입출고 DB 없음 → 회사 메일 안내 + assert c.post("/vacation/options", data={"approvers": ["lee@test.local"]}).status_code == 403 + # 승인자 미지정 = 예전처럼 vacation_approver 칩(chip)이 승인 + who["u"] = chip + assert c.post("/vacation/r1/approve").status_code == 303 + assert sent[-1] == ("approved", "chip@test.local", "https://erp.test/vacation/r1"), sent + # 관리자 저장 — 휴가 사용자만, 그 밖은 400 + who["u"] = admin + assert c.post("/vacation/options", data={"approvers": ["nobody@test.local"]}).status_code == 400 + r = c.post("/vacation/options", data={"approvers": ["lee@test.local"], "notifiers": ["kim@test.local"]}) + assert r.status_code == 303 and r.headers["location"].startswith("/vacation/options?msg="), r.status_code + assert st.opts["approvers"] == ["lee@test.local"] and st.opts["notifiers"] == ["kim@test.local"] + assert 'value="lee@test.local" checked' in c.get("/vacation/options").text + # 승인자를 지정하면 그 사람만(+관리자) — 칩만 있는 chip 은 이제 403 + st.req["status"] = "제출" + who["u"] = chip + assert c.post("/vacation/r1/approve").status_code == 403 + assert c.post("/vacation/r1/reject", data={"reject_reason": "x"}).status_code == 403 + who["u"] = lee + n = len(sent) + assert c.post("/vacation/r1/reject", data={"reject_reason": "일정 겹침"}).status_code == 303 + assert sent[n:] == [("rejected", "lee@test.local", "https://erp.test/vacation/r1")], sent + # 제출 → 제출 메일(보내는 사람 = 신청자) + who["u"] = kim + assert c.post("/vacation/r1/submit").status_code == 303 + assert sent[-1][:2] == ("submitted", "kim@test.local"), sent + # 관리자는 승인자 목록에 없어도 승인 + who["u"] = admin + assert c.post("/vacation/r1/approve").status_code == 303 and sent[-1][:2] == ("approved", "admin@test.local") + # Gmail 연결 — 저장소(입출고 DB)가 없으면 옵션으로 돌아와 안내 + who["u"] = kim + r = c.get("/vacation/gmail/connect") + assert r.status_code == 303 and "/vacation/options?msg=" in r.headers["location"] + print("OK") +run(body) +''') + self.assertEqual(res.returncode, 0, res.stdout + res.stderr) + self.assertIn("OK", res.stdout) + + def test_vacation_gmail_callback_branch(self): + """휴가에서 시작한 연결은 입출고 콜백이 휴가 권한으로 처리 — 입출고 권한 없이도, 끝나면 휴가 옵션으로.""" + res = _run(''' +from app.modules.inout import router as inout_router, gmail + +class Inout: + saved = [] + def save_gmail_token(self, email, refresh_token_enc, scopes): + self.saved.append((email, refresh_token_enc, scopes)) + +class Client: + async def authorize_access_token(self, request): + return {"userinfo": {"email": "kim@test.local"}, "scope": "openid email " + gmail.GMAIL_SCOPE, "refresh_token": "R"} + +inout = Inout() +def body(c): + main.app.state.inout_store = inout + who["u"] = kim # 입출고 권한 없음, 휴가만 + with patch.object(gmail, "oauth_client", return_value=Client()), \\ + patch.object(gmail, "encrypt_token", side_effect=lambda e, r: "enc:" + r), \\ + patch.object(gmail, "configured", return_value=True): + assert "Gmail 연결" in c.get("/vacation/options").text + # 세션에 휴가 표시를 넣는다(연결 시작 = /vacation/gmail/connect 가 하는 일) + from starlette.requests import Request + @main.app.get("/__test_mark") + def mark(request: Request): + request.session["_gmail_origin"] = "vacation" + request.session["_vacation_gmail_next"] = "/vacation/options" + return {"ok": True} + assert c.get("/__test_mark").status_code == 200 + r = c.get("/inout/gmail/callback") + assert r.status_code == 303, (r.status_code, r.text[:200]) + assert r.headers["location"].startswith("/vacation/options?msg="), r.headers["location"] + assert inout.saved == [("kim@test.local", "enc:R", "openid email " + gmail.GMAIL_SCOPE)], inout.saved + # 표시가 없으면 예전처럼 입출고 권한 확인(휴가 사용자는 입출고 권한 없음 → 거절) + r = c.get("/inout/gmail/callback") + assert r.status_code in (403, 503), r.status_code + print("OK") +run(body) +''') + self.assertEqual(res.returncode, 0, res.stdout + res.stderr) + self.assertIn("OK", res.stdout) + + +if __name__ == "__main__": + unittest.main()