feat(vacation): 입사일(이름 옆 날짜) · 근로기준법 연차 자동 · 2026 시스템 전 사용 연차
- 잔여 연차 표 이름 옆 입사일 날짜 버튼(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>
This commit is contained in:
+95
-44
@@ -24,7 +24,9 @@ from psycopg_pool import ConnectionPool
|
||||
|
||||
from app.timezone import KST
|
||||
|
||||
from .store import DEDUCT_TYPES, EDITABLE_STATUSES, STATUSES, VACATION_TYPES, compute_days, normalize_half
|
||||
from .store import (
|
||||
DEDUCT_TYPES, EDITABLE_STATUSES, STATUSES, VACATION_TYPES, compute_days, legal_annual_leave, normalize_half,
|
||||
)
|
||||
|
||||
|
||||
def _email_list(value: Any) -> list[str]:
|
||||
@@ -156,26 +158,6 @@ class VacationDBStore:
|
||||
).fetchall()
|
||||
return [self._balance_serialize(r) for r in rows]
|
||||
|
||||
def upsert_balance(
|
||||
self, *, user_email: str, year: int, total_days: float, memo: str = ""
|
||||
) -> dict[str, Any]:
|
||||
email = (user_email or "").lower().strip()
|
||||
if not email or "@" not in email:
|
||||
raise ValueError("올바른 이메일이 필요합니다.")
|
||||
with self._pool.connection() as conn:
|
||||
row = 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
|
||||
RETURNING *
|
||||
""",
|
||||
(email, year, total_days, (memo or "").strip()),
|
||||
).fetchone()
|
||||
return self._balance_serialize(row)
|
||||
|
||||
def used_days(self, *, user_email: str, year: int) -> float:
|
||||
"""그해 사용 연차 = 승인된 연차·반차(DEDUCT_TYPES)의 그해 날짜분 합계(2026-10-27).
|
||||
|
||||
@@ -208,35 +190,103 @@ class VacationDBStore:
|
||||
)
|
||||
return round(total, 2)
|
||||
|
||||
def save_balances(self, *, year: int, rows: list[dict[str, Any]]) -> int:
|
||||
"""잔여 연차 한꺼번에 저장 [{user_email, total_days, memo}] — 한 트랜잭션, 저장한 줄 수."""
|
||||
n = 0
|
||||
def save_balances(self, *, year: int, rows: list[dict[str, Any]], by: str = "") -> int:
|
||||
"""잔여 연차 한꺼번에 저장 — 한 트랜잭션, 한 줄이라도 틀리면 전부 안 함. 저장한 줄 수.
|
||||
|
||||
row = {user_email, total_days(None = 입사일 기준 법정 연차), prior_used(시스템 전 사용, None = 0), memo,
|
||||
hire_date("YYYY-MM-DD" | "" = 지움 | 키 없음 = 그대로)}. 002 전이면 입사일·시스템 전 사용은 무시하고
|
||||
total_days 가 없는 줄은 건너뛴다(예전처럼).
|
||||
"""
|
||||
v002 = self.hire_ready()
|
||||
clean = []
|
||||
for r in rows:
|
||||
email = (r.get("user_email") or "").lower().strip()
|
||||
if "@" not in email:
|
||||
raise ValueError(f"올바른 이메일이 아닙니다: {email}")
|
||||
total, prior = r.get("total_days"), r.get("prior_used")
|
||||
for label, v in (("연차", total), ("시스템 전 사용", prior)):
|
||||
if v is not None and (float(v) < 0 or float(v) > 365 or round(float(v) * 2) != float(v) * 2):
|
||||
raise ValueError(f"{label} 일수는 0~365, 0.5일 단위입니다: {email}")
|
||||
hire: Any = ...
|
||||
if "hire_date" in r:
|
||||
hv = str(r.get("hire_date") or "").strip()
|
||||
hire = None
|
||||
if hv:
|
||||
try:
|
||||
hire = date.fromisoformat(hv)
|
||||
except ValueError:
|
||||
raise ValueError(f"입사일이 올바르지 않습니다: {email} {hv}") from None
|
||||
if not date(1950, 1, 1) <= hire <= date(year + 1, 12, 31):
|
||||
raise ValueError(f"입사일이 올바르지 않습니다: {email} {hv}")
|
||||
if not v002 and total is None:
|
||||
continue
|
||||
clean.append((email, None if total is None else float(total), float(prior or 0),
|
||||
(r.get("memo") or "").strip()[:200], hire))
|
||||
who = (by or "").lower().strip()
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
for r in rows:
|
||||
email = (r.get("user_email") or "").lower().strip()
|
||||
if "@" not in email:
|
||||
raise ValueError(f"올바른 이메일이 아닙니다: {email}")
|
||||
total = float(r["total_days"])
|
||||
if total < 0 or total > 365 or round(total * 2) != total * 2:
|
||||
raise ValueError(f"연차 일수는 0~365, 0.5일 단위입니다: {email}")
|
||||
for email, total, prior, memo, hire 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),
|
||||
)
|
||||
continue
|
||||
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, (r.get("memo") or "").strip()[:200]),
|
||||
"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),
|
||||
)
|
||||
n += 1
|
||||
return n
|
||||
if hire is not ...:
|
||||
conn.execute(
|
||||
"INSERT INTO vacation_employees (user_email, hire_date, updated_by, updated_at) VALUES (%s, %s, %s, now()) "
|
||||
"ON CONFLICT (user_email) DO UPDATE SET hire_date = EXCLUDED.hire_date, "
|
||||
"updated_by = EXCLUDED.updated_by, updated_at = now()",
|
||||
(email, hire, who),
|
||||
)
|
||||
return len(clean)
|
||||
|
||||
def balance_summary(self, *, user_email: str, year: int) -> dict[str, Any]:
|
||||
bal = self.get_balance(user_email=user_email, year=year)
|
||||
total = float(bal["total_days"]) if bal else 0.0
|
||||
used = self.used_days(user_email=user_email, year=year)
|
||||
# ── 입사일(마이그레이션 002 vacation_employees) — 없으면 입사일 없음 ──
|
||||
def hire_ready(self) -> bool:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute("SELECT to_regclass('public.vacation_employees') AS r").fetchone()
|
||||
return bool(row and row["r"])
|
||||
|
||||
def hire_dates(self) -> dict[str, str]:
|
||||
"""{이메일: 입사일 ISO}."""
|
||||
if not self.hire_ready():
|
||||
return {}
|
||||
with self._pool.connection() as conn:
|
||||
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 = 없음) 다시 읽지 않는다."""
|
||||
email = user_email.lower().strip()
|
||||
bal = self.get_balance(user_email=email, year=year)
|
||||
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)
|
||||
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)
|
||||
return {
|
||||
"year": year,
|
||||
"total_days": total,
|
||||
"used_days": used,
|
||||
"remaining_days": round(total - used, 2),
|
||||
"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"],
|
||||
"hire_date": hire_date or "",
|
||||
"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 "",
|
||||
}
|
||||
|
||||
@@ -553,8 +603,9 @@ class VacationDBStore:
|
||||
out = dict(row)
|
||||
out["id"] = int(out["id"])
|
||||
out["year"] = int(out["year"])
|
||||
out["total_days"] = cls._num(out.get("total_days", 0))
|
||||
out["total_days"] = None if out.get("total_days") is None else cls._num(out["total_days"]) # 002: NULL = 법정 연차
|
||||
out["used_days"] = cls._num(out.get("used_days", 0))
|
||||
out["prior_used"] = cls._num(out.get("prior_used", 0))
|
||||
for k in ("created_at", "updated_at"):
|
||||
v = out.get(k)
|
||||
if isinstance(v, datetime):
|
||||
|
||||
Reference in New Issue
Block a user