fix(휴가): 메일 실패 시 Gmail 연결 안내·다시 보내기 — 휴가 권한 없는 협의자 포함
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user