d20ce1efac
- 잔여 연차 표 이름 옆 입사일 날짜 버튼(ErpDatePop.enhance, « » 1년씩) → vacation_employees(마이그레이션 002) - 법정 연차 = 근로기준법 제60조 입사일 기준(1년 미만 월 1일·최대 11, 근속 n년 min(25, 15+(n-1)//2)), 그해 생기는 날을 모음 (store.legal_annual_leave, 화면도 같은 계산으로 바로 표시) — 연차 칸을 비우면 법정, 숫자면 직접 입력(total_days NULL 허용) - 2026(도입 해)만 "시스템 전 사용"(prior_used) 칸 — 잔여 = 총 − 시스템 전 사용 − 승인된 연차·반차(db.balance_summary 한 곳) - 테스트: 법정 연차 규칙, 실제 PG(입사일·법정·직접·시스템 전·검증), 실제 앱 저장, 브라우저(입사일 버튼·바로 계산·전송) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
219 lines
14 KiB
Python
219 lines
14 KiB
Python
"""휴가 DB(vacation_db) — 옵션·메일 기록(마이그레이션 001, 2026-10-27) 실제 PostgreSQL 확인.
|
||
|
||
VACATION_TEST_DB_URL 이 localhost/127.0.0.1 일 때만 돈다(아니면 skip). 앱 계정(vacation_app)으로 접속해 권한(GRANT)까지 본다.
|
||
psql … -v app_password=… -f scripts/sql/vacation_db_init.sql
|
||
psql … -d vacation_db -f scripts/sql/vacation_db_001_options_mail.sql
|
||
VACATION_TEST_DB_URL=postgresql://vacation_app:<pw>@localhost:55432/vacation_db python -m pytest tests/test_vacation_db.py
|
||
"""
|
||
import os
|
||
import sys
|
||
import unittest
|
||
import uuid
|
||
from pathlib import Path
|
||
from unittest.mock import patch
|
||
from urllib.parse import urlparse
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
sys.path.insert(0, str(ROOT))
|
||
|
||
DSN = os.getenv("VACATION_TEST_DB_URL", "")
|
||
ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1")
|
||
|
||
|
||
@unittest.skipUnless(ENABLED, "VACATION_TEST_DB_URL(localhost) 미설정")
|
||
class VacationOptionsDBTests(unittest.TestCase):
|
||
@classmethod
|
||
def setUpClass(cls):
|
||
from app.modules.vacation.db import VacationDBStore
|
||
|
||
cls.st = VacationDBStore(DSN)
|
||
|
||
@classmethod
|
||
def tearDownClass(cls):
|
||
cls.st.close()
|
||
|
||
def test_options_roundtrip(self):
|
||
self.assertTrue(self.st.options_ready())
|
||
saved = self.st.save_options(approvers=[" Lee@Test.local", "lee@test.local", "boss@test.local", "x"],
|
||
notifiers=["HR@test.local"], by="Admin@Test.local")
|
||
self.assertEqual(saved["approvers"], ["lee@test.local", "boss@test.local"]) # 소문자·중복·@ 없는 값 정리
|
||
self.assertEqual(saved["notifiers"], ["hr@test.local"])
|
||
self.assertEqual(saved["updated_by"], "admin@test.local")
|
||
self.assertTrue(saved["ready"] and saved["updated_at"])
|
||
again = self.st.save_options(approvers=[], notifiers=[], by="admin@test.local") # 덮어쓰기(키 하나)
|
||
self.assertEqual((again["approvers"], again["notifiers"]), ([], []))
|
||
|
||
def test_submit_approve_mail_log_end_to_end(self):
|
||
"""신청 → 제출 → 승인을 실제 DB 로, 메일은 가짜 SMTP — 기록이 상세 화면용 목록으로 나온다."""
|
||
from app.modules.vacation import notify
|
||
|
||
self.st.save_options(approvers=["lee@test.local"], notifiers=["hr@test.local"], by="admin@test.local")
|
||
owner = f"kim-{uuid.uuid4().hex[:6]}@test.local"
|
||
req = self.st.create_request(owner=owner, owner_name="김철수", status="작성중",
|
||
payload={"vacation_type": "연차", "start_date": "2026-11-02", "end_date": "2026-11-03",
|
||
"start_half": "full", "end_half": "full", "reason": "가족 행사"})
|
||
sub = self.st.submit(request_id=req["id"], owner=owner)
|
||
done = self.st.approve(request_id=req["id"], approver_email="lee@test.local")
|
||
users = [{"email": "lee@test.local", "name": "이팀장", "modules": {"vacation": True}}]
|
||
with patch("app.mail.send_email", return_value=True) as smtp, patch("app.mail.mail_enabled", return_value=True):
|
||
r1 = notify.deliver(self.st, None, event="submitted", req=sub, actor={"email": owner, "name": "김철수"},
|
||
users=users, link="https://erp.test/vacation/" + req["id"])
|
||
r2 = notify.deliver(self.st, None, event="approved", req=done, actor={"email": "lee@test.local", "name": "이팀장"},
|
||
users=users, link="https://erp.test/vacation/" + req["id"])
|
||
self.assertTrue(r1["ok"] and r2["ok"])
|
||
self.assertEqual(smtp.call_args_list[1].kwargs["to"], ["lee@test.local", "hr@test.local", owner])
|
||
log = self.st.list_mail_log(request_id=req["id"])
|
||
self.assertEqual([(m["event"], m["via"], m["ok"]) for m in log], [("submitted", "smtp", True), ("approved", "smtp", True)])
|
||
self.assertEqual(log[0]["sender"], owner)
|
||
self.assertEqual(log[1]["recipients"], f"lee@test.local, hr@test.local, {owner}")
|
||
self.assertIn("[휴가 승인] 김철수 · 연차", log[1]["subject"])
|
||
self.st.hard_delete(request_id=req["id"], user_email=owner, is_admin=True)
|
||
self.st.save_options(approvers=[], notifiers=[], by="admin@test.local")
|
||
|
||
|
||
@unittest.skipUnless(ENABLED, "VACATION_TEST_DB_URL(localhost) 미설정")
|
||
class VacationHolidayBalanceDBTests(unittest.TestCase):
|
||
"""2026-10-27 — 쉬는 날 = 국경일·대체공휴일 표, 연차 = 승인된 연차·반차만·해마다 나눠 셈, 잔여 연차 한꺼번에 저장."""
|
||
|
||
@classmethod
|
||
def setUpClass(cls):
|
||
from app.modules.vacation.db import VacationDBStore
|
||
|
||
cls.st = VacationDBStore(DSN)
|
||
|
||
@classmethod
|
||
def tearDownClass(cls):
|
||
cls.st.close()
|
||
|
||
def test_holiday_map_is_national_table_only(self):
|
||
"""쉬는 날 = 국경일·대체공휴일 표만(공휴일 설정 화면 삭제 — vacation_holidays 에 남은 줄은 읽지 않음)."""
|
||
st = self.st
|
||
m = st.holiday_map(date_from="2027-10-01", date_to="2027-10-31")
|
||
self.assertEqual(m, {"2027-10-03": "개천절", "2027-10-04": "개천절 대체", "2027-10-09": "한글날", "2027-10-11": "한글날 대체"})
|
||
self.assertEqual(st.holiday_map(date_from="2026-07-17", date_to="2026-07-17"), {"2026-07-17": "제헌절"}) # 예전 seed 에 없던 날
|
||
with st._pool.connection() as conn: # noqa: SLF001 — 예전 설정 화면이 남긴 줄을 흉내
|
||
conn.execute("INSERT INTO vacation_holidays (holiday_date, name, kind, is_red) VALUES ('2027-10-08', '창립기념일', 'company', TRUE), "
|
||
"('2027-10-11', '한글날 대체', 'substitute', FALSE) ON CONFLICT (holiday_date) DO NOTHING")
|
||
try:
|
||
self.assertEqual(st.holiday_map(date_from="2027-10-01", date_to="2027-10-31"), m) # 그대로
|
||
self.assertEqual(st.red_holiday_set(date_from="2027-10-01", date_to="2027-10-31"), set(m))
|
||
finally:
|
||
with st._pool.connection() as conn: # noqa: SLF001
|
||
conn.execute("DELETE FROM vacation_holidays WHERE holiday_date IN ('2027-10-08', '2027-10-11')")
|
||
|
||
def _approved(self, owner, vtype, start, end, sh="full", eh="full"):
|
||
req = self.st.create_request(owner=owner, owner_name="테스트", status="제출",
|
||
payload={"vacation_type": vtype, "start_date": start, "end_date": end,
|
||
"start_half": sh, "end_half": eh, "reason": ""})
|
||
self.st.approve(request_id=req["id"], approver_email="lee@test.local")
|
||
return req
|
||
|
||
def test_used_days_only_annual_types_and_split_by_year(self):
|
||
st = self.st
|
||
owner = f"bal-{uuid.uuid4().hex[:6]}@test.local"
|
||
made = [
|
||
self._approved(owner, "연차", "2026-11-02", "2026-11-03"), # 2
|
||
self._approved(owner, "오전반차", "2026-11-04", "2026-11-04"), # 0.5
|
||
self._approved(owner, "병가", "2026-11-05", "2026-11-06"), # 차감 안 함
|
||
self._approved(owner, "경조", "2026-11-09", "2026-11-09"), # 차감 안 함
|
||
self._approved(owner, "연차", "2026-12-30", "2027-01-04"), # 12/30·31 = 2, 1/4 = 1 (1/1 신정·주말 뺌)
|
||
]
|
||
st.create_request(owner=owner, owner_name="테스트", status="제출", # 제출(승인 전)은 차감 안 함
|
||
payload={"vacation_type": "연차", "start_date": "2026-11-10", "end_date": "2026-11-10",
|
||
"start_half": "full", "end_half": "full", "reason": ""})
|
||
try:
|
||
self.assertEqual(st.used_days(user_email=owner, year=2026), 4.5)
|
||
self.assertEqual(st.used_days(user_email=owner, year=2027), 1.0)
|
||
st.save_balances(year=2026, rows=[{"user_email": owner, "total_days": 15, "memo": "입사 2020"}])
|
||
s26 = st.balance_summary(user_email=owner, year=2026)
|
||
self.assertEqual((s26["total_days"], s26["used_days"], s26["remaining_days"]), (15.0, 4.5, 10.5))
|
||
s27 = st.balance_summary(user_email=owner, year=2027) # 다음 해로 넘어가지 않음(등록 전 = 0)
|
||
self.assertEqual((s27["total_days"], s27["remaining_days"]), (0.0, -1.0))
|
||
finally:
|
||
for r in st.list_for(owner):
|
||
st.hard_delete(request_id=r["id"], user_email=owner, is_admin=True)
|
||
|
||
def test_save_balances_validates_all_or_nothing(self):
|
||
st = self.st
|
||
a, b = f"a-{uuid.uuid4().hex[:6]}@test.local", f"b-{uuid.uuid4().hex[:6]}@test.local"
|
||
with self.assertRaises(ValueError):
|
||
st.save_balances(year=2031, rows=[{"user_email": a, "total_days": 15}, {"user_email": b, "total_days": 15.3}])
|
||
self.assertIsNone(st.get_balance(user_email=a, year=2031)) # 한 줄이라도 틀리면 전부 저장 안 함
|
||
self.assertEqual(st.save_balances(year=2031, rows=[{"user_email": a.upper(), "total_days": 15.5, "memo": " x "},
|
||
{"user_email": b, "total_days": 0}]), 2)
|
||
self.assertEqual((st.get_balance(user_email=a, year=2031)["total_days"], st.get_balance(user_email=a, year=2031)["memo"]),
|
||
(15.5, "x"))
|
||
st.save_balances(year=2031, rows=[{"user_email": a, "total_days": 20, "memo": ""}]) # 덮어쓰기
|
||
self.assertEqual(st.get_balance(user_email=a, year=2031)["total_days"], 20.0)
|
||
|
||
|
||
class LegalAnnualLeaveTests(unittest.TestCase):
|
||
"""근로기준법 제60조 — 입사일 기준으로 생기는 연차를 그해에 모은다(2026-10-27, DB 없음)."""
|
||
|
||
def test_rules(self):
|
||
from datetime import date
|
||
|
||
from app.modules.vacation.store import add_months, legal_annual_leave as L
|
||
|
||
self.assertEqual(add_months(date(2026, 1, 31), 1), date(2026, 2, 28))
|
||
self.assertEqual(add_months(date(2024, 2, 29), 12), date(2025, 2, 28))
|
||
# 입사 1년 미만 = 1개월마다 1일, 입사일이 돌아오면 15일 — 2025-03-01 입사
|
||
self.assertEqual(L(date(2025, 3, 1), 2025)["days"], 9.0) # 4/1 ~ 12/1
|
||
r = L(date(2025, 3, 1), 2026)
|
||
self.assertEqual((r["days"], r["service_years"]), (17.0, 1)) # 1/1·2/1(월 1일) + 3/1 근속 1년 15일
|
||
self.assertEqual([i["date"] for i in r["items"]], ["2026-01-01", "2026-02-01", "2026-03-01"])
|
||
self.assertEqual(L(date(2025, 3, 1), 2027)["days"], 15.0) # 근속 2년 = 15일
|
||
# 3년 이상 = 최초 1년을 넘는 근속 2년마다 1일, 최대 25일
|
||
self.assertEqual(L(date(2023, 5, 10), 2026)["days"], 16.0) # 근속 3년
|
||
self.assertEqual(L(date(2020, 3, 2), 2026)["days"], 17.0) # 근속 6년 = 15 + 2
|
||
self.assertEqual(L(date(2001, 1, 1), 2026)["days"], 25.0) # 근속 25년 → 한도 25
|
||
self.assertEqual(L(date(2027, 1, 2), 2026)["days"], 0.0) # 아직 입사 전
|
||
self.assertEqual(L(None, 2026)["days"], 0.0)
|
||
|
||
|
||
@unittest.skipUnless(ENABLED, "VACATION_TEST_DB_URL(localhost) 미설정")
|
||
class VacationHireDBTests(unittest.TestCase):
|
||
"""002 — 입사일·시스템 전 사용·연차 비우면 법정(실제 PostgreSQL, 002 적용 DB)."""
|
||
|
||
@classmethod
|
||
def setUpClass(cls):
|
||
from app.modules.vacation.db import VacationDBStore
|
||
|
||
cls.st = VacationDBStore(DSN)
|
||
|
||
@classmethod
|
||
def tearDownClass(cls):
|
||
cls.st.close()
|
||
|
||
def test_hire_legal_manual_prior(self):
|
||
st = self.st
|
||
self.assertTrue(st.hire_ready())
|
||
a, b = f"h-{uuid.uuid4().hex[:6]}@test.local", f"h-{uuid.uuid4().hex[:6]}@test.local"
|
||
n = st.save_balances(year=2026, by="admin@test.local", rows=[
|
||
{"user_email": a, "total_days": None, "prior_used": 3.5, "memo": "", "hire_date": "2025-03-01"},
|
||
{"user_email": b, "total_days": 20, "prior_used": None, "memo": "직접", "hire_date": "2020-03-02"},
|
||
])
|
||
self.assertEqual(n, 2)
|
||
self.assertEqual(st.hire_dates()[a], "2025-03-01")
|
||
sa = st.balance_summary(user_email=a, year=2026)
|
||
self.assertEqual((sa["total_days"], sa["manual_total"], sa["legal_days"], sa["prior_used"], sa["remaining_days"]),
|
||
(17.0, None, 17.0, 3.5, 13.5)) # 법정 17 − 시스템 전 3.5
|
||
sb = st.balance_summary(user_email=b, year=2026)
|
||
self.assertEqual((sb["total_days"], sb["legal_days"], sb["remaining_days"], sb["service_years"]), (20.0, 17.0, 20.0, 6))
|
||
# 2027 — 아무것도 등록 안 해도 입사일로 법정 연차(이월 없음)
|
||
self.assertEqual(st.balance_summary(user_email=a, year=2027)["total_days"], 15.0)
|
||
# 입사일 지우기("") · 키 없으면 그대로 · 틀린 입사일은 전부 저장 안 함
|
||
st.save_balances(year=2026, rows=[{"user_email": a, "total_days": None, "prior_used": 0, "memo": ""}])
|
||
self.assertEqual(st.hire_dates()[a], "2025-03-01")
|
||
with self.assertRaises(ValueError):
|
||
st.save_balances(year=2026, rows=[{"user_email": a, "total_days": None, "hire_date": ""},
|
||
{"user_email": b, "total_days": None, "hire_date": "2020-13-01"}])
|
||
self.assertEqual(st.hire_dates()[a], "2025-03-01")
|
||
st.save_balances(year=2026, rows=[{"user_email": a, "total_days": None, "hire_date": ""}])
|
||
self.assertNotIn(a, st.hire_dates())
|
||
self.assertEqual(st.balance_summary(user_email=a, year=2026)["total_days"], 0.0)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
unittest.main()
|