From f4b80e8abc94b9bef2a5d8ee25970a1b2680af91 Mon Sep 17 00:00:00 2001 From: king Date: Mon, 2 Nov 2026 16:26:13 +0900 Subject: [PATCH] =?UTF-8?q?fix(=ED=9C=B4=EA=B0=80):=20=EB=A9=94=EC=9D=BC?= =?UTF-8?q?=20=EC=8B=A4=ED=8C=A8=20=EC=8B=9C=20Gmail=20=EC=97=B0=EA=B2=B0?= =?UTF-8?q?=20=EC=95=88=EB=82=B4=C2=B7=EB=8B=A4=EC=8B=9C=20=EB=B3=B4?= =?UTF-8?q?=EB=82=B4=EA=B8=B0=20=E2=80=94=20=ED=9C=B4=EA=B0=80=20=EA=B6=8C?= =?UTF-8?q?=ED=95=9C=20=EC=97=86=EB=8A=94=20=ED=98=91=EC=9D=98=EC=9E=90=20?= =?UTF-8?q?=ED=8F=AC=ED=95=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- app/modules/inout/router.py | 3 +- app/modules/vacation/CLAUDE.md | 2 + app/modules/vacation/notify.py | 2 + app/modules/vacation/router.py | 73 ++++++++++++-- .../vacation/templates/vacation/detail.html | 19 +++- .../vacation/templates/vacation/form.html | 2 +- .../vacation/templates/vacation/index.html | 2 +- .../vacation/templates/vacation/mine.html | 2 +- .../vacation/templates/vacation/options.html | 2 +- .../vacation/templates/vacation/pending.html | 2 +- app/static/vacation.css | 1 + tests/test_vacation_options_mail.py | 96 +++++++++++++++++++ 12 files changed, 190 insertions(+), 16 deletions(-) diff --git a/app/modules/inout/router.py b/app/modules/inout/router.py index 81f9b55..119914e 100644 --- a/app/modules/inout/router.py +++ b/app/modules/inout/router.py @@ -659,7 +659,8 @@ async def _gmail_callback_vacation(request: Request) -> Any: 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, origin): + # 휴가 협의자는 휴가 권한이 없어도 연결한다 — 휴가 연결 시작 때 그 신청의 협의자인지 확인해 세션에 남긴 값(2026-11-02) + if not request.session.pop("_gmail_consultant", False) and not has_module(user, origin): raise HTTPException(status_code=403, detail=denied) st = _store(request) if st is None: diff --git a/app/modules/vacation/CLAUDE.md b/app/modules/vacation/CLAUDE.md index 7119d86..5848c64 100644 --- a/app/modules/vacation/CLAUDE.md +++ b/app/modules/vacation/CLAUDE.md @@ -23,6 +23,8 @@ - 화면: 달력 위 [내 신청 내역] `/vacation/mine`(협의자별 상태 → 결재 상태), [협의 대기 N] → `/vacation/pending#consults`(이 화면은 이제 누구나, 승인 대기 표는 결재자만, 표에 협의 내용). 상세 = 결재 진행·협의자별 내용·협의 승인/반려. **보기 권한**: 신청자·결재자·통보자 = 전체, 협의자 = 자기 줄만(서버가 거름, 메일 기록도 안 보임). - **휴가 권한 없는 협의자**: 사이드바에 휴가 메뉴가 없어 메일 링크로 상세(`_guard(consult_of=…)`)에 들어와 처리한다. 달력·내역·대기 화면은 권한이 있어야 함. +- **메일 실패 → Gmail 연결·다시 보내기**(2026-11-02): 처리는 먼저 저장(메일 때문에 결재가 막히지 않음). Gmail 미연결이면 `_notify` 가 메일을 바로 시도해 실패 기록을 남기고, 상세 위에 안내(`router._failed_mail` — 그 신청의 마지막 메일이 내가 보내다 실패한 것이고 상태가 그대로일 때, 협의자·신청자·결재자 공통). + [Gmail 연결] → `/vacation/gmail/connect?next=/vacation/{id}` → 구글 → 상세로 복귀 → [메일 다시 보내기] `POST /vacation/{id}/mail-retry`. 협의자는 휴가 권한이 없어도 연결(세션 `_gmail_consultant`, 콜백은 `inout/router.py`). 다시 보낼 때 이미 처리한 협의자에게는 협의 요청을 안 보냄. - 테스트 `tests/test_vacation_options_mail.py`(메일 내용·폼·권한), `tests/test_vacation_db.py`(실제 PG 흐름). ## 공휴일 · 연차 (2026-10-27) diff --git a/app/modules/vacation/notify.py b/app/modules/vacation/notify.py index 06b473e..f43637d 100644 --- a/app/modules/vacation/notify.py +++ b/app/modules/vacation/notify.py @@ -189,6 +189,8 @@ def deliver(store: Any, inout_store: Any, *, event: str, req: dict[str, Any], ac if event == "submitted": for c in req.get("consults") or []: + if c.get("state", "대기") != "대기": # 다시 보내기 — 이미 처리한 협의자에게는 안 보냄 + continue mail = build("consult_request", req, actor_name=name, actor_email=email, link=link, name_of=name_of, consult=c) _send_and_log(store, inout_store, "consult_request", req, _uniq([c.get("email")]), mail, email, name) result: dict[str, Any] = {"ok": False, "via": "", "to": to, "error": ""} diff --git a/app/modules/vacation/router.py b/app/modules/vacation/router.py index 36650e6..4b20a9a 100644 --- a/app/modules/vacation/router.py +++ b/app/modules/vacation/router.py @@ -155,8 +155,9 @@ def _form_consults(store: Any, owner: str, emails: list[str], messages: list[str def _notify(bg: BackgroundTasks, request: Request, event: str, req: dict[str, Any] | None, - actor: dict[str, Any]) -> None: - """제출·승인·반려 메일을 응답 뒤 백그라운드로(notify.deliver — 받는 사람·보내는 사람 규칙은 그쪽).""" + actor: dict[str, Any], now: bool = False) -> None: + """제출·승인·반려 메일을 응답 뒤 백그라운드로(notify.deliver — 받는 사람·보내는 사람 규칙은 그쪽). + Gmail 연결이 없거나 now 면 바로 — 실패 기록이 다음 화면에 보여 [Gmail 연결]·[다시 보내기]를 띄울 수 있게.""" from app.main import env # noqa: WPS433 from . import notify # noqa: WPS433 @@ -170,8 +171,14 @@ def _notify(bg: BackgroundTasks, request: Request, event: str, req: dict[str, An req = {**req, "consults": []} base = (env("PUBLIC_BASE_URL") or str(request.base_url)).rstrip("/") inout_store = getattr(request.app.state, "inout_store", None) - bg.add_task(notify.deliver, st, inout_store, event=event, req=req, actor=dict(actor), - users=_vacation_users(), link=f"{base}/vacation/{req['id']}") + args = {"event": event, "req": req, "actor": dict(actor), "users": _vacation_users(), "link": f"{base}/vacation/{req['id']}"} + if not now and _gmail_state(request, actor)["connected"]: + bg.add_task(notify.deliver, st, inout_store, **args) + return + try: + notify.deliver(st, inout_store, **args) + except Exception: # noqa: BLE001 — 메일이 실패해도 휴가 처리는 그대로 + notify.logger.exception("휴가 메일 처리 실패 — %s %s", event, req.get("id")) def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLResponse: @@ -835,22 +842,33 @@ def options_save( @router.get("/gmail/connect") async def gmail_connect(request: Request) -> Any: """내 Gmail 연결 — 입출고와 같은 연결(같은 OAuth 클라이언트·같은 구글 리디렉션 주소 /inout/gmail/callback). - 콜백은 세션 표시(_gmail_origin=vacation)를 보고 휴가 권한으로 처리한 뒤 휴가 옵션으로 돌아온다.""" + 콜백은 세션 표시(_gmail_origin=vacation)를 보고 휴가 권한으로 처리한 뒤 휴가 옵션으로 돌아온다. + ?next=/vacation/{신청 id} = 그 상세로 돌아옴 — 그 신청의 협의자면 휴가 권한이 없어도 연결(콜백에 _gmail_consultant 로 알림).""" + import re # noqa: WPS433 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 + from app.store import has_module # noqa: WPS433 - user = _require_user(request) + user = _require_login(request) + nxt = request.query_params.get("next", "") + back = nxt if re.fullmatch(r"/vacation/[0-9a-z]+", nxt) else "/vacation/options" + st = _store(request) + consultant = back != "/vacation/options" and st is not None and any( + c["email"] == user["email"].lower() for c in st.list_consults(request_id=back.rsplit("/", 1)[1])) + if not consultant and not has_module(user, "vacation"): + raise HTTPException(status_code=403, detail="휴가 관리 모듈 권한이 없습니다.") if getattr(request.app.state, "inout_store", None) is None: - return RedirectResponse(url="/vacation/options?" + urlencode( + return RedirectResponse(url=back + "?" + 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) + return RedirectResponse(url=back + "?" + urlencode({"msg": str(exc)}), status_code=303) request.session["_gmail_origin"] = "vacation" - request.session["_gmail_next"] = "/vacation/options" + request.session["_gmail_next"] = back + request.session["_gmail_consultant"] = bool(consultant) return await client.authorize_redirect( request, public_url_for(request, "inout_gmail_callback"), access_type="offline", prompt="consent", include_granted_scopes="true", @@ -907,6 +925,7 @@ def detail(request: Request, request_id: str) -> HTMLResponse: ) req["consults"] = consults if see_all else [mine] # 협의자는 자기 몫 협의 내용만 people = _people() + failed_mail = _failed_mail(store, req, email) return render_template( request, "vacation/detail.html", @@ -922,6 +941,9 @@ def detail(request: Request, request_id: str) -> HTMLResponse: "half_labels": HALF_LABELS, "can_edit": is_owner and req["status"] in ("작성중", "반려"), "can_consult": bool(mine and mine["state"] == "대기" and req["status"] == "협의중"), + "failed_mail": failed_mail, + "gmail": _gmail_state(request, user) if failed_mail else None, + "msg": request.query_params.get("msg", ""), "people": people, "line": _approval_line(request, people), "mail_log": _mail_log(store, request_id) if see_all else [], @@ -930,6 +952,19 @@ def detail(request: Request, request_id: str) -> HTMLResponse: ) +# 다시 보낼 의미가 있는 신청 상태 — 일이 더 진행됐거나 수정 중이면 예전 메일은 다시 보내지 않는다 +_RETRY_STATUS = {"submitted": ("협의중", "제출"), "consulted": ("제출",), "approved": ("승인",), "rejected": ("반려",)} + + +def _failed_mail(store: Any, req: dict[str, Any], email: str) -> dict[str, Any] | None: + """내가 보내다 실패한 메일 — 그 신청의 마지막 메일(협의 요청은 제출과 함께 다루므로 뺌)이 실패이고 상태가 그대로일 때.""" + logs = [m for m in _mail_log(store, req["id"]) if m["event"] != "consult_request"] + last = logs[-1] if logs else None + if last and not last["ok"] and last["sender"] == email and req["status"] in _RETRY_STATUS.get(last["event"], ()): + return last + return None + + def _mail_log(store: Any, request_id: str) -> list[dict[str, Any]]: """그 신청의 휴가 메일 기록(001) — 실패해도 상세 화면은 그대로.""" try: @@ -1060,6 +1095,26 @@ def consult_decide( return RedirectResponse(url=f"/vacation/{request_id}", status_code=303) +@router.post("/{request_id}/mail-retry") +def mail_retry( + request: Request, + request_id: str, + bg: BackgroundTasks, + user: dict[str, Any] = Depends(_require_login), +) -> RedirectResponse: + """내가 보내다 실패한 메일 다시 보내기(Gmail 을 연결한 뒤 등) — 결과가 바로 화면에 나오게 기다렸다 돌아간다.""" + store = _store(request) + if store is None: + raise HTTPException(status_code=503, detail="vacation_db 미설정") + req = store.get_request(request_id=request_id) + if not req: + raise HTTPException(status_code=404, detail="휴가 신청을 찾을 수 없습니다.") + failed = _failed_mail(store, req, user["email"].lower()) + if failed: + _notify(bg, request, failed["event"], req, user, now=True) + return RedirectResponse(url=f"/vacation/{request_id}", status_code=303) + + @router.post("/{request_id}/approve") def approve( request: Request, diff --git a/app/modules/vacation/templates/vacation/detail.html b/app/modules/vacation/templates/vacation/detail.html index 1dbc3ea..99d4114 100644 --- a/app/modules/vacation/templates/vacation/detail.html +++ b/app/modules/vacation/templates/vacation/detail.html @@ -1,11 +1,28 @@ {% extends "erp_base.html" %} {% import "vacation/_macros.html" as vm %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
+ {% if msg %}

{{ msg }}

{% endif %} + {#- 내가 보내다 실패한 메일(2026-11-02) — Gmail 을 연결하고 다시 보낸다 -#} + {% if failed_mail %} + + {% endif %}
diff --git a/app/modules/vacation/templates/vacation/form.html b/app/modules/vacation/templates/vacation/form.html index b8cf26d..5be5ea9 100644 --- a/app/modules/vacation/templates/vacation/form.html +++ b/app/modules/vacation/templates/vacation/form.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% import "vacation/_macros.html" as vm %} -{% block head_extra %} +{% block head_extra %} {#- 달력 = ERP 공용 달력 서식(2026-11-02, erp-datepop mountRange) -#} {% endblock %} diff --git a/app/modules/vacation/templates/vacation/index.html b/app/modules/vacation/templates/vacation/index.html index 3459b99..0590378 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 %}
diff --git a/app/modules/vacation/templates/vacation/mine.html b/app/modules/vacation/templates/vacation/mine.html index e05c15f..3ca7498 100644 --- a/app/modules/vacation/templates/vacation/mine.html +++ b/app/modules/vacation/templates/vacation/mine.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% import "vacation/_macros.html" as vm %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
diff --git a/app/modules/vacation/templates/vacation/options.html b/app/modules/vacation/templates/vacation/options.html index dfe1f01..8a79273 100644 --- a/app/modules/vacation/templates/vacation/options.html +++ b/app/modules/vacation/templates/vacation/options.html @@ -2,7 +2,7 @@ {#- 휴가 옵션(2026-10-27) — 승인자·승인 통보자·잔여 연차(수정 = ERP 관리자·승인자·통보자, 나머지는 보기만) + 내 Gmail 연결(누구나). 메일: 제출 = 승인자·통보자(+ 협의자마다 자기 몫), 협의 완료·승인·반려 = 승인자·통보자·신청자. 보내는 사람 = 처리한 사람 본인 Gmail(없으면 회사 메일). -#} -{% block head_extra %} +{% block head_extra %} {% endblock %} diff --git a/app/modules/vacation/templates/vacation/pending.html b/app/modules/vacation/templates/vacation/pending.html index 68d3719..e959f6d 100644 --- a/app/modules/vacation/templates/vacation/pending.html +++ b/app/modules/vacation/templates/vacation/pending.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% import "vacation/_macros.html" as vm %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
diff --git a/app/static/vacation.css b/app/static/vacation.css index 4fd1c69..6fe3e46 100644 --- a/app/static/vacation.css +++ b/app/static/vacation.css @@ -261,6 +261,7 @@ /* ── 휴가 옵션(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-mail-retry { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; } .vac-opt-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; align-items: start; } .vac-opt-card { padding: 16px; } /* .erp-page > .vac 는 화면 높이 flex 라 카드가 줄어 내용이 잘렸다(잔여 연차 줄·메일 글) — 옵션 화면은 줄이지 않고 페이지 스크롤 */ diff --git a/tests/test_vacation_options_mail.py b/tests/test_vacation_options_mail.py index 24068ed..0a45c79 100644 --- a/tests/test_vacation_options_mail.py +++ b/tests/test_vacation_options_mail.py @@ -114,6 +114,12 @@ class ConsultMailTests(unittest.TestCase): self.assertTrue(res["ok"]) self.assertEqual(res["to"], ["lee@test.local", "hr@test.local"]) + def test_resend_skips_consultants_who_already_decided(self): + cs = [dict(self.CONSULTS[0], state="승인"), self.CONSULTS[1]] + with patch("app.mail.send_email", return_value=True) as smtp, patch("app.mail.mail_enabled", return_value=True): + notify.deliver(FakeStore(["lee@test.local"]), None, event="submitted", req=dict(REQ, consults=cs), actor=self.OWNER, users=USERS, link="x") + self.assertEqual([c.kwargs["to"] for c in smtp.call_args_list], [["choi@test.local"], ["lee@test.local"]]) + def test_consulted_goes_to_approver_notifier_owner_and_lists_consults(self): done = [dict(c, state="승인") for c in self.CONSULTS] store = FakeStore(["lee@test.local"], ["hr@test.local"]) @@ -467,6 +473,96 @@ def body(c): assert "바깥 사람 전용" in t and "이팀장 전용" in t and "협의 승인" not in t print("OK") run(body) +''') + self.assertEqual(res.returncode, 0, res.stdout + res.stderr) + self.assertIn("OK", res.stdout) + + def test_failed_mail_gmail_connect_and_retry(self): + """협의자가 Gmail 미연결로 메일 실패 → 상세에 안내 → (휴가 권한 없어도) 연결 → 다시 보내기 → 안내 사라짐.""" + res = _run(''' +from fastapi.responses import RedirectResponse +from app.modules.inout import gmail + +outsider = U("out@test.local"); outsider["modules"] = {} +other = U("other@test.local"); other["modules"] = {} +users.extend([outsider, other]) +LOG = [] +class Store4(Store): + def list_consults(self, request_id): + return [{"email": "out@test.local", "name": "out", "message": "m", "state": "승인", "comment": "", "decided_at": None}] + def get_request(self, request_id): + return dict(self.req) + def list_mail_log(self, request_id): + return list(LOG) + def decide_consult(self, request_id, email, approve, reason=""): + self.req["status"] = "제출" + return dict(self.req), "consulted" + +class Inout: + tokens = set() + def gmail_token(self, email): + return {"refresh_token_enc": "x"} if email in self.tokens else None + def save_gmail_token(self, email, refresh_token_enc, scopes): + self.tokens.add(email) + +class Client: + async def authorize_redirect(self, request, url, **kw): + return RedirectResponse("https://accounts.test/", status_code=302) + async def authorize_access_token(self, request): + return {"userinfo": {"email": "out@test.local"}, "scope": "openid email " + gmail.GMAIL_SCOPE, "refresh_token": "R"} + +st4 = Store4() +st4.req["status"] = "협의중" +inout = Inout() +def fail(event, sender="out@test.local", ok=False): + LOG.append({"event": event, "sender": sender, "ok": ok, "via": "smtp", "recipients": "a@test.local", "sent_at": "2026-11-02T15:59:00", "error": "SMTP 미설정"}) +def body(c): + main.app.state.vacation_store = st4 + main.app.state.inout_store = inout + 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), \\ + patch("app.mail.mail_enabled", return_value=False): + # 미연결 — 처리는 저장되고 메일은 바로 시도(응답 뒤로 미루지 않음), 기록이 실패면 Gmail 연결 안내 + who["u"] = outsider + n = len(sent) + assert c.post("/vacation/r1/consult", data={"decision": "approve"}).status_code == 303 + assert sent[n:] == [("consulted", "out@test.local", "https://erp.test/vacation/r1")], sent + fail("consulted") + t = c.get("/vacation/r1").text + assert "협의 완료 메일을 보내지 못했습니다" in t and '/vacation/gmail/connect?next=/vacation/r1"' in t and "메일 다시 보내기" not in t + # 다른 사람(신청자)에게는 안내 없음, 다시 보내기도 안 됨 + who["u"] = kim + assert "보내지 못했습니다" not in c.get("/vacation/r1").text + n = len(sent) + assert c.post("/vacation/r1/mail-retry").status_code == 303 and len(sent) == n + # 휴가 권한 없는 협의자 — 연결 시작 → 콜백 통과 → 그 상세로 복귀 + who["u"] = outsider + assert c.get("/vacation/gmail/connect").status_code == 403 # 협의 신청 없이는 권한 필요 + r = c.get("/vacation/gmail/connect?next=/vacation/r1") + assert r.status_code == 302, r.status_code + r = c.get("/inout/gmail/callback") + assert r.status_code == 303 and r.headers["location"].startswith("/vacation/r1?msg="), (r.status_code, r.headers.get("location")) + assert "out@test.local" in inout.tokens + assert "Gmail" in c.get(r.headers["location"]).text + # 협의자가 아닌 신청의 next 는 권한 없으면 거절 + who["u"] = other + assert c.get("/vacation/gmail/connect?next=/vacation/r1").status_code == 403 + who["u"] = outsider + # 연결 뒤 — 다시 보내기 버튼, 누르면 응답 전에 보냄, 성공 기록이면 안내 사라짐 + t = c.get("/vacation/r1").text + assert "메일 다시 보내기" in t and "/vacation/gmail/connect" not in t + n = len(sent) + assert c.post("/vacation/r1/mail-retry").status_code == 303 + assert sent[n:] == [("consulted", "out@test.local", "https://erp.test/vacation/r1")], sent + fail("consulted", ok=True) + assert "보내지 못했습니다" not in c.get("/vacation/r1").text + # 일이 더 진행되면(승인 메일 성공) 예전 실패는 안내하지 않음 — 스크린샷 사례 + LOG.clear(); fail("consulted"); fail("approved", sender="lee@test.local", ok=True) + st4.req["status"] = "승인" + assert "보내지 못했습니다" not in c.get("/vacation/r1").text + print("OK") +run(body) ''') self.assertEqual(res.returncode, 0, res.stdout + res.stderr) self.assertIn("OK", res.stdout)