fix(휴가): 메일 실패 시 Gmail 연결 안내·다시 보내기 — 휴가 권한 없는 협의자 포함

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-02 16:26:13 +09:00
parent 7e86e9c91b
commit f4b80e8abc
12 changed files with 190 additions and 16 deletions
+2 -1
View File
@@ -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:
+2
View File
@@ -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)
+2
View File
@@ -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": ""}
+64 -9
View File
@@ -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,
@@ -1,11 +1,28 @@
{% extends "erp_base.html" %}
{% import "vacation/_macros.html" as vm %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261102b" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261102c" />{% endblock %}
{% block content %}
<section class="vac">
<div class="erp-card vac-detail-card">
{% if msg %}<p class="vac-opt-msg" role="status">{{ msg }}</p>{% endif %}
{#- 내가 보내다 실패한 메일(2026-11-02) — Gmail 을 연결하고 다시 보낸다 -#}
{% if failed_mail %}
<div class="vac-opt-msg is-warn vac-mail-retry" role="alert">
<b>{{ event_words.get(failed_mail.event, failed_mail.event) }} 메일을 보내지 못했습니다.</b>
{% if gmail.connected or gmail.smtp %}
<form method="post" action="/vacation/{{ req.id }}/mail-retry" class="vac-inline-form">
<button type="submit" class="erp-btn erp-btn-primary">메일 다시 보내기</button>
</form>
{% elif gmail.available %}
<span>내 Gmail 이 연결되어 있지 않습니다. 연결한 뒤 다시 보낼 수 있습니다.</span>
<a class="erp-btn erp-btn-primary" href="/vacation/gmail/connect?next=/vacation/{{ req.id }}">Gmail 연결</a>
{% else %}
<span>메일을 보낼 방법이 설정되어 있지 않습니다. 관리자에게 알려 주세요.</span>
{% endif %}
</div>
{% endif %}
<div class="vac-detail-head">
<div>
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% import "vacation/_macros.html" as vm %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261102b" />
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261102c" />
{#- 달력 = ERP 공용 달력 서식(2026-11-02, erp-datepop mountRange) -#}
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<link rel="stylesheet" href="/static/erp-datepop.css?v=20261102a" />{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261102b" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261102c" />{% endblock %}
{% block content %}
<section class="vac">
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% import "vacation/_macros.html" as vm %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261102b" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261102c" />{% endblock %}
{% block content %}
<section class="vac vac-options">
@@ -2,7 +2,7 @@
{#- 휴가 옵션(2026-10-27) — 승인자·승인 통보자·잔여 연차(수정 = ERP 관리자·승인자·통보자, 나머지는 보기만) + 내 Gmail 연결(누구나).
메일: 제출 = 승인자·통보자(+ 협의자마다 자기 몫), 협의 완료·승인·반려 = 승인자·통보자·신청자. 보내는 사람 = 처리한 사람 본인 Gmail(없으면 회사 메일). -#}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261102b" />
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261102c" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<link rel="stylesheet" href="/static/erp-datepop.css?v=20261102a" />{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% import "vacation/_macros.html" as vm %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261102b" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261102c" />{% endblock %}
{% block content %}
<section class="vac vac-options">
+1
View File
@@ -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 라 카드가 줄어 내용이 잘렸다(잔여 연차 줄·메일 글) — 옵션 화면은 줄이지 않고 페이지 스크롤 */
+96
View File
@@ -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)