09f6a2ee6f
- /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 <noreply@anthropic.com>
323 lines
16 KiB
Python
323 lines
16 KiB
Python
"""휴가 옵션(승인자·승인 통보자)·휴가 메일(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": "<b>가족</b> 행사", "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("<b>가족</b>", 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 ">저장</button>" 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 연결</a>" 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()
|