From d20ce1efac56cfcc059f384033f019325ae0be77 Mon Sep 17 00:00:00 2001 From: king Date: Mon, 26 Oct 2026 15:53:45 +0900 Subject: [PATCH] =?UTF-8?q?feat(vacation):=20=EC=9E=85=EC=82=AC=EC=9D=BC(?= =?UTF-8?q?=EC=9D=B4=EB=A6=84=20=EC=98=86=20=EB=82=A0=EC=A7=9C)=20=C2=B7?= =?UTF-8?q?=20=EA=B7=BC=EB=A1=9C=EA=B8=B0=EC=A4=80=EB=B2=95=20=EC=97=B0?= =?UTF-8?q?=EC=B0=A8=20=EC=9E=90=EB=8F=99=20=C2=B7=202026=20=EC=8B=9C?= =?UTF-8?q?=EC=8A=A4=ED=85=9C=20=EC=A0=84=20=EC=82=AC=EC=9A=A9=20=EC=97=B0?= =?UTF-8?q?=EC=B0=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 잔여 연차 표 이름 옆 입사일 날짜 버튼(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 --- app/modules/vacation/CLAUDE.md | 12 ++ app/modules/vacation/db.py | 139 ++++++++++++------ app/modules/vacation/router.py | 49 +++--- app/modules/vacation/store.py | 43 ++++++ .../vacation/templates/vacation/detail.html | 2 +- .../vacation/templates/vacation/form.html | 6 +- .../vacation/templates/vacation/index.html | 2 +- .../vacation/templates/vacation/options.html | 47 ++++-- .../vacation/templates/vacation/pending.html | 2 +- app/static/erp-datepop.js | 63 +++++++- app/static/vacation.css | 7 + app/static/vacation.js | 69 ++++++++- docs/DATABASES.md | 7 + scripts/sql/vacation_db_002_hire_prior.sql | 26 ++++ tests/js/render_vacation.py | 15 ++ tests/js/vacation_balances.browser.test.js | 87 +++++++++++ tests/test_vacation_db.py | 67 +++++++++ tests/test_vacation_options_mail.py | 46 ++++-- 18 files changed, 592 insertions(+), 97 deletions(-) create mode 100644 scripts/sql/vacation_db_002_hire_prior.sql create mode 100644 tests/js/vacation_balances.browser.test.js diff --git a/app/modules/vacation/CLAUDE.md b/app/modules/vacation/CLAUDE.md index 74e35d6..db8184f 100644 --- a/app/modules/vacation/CLAUDE.md +++ b/app/modules/vacation/CLAUDE.md @@ -26,6 +26,18 @@ (연차 입력·사용·잔여(음수 빨강)·메모, 아직 없으면 작년 연차를 회색 참고, 예전에 등록됐지만 권한이 없는 사람도 아래에), 연도 ‹ › 이동, `POST /vacation/options/balances` 한꺼번에(`db.save_balances` 한 트랜잭션 — 0~365·0.5일 단위, 빈 칸 = 그대로). 예전 `POST /settings/balances` 는 없앴다. +## 입사일 · 근로기준법 연차 · 시스템 전 사용 (2026-10-27, 마이그레이션 `vacation_db_002_hire_prior.sql`) + +- 옵션 잔여 연차 표 **이름 옆 입사일** = 날짜 버튼(`ErpDatePop.enhance`, « » 1년씩·직접 입력 2020-03-02 Enter, 지우기) → `vacation_employees`(사람마다 하나). +- **법정 연차** = `store.legal_annual_leave(입사일, 연도)` — 근로기준법 제60조를 **입사일 기준으로 생기는 날을 그해(1/1~12/31)에 모음** + (12/31 소멸 규칙과 맞춤): 입사 1년 미만 = 입사일 + 1~11개월마다 1일, 입사일이 돌아올 때마다(근속 n년) `min(25, 15 + (n−1)//2)`. + 출근율(개근·80%)은 따지지 않음(모두 채운 것으로). 화면(vacation.js)도 같은 계산으로 입사일을 고르는 즉시 근속·법정·잔여를 다시 보여 줌. +- 연차 칸 = 직접 입력(값이 있으면 그 값), **비우면 법정 연차**(`vacation_balances.total_days` NULL). 입사일도 연차도 없으면 0. +- **시스템 전 사용**(`prior_used`) — 이 시스템을 쓰기 전에 그해 이미 쓴 연차, **도입 해(`store.SYSTEM_START_YEAR` = 2026)만** 표에 칸. +- 잔여 = 총(직접 또는 법정) − 시스템 전 사용 − 승인된 연차·반차 — `db.balance_summary` 한 곳(달력 잔여·옵션 표 모두). +- 저장 `POST /vacation/options/balances` 줄마다 email·hire·total·prior·memo(칸 수가 다르면 400, 한 줄이라도 틀리면 전부 안 함 — `db.save_balances`). + 002 전이면 입사일·시스템 전 사용은 무시(입사일 칸은 숨김 칸, 안내 문구), 연차 직접 입력만 예전처럼. + ## 휴가 옵션 · 휴가 메일 (2026-10-27, 마이그레이션 `vacation_db_001_options_mail.sql`) - **옵션** `/vacation/options`(달력 위 [옵션], 누구나 보기): 휴가 승인자(여러 명) · 휴가 승인 통보자 · 잔여 연차. diff --git a/app/modules/vacation/db.py b/app/modules/vacation/db.py index 190bb4c..7425037 100644 --- a/app/modules/vacation/db.py +++ b/app/modules/vacation/db.py @@ -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): diff --git a/app/modules/vacation/router.py b/app/modules/vacation/router.py index de30731..f283870 100644 --- a/app/modules/vacation/router.py +++ b/app/modules/vacation/router.py @@ -26,7 +26,7 @@ from fastapi.responses import ( from app.timezone import now_kst, today_kst -from .store import HALF_LABELS, HALVES, VACATION_TYPES +from .store import HALF_LABELS, HALVES, SYSTEM_START_YEAR, VACATION_TYPES router = APIRouter(prefix="/vacation", tags=["vacation"]) @@ -486,7 +486,8 @@ def settings_page(request: Request) -> RedirectResponse: @router.post("/options/balances") async def balances_save(request: Request) -> RedirectResponse: - """잔여 연차 한꺼번에(옵션 — ERP 관리자·휴가 승인자·승인 통보자) — 참여자 줄마다 email·total·memo. 연차 칸을 비운 줄은 그대로 둔다(새로 만들지 않음).""" + """잔여 연차 한꺼번에(옵션 — ERP 관리자·휴가 승인자·승인 통보자) — 참여자 줄마다 email·hire·total·prior·memo(2026-10-27). + hire = 입사일(빈 칸 = 지움), total = 연차 직접 입력(빈 칸 = 입사일 기준 법정 연차), prior = 시스템 전에 그해 쓴 연차(빈 칸 = 0).""" from urllib.parse import urlencode # noqa: WPS433 user = _require_user(request) @@ -502,22 +503,27 @@ async def balances_save(request: Request) -> RedirectResponse: raise HTTPException(status_code=400, detail="연도가 올바르지 않습니다.") if not 2000 <= year <= 2100: raise HTTPException(status_code=400, detail="연도가 올바르지 않습니다.") - emails, totals, memos = form.getlist("email"), form.getlist("total"), form.getlist("memo") - if not (len(emails) == len(totals) == len(memos)): + emails, memos = form.getlist("email"), form.getlist("memo") + totals, priors, hires = form.getlist("total"), form.getlist("prior"), form.getlist("hire") + if not (len(emails) == len(totals) == len(memos) == len(priors) == len(hires)): raise HTTPException(status_code=400, detail="잔여 연차 칸이 맞지 않습니다.") - rows = [] - for email, total, memo in zip(emails, totals, memos): - total = str(total).strip() - if not total: - continue + + def num(v: Any, label: str, email: str) -> float | None: + v = str(v).strip() + if not v: + return None try: - rows.append({"user_email": email, "total_days": float(total), "memo": memo}) + return float(v) except ValueError: - raise HTTPException(status_code=400, detail=f"연차 일수가 숫자가 아닙니다: {email}") + raise HTTPException(status_code=400, detail=f"{label}이(가) 숫자가 아닙니다: {email}") + + rows = [{"user_email": email, "total_days": num(total, "연차 일수", email), "prior_used": num(prior, "시스템 전 사용", email), + "memo": memo, "hire_date": str(hire).strip()} + for email, total, prior, memo, hire in zip(emails, totals, priors, memos, hires)] from starlette.concurrency import run_in_threadpool # noqa: WPS433 — 폼 배열을 읽으려 async, DB 는 동기라 스레드에서 try: - n = await run_in_threadpool(store.save_balances, year=year, rows=rows) + n = await run_in_threadpool(store.save_balances, year=year, rows=rows, by=user["email"]) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) return RedirectResponse(url="/vacation/options?" + urlencode({"year": year, "msg": f"{year}년 잔여 연차 {n}명을 저장했습니다."}) @@ -526,22 +532,25 @@ async def balances_save(request: Request) -> RedirectResponse: def _balance_rows(store: Any, year: int) -> list[dict[str, Any]]: """옵션 잔여 연차 표 — 참여자(휴가 모듈 사용자) 전원 + 예전에 등록됐지만 지금 권한이 없는 사람. - 줄마다 그해 연차·사용(승인된 연차·반차)·잔여·메모, 아직 없으면 작년 연차를 참고로.""" + 줄마다 입사일·근속·법정 연차(근로기준법, 입사일 기준)·연차(직접 입력)·시스템 전 사용·사용·잔여·메모(db.balance_summary 한 곳).""" users = _vacation_users() this_year = {b["user_email"]: b for b in store.list_balances(year=year)} last_year = {b["user_email"]: b for b in store.list_balances(year=year - 1)} + hires = store.hire_dates() rows = [] people = [(u["email"].lower(), u.get("name") or u["email"].split("@")[0], u.get("picture") or "", True) for u in users] known = {p[0] for p in people} people += [(e, e.split("@")[0], "", False) for e in sorted(this_year) if e not in known] for email, name, picture, active in people: - bal = this_year.get(email) - used = store.used_days(user_email=email, year=year) - total = float(bal["total_days"]) if bal else None + s = store.balance_summary(user_email=email, year=year, hire_date=hires.get(email)) + last = last_year.get(email) rows.append({"email": email, "name": name, "picture": picture, "active": active, - "total": total, "used": used, "remaining": round(total - used, 2) if total is not None else None, - "memo": (bal or {}).get("memo") or "", - "last_total": float(last_year[email]["total_days"]) if email in last_year else None}) + "hire_date": s["hire_date"], "service_years": s["service_years"], + "legal": s["legal_days"], "legal_tip": ", ".join(f"{i['date'][5:]} {i['label']} {i['days']:g}일" for i in s["legal_items"]), + "total": s["manual_total"], "effective_total": s["total_days"], "prior": s["prior_used"], + "used": s["erp_used"], "remaining": s["remaining_days"] if (s["manual_total"] is not None or s["hire_date"]) else None, + "memo": s["memo"], + "last_total": last["total_days"] if last and last.get("total_days") is not None else None}) return rows @@ -691,6 +700,8 @@ def options_page(request: Request) -> HTMLResponse: "gmail": _gmail_state(request, user), "msg": request.query_params.get("msg", ""), "bal_year": bal_year, + "bal_prior_year": bal_year == SYSTEM_START_YEAR, # 시스템 도입 해만 "시스템 전 사용" 칸 + "hire_ready": store.hire_ready() if can_edit else False, "can_edit": can_edit, "bal_rows": _balance_rows(store, bal_year) if can_edit else [], }, diff --git a/app/modules/vacation/store.py b/app/modules/vacation/store.py index 6ca1ff4..cc39c2c 100644 --- a/app/modules/vacation/store.py +++ b/app/modules/vacation/store.py @@ -37,6 +37,49 @@ EDITABLE_STATUSES: tuple[str, ...] = ("작성중", "반려") # 연차는 그해(1/1~12/31) 것만 쓰고 다음 해로 넘기지 않는다(12/31 소멸 — 해마다 잔여 연차를 새로 등록). DEDUCT_TYPES: tuple[str, ...] = ("연차", "오전반차", "오후반차") +# 이 시스템을 쓰기 시작한 해 — 그해만 잔여 연차 표에 "시스템 전 사용"(도입 전에 이미 쓴 연차) 칸(2026-10-27) +SYSTEM_START_YEAR = 2026 + + +def add_months(d: date, n: int) -> date: + """d 에서 n 달 뒤 같은 날(없는 날이면 그 달 말일 — 1/31 + 1달 = 2/28).""" + m = d.month - 1 + n + y, m = d.year + m // 12, m % 12 + 1 + last = (date(y + (m == 12), m % 12 + 1, 1) - timedelta(days=1)).day + return date(y, m, min(d.day, last)) + + +def legal_annual_leave(hire: date | None, year: int) -> dict: + """근로기준법 제60조 연차 — 입사일 기준으로 생기는 날을 그해(1/1~12/31)에 모은다(연차는 12/31 소멸 규칙과 맞춤). + + · 입사 1년 미만: 1개월 개근마다 1일(입사일 + 1~11개월 되는 날, 최대 11일) — 제60조 ② + · 입사일이 돌아올 때마다(근속 n년): 15일 + 최초 1년을 넘는 근속 2년마다 1일, 최대 25일 = min(25, 15 + (n−1)//2) — 제60조 ①④ + 출근율(1개월 개근·1년 80%)은 따지지 않는다(모두 채운 것으로 본다). 입사일이 없거나 그해 뒤면 0일. + 반환 {"days", "items": [{"date", "days", "label"}], "service_years"(12/31 기준 만 근속 연수)}. + """ + out: dict = {"days": 0.0, "items": [], "service_years": 0} + if hire is None: + return out + y0, y1 = date(year, 1, 1), date(year, 12, 31) + items = [] + for m in range(1, 12): + d = add_months(hire, m) + if y0 <= d <= y1: + items.append({"date": d.isoformat(), "days": 1.0, "label": f"입사 {m}개월(월 1일)"}) + n = 1 + while True: + d = add_months(hire, 12 * n) + if d > y1: + break + if d >= y0: + items.append({"date": d.isoformat(), "days": float(min(25, 15 + (n - 1) // 2)), "label": f"근속 {n}년"}) + n += 1 + out["items"] = items + out["days"] = float(sum(i["days"] for i in items)) + out["service_years"] = max(0, n - 1) + return out + + # 반차 성격의 휴가 종류 (단일 일자 0.5일 강제) _HALF_DAY_TYPES: dict[str, str] = {"오전반차": "am", "오후반차": "pm"} diff --git a/app/modules/vacation/templates/vacation/detail.html b/app/modules/vacation/templates/vacation/detail.html index 7a092a1..d34b3f4 100644 --- a/app/modules/vacation/templates/vacation/detail.html +++ b/app/modules/vacation/templates/vacation/detail.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
diff --git a/app/modules/vacation/templates/vacation/form.html b/app/modules/vacation/templates/vacation/form.html index ed4ab13..565e3d4 100644 --- a/app/modules/vacation/templates/vacation/form.html +++ b/app/modules/vacation/templates/vacation/form.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %} +{% block head_extra %} {#- 날짜 칸 = 프로젝트와 같은 아사나식 날짜 팝업(2026-10-27, erp-datepop) -#} {% endblock %} @@ -72,5 +72,5 @@ {% endblock %} {% block scripts %} - -{% endblock %} + +{% endblock %} diff --git a/app/modules/vacation/templates/vacation/index.html b/app/modules/vacation/templates/vacation/index.html index 9d93e75..dd6bf25 100644 --- a/app/modules/vacation/templates/vacation/index.html +++ b/app/modules/vacation/templates/vacation/index.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
diff --git a/app/modules/vacation/templates/vacation/options.html b/app/modules/vacation/templates/vacation/options.html index c5fc190..5b08844 100644 --- a/app/modules/vacation/templates/vacation/options.html +++ b/app/modules/vacation/templates/vacation/options.html @@ -2,7 +2,9 @@ {#- 휴가 옵션(2026-10-27) — 승인자·승인 통보자·잔여 연차(수정 = ERP 관리자·승인자·통보자, 나머지는 보기만) + 내 Gmail 연결(누구나). 메일: 제출 = 승인자·통보자, 승인·반려 = 승인자·통보자·신청자. 보내는 사람 = 처리한 사람 본인 Gmail(없으면 회사 메일). -#} -{% block head_extra %}{% endblock %} +{% block head_extra %} + +{% endblock %} {% block content %}
@@ -67,33 +69,51 @@ {{ bal_year + 1 }} › -

연차는 휴가가 승인되면 차감됩니다(연차·오전반차·오후반차 — 병가·경조·대체휴무·기타는 차감 안 함). - {{ bal_year }}년 연차는 {{ bal_year }}.12.31 에 소멸하고 다음 해로 넘어가지 않습니다 — 해마다 새로 등록하세요(빈 칸 = 그대로, 회색 숫자 = 작년 연차).

+

이름 옆 입사일을 고르면 근로기준법 제60조대로 {{ bal_year }}년에 생기는 연차를 계산합니다 + (입사 1년 미만 = 1개월마다 1일·최대 11일, 입사일이 돌아올 때마다 15일 + 최초 1년을 넘는 근속 2년마다 1일·최대 25일, 출근율은 모두 채운 것으로 봄). + 연차 칸을 비우면 법정 연차를 쓰고, 숫자를 넣으면 그 값을 씁니다. 휴가가 승인되면 차감됩니다(연차·오전반차·오후반차 — 병가·경조·대체휴무·기타는 차감 안 함). + {{ bal_year }}년 연차는 {{ bal_year }}.12.31 에 소멸하고 다음 해로 넘어가지 않습니다. + {% if bal_prior_year %}시스템 전 사용 = 이 시스템을 쓰기 전에 {{ bal_year }}년에 이미 쓴 연차(잔여에서 뺍니다).{% endif %}

+ {% if not hire_ready %}{% endif %}
- - +
참여자연차사용잔여메모
+ + {% if bal_prior_year %}{% endif %} + {% for b in bal_rows %} - + + + + placeholder="{{ ('%g' % b.legal) if b.legal is not none else (('%g' % b.last_total) if b.last_total is not none else '') }}" + aria-label="{{ b.name }} 연차(비우면 법정 연차)" /> + {% if bal_prior_year %} + + {% else %}{% endif %} - - + + {% else %} - + {% endfor %}
참여자 · 입사일근속법정 연차연차시스템 전 사용사용잔여메모
{% if b.picture %} {% else %}{{ b.name[:1] }}{% endif %} - {{ b.name }} - {{ b.email }}{% if not b.active %} · 휴가 권한 없음{% endif %} + + {{ b.name }} + {{ b.email }}{% if not b.active %} · 휴가 권한 없음{% endif %} + + {#- 입사일 — 이름 옆 날짜 버튼(erp-datepop, 숨긴 input 이 값) -#} + {#- 002 전이면 숨김 칸만(서버가 무시) — disabled 는 폼에서 빠져 칸 수가 어긋나므로 쓰지 않는다 -#} + {% if b.hire_date %}{{ b.service_years }}년{% else %}—{% endif %} {{ '%g' % b.used }}{{ '%g' % b.remaining if b.remaining is not none else '—' }}{{ '%g' % b.remaining if b.remaining is not none else '—' }}
휴가 모듈 권한이 있는 사용자가 없습니다.
휴가 모듈 권한이 있는 사용자가 없습니다.
@@ -130,3 +150,6 @@
{% endblock %} + +{% block scripts %} +{% endblock %} diff --git a/app/modules/vacation/templates/vacation/pending.html b/app/modules/vacation/templates/vacation/pending.html index 39cbaea..7bc505d 100644 --- a/app/modules/vacation/templates/vacation/pending.html +++ b/app/modules/vacation/templates/vacation/pending.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
diff --git a/app/static/erp-datepop.js b/app/static/erp-datepop.js index 7596c0e..0310b07 100644 --- a/app/static/erp-datepop.js +++ b/app/static/erp-datepop.js @@ -4,7 +4,7 @@ · 브라우저 기본 달력(input[type=date])은 숨기고 그 옆에 날짜 버튼을 둔다 — input 은 값 저장소(.value 읽기/쓰기·change 이벤트 그대로). · 팝업: 위 칸(시작일·종료일 — 직접 입력 2026-10-27 / 10.27 / 10월 27일 / 1027, Enter), 월 달력(일·공휴일 빨강, 토 파랑, 공휴일 이름은 숫자 밑, 오늘 테두리, 기간 옅은 파랑), 오늘 · 지우기. 바깥 클릭·Esc 로 닫힘, 앵커 아래(자리 없으면 위). - window.ErpDatePop = { open(anchor, opts), close(), enhanceRange(startInput, endInput, opts), fmt(iso) } */ + window.ErpDatePop = { open(anchor, opts), close(), enhance(input, opts), enhanceRange(startInput, endInput, opts), fmt(iso), fmtFull(iso) } */ (function () { "use strict"; @@ -32,6 +32,14 @@ const md = String(d.getMonth() + 1).padStart(2, "0") + "/" + String(d.getDate()).padStart(2, "0") + "(" + wd + ")"; return (String(d.getFullYear()) === today.slice(0, 4) ? "" : d.getFullYear() + "/") + md; } + // 'YYYY-MM-DD' → 'YYYY.MM.DD(요일)' — 입사일처럼 연도가 꼭 보여야 하는 날짜(2026-10-27) + function fmtFull(iso) { + if (!iso) return ""; + const d = new Date(String(iso).slice(0, 10) + "T00:00:00"); + if (isNaN(d.getTime())) return iso; + return d.getFullYear() + "." + String(d.getMonth() + 1).padStart(2, "0") + "." + String(d.getDate()).padStart(2, "0") + + "(" + ["일", "월", "화", "수", "목", "금", "토"][d.getDay()] + ")"; + } function fmtField(iso) { if (!iso) return ""; const d = new Date(iso + "T00:00:00"); @@ -62,7 +70,8 @@ } // opts: { start, due, allowStart, active("start"|"due"), labels {start, due}, holidays {iso: 이름}, clear(bool, 기본 true), - // onChange(patch {due_date, start_date?}) } — 날짜를 누를 때마다 onChange, 마감(종료)일을 고르면 닫힘. + // yearNav(bool — « » 1년씩, 입사일처럼 먼 날짜), onChange(patch {due_date, start_date?}) } + // — 날짜를 누를 때마다 onChange, 마감(종료)일을 고르면 닫힘. function open(anchor, opts) { close(); opts = opts || {}; @@ -118,9 +127,11 @@ field("due", due) + "" + '
' + + (opts.yearNav ? '' : "") + '' + '' + viewY + "년 " + (viewM + 1) + "월" + '' + + (opts.yearNav ? '' : "") + "
" + '
' + ["일", "월", "화", "수", "목", "금", "토"].map(function (w, i) { @@ -154,7 +165,8 @@ pop.querySelectorAll(".pj-dp-navbtn").forEach(function (b) { b.addEventListener("click", function () { viewM += +b.dataset.nav; - if (viewM < 0) { viewM = 11; viewY--; } else if (viewM > 11) { viewM = 0; viewY++; } + while (viewM < 0) { viewM += 12; viewY--; } + while (viewM > 11) { viewM -= 12; viewY++; } render(); }); }); @@ -230,6 +242,49 @@ focusActive(); } + // 날짜 input 하나 → 날짜 버튼 하나(2026-10-27, 입사일 등). opts: { label, placeholder, format(iso), yearNav, clear(기본 true), holidays } + // input 은 숨긴 값 저장소 — value 쓰기를 가로채 버튼 글자도 바뀌고, 고르거나 지우면 input·change 이벤트를 낸다. + function enhance(input, opts) { + if (!input || input.dataset.erpDate) return null; + opts = opts || {}; + const desc = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value"); + const format = opts.format || fmt; + input.dataset.erpDate = "1"; + input.style.display = "none"; + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = "pj-date-btn erp-date-btn" + (opts.className ? " " + opts.className : ""); + input.after(btn); + Object.defineProperty(input, "value", { + configurable: true, + get: function () { return desc.get.call(this); }, + set: function (v) { desc.set.call(this, v); sync(); }, + }); + function sync() { + const text = format(input.value); + btn.innerHTML = 'calendar_month'; + btn.querySelector(".pj-date-btn-text").textContent = text || opts.placeholder || "날짜 선택"; + btn.classList.toggle("is-empty", !text); + btn.title = (opts.label || "날짜") + (text ? " 변경" : " 지정"); + } + btn.addEventListener("click", function (e) { + e.preventDefault(); e.stopPropagation(); + open(btn, { + due: input.value, allowStart: false, clear: opts.clear !== false, yearNav: !!opts.yearNav, holidays: opts.holidays || {}, + labels: { due: opts.label || "날짜" }, + onChange: function (patch) { + const v = patch.due_date || ""; + if ((input.value || "") === v) return; + input.value = v; + input.dispatchEvent(new Event("input", { bubbles: true })); + input.dispatchEvent(new Event("change", { bubbles: true })); + }, + }); + }); + sync(); + return { sync: sync, button: btn }; + } + // 시작·끝 날짜 input 두 개 → 날짜 버튼 두 개(각 input 자리), 어느 쪽을 눌러도 같은 기간 팝업(누른 쪽 칸이 먼저). // endInput 이 숨겨져 있으면(opts.single() 이 true — 예: 반차) 하루짜리 팝업으로 시작=끝을 같이 맞춘다. // input 은 숨겨 값 저장소로 둔다 — value 쓰기를 가로채 버튼 글자도 따라 바뀌고, 고르면 input·change 이벤트를 낸다. @@ -290,5 +345,5 @@ return { sync: sync, buttons: btns }; } - window.ErpDatePop = { open: open, close: close, enhanceRange: enhanceRange, fmt: fmt, parse: parseTyped }; + window.ErpDatePop = { open: open, close: close, enhance: enhance, enhanceRange: enhanceRange, fmt: fmt, fmtFull: fmtFull, parse: parseTyped }; })(); diff --git a/app/static/vacation.css b/app/static/vacation.css index d28646c..f7acfe3 100644 --- a/app/static/vacation.css +++ b/app/static/vacation.css @@ -255,3 +255,10 @@ .vac-bal-num { text-align: right; font-variant-numeric: tabular-nums; } .vac-bal-num.is-minus { color: var(--vac-red); font-weight: 700; } .vac-bal-table tr.is-inactive td { color: var(--vac-muted); } +/* 잔여 연차 — 이름 옆 입사일 날짜 버튼(2026-10-27) */ +.vac-bal-who { display: inline-flex; flex-direction: column; line-height: 1.25; min-width: 0; } +.vac-bal-who .vac-opt-mail { margin-left: 0; font-size: 11.5px; } +.vac-bal-person .vac-hire-btn { margin: 0 0 0 auto; height: 30px; padding: 0 10px; font-size: 12.5px; } +.vac-bal-person .vac-hire-btn .material-symbols-outlined { font-size: 16px; } +.vac-bal-legal { color: #1a56db; font-weight: 600; } +.vac-bal-years-cell { color: var(--vac-muted); } diff --git a/app/static/vacation.js b/app/static/vacation.js index 099bf5c..be199ad 100644 --- a/app/static/vacation.js +++ b/app/static/vacation.js @@ -1,7 +1,7 @@ /* 휴가 신청 폼 — 종류에 따른 필드 토글 + 예상 일수 미리보기. 서버(store.compute_days)가 공휴일 포함 정확히 재계산한다. 여기선 주말만 제외한 근사치. 시작일·종료일 = 프로젝트와 같은 아사나식 날짜 팝업(2026-10-27, erp-datepop.js — 숨긴 input 옆 날짜 버튼, 둘 중 어느 쪽을 눌러도 - 같은 기간 팝업, 반차는 하루짜리 팝업). 공휴일 = 휴가 설정의 공휴일(#vac-holidays). */ + 같은 기간 팝업, 반차는 하루짜리 팝업). 공휴일 = 국경일·대체공휴일(#vac-holidays). 아래쪽은 옵션 잔여 연차 표. */ (function () { "use strict"; var form = document.getElementById("vac-form"); @@ -100,3 +100,70 @@ recalc(); })(); + +/* 휴가 옵션 — 잔여 연차 표(2026-10-27): 이름 옆 입사일 = 날짜 버튼(erp-datepop), 고르면 근속·법정 연차·잔여를 바로 다시 계산 + (서버 store.legal_annual_leave 와 같은 규칙 — 근로기준법 제60조, 입사일 기준으로 그해에 생기는 연차). 저장은 [잔여 연차 저장]. */ +(function () { + "use strict"; + var table = document.querySelector(".vac-bal-table"); + if (!table) return; + var year = +table.dataset.year; + + function iso(d) { + return d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0"); + } + function addMonths(d, n) { // 같은 날, 없으면 그 달 말일(1/31 + 1달 = 2/28) + var m = d.getMonth() + n, y = d.getFullYear() + Math.floor(m / 12); + m = ((m % 12) + 12) % 12; + var last = new Date(y, m + 1, 0).getDate(); + return new Date(y, m, Math.min(d.getDate(), last)); + } + function legal(hireIso) { + if (!hireIso) return null; + var p = hireIso.split("-"), hire = new Date(+p[0], +p[1] - 1, +p[2]); + var y0 = iso(new Date(year, 0, 1)), y1 = iso(new Date(year, 11, 31)); + var days = 0, items = [], n = 1, d; + for (var m = 1; m < 12; m++) { + d = iso(addMonths(hire, m)); + if (d >= y0 && d <= y1) { days += 1; items.push(d.slice(5) + " 입사 " + m + "개월(월 1일) 1일"); } + } + for (;;) { + d = iso(addMonths(hire, 12 * n)); + if (d > y1) break; + if (d >= y0) { var g = Math.min(25, 15 + Math.floor((n - 1) / 2)); days += g; items.push(d.slice(5) + " 근속 " + n + "년 " + g + "일"); } + n++; + } + return { days: days, years: n - 1, tip: items.join(", ") }; + } + function g(v) { return String(Math.round(v * 100) / 100); } + + table.querySelectorAll("tr.vac-bal-row").forEach(function (tr) { + var hire = tr.querySelector(".vac-hire-input"); + var total = tr.querySelector('input[name="total"]'); + var prior = tr.querySelector('input[name="prior"]'); + var used = +tr.dataset.used || 0; + function recalc() { + var L = legal(hire.value); + tr.querySelector(".vac-bal-years-cell").textContent = L ? L.years + "년" : "—"; + var lg = tr.querySelector(".vac-bal-legal"); + lg.textContent = L ? g(L.days) : "—"; + if (L && L.tip) lg.title = L.tip; else lg.removeAttribute("title"); + if (L) total.placeholder = g(L.days); + var manual = total.value.trim() === "" ? null : +total.value; + var base = manual != null ? manual : (L ? L.days : null); + var cell = tr.querySelector(".vac-bal-remain"); + if (base == null) { cell.textContent = "—"; cell.classList.remove("is-minus"); return; } + var rem = base - (prior && prior.value.trim() !== "" ? +prior.value : 0) - used; + cell.textContent = g(rem); + cell.classList.toggle("is-minus", rem < 0); + } + if (hire && hire.type !== "hidden" && window.ErpDatePop) { + window.ErpDatePop.enhance(hire, { label: "입사일", placeholder: "입사일", yearNav: true, format: window.ErpDatePop.fmtFull, + className: "vac-hire-btn" }); + } + if (hire) hire.addEventListener("change", recalc); + total.addEventListener("input", recalc); + if (prior) prior.addEventListener("input", recalc); + }); +})(); + diff --git a/docs/DATABASES.md b/docs/DATABASES.md index b189195..86adb08 100644 --- a/docs/DATABASES.md +++ b/docs/DATABASES.md @@ -267,6 +267,13 @@ DDL: `scripts/sql/vacation_db_init.sql` (멱등). DB·역할(`vacation_app`)· docker exec -i postgres-db psql -U postgres -d vacation_db -v ON_ERROR_STOP=1 < scripts/sql/vacation_db_001_options_mail.sql ``` +**마이그레이션 002**(`scripts/sql/vacation_db_002_hire_prior.sql`, 2026-10-27, 멱등): `vacation_employees`(사람마다 입사일 → 근로기준법 제60조 연차, +`store.legal_annual_leave`) · `vacation_balances.prior_used`(시스템 전에 그해 쓴 연차) · `vacation_balances.total_days` NULL 허용(NULL = 입사일 기준 법정 연차). + +```bash +docker exec -i postgres-db psql -U postgres -d vacation_db -v ON_ERROR_STOP=1 < scripts/sql/vacation_db_002_hire_prior.sql +``` + ### 운영 서버 초기화 (1회, 사용자 승인 후) ```bash diff --git a/scripts/sql/vacation_db_002_hire_prior.sql b/scripts/sql/vacation_db_002_hire_prior.sql new file mode 100644 index 0000000..99ab103 --- /dev/null +++ b/scripts/sql/vacation_db_002_hire_prior.sql @@ -0,0 +1,26 @@ +-- ════════════════════════════════════════════════════════════ +-- vacation_db 002 — 입사일 · 시스템 전 사용 연차 · 연차 직접 입력 선택 (2026-10-27) +-- ════════════════════════════════════════════════════════════ +-- · vacation_employees: 사람마다 입사일 하나 → 근로기준법 제60조 연차를 입사일 기준으로 계산(store.legal_annual_leave). +-- · vacation_balances.prior_used: 이 시스템을 쓰기 전에 그해 이미 쓴 연차(2026 년만 화면에서 입력) — 잔여에서 뺀다. +-- · vacation_balances.total_days NULL 허용: 비우면 입사일 기준 법정 연차를 쓴다(값이 있으면 그 값 = 직접 입력). +-- 적용(운영, superuser, 1회 — 여러 번 돌려도 안전, 기존 값은 그대로): +-- docker exec -i postgres-db psql -U postgres -d vacation_db -v ON_ERROR_STOP=1 < scripts/sql/vacation_db_002_hire_prior.sql +-- 되돌리기: DROP TABLE vacation_employees; ALTER TABLE vacation_balances DROP COLUMN prior_used; +-- (total_days 를 다시 NOT NULL 로 하려면 먼저 UPDATE vacation_balances SET total_days = 0 WHERE total_days IS NULL) +\set ON_ERROR_STOP on + +CREATE TABLE IF NOT EXISTS vacation_employees ( + user_email TEXT PRIMARY KEY, + hire_date DATE, + updated_by TEXT NOT NULL DEFAULT '', + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +ALTER TABLE vacation_balances ADD COLUMN IF NOT EXISTS prior_used NUMERIC(5,2) NOT NULL DEFAULT 0; +ALTER TABLE vacation_balances ALTER COLUMN total_days DROP NOT NULL; +ALTER TABLE vacation_balances ALTER COLUMN total_days DROP DEFAULT; + +GRANT SELECT, INSERT, UPDATE, DELETE ON vacation_employees TO vacation_app; + +SELECT 'vacation_db 002 ready' AS status; diff --git a/tests/js/render_vacation.py b/tests/js/render_vacation.py index 86b3c23..964dfb9 100644 --- a/tests/js/render_vacation.py +++ b/tests/js/render_vacation.py @@ -30,6 +30,21 @@ def main() -> None: html = env.get_template("vacation/form.html").render(**ctx) with open(os.path.join(OUT_DIR, "vac_form.html"), "w", encoding="utf-8") as f: f.write(html) + # 옵션 — 잔여 연차 표(2026, 입사일·법정 연차·시스템 전 사용) → tests/js/.out/vac_options.html + row = {"active": True, "picture": "", "service_years": 0, "legal": None, "legal_tip": "", "total": None, "effective_total": 0, + "prior": 0.0, "used": 0.0, "remaining": None, "memo": "", "last_total": None, "hire_date": ""} + octx = {**ctx, "page_title": "휴가 — 옵션", "is_admin": True, "can_edit": True, "msg": "", + "options": {"approvers": [], "notifiers": [], "ready": True, "updated_by": "", "updated_at": ""}, + "candidates": [], "effective_approvers": [], "gmail": {"available": False, "connected": False, "smtp": True}, + "bal_year": 2026, "bal_prior_year": True, "hire_ready": True, + "bal_rows": [ + {**row, "email": "lee@test.local", "name": "이팀장", "hire_date": "2020-03-02", "service_years": 6, "legal": 17.0, + "legal_tip": "03-02 근속 6년 17일", "used": 4.5, "remaining": 12.5}, + {**row, "email": "kim@test.local", "name": "김철수", "used": 1.0}, + ]} + html = env.get_template("vacation/options.html").render(**octx) + with open(os.path.join(OUT_DIR, "vac_options.html"), "w", encoding="utf-8") as f: + f.write(html) if __name__ == "__main__": diff --git a/tests/js/vacation_balances.browser.test.js b/tests/js/vacation_balances.browser.test.js new file mode 100644 index 0000000..fa846ac --- /dev/null +++ b/tests/js/vacation_balances.browser.test.js @@ -0,0 +1,87 @@ +// 휴가 옵션 잔여 연차 — 이름 옆 입사일 날짜 버튼 · 근로기준법 연차 바로 계산 · 시스템 전 사용(2026-10-27) — 실제 브라우저(Chromium). +// python tests/js/render_vacation.py +// NODE_PATH= PJ_TEST_BROWSER= node tests/js/vacation_balances.browser.test.js +const fs = require("fs"), path = require("path"); +const { chromium } = require("playwright"); +const ROOT = path.join(__dirname, "..", ".."); +const fails = []; +function check(name, cond, extra) { + if (cond) console.log("PASS " + name); + else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); } +} + +(async function () { + const exe = process.env.PJ_TEST_BROWSER; + const browser = await chromium.launch(exe ? { executablePath: exe } : {}); + const posts = []; + try { + const p = await (await browser.newContext({ viewport: { width: 1400, height: 900 } })).newPage(); + await p.route("**/*", function (r) { + const req = r.request(), url = new URL(req.url()).pathname; + if (url.startsWith("/static/")) { + const f = path.join(ROOT, "app", url); + if (!fs.existsSync(f)) return r.fulfill({ status: 404, body: "" }); + const type = f.endsWith(".css") ? "text/css" : f.endsWith(".js") ? "application/javascript" : "font/woff2"; + return r.fulfill({ status: 200, contentType: type, body: fs.readFileSync(f) }); + } + if (req.method() === "POST") { posts.push(req.postData()); return r.fulfill({ status: 200, contentType: "text/html", body: "ok" }); } + r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: fs.readFileSync(path.join(__dirname, ".out", "vac_options.html"), "utf8") }); + }); + await p.goto("http://erp.test/vacation/options"); + await p.waitForTimeout(200); + const rowState = function (email) { + return p.evaluate(function (email) { + const tr = document.querySelector('input[name="email"][value="' + email + '"]').closest("tr"); + const btn = tr.querySelector(".vac-hire-btn"); + return { btn: btn && btn.textContent.replace("calendar_month", "").trim(), nextToName: !!btn && btn.parentElement === tr.querySelector(".vac-bal-person"), + hire: tr.querySelector('input[name="hire"]').value, hireShown: getComputedStyle(tr.querySelector('input[name="hire"]')).display !== "none", + years: tr.querySelector(".vac-bal-years-cell").textContent.trim(), legal: tr.querySelector(".vac-bal-legal").textContent.trim(), + placeholder: tr.querySelector('input[name="total"]').placeholder, remain: tr.querySelector(".vac-bal-remain").textContent.trim(), + minus: tr.querySelector(".vac-bal-remain").classList.contains("is-minus") }; + }, email); + }; + const lee = await rowState("lee@test.local"); + check("입사일 = 이름 옆 날짜 버튼(연도까지), 숨긴 input 이 값", lee.nextToName && !lee.hireShown && lee.btn === "2020.03.02(월)" && + lee.hire === "2020-03-02" && lee.legal === "17" && lee.remain === "12.5", lee); + const kim0 = await rowState("kim@test.local"); + check("입사일 없음 = '입사일' 버튼, 근속·법정 —", kim0.btn === "입사일" && kim0.years === "—" && kim0.legal === "—" && kim0.remain === "—", kim0); + // 김철수 입사일 2025-03-01 직접 입력(Enter) → 근속 1년 · 법정 17(1/1·2/1 월 1일 + 3/1 15일) · 잔여 17 − 1(사용) + await p.click('tr:has(input[value="kim@test.local"]) .vac-hire-btn'); + const pop = await p.evaluate(function () { + const el = document.querySelector(".pj-datepop"); + return el && { navs: el.querySelectorAll(".pj-dp-navbtn").length, field: el.querySelector(".pj-dp-field").placeholder, + clear: !!el.querySelector(".pj-dp-clear") }; + }); + check("입사일 팝업 = 날짜 하나, « ‹ › » (1년씩 이동), 지우기", !!pop && pop.navs === 4 && pop.field === "입사일" && pop.clear, pop); + await p.fill(".pj-dp-field", "2025-03-01"); + await p.press(".pj-dp-field", "Enter"); + const kim1 = await rowState("kim@test.local"); + check("입사일 고르면 근속·법정 연차·잔여 바로 계산(근로기준법)", kim1.btn === "2025.03.01(토)" && kim1.hire === "2025-03-01" && + kim1.years === "1년" && kim1.legal === "17" && kim1.placeholder === "17" && kim1.remain === "16", kim1); + // 시스템 전 사용 3.5 → 잔여 12.5, 연차 직접 10 → 10 − 3.5 − 1 = 5.5, 20 넘게 쓰면 빨강 + await p.fill('tr:has(input[value="kim@test.local"]) input[name="prior"]', "3.5"); + check("시스템 전 사용 → 잔여에서 뺌", (await rowState("kim@test.local")).remain === "12.5"); + await p.fill('tr:has(input[value="kim@test.local"]) input[name="total"]', "10"); + check("연차 직접 입력이 법정보다 먼저", (await rowState("kim@test.local")).remain === "5.5"); + await p.fill('tr:has(input[value="kim@test.local"]) input[name="prior"]', "12"); + const kim2 = await rowState("kim@test.local"); + check("모자라면 잔여 빨강", kim2.remain === "-3" && kim2.minus, kim2); + // 1년씩 이동 버튼 — 2025년 3월 → « → 2024년 3월 + await p.click('tr:has(input[value="lee@test.local"]) .vac-hire-btn'); + const t0 = await p.textContent(".pj-dp-title"); + await p.click('.pj-dp-navbtn[data-nav="-12"]'); + const t1 = await p.textContent(".pj-dp-title"); + check("« = 1년 전 달력", t0 === "2020년 3월" && t1 === "2019년 3월", [t0, t1]); + await p.keyboard.press("Escape"); + // 저장 — 줄마다 email·hire·total·prior·memo + await p.click('button[type="submit"]:has-text("잔여 연차 저장")'); + await p.waitForTimeout(200); + const body = decodeURIComponent((posts[0] || "").replace(/\+/g, " ")); + check("저장 → 입사일·연차·시스템 전 사용이 줄마다 전송", /email=kim@test.local/.test(body) && /hire=2025-03-01/.test(body) && + /hire=2020-03-02/.test(body) && /total=10/.test(body) && /prior=12/.test(body) && (body.match(/hire=/g) || []).length === 2, body); + } finally { + await browser.close(); + } + if (fails.length) { console.log("\n" + fails.length + " FAILED"); process.exit(1); } + console.log("\nALL PASS"); +})().catch(function (e) { console.error(e); process.exit(1); }); diff --git a/tests/test_vacation_db.py b/tests/test_vacation_db.py index 53de035..8a1da71 100644 --- a/tests/test_vacation_db.py +++ b/tests/test_vacation_db.py @@ -147,5 +147,72 @@ class VacationHolidayBalanceDBTests(unittest.TestCase): 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() diff --git a/tests/test_vacation_options_mail.py b/tests/test_vacation_options_mail.py index 7a3e4cb..27f79a7 100644 --- a/tests/test_vacation_options_mail.py +++ b/tests/test_vacation_options_mail.py @@ -201,6 +201,18 @@ class Store: 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, year, hire_date=None): + bal = {b["user_email"]: b for b in self.list_balances(year)}.get(user_email) + used = self.used_days(user_email, year) + manual = bal["total_days"] if bal else None + total = manual if manual is not None else 0.0 + return {"year": year, "total_days": total, "manual_total": manual, "legal_days": None, "legal_items": [], + "service_years": 0, "hire_date": hire_date or "", "prior_used": 0.0, "erp_used": used, + "used_days": used, "remaining_days": total - used, "memo": bal["memo"] if bal else ""} 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)} @@ -356,8 +368,10 @@ class Store2(Store): [{"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, year, rows): - saved.update(year=year, rows=rows); return len(rows) + def save_balances(self, year, rows, by=""): + saved.update(year=year, 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): @@ -365,8 +379,6 @@ class Store2(Store): if date_from <= d <= date_to} def list_overlapping(self, date_from, date_to): return [] - def balance_summary(self, user_email, year): - return {"year": year, "total_days": 15.0, "used_days": 4.5, "remaining_days": 10.5, "memo": ""} def list_pending(self): return [] st2 = Store2() @@ -383,26 +395,38 @@ def body(c): assert 'k' in t assert "gone@test.local · 휴가 권한 없음" in t # 예전에 등록된 사람도 보여 줌 i = t.index('name="email" value="lee@test.local"') - row = t[i:i + 900] + 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 'placeholder="12"' in t[j:j + 600], t[j:j + 600] # 올해 없음 → 작년 연차를 회색 참고 assert "2026.12.31 에 소멸" in t and "승인되면" in t # 저장 — 빈 칸은 건너뜀, 연도·이메일·메모 그대로 + # 저장 — 줄마다 입사일·연차(빈 칸 = 법정)·시스템 전 사용·메모, 저장한 사람 r = c.post("/vacation/options/balances", data={"year": "2026", "email": ["lee@test.local", "kim@test.local", "chip@test.local"], - "total": ["16", "", "15.5"], "memo": ["a", "b", "c"]}) + "hire": ["2020-03-02", "", "2025-03-01"], "total": ["16", "", ""], + "prior": ["", "2.5", ""], "memo": ["a", "b", "c"]}) assert r.status_code == 303 and "year=2026" in r.headers["location"], r.status_code - assert saved == {"year": 2026, "rows": [{"user_email": "lee@test.local", "total_days": 16.0, "memo": "a"}, - {"user_email": "chip@test.local", "total_days": 15.5, "memo": "c"}]}, saved - assert c.post("/vacation/options/balances", data={"year": "2026", "email": ["lee@test.local"], "total": ["x"], "memo": [""]}).status_code == 400 + assert saved == {"year": 2026, "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 "시스템 전 사용" not in c.get("/vacation/options?year=2027").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"], "total": ["14"], "memo": [""]}).status_code == 303 + 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"], "total": ["30"], "memo": [""]}).status_code == 403 + 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")