97f4a904cd
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
568 lines
32 KiB
Python
568 lines
32 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 ConsultMailTests(unittest.TestCase):
|
|
"""협의자(2026-11-02) — 협의자마다 자기 몫만, 결재자·통보자는 전체."""
|
|
CONSULTS = [{"email": "park@test.local", "name": "박과장", "message": "박과장 전용 <업무>", "state": "대기"},
|
|
{"email": "choi@test.local", "name": "최대리", "message": "최대리 전용 내용", "state": "대기"}]
|
|
OWNER = {"email": "kim@test.local", "name": "김철수"}
|
|
|
|
def test_each_consultant_gets_only_own_message_and_others_get_all(self):
|
|
store = FakeStore(["lee@test.local"], ["hr@test.local"])
|
|
sent = []
|
|
with patch("app.mail.send_email", side_effect=lambda **kw: sent.append(kw) or True), patch("app.mail.mail_enabled", return_value=True):
|
|
res = notify.deliver(store, None, event="submitted", req=dict(REQ, status="협의중", consults=self.CONSULTS),
|
|
actor=self.OWNER, users=USERS, link="https://erp.test/vacation/r1")
|
|
self.assertEqual([m["to"] for m in sent], [["park@test.local"], ["choi@test.local"], ["lee@test.local", "hr@test.local"]])
|
|
park, choi, line = sent
|
|
self.assertIn("[휴가 협의 요청]", park["subject"])
|
|
self.assertIn("박과장 전용 <업무>", park["html"])
|
|
self.assertNotIn("최대리", park["html"] + park["body"])
|
|
self.assertIn("최대리 전용 내용", choi["body"])
|
|
self.assertNotIn("박과장", choi["html"] + choi["body"])
|
|
for text in ("박과장", "박과장 전용 <업무>", "최대리", "최대리 전용 내용", "협의 진행 중"):
|
|
self.assertIn(text, line["body"])
|
|
self.assertIn("협의자가 모두 승인하면", line["html"])
|
|
self.assertEqual([log["event"] for log in store.logs], ["consult_request", "consult_request", "submitted"])
|
|
self.assertTrue(res["ok"])
|
|
self.assertEqual(res["to"], ["lee@test.local", "hr@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"])
|
|
with patch("app.mail.send_email", return_value=True) as smtp, patch("app.mail.mail_enabled", return_value=True):
|
|
notify.deliver(store, None, event="consulted", req=dict(REQ, consults=done), actor={"email": "choi@test.local"},
|
|
users=USERS, link="x")
|
|
kw = smtp.call_args.kwargs
|
|
self.assertEqual(smtp.call_count, 1)
|
|
self.assertEqual(kw["to"], ["lee@test.local", "hr@test.local", "kim@test.local"])
|
|
self.assertIn("[휴가 협의 완료]", kw["subject"])
|
|
self.assertIn("협의자 박과장: 승인", kw["body"])
|
|
|
|
|
|
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 []
|
|
def consults_ready(self):
|
|
return True
|
|
def list_consults(self, request_id):
|
|
return []
|
|
def consults_for(self, request_ids):
|
|
return {}
|
|
def my_consults(self, email):
|
|
return []
|
|
def list_balances(self, year):
|
|
return []
|
|
def used_days(self, user_email, year):
|
|
return 0.0
|
|
def hire_ready(self):
|
|
return True
|
|
def hire_dates(self):
|
|
return {}
|
|
def balance_summary(self, user_email, as_of=None, hire_date=None): # db.balance_summary 모양(입사일 기준, 가짜 계산)
|
|
from app.timezone import today_kst
|
|
as_of = as_of or today_kst()
|
|
bal = {b["user_email"]: b for b in self.list_balances(as_of.year)}.get(user_email)
|
|
used = self.used_days(user_email, as_of.year)
|
|
manual = bal["total_days"] if bal else None
|
|
total = manual if manual is not None else 0.0
|
|
return {"has_hire": bool(hire_date), "service_years": 0, "period_start": f"{as_of.year}-01-01" if manual is not None else "",
|
|
"period_end": f"{as_of.year}-12-31" if manual is not None else "", "granted": total, "granted_so_far": total,
|
|
"upcoming": 0.0, "used": used, "available": total - used, "expiring": None, "grants": [], "as_of": as_of.isoformat(),
|
|
"hire_date": hire_date or "", "key_year": as_of.year, "manual_total": manual, "prior_used": 0.0,
|
|
"memo": bal["memo"] if bal else "", "total_days": total, "used_days": used, "remaining_days": total - used}
|
|
def holiday_map(self, date_from, date_to): # 국경일 + 설정 공휴일(db.holiday_map) — 해마다 한글날만
|
|
return {f"{y}-10-09": "한글날" for y in range(int(date_from[:4]), int(date_to[:4]) + 1)}
|
|
|
|
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
|
|
# 옵션 수정 = 관리자 + 승인자 + 통보자(2026-10-27) — 통보자 kim·승인자 lee 는 저장 가능, 칩만 있는 chip 은 이제 승인자가 아니라 403
|
|
who["u"] = kim
|
|
r = c.get("/vacation/options")
|
|
assert 'value="lee@test.local" checked' in r.text and 'value="chip@test.local" disabled' not in r.text and ">저장</button>" in r.text
|
|
assert c.post("/vacation/options", data={"approvers": ["lee@test.local"], "notifiers": ["kim@test.local"]}).status_code == 303
|
|
who["u"] = lee
|
|
assert c.post("/vacation/options", data={"approvers": ["lee@test.local"], "notifiers": ["kim@test.local"]}).status_code == 303
|
|
who["u"] = chip
|
|
assert c.post("/vacation/options", data={"approvers": ["chip@test.local"]}).status_code == 403
|
|
assert st.opts["approvers"] == ["lee@test.local"] and st.opts["notifiers"] == ["kim@test.local"]
|
|
who["u"] = admin
|
|
# 승인자를 지정하면 그 사람만(+관리자) — 칩만 있는 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")
|
|
# 휴가 신청 화면 — 날짜 칸 = 공용 날짜 팝업(erp-datepop), 공휴일(빨강만) 작년~내년을 화면에
|
|
import json, re
|
|
from app.timezone import today_kst
|
|
r = c.get("/vacation/new")
|
|
assert r.status_code == 200, r.status_code
|
|
assert "/static/erp-datepop.js" in r.text and "/static/erp-datepop.css" in r.text and "material-symbols.css" in r.text
|
|
hol = json.loads(re.search(r'<script type="application/json" id="vac-holidays">(.*?)</script>', r.text, re.S).group(1))
|
|
y = today_kst().year
|
|
assert hol == {f"{yy}-10-09": "한글날" for yy in (y - 1, y, y + 1)}, hol
|
|
# 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)
|
|
|
|
|
|
def test_consult_access_and_form(self):
|
|
"""협의자(2026-11-02) — 폼 값 저장 규칙, 휴가 권한 없는 협의자도 자기 신청은 보고 처리, 다른 협의자 내용은 안 보임."""
|
|
res = _run('''
|
|
outsider = U("out@test.local"); outsider["modules"] = {}
|
|
other = U("other@test.local"); other["modules"] = {}
|
|
users.extend([outsider, other])
|
|
CONSULTS = [{"email": "out@test.local", "name": "out", "message": "바깥 사람 전용", "state": "대기", "comment": "", "decided_at": None},
|
|
{"email": "lee@test.local", "name": "lee", "message": "이팀장 전용", "state": "대기", "comment": "", "decided_at": None}]
|
|
class Store3(Store):
|
|
created = None
|
|
decided = []
|
|
def list_consults(self, request_id):
|
|
return [dict(c) for c in CONSULTS]
|
|
def get_request(self, request_id):
|
|
return dict(self.req)
|
|
def create_request(self, owner, owner_name, payload, status, consults=None):
|
|
Store3.created = {"status": status, "consults": consults, "owner": owner}
|
|
return dict(self.req, id="new1")
|
|
def decide_consult(self, request_id, email, approve, reason=""):
|
|
Store3.decided.append((email, approve, reason))
|
|
return dict(self.req, status="제출"), ("consulted" if approve else "rejected")
|
|
def list_overlapping(self, date_from, date_to):
|
|
return []
|
|
def list_pending(self):
|
|
return []
|
|
st3 = Store3()
|
|
st3.req["status"] = "협의중"
|
|
FORM = {"vacation_type": "연차", "start_date": "2026-11-03", "end_date": "2026-11-03", "action": "submit"}
|
|
def body(c):
|
|
main.app.state.vacation_store = st3
|
|
who["u"] = kim
|
|
# 신청 화면 — 구성원 전체(휴가 권한 없는 사람 포함, 나 빼고)
|
|
t = c.get("/vacation/new").text
|
|
assert 'data-email="out@test.local"' in t and 'data-email="lee@test.local"' in t and 'data-email="kim@test.local"' not in t
|
|
# 제출 — 협의자도 "협의자 없음"도 없으면 400, 작성중 저장은 통과
|
|
assert c.post("/vacation/new", data=FORM).status_code == 400
|
|
assert c.post("/vacation/new", data=dict(FORM, action="draft")).status_code == 303 and Store3.created["consults"] == []
|
|
assert c.post("/vacation/new", data=dict(FORM, no_consult="1")).status_code == 303 and Store3.created["consults"] == []
|
|
# 빈 협의 내용이 있어도 사람과 내용 칸이 어긋나지 않음, 본인은 빠짐
|
|
r = c.post("/vacation/new", data=dict(FORM, consult_email=["kim@test.local", "lee@test.local", "out@test.local"], consult_message=["나", "", "부탁드립니다"]))
|
|
assert r.status_code == 303, r.text
|
|
assert Store3.created["consults"] == [{"email": "lee@test.local", "name": "lee", "message": ""},
|
|
{"email": "out@test.local", "name": "out", "message": "부탁드립니다"}], Store3.created
|
|
assert c.post("/vacation/new", data=dict(FORM, consult_email=["nobody@test.local"], consult_message=[""])).status_code == 400
|
|
# 휴가 권한 없는 협의자 — 메일 링크로 자기 신청을 열어 처리, 자기 내용만
|
|
who["u"] = outsider
|
|
t = c.get("/vacation/r1").text
|
|
assert "바깥 사람 전용" in t and "이팀장 전용" not in t and "협의 승인" in t
|
|
assert c.get("/vacation/").status_code == 403
|
|
assert c.post("/vacation/r1/consult", data={"decision": "approve"}).status_code == 303
|
|
assert Store3.decided[-1] == ("out@test.local", True, "") and sent[-1][0] == "consulted", sent
|
|
# 협의자가 아니고 권한도 없으면 못 봄
|
|
who["u"] = other
|
|
assert c.get("/vacation/r1").status_code == 403
|
|
# 신청자·결재자는 전체, 내 신청 내역은 라우팅이 신청 id 보다 먼저
|
|
who["u"] = kim
|
|
t = c.get("/vacation/r1").text
|
|
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_balances_in_options_settings_and_calendar_holidays(self):
|
|
"""2026-10-27 — 잔여 연차는 옵션(관리자, 참여자 전원 아이콘·이름 미리), 설정엔 없음, 달력 공휴일 이름."""
|
|
res = _run('''
|
|
lee["picture"] = "https://img.test/lee.png"
|
|
saved = {}
|
|
class Store2(Store):
|
|
def list_balances(self, year):
|
|
return [{"user_email": "lee@test.local", "year": year, "total_days": 15, "memo": "입사 2020"},
|
|
{"user_email": "gone@test.local", "year": year, "total_days": 10, "memo": ""}] if year == 2026 else \
|
|
[{"user_email": "kim@test.local", "year": year, "total_days": 12, "memo": ""}]
|
|
def used_days(self, user_email, year):
|
|
return {"lee@test.local": 4.5}.get(user_email, 0.0)
|
|
def save_balances(self, rows, by="", as_of=None):
|
|
saved.update(rows=rows, by=by); return len(rows)
|
|
def hire_dates(self):
|
|
return {"lee@test.local": "2020-03-02"}
|
|
def list_holidays(self, year=None):
|
|
return []
|
|
def holiday_map(self, date_from, date_to):
|
|
return {d: n for d, n in {"2026-10-03": "개천절", "2026-10-05": "개천절 대체", "2026-10-09": "한글날"}.items()
|
|
if date_from <= d <= date_to}
|
|
def list_overlapping(self, date_from, date_to):
|
|
return []
|
|
def list_pending(self):
|
|
return []
|
|
st2 = Store2()
|
|
def body(c):
|
|
main.app.state.vacation_store = st2
|
|
who["u"] = admin
|
|
r = c.get("/vacation/options?year=2026")
|
|
assert r.status_code == 200, r.status_code
|
|
t = r.text
|
|
assert 'id="balances"' in t and "기준 · 참여자 4명" in t, t[t.find("잔여 연차"):t.find("잔여 연차") + 200]
|
|
for u in users: # 참여자 전원 미리(이름 + 이메일 + 줄마다 칸)
|
|
assert f'name="email" value="{u["email"]}"' in t, u["email"]
|
|
assert 'src="https://img.test/lee.png"' in t # 사진 있으면 사진, 없으면 첫 글자
|
|
assert '<span class="vac-opt-face is-ini">k</span>' in t
|
|
assert "gone@test.local · 휴가 권한 없음" in t # 예전에 등록된 사람도 보여 줌
|
|
i = t.index('name="email" value="lee@test.local"')
|
|
row = t[i:i + 1800]
|
|
h = t.rfind('name="hire"', 0, i)
|
|
assert 'value="2020-03-02"' in t[h:i], t[h:i] # 입사일 = 이름 옆 날짜 칸(값 저장소)
|
|
assert "법정 연차" in t and "시스템 전 사용" in t and "근로기준법 제60조" in t
|
|
assert 'value="15"' in row and ">4.5<" in row and ">10.5<" in row and 'value="입사 2020"' in row, row
|
|
j = t.index('name="email" value="kim@test.local"')
|
|
assert "입사일 기준" in t and "12/31 에 없어지지 않음" in t and "승인되면" in t and "먼저 소멸" in t
|
|
assert "12.31 에 소멸" not in t and "12.31 소멸" not in t
|
|
# 저장 — 빈 칸은 건너뜀, 연도·이메일·메모 그대로
|
|
# 저장 — 줄마다 입사일·연차(빈 칸 = 법정)·시스템 전 사용·메모, 저장한 사람
|
|
r = c.post("/vacation/options/balances", data={"year": "2026", "email": ["lee@test.local", "kim@test.local", "chip@test.local"],
|
|
"hire": ["2020-03-02", "", "2025-03-01"], "total": ["16", "", ""],
|
|
"prior": ["", "2.5", ""], "memo": ["a", "b", "c"]})
|
|
assert r.status_code == 303 and r.headers["location"].startswith("/vacation/options?msg="), r.status_code
|
|
assert saved == {"by": "admin@test.local", "rows": [
|
|
{"user_email": "lee@test.local", "total_days": 16.0, "prior_used": None, "memo": "a", "hire_date": "2020-03-02"},
|
|
{"user_email": "kim@test.local", "total_days": None, "prior_used": 2.5, "memo": "b", "hire_date": ""},
|
|
{"user_email": "chip@test.local", "total_days": None, "prior_used": None, "memo": "c", "hire_date": "2025-03-01"}]}, saved
|
|
bad = {"year": "2026", "email": ["lee@test.local"], "hire": [""], "prior": [""], "memo": [""]}
|
|
assert c.post("/vacation/options/balances", data=dict(bad, total=["x"])).status_code == 400
|
|
assert c.post("/vacation/options/balances", data={"year": "2026", "email": ["lee@test.local"], "total": ["1"], "memo": [""]}).status_code == 400 # 칸 수
|
|
assert "시스템 전 사용</th>" in c.get("/vacation/options").text # 도입 해(2026)·다음 해까지 칸
|
|
# 승인자(옵션 미지정 → 휴가 승인 권한 chip)는 잔여 연차도 보고 저장
|
|
who["u"] = chip
|
|
assert 'id="balances"' in c.get("/vacation/options").text
|
|
assert c.post("/vacation/options/balances", data={"year": "2026", "email": ["kim@test.local"], "hire": [""], "total": ["14"],
|
|
"prior": [""], "memo": [""]}).status_code == 303
|
|
# 관리자·승인자·통보자 아님 — 표 안 보임, 저장 403
|
|
who["u"] = kim
|
|
assert 'id="balances"' not in c.get("/vacation/options").text
|
|
assert c.post("/vacation/options/balances", data={"year": "2026", "email": ["kim@test.local"], "hire": [""], "total": ["30"],
|
|
"prior": [""], "memo": [""]}).status_code == 403
|
|
# 설정 화면 삭제 — 예전 주소는 옵션으로, 공휴일·잔여 연차 저장 주소 없음
|
|
who["u"] = admin
|
|
r = c.get("/vacation/settings?year=2026")
|
|
assert r.status_code == 303 and r.headers["location"] == "/vacation/options", r.status_code
|
|
for url, data in (("/vacation/settings/holidays", {"holiday_date": "2026-10-08", "name": "x"}),
|
|
("/vacation/settings/holidays/1/delete", {}),
|
|
("/vacation/settings/balances", {"user_email": "a@test.local", "year": "2026", "total_days": "1"})):
|
|
assert c.post(url, data=data).status_code in (404, 405), url
|
|
# 달력 — 국경일·대체공휴일 이름이 날짜 아래, 그 주는 has-hol, 내 연차 = 입사일 기준(12/31 소멸 없음)
|
|
t = c.get("/vacation/?year=2026&month=10").text
|
|
assert '<span class="vac-hol-name">개천절</span>' in t and '<span class="vac-hol-name">개천절 대체</span>' in t
|
|
assert '<span class="vac-hol-name">한글날</span>' in t and t.count("has-hol") == 2, t.count("has-hol")
|
|
assert "12.31 소멸" not in t and "입사일 미등록(옵션)" in t and "발생 <strong>" in t
|
|
assert 'href="/vacation/settings' not in t and ">설정</a>" not in t and 'href="/vacation/options"' in t # 설정 버튼 없음
|
|
print("OK")
|
|
run(body)
|
|
''')
|
|
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
|
|
self.assertIn("OK", res.stdout)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|