feat(vacation): 연차 12/31 소멸 삭제 — 입사일 기준, 연차마다 쓸 수 있는 기한

- store.leave_grants/leave_period/leave_status: 1년 미만 월 1일 = 입사일부터 1년까지, 근속 n년 연차 = 생긴 날부터 1년까지(근로기준법 제60조)
- 승인된 연차·반차를 날짜별(usage_units = compute_days 규칙)로 나눠 그날 쓸 수 있는 연차 중 먼저 소멸하는 것부터 차감, 생기기 전이면 당겨 씀
- 화면: 지금 연차 기간 · 생기는 연차(오늘까지 +앞으로) · 사용 · 오늘 쓸 수 있는 잔여 · 먼저 소멸(날짜·일수), 해 이동 없음, 달력 위 내 연차도 같은 값
- 직접 입력 = 지금 연차 기간이 시작한 해 줄(override_year), 시스템 전 사용 = 2026 줄(도입일에 쓴 것으로)
- 테스트: 규칙(10/12 입사 사례·먼저 소멸·당겨 씀·시스템 전·입사일 없음), 실제 PG, 실제 앱, 브라우저

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-26 16:27:50 +09:00
parent 197c3c13a3
commit 4b2defac3a
16 changed files with 500 additions and 311 deletions
+71 -58
View File
@@ -15,7 +15,7 @@
from __future__ import annotations
import uuid
from datetime import date, datetime, timedelta, timezone
from datetime import date, datetime, timezone
from decimal import Decimal
from typing import Any
@@ -25,7 +25,8 @@ from psycopg_pool import ConnectionPool
from app.timezone import KST
from .store import (
DEDUCT_TYPES, EDITABLE_STATUSES, STATUSES, VACATION_TYPES, compute_days, legal_annual_leave, normalize_half,
DEDUCT_TYPES, EDITABLE_STATUSES, STATUSES, SYSTEM_START_YEAR, VACATION_TYPES, compute_days, leave_period, leave_status,
normalize_half, usage_units,
)
@@ -158,46 +159,43 @@ class VacationDBStore:
).fetchall()
return [self._balance_serialize(r) for r in rows]
def used_days(self, *, user_email: str, year: int) -> float:
"""그해 사용 연차 = 승인된 연차·반차(DEDUCT_TYPES)의 그해 날짜분 합계(2026-10-27).
병가·경조·대체휴무·기타는 빼지 않는다. 해를 넘는 신청(12/30~1/2)은 해마다 그 해 날짜만큼 나눠 센다
(예전엔 모든 승인 휴가를 시작일 연도에 통째로 셌다). 그해 안에 다 들어가는 신청은 저장된 일수 그대로.
"""
y0, y1 = date(year, 1, 1), date(year, 12, 31)
def usage_events(self, *, user_email: str) -> list[tuple[date, float]]:
"""쓴 연차 = 승인된 연차·오전반차·오후반차(DEDUCT_TYPES)를 날짜별 [(날짜, 1|0.5)]로(store.usage_units — compute_days 와 같은 규칙).
병가·경조·대체휴무·기타는 빼지 않는다. 앞날짜로 승인된 휴가도 넣는다(승인되면 차감). 어느 연차에서 빼는지는 store.leave_status."""
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT start_date, end_date, start_half, end_half, vacation_type, days FROM vacation_requests "
"WHERE owner = %s AND status = '승인' AND vacation_type = ANY(%s) "
"AND start_date <= %s AND end_date >= %s",
(user_email.lower().strip(), list(DEDUCT_TYPES), y1, y0),
"SELECT start_date, end_date, start_half, end_half, vacation_type FROM vacation_requests "
"WHERE owner = %s AND status = '승인' AND vacation_type = ANY(%s) ORDER BY start_date",
(user_email.lower().strip(), list(DEDUCT_TYPES)),
).fetchall()
total = 0.0
holidays: set[str] | None = None
if not rows:
return []
holidays = self.red_holiday_set(date_from=min(r["start_date"] for r in rows).isoformat(),
date_to=max(r["end_date"] for r in rows).isoformat())
out: list[tuple[date, float]] = []
for r in rows:
sd, ed = r["start_date"], r["end_date"]
if sd >= y0 and ed <= y1:
total += self._num(r["days"])
continue
if holidays is None:
holidays = self.red_holiday_set(date_from=(y0 - timedelta(days=7)).isoformat(),
date_to=(y1 + timedelta(days=7)).isoformat())
total += compute_days(
start_date=max(sd, y0), end_date=min(ed, y1),
start_half=r["start_half"] if sd >= y0 else "full",
end_half=r["end_half"] if ed <= y1 else "full",
vacation_type=r["vacation_type"], holidays=holidays,
)
return round(total, 2)
out += usage_units(start_date=r["start_date"], end_date=r["end_date"], start_half=r["start_half"],
end_half=r["end_half"], vacation_type=r["vacation_type"], holidays=holidays)
return out
def save_balances(self, *, year: int, rows: list[dict[str, Any]], by: str = "") -> int:
def used_days(self, *, user_email: str, year: int) -> float:
"""그해(1/1~12/31) 쓴 연차 합 — 엑셀·참고용(잔여 계산은 입사일 기준 balance_summary)."""
return round(sum(a for d, a in self.usage_events(user_email=user_email) if d.year == year), 2)
def save_balances(self, *, rows: list[dict[str, Any]], by: str = "", as_of: date | None = None) -> int:
"""잔여 연차 한꺼번에 저장 — 한 트랜잭션, 한 줄이라도 틀리면 전부 안 함. 저장한 줄 수.
row = {user_email, total_days(None = 입사일 기준 법정 연차), prior_used(시스템 전 사용, None = 0), memo,
hire_date("YYYY-MM-DD" | "" = 지움 | 키 없음 = 그대로)}. 002 전이면 입사일·시스템 전 사용은 무시하고
total_days 가 없는 줄은 건너뛴다(예전처럼).
hire_date("YYYY-MM-DD" | "" = 지움 | 키 없음 = 그대로)}.
직접 입력·메모는 그 사람의 **지금 연차 기간이 시작한 해** 줄에(override_year — 바꾼 입사일 기준으로 서버가 계산),
시스템 전 사용은 SYSTEM_START_YEAR 줄에. 002 전이면 입사일·시스템 전 사용은 무시하고 total_days 가 없는 줄은 건너뛴다.
"""
from app.timezone import today_kst # noqa: WPS433
as_of = as_of or today_kst()
year = as_of.year
v002 = self.hire_ready()
old_hires = self.hire_dates()
clean = []
for r in rows:
email = (r.get("user_email") or "").lower().strip()
@@ -220,24 +218,30 @@ class VacationDBStore:
raise ValueError(f"입사일이 올바르지 않습니다: {email} {hv}")
if not v002 and total is None:
continue
hire_iso = (hire.isoformat() if hire else None) if hire is not ... else old_hires.get(email)
key_year = self.override_year(hire_iso, as_of) if v002 else year
clean.append((email, None if total is None else float(total), float(prior or 0),
(r.get("memo") or "").strip()[:200], hire))
(r.get("memo") or "").strip()[:200], hire, key_year))
who = (by or "").lower().strip()
with self._pool.connection() as conn:
with conn.transaction():
for email, total, prior, memo, hire in clean:
for email, total, prior, memo, hire, key_year in clean:
if not v002:
conn.execute(
"INSERT INTO vacation_balances (user_email, year, total_days, memo) VALUES (%s, %s, %s, %s) "
"ON CONFLICT (user_email, year) DO UPDATE SET total_days = EXCLUDED.total_days, memo = EXCLUDED.memo",
(email, year, total, memo),
(email, key_year, total, memo),
)
continue
conn.execute(
"INSERT INTO vacation_balances (user_email, year, total_days, prior_used, memo) VALUES (%s, %s, %s, %s, %s) "
"ON CONFLICT (user_email, year) DO UPDATE SET total_days = EXCLUDED.total_days, "
"prior_used = EXCLUDED.prior_used, memo = EXCLUDED.memo",
(email, year, total, prior, memo),
"INSERT INTO vacation_balances (user_email, year, total_days, memo) VALUES (%s, %s, %s, %s) "
"ON CONFLICT (user_email, year) DO UPDATE SET total_days = EXCLUDED.total_days, memo = EXCLUDED.memo",
(email, key_year, total, memo),
)
conn.execute( # 시스템 전 사용 — 도입 해 줄(직접 입력·메모는 건드리지 않음)
"INSERT INTO vacation_balances (user_email, year, total_days, prior_used) VALUES (%s, %s, NULL, %s) "
"ON CONFLICT (user_email, year) DO UPDATE SET prior_used = EXCLUDED.prior_used",
(email, SYSTEM_START_YEAR, prior),
)
if hire is not ...:
conn.execute(
@@ -262,32 +266,41 @@ class VacationDBStore:
rows = conn.execute("SELECT user_email, hire_date FROM vacation_employees WHERE hire_date IS NOT NULL").fetchall()
return {r["user_email"]: r["hire_date"].isoformat() for r in rows}
def balance_summary(self, *, user_email: str, year: int, hire_date: Any = ...) -> dict[str, Any]:
"""그해 연차(2026-10-27) — 총 = 직접 입력(있으면) 아니면 입사일 기준 법정 연차(근로기준법 제60조, store.legal_annual_leave),
사용 = 시스템 전 사용(prior_used, 002) + 승인된 연차·반차(used_days), 잔여 = 총 − 사용.
hire_date 를 넘기면(목록에서 한 번에 읽은 값, None = 없음) 다시 읽지 않는다."""
@staticmethod
def override_year(hire_date: str | None, as_of: date) -> int:
"""직접 입력 연차를 둘 해 = 지금 연차 기간이 시작한 해(입사일 없으면 as_of 의 해) — vacation_balances.year 키."""
if not hire_date:
return as_of.year
hire = date.fromisoformat(hire_date)
return as_of.year if as_of < hire else leave_period(hire, as_of)[1].year
def balance_summary(self, *, user_email: str, as_of: date | None = None, hire_date: Any = ...) -> dict[str, Any]:
"""입사일 기준 연차 현황(2026-10-27 — 12/31 소멸 없음, store.leave_status): 지금 연차 기간·생긴 연차·쓴 연차·
지금 쓸 수 있는 잔여·가장 먼저 소멸할 잔여. 직접 입력(그 기간 시작한 해 줄의 total_days)이 있으면 그 기간 법정 연차 대신,
시스템 전 사용 = SYSTEM_START_YEAR 줄의 prior_used. hire_date 를 넘기면(목록에서 한 번에 읽은 값, None = 없음) 다시 읽지 않는다."""
from app.timezone import today_kst # noqa: WPS433
email = user_email.lower().strip()
bal = self.get_balance(user_email=email, year=year)
as_of = as_of or today_kst()
if hire_date is ...:
hire_date = self.hire_dates().get(email)
legal = legal_annual_leave(date.fromisoformat(hire_date) if hire_date else None, year)
key_year = self.override_year(hire_date, as_of)
bal = self.get_balance(user_email=email, year=key_year)
prior_row = bal if key_year == SYSTEM_START_YEAR else self.get_balance(user_email=email, year=SYSTEM_START_YEAR)
manual = bal["total_days"] if bal and bal.get("total_days") is not None else None
total = manual if manual is not None else (legal["days"] if hire_date else 0.0)
prior = float(bal.get("prior_used") or 0) if bal else 0.0
erp_used = self.used_days(user_email=email, year=year)
prior = float((prior_row or {}).get("prior_used") or 0)
st = leave_status(hire=date.fromisoformat(hire_date) if hire_date else None, as_of=as_of,
usages=self.usage_events(user_email=email), prior=prior, override=manual)
return {
"year": year,
"total_days": round(float(total), 2),
"manual_total": manual,
"legal_days": legal["days"] if hire_date else None,
"legal_items": legal["items"],
"service_years": legal["service_years"],
**st,
"as_of": as_of.isoformat(),
"hire_date": hire_date or "",
"key_year": key_year,
"manual_total": manual,
"prior_used": prior,
"erp_used": erp_used,
"used_days": round(prior + erp_used, 2),
"remaining_days": round(float(total) - prior - erp_used, 2),
"memo": bal["memo"] if bal else "",
"memo": (bal or {}).get("memo") or "",
# 예전 이름(달력 잔여 줄) — 총 = 이번 기간 생기는 연차, 사용 = 이번 기간 쓴 날, 잔여 = 지금 쓸 수 있는 연차
"total_days": st["granted"], "used_days": st["used"], "remaining_days": st["available"],
}
# ════════════════════════════════════════════════════════════