feat(vacation): 달력 공휴일 이름 · 잔여 연차를 옵션으로(참여자 표) · 연차 차감·12/31 소멸

- 쉬는 날 = 국경일·대체공휴일(project KR_HOLIDAYS, 2026~2030) + 휴가 설정 공휴일(덮어쓰기, 빨강 해제 = 근무일) — db.holiday_map 한 곳
  (달력·날짜 팝업·일수 계산), 메인 달력은 날짜 아래 이름 + 그 주 막대 내림
- 잔여 연차 등록을 설정 → 옵션(관리자): 참여자 전원 아이콘·이름 미리 보여 주는 표, 사용·잔여·작년 참고, 한꺼번에 저장(save_balances)
- 사용 연차 = 승인된 연차·오전반차·오후반차만(병가·경조·대체휴무·기타 제외), 해를 넘는 신청은 해마다 나눔, 연도별 12/31 소멸 안내
- 옵션 화면 카드가 화면 높이에 눌려 잘리던 것·입력 칸 최소 너비 수정
- 테스트: 실제 PG(holiday_map·used_days·save_balances), 실제 앱(옵션 표·저장 권한·설정 없음·달력 이름)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-26 15:06:15 +09:00
parent 6a1c9f4434
commit 36d000eb17
15 changed files with 400 additions and 99 deletions
+1
View File
@@ -64,6 +64,7 @@
- `app/mail.py`: 프로젝트 알림 메일.
- ERP 모든 화면 스크립트: `erp-notice.js`(공지) · `erp-overdue.js`(프로젝트 마감 알림).
- 아사나식 날짜 팝업: 프로젝트(`project.js` 안) + 공용 복사본 `erp-datepop.js/css`(휴가 신청) — 바꾸면 둘 다.
- 국경일·대체공휴일 표 `project/store.py KR_HOLIDAYS`: 프로젝트 캘린더·날짜 팝업 + 휴가(달력·일수 계산 `vacation/db.holiday_map`).
---
+14
View File
@@ -11,6 +11,20 @@
공휴일 = 휴가 설정 공휴일 중 빨강(`router._red_holidays`, 작년~내년, `#vac-holidays`) — 팝업 빨강·이름 + 예상 일수에서도 뺀다(서버 compute_days 와 같은 표).
테스트 `tests/js/vacation_datepop.browser.test.js`(`render_vacation.py`).
## 공휴일 · 연차 (2026-10-27)
- **쉬는 날 = 대한민국 국경일·대체공휴일 + 휴가 설정 공휴일**(`db.holiday_map` 한 곳 — 달력·날짜 팝업·일수 계산 `red_holiday_set` 모두).
국경일 표는 프로젝트 모듈 `app/modules/project/store.py` `KR_HOLIDAYS`(2026~2030, 새 연도는 그 표에 추가). 설정 공휴일이 덮어씀 —
빨강 = 쉬는 날(이름은 설정 값, 회사 휴일 추가), **빨강 해제 = 그 국경일을 근무일로**. 예전엔 설정 표만 써서 seed 가 없는 해·제헌절은 근무일로 셌다.
이미 저장된 신청의 일수는 그대로(새로 저장·수정할 때 다시 계산).
- 메인 달력: 공휴일 이름이 **날짜 숫자 아래**(`.vac-hol-name`), 그 주는 `.vac-week.has-hol`(휴가 막대 top 38 → 54px).
- **연차 차감** = 승인된 `DEDUCT_TYPES`(연차·오전반차·오후반차)만(`db.used_days`, 병가·경조·대체휴무·기타는 안 뺌 — 예전엔 모든 승인 휴가를 뺐다),
제출·작성중은 안 뺌. 해를 넘는 신청은 해마다 그 해 날짜만큼 나눔(예전엔 시작일 연도에 통째로). **연차는 그해 것만 — 12/31 소멸**, 다음 해로 넘기지 않음
(`vacation_balances` 가 연도별, 새해는 새로 등록. 달력 잔여 옆 "yyyy.12.31 소멸").
- **잔여 연차 등록 = 옵션**(설정에서 옮김, ERP 관리자만 보기·저장) — 참여자(휴가 모듈 사용자) 전원을 아이콘·이름·이메일과 함께 미리 보여 주는 표
(연차 입력·사용·잔여(음수 빨강)·메모, 아직 없으면 작년 연차를 회색 참고, 예전에 등록됐지만 권한이 없는 사람도 아래에), 연도 ‹ › 이동,
`POST /vacation/options/balances` 한꺼번에(`db.save_balances` 한 트랜잭션 — 0~365·0.5일 단위, 빈 칸 = 그대로). 예전 `POST /settings/balances` 는 없앴다.
## 휴가 옵션 · 휴가 메일 (2026-10-27, 마이그레이션 `vacation_db_001_options_mail.sql`)
- **옵션** `/vacation/options`(달력 위 [옵션], 누구나 보기 · **수정 = ERP 관리자**): 휴가 승인자(여러 명) · 휴가 승인 통보자.
+72 -18
View File
@@ -15,7 +15,7 @@
from __future__ import annotations
import uuid
from datetime import date, datetime, timezone
from datetime import date, datetime, timedelta, timezone
from decimal import Decimal
from typing import Any
@@ -24,7 +24,7 @@ from psycopg_pool import ConnectionPool
from app.timezone import KST
from .store import EDITABLE_STATUSES, STATUSES, VACATION_TYPES, compute_days, normalize_half
from .store import DEDUCT_TYPES, EDITABLE_STATUSES, STATUSES, VACATION_TYPES, compute_days, normalize_half
def _email_list(value: Any) -> list[str]:
@@ -135,22 +135,35 @@ class VacationDBStore:
).fetchall()
return [self._holiday_serialize(r) for r in rows]
def red_holiday_set(self, *, date_from: str, date_to: str) -> set[str]:
"""[date_from, date_to] 범위의 is_red=TRUE 공휴일 ISO 날짜 집합.
def holiday_map(self, *, date_from: str, date_to: str) -> dict[str, str]:
"""[date_from, date_to] 범위의 쉬는 날 {ISO 날짜: 이름} — 휴가일수 계산·달력·날짜 팝업의 단일 진실 공급원.
휴가일수 계산/달력 색상의 단일 진실 공급원.
= 대한민국 국경일·대체공휴일(프로젝트 모듈 `KR_HOLIDAYS`, 2026~2030 — 새 연도는 그 표에 추가) 위에
휴가 설정 공휴일(vacation_holidays)을 덮어쓴다: 빨강(is_red) 이면 쉬는 날(이름은 설정 값), 빨강 해제면 쉬지 않는 날로 뺀다
(2026-10-27 — 예전엔 설정 표만 써서 seed 가 없는 해·제헌절은 근무일로 셌다).
"""
from app.modules.project.store import KR_HOLIDAYS # noqa: WPS433
date_from, date_to = str(date_from)[:10], str(date_to)[:10]
out = {d: n for d, n in KR_HOLIDAYS.items() if date_from <= d <= date_to}
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT holiday_date FROM vacation_holidays "
"WHERE is_red = TRUE AND holiday_date BETWEEN %s AND %s",
"SELECT holiday_date, name, is_red FROM vacation_holidays "
"WHERE holiday_date BETWEEN %s AND %s",
(date_from, date_to),
).fetchall()
out: set[str] = set()
for r in rows:
d = r["holiday_date"]
out.add(d.isoformat() if isinstance(d, date) else str(d))
return out
iso = d.isoformat() if isinstance(d, date) else str(d)
if r["is_red"]:
out[iso] = r["name"] or out.get(iso, "")
else:
out.pop(iso, None)
return dict(sorted(out.items()))
def red_holiday_set(self, *, date_from: str, date_to: str) -> set[str]:
"""[date_from, date_to] 범위의 쉬는 날 ISO 날짜 집합(holiday_map 과 같은 기준)."""
return set(self.holiday_map(date_from=date_from, date_to=date_to))
def upsert_holiday(
self,
@@ -227,15 +240,56 @@ class VacationDBStore:
return self._balance_serialize(row)
def used_days(self, *, user_email: str, year: int) -> float:
"""해당 연도 승인된 휴가의 합계 일수(사용 연차). start_date 연도 기준."""
"""그해 사용 연차 = 승인된 연차·반차(DEDUCT_TYPES)의 그해 날짜분 합계(2026-10-27).
병가·경조·대체휴무·기타는 빼지 않는다. 해를 넘는 신청(12/30~1/2)은 해마다 그 해 날짜만큼 나눠 센다
(예전엔 모든 승인 휴가를 시작일 연도에 통째로 셌다). 그해 안에 다 들어가는 신청은 저장된 일수 그대로.
"""
y0, y1 = date(year, 1, 1), date(year, 12, 31)
with self._pool.connection() as conn:
row = conn.execute(
"SELECT COALESCE(SUM(days), 0) AS s FROM vacation_requests "
"WHERE owner = %s AND status = '승인' "
"AND EXTRACT(YEAR FROM start_date) = %s",
(user_email.lower().strip(), year),
).fetchone()
return float(row["s"]) if row else 0.0
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),
).fetchall()
total = 0.0
holidays: set[str] | None = None
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)
def save_balances(self, *, year: int, rows: list[dict[str, Any]]) -> int:
"""잔여 연차 한꺼번에 저장 [{user_email, total_days, memo}] — 한 트랜잭션, 저장한 줄 수."""
n = 0
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}")
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]),
)
n += 1
return n
def balance_summary(self, *, user_email: str, year: int) -> dict[str, Any]:
bal = self.get_balance(user_email=user_email, year=year)
+65 -33
View File
@@ -204,14 +204,10 @@ def _build_calendar(
range_start = weeks_dates[0][0]
range_end = weeks_dates[-1][-1]
red_set = store.red_holiday_set(
# 쉬는 날 = 국경일·대체공휴일 + 휴가 설정 공휴일(db.holiday_map) — 빨강 + 날짜 밑 이름(2026-10-27)
holiday_names = store.holiday_map(
date_from=range_start.isoformat(), date_to=range_end.isoformat()
)
holiday_names = {
h["holiday_date"]: h["name"]
for h in store.list_holidays()
if h.get("is_red")
}
requests = store.list_overlapping(
date_from=range_start.isoformat(), date_to=range_end.isoformat()
)
@@ -229,7 +225,7 @@ def _build_calendar(
"is_selected": d.isoformat() == sel,
"is_sunday": d.weekday() == 6,
"is_saturday": d.weekday() == 5,
"is_holiday": d.isoformat() in red_set,
"is_holiday": d.isoformat() in holiday_names,
"holiday_name": holiday_names.get(d.isoformat(), ""),
}
for d in week
@@ -348,20 +344,15 @@ def _form_context(request: Request, user: dict[str, Any]) -> dict[str, Any]:
def _red_holidays(request: Request) -> dict[str, str]:
"""날짜 팝업 공휴일(빨강·이름) — 휴가 설정의 공휴일(is_red) 작년~내년. 일수 계산과 같은 표."""
"""날짜 팝업 공휴일(빨강·이름) — 국경일·대체공휴일 + 휴가 설정 공휴일, 작년~내년. 일수 계산과 같은 표(db.holiday_map)."""
st = _store(request)
if st is None:
return {}
year = today_kst().year
out: dict[str, str] = {}
try:
for y in (year - 1, year, year + 1):
for h in st.list_holidays(year=y):
if h.get("is_red", True):
out[h["holiday_date"]] = h.get("name") or ""
return st.holiday_map(date_from=f"{year - 1}-01-01", date_to=f"{year + 1}-12-31")
except Exception: # noqa: BLE001 — 공휴일 표시가 신청 화면을 막지 않게
return {}
return out
@router.get("/new", response_class=HTMLResponse)
@@ -491,9 +482,6 @@ def settings_page(request: Request) -> HTMLResponse:
year = int(request.query_params.get("year") or today.year)
except ValueError:
year = today.year
balances = store.list_balances(year=year)
for b in balances:
b["used_days"] = store.used_days(user_email=b["user_email"], year=year)
return render_template(
request,
"vacation/settings.html",
@@ -503,10 +491,9 @@ def settings_page(request: Request) -> HTMLResponse:
"is_approver": True,
"nav_items": build_erp_nav(user, active="vacation"),
"page_title": "휴가 — 설정",
"page_subtitle": "공휴일 · 연차 잔여 관리",
"page_subtitle": "공휴일 관리 (잔여 연차는 옵션)",
"year": year,
"holidays": store.list_holidays(year=year),
"balances": balances,
},
)
@@ -562,29 +549,67 @@ def holiday_delete(
return RedirectResponse(url=f"/vacation/settings{suffix}", status_code=303)
@router.post("/settings/balances")
def balance_upsert(
request: Request,
user_email: str = Form(...),
year: int = Form(...),
total_days: float = Form(...),
memo: str = Form(""),
user: dict[str, Any] = Depends(_require_user),
) -> RedirectResponse:
@router.post("/options/balances")
async def balances_save(request: Request) -> RedirectResponse:
"""잔여 연차 한꺼번에(옵션, ERP 관리자) — 참여자 줄마다 email·total·memo. 연차 칸을 비운 줄은 그대로 둔다(새로 만들지 않음)."""
from urllib.parse import urlencode # noqa: WPS433
from app.store import is_admin # noqa: WPS433
user = _require_user(request)
if not is_admin(user):
raise HTTPException(status_code=403, detail="관리자만 가능합니다.")
raise HTTPException(status_code=403, detail="잔여 연차는 ERP 관리자만 등록할 수 있습니다.")
store = _store(request)
if store is None:
raise HTTPException(status_code=503, detail="vacation_db 미설정")
form = await request.form()
try:
store.upsert_balance(
user_email=user_email, year=year, total_days=total_days, memo=memo
)
year = int(str(form.get("year") or ""))
except ValueError:
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)):
raise HTTPException(status_code=400, detail="잔여 연차 칸이 맞지 않습니다.")
rows = []
for email, total, memo in zip(emails, totals, memos):
total = str(total).strip()
if not total:
continue
try:
rows.append({"user_email": email, "total_days": float(total), "memo": memo})
except ValueError:
raise HTTPException(status_code=400, detail=f"연차 일수가 숫자가 아닙니다: {email}")
from starlette.concurrency import run_in_threadpool # noqa: WPS433 — 폼 배열을 읽으려 async, DB 는 동기라 스레드에서
try:
n = await run_in_threadpool(store.save_balances, year=year, rows=rows)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return RedirectResponse(url=f"/vacation/settings?year={year}", status_code=303)
return RedirectResponse(url="/vacation/options?" + urlencode({"year": year, "msg": f"{year}년 잔여 연차 {n}명을 저장했습니다."})
+ "#balances", status_code=303)
def _balance_rows(store: Any, year: int) -> list[dict[str, Any]]:
"""옵션 잔여 연차 표 — 참여자(휴가 모듈 사용자) 전원 + 예전에 등록됐지만 지금 권한이 없는 사람.
줄마다 그해 연차·사용(승인된 연차·반차)·잔여·메모, 아직 없으면 작년 연차를 참고로."""
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)}
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
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})
return rows
@router.get("/api/calendar")
@@ -710,6 +735,11 @@ def options_page(request: Request) -> HTMLResponse:
store, user = guard
opts = _options(request)
users = _vacation_users()
today = today_kst()
try:
bal_year = int(request.query_params.get("year") or today.year)
except ValueError:
bal_year = today.year
return render_template(
request,
"vacation/options.html",
@@ -726,6 +756,8 @@ def options_page(request: Request) -> HTMLResponse:
"effective_approvers": notify.approver_emails(opts, users),
"gmail": _gmail_state(request, user),
"msg": request.query_params.get("msg", ""),
"bal_year": bal_year,
"bal_rows": _balance_rows(store, bal_year) if is_admin(user) else [],
},
)
+4
View File
@@ -33,6 +33,10 @@ HALF_LABELS: dict[str, str] = {"full": "종일", "am": "오전", "pm": "오후"}
# 수정/삭제(취소) 가능한 상태 — 본인 편집 허용
EDITABLE_STATUSES: tuple[str, ...] = ("작성중", "반려")
# 연차에서 차감하는 휴가 종류(2026-10-27) — 승인되면 그해 연차에서 빠진다. 병가·경조·대체휴무·기타는 차감하지 않는다.
# 연차는 그해(1/1~12/31) 것만 쓰고 다음 해로 넘기지 않는다(12/31 소멸 — 해마다 잔여 연차를 새로 등록).
DEDUCT_TYPES: tuple[str, ...] = ("연차", "오전반차", "오후반차")
# 반차 성격의 휴가 종류 (단일 일자 0.5일 강제)
_HALF_DAY_TYPES: dict[str, str] = {"오전반차": "am", "오후반차": "pm"}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027a" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027b" />{% endblock %}
{% block content %}
<section class="vac">
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027a" />
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027b" />
{#- 날짜 칸 = 프로젝트와 같은 아사나식 날짜 팝업(2026-10-27, erp-datepop) -#}
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<link rel="stylesheet" href="/static/erp-datepop.css?v=20261027a" />{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027a" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027b" />{% endblock %}
{% block content %}
<section class="vac">
@@ -27,7 +27,8 @@
<span class="vac-bal-item">사용 <strong>{{ balance.used_days }}</strong></span>
<span class="vac-bal-sep">·</span>
<span class="vac-bal-item vac-bal-remain">잔여 <strong>{{ balance.remaining_days }}</strong></span>
<span class="erp-muted vac-bal-year">{{ year }}년</span>
{#- 연차는 그해 것만 — 12/31 소멸, 다음 해로 넘어가지 않음(2026-10-27). 사용 = 승인된 연차·반차 -#}
<span class="erp-muted vac-bal-year" title="사용 = 승인된 연차·오전반차·오후반차(병가·경조·대체휴무·기타는 빼지 않음)">{{ year }}년 · {{ year }}.12.31 소멸</span>
</div>
</div>
@@ -51,7 +52,7 @@
</div>
{% for week in weeks %}
<div class="vac-week">
<div class="vac-week{% if week.days | selectattr('holiday_name') | list %} has-hol{% endif %}">
<div class="vac-week-days">
{% for cell in week.days %}
<a class="vac-day
@@ -62,6 +63,8 @@
{% if cell.holiday_name %}title="{{ cell.holiday_name }}"{% endif %}>
<span class="vac-day-num
{% if cell.is_sunday or cell.is_holiday %}vac-red{% elif cell.is_saturday %}vac-blue{% endif %}">{{ cell.day }}</span>
{#- 국경일·대체공휴일·회사 휴일 이름 — 날짜 숫자 아래(2026-10-27) -#}
{% if cell.holiday_name %}<span class="vac-hol-name">{{ cell.holiday_name }}</span>{% endif %}
</a>
{% endfor %}
</div>
@@ -2,7 +2,7 @@
{#- 휴가 옵션(2026-10-27) — 승인자·승인 통보자(수정 = ERP 관리자, 나머지는 보기만) + 내 Gmail 연결(누구나).
메일: 제출 = 승인자·통보자, 승인·반려 = 승인자·통보자·신청자. 보내는 사람 = 처리한 사람 본인 Gmail(없으면 회사 메일). -#}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027a" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027b" />{% endblock %}
{% block content %}
<section class="vac vac-options">
@@ -57,6 +57,51 @@
</div>
</form>
{% if is_admin %}
{#- 잔여 연차(2026-10-27, 설정에서 옮김) — 참여자(휴가 모듈 사용자) 전원을 미리 보여 주고 줄마다 연차 입력. 관리자만 보임·저장. -#}
<form method="post" action="/vacation/options/balances" class="erp-card vac-opt-card vac-opt-balcard" id="balances">
<div class="vac-card-head vac-bal-head">
<h2>잔여 연차 <span class="erp-muted vac-opt-count">{{ bal_year }}년 · 참여자 {{ bal_rows | selectattr('active') | list | length }}명</span></h2>
<span class="vac-bal-years">
<a class="erp-btn erp-btn-outline erp-btn-sm" href="/vacation/options?year={{ bal_year - 1 }}#balances">‹ {{ bal_year - 1 }}</a>
<a class="erp-btn erp-btn-outline erp-btn-sm" href="/vacation/options?year={{ bal_year + 1 }}#balances">{{ bal_year + 1 }} ›</a>
</span>
</div>
<p class="erp-muted vac-opt-hint">연차는 휴가가 <b>승인되면</b> 차감됩니다(연차·오전반차·오후반차 — 병가·경조·대체휴무·기타는 차감 안 함).
{{ bal_year }}년 연차는 <b>{{ bal_year }}.12.31 에 소멸</b>하고 다음 해로 넘어가지 않습니다 — 해마다 새로 등록하세요(빈 칸 = 그대로, 회색 숫자 = 작년 연차).</p>
<input type="hidden" name="year" value="{{ bal_year }}" />
<div class="erp-table-wrap">
<table class="erp-table vac-bal-table">
<thead><tr><th>참여자</th><th>연차</th><th>사용</th><th>잔여</th><th>메모</th></tr></thead>
<tbody>
{% for b in bal_rows %}
<tr class="{{ '' if b.active else 'is-inactive' }}">
<td>
<span class="vac-bal-person">
{% if b.picture %}<img class="vac-opt-face" src="{{ b.picture }}" alt="" referrerpolicy="no-referrer" />
{% else %}<span class="vac-opt-face is-ini">{{ b.name[:1] }}</span>{% endif %}
<span class="vac-opt-name">{{ b.name }}</span>
<span class="erp-muted vac-opt-mail">{{ b.email }}{% if not b.active %} · 휴가 권한 없음{% endif %}</span>
</span>
<input type="hidden" name="email" value="{{ b.email }}" />
</td>
<td><input class="erp-input vac-bal-input" type="number" name="total" step="0.5" min="0" max="365"
value="{{ '%g' % b.total if b.total is not none else '' }}"
placeholder="{{ '%g' % b.last_total if b.last_total is not none else '' }}" aria-label="{{ b.name }} 연차" /></td>
<td class="vac-bal-num">{{ '%g' % b.used }}</td>
<td class="vac-bal-num{% if b.remaining is not none and b.remaining < 0 %} is-minus{% endif %}">{{ '%g' % b.remaining if b.remaining is not none else '—' }}</td>
<td><input class="erp-input vac-bal-memo" type="text" name="memo" maxlength="200" value="{{ b.memo }}" placeholder="입사일·비고" aria-label="{{ b.name }} 메모" /></td>
</tr>
{% else %}
<tr><td colspan="5" class="erp-muted">휴가 모듈 권한이 있는 사용자가 없습니다.</td></tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="vac-opt-save"><button type="submit" class="erp-btn erp-btn-primary">{{ bal_year }}년 잔여 연차 저장</button></div>
</form>
{% endif %}
<div class="erp-card vac-opt-card vac-opt-mailcard">
<div class="vac-card-head"><h2>메일</h2></div>
<ul class="vac-opt-rules">
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027a" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027b" />{% endblock %}
{% block content %}
<section class="vac">
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027a" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027b" />{% endblock %}
{% block content %}
<section class="vac">
@@ -65,43 +65,13 @@
</div>
</div>
<!-- ── 연차 잔여 관리 ── -->
<!-- ── 잔여 연차는 옵션으로 옮겼다(2026-10-27) ── -->
<div class="erp-card vac-set-card">
<div class="vac-card-head"><h2>연차 잔여 ({{ year }})</h2></div>
<form method="post" action="/vacation/settings/balances" class="vac-balance-form">
<input type="hidden" name="year" value="{{ year }}" />
<label class="erp-field"><span>이메일 *</span>
<input class="erp-input" type="email" name="user_email" required
placeholder="user@dbxcorp.co.kr" />
</label>
<label class="erp-field"><span>연차 일수 *</span>
<input class="erp-input" type="number" name="total_days" step="0.5" min="0" required value="15" />
</label>
<label class="erp-field vac-full"><span>메모</span>
<input class="erp-input" type="text" name="memo" placeholder="입사일/비고 등" />
</label>
<button type="submit" class="erp-btn erp-btn-primary">설정</button>
</form>
<div class="erp-table-wrap vac-set-scroll">
<table class="erp-table">
<thead><tr><th>이메일</th><th>연차</th><th>사용</th><th>메모</th></tr></thead>
<tbody>
{% for b in balances %}
<tr>
<td>{{ b.user_email }}</td>
<td>{{ b.total_days }}</td>
<td class="erp-muted">{{ b.used_days }}</td>
<td class="erp-muted">{{ b.memo }}</td>
</tr>
{% else %}
<tr><td colspan="4" class="erp-muted">설정된 연차가 없습니다.</td></tr>
{% endfor %}
</tbody>
</table>
</div>
<p class="erp-muted vac-set-note">사용 일수는 승인된 휴가 합계로 자동 계산됩니다.</p>
<div class="vac-card-head"><h2>잔여 연차</h2></div>
<p class="erp-muted">잔여 연차 등록은 <a href="/vacation/options?year={{ year }}#balances">휴가 → 옵션 → 잔여 연차</a>로 옮겼습니다 —
참여자 전원을 한 표에서 아이콘·이름과 함께 등록합니다.</p>
<p class="erp-muted vac-set-note">국경일·대체공휴일(2026~2030)은 자동으로 쉬는 날입니다. 여기 공휴일은 회사 지정 휴일 추가용이고,
국경일 날짜를 <b>빨강 해제</b>로 등록하면 그날은 근무일로 셉니다.</p>
</div>
</div>
+22
View File
@@ -225,6 +225,8 @@
.vac-opt-msg.is-warn { background: #fff7e6; color: #8a5a00; }
.vac-opt-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; align-items: start; }
.vac-opt-card { padding: 16px; }
/* .erp-page > .vac 는 화면 높이 flex 라 카드가 줄어 내용이 잘렸다(잔여 연차 줄·메일 글) — 옵션 화면은 줄이지 않고 페이지 스크롤 */
.vac-options > * { flex-shrink: 0; }
.vac-opt-count { font-size: 12px; font-weight: 500; margin-left: 4px; }
.vac-opt-hint { margin: 4px 0 10px; font-size: 12px; line-height: 1.5; }
.vac-opt-now { margin: 0 0 10px; font-size: 12px; color: var(--vac-muted); }
@@ -249,3 +251,23 @@
.vac-mail-log li.is-fail b { color: #c22b10; }
.vac-mail-when { color: var(--vac-muted); margin-right: 6px; font-variant-numeric: tabular-nums; }
.vac-mail-err { display: block; margin-left: 2px; color: #c22b10; font-size: 12px; }
/* 달력 — 공휴일 이름(국경일·대체공휴일·회사 휴일) 날짜 아래(2026-10-27) */
.vac-hol-name { display: block; margin-top: 2px; font-size: 11px; font-weight: 600; line-height: 1.2; color: var(--vac-red);
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.vac-out .vac-hol-name { color: #f0a9a9; }
/* 공휴일이 있는 주 — 이름 줄만큼 휴가 막대를 내린다(막대 top 38px → 54px) */
.vac-week.has-hol { min-height: 104px; }
.vac-week.has-hol .vac-week-bars { top: 54px; }
/* 옵션 — 잔여 연차 표(설정에서 옮김) */
.vac-opt-balcard { margin-top: 16px; }
.vac-bal-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; }
.vac-bal-years { display: inline-flex; gap: 6px; }
.vac-bal-table td { vertical-align: middle; }
.vac-bal-person { display: flex; align-items: center; gap: 8px; min-width: 260px; }
.vac-bal-person .vac-opt-mail { margin-left: 4px; }
.vac-bal-input { width: 88px; min-width: 0; text-align: right; } /* erp-input 의 min-width 240px 끔 */
.vac-bal-memo { width: 100%; min-width: 160px; max-width: 360px; box-sizing: border-box; }
.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); }
+3 -1
View File
@@ -253,7 +253,9 @@ DDL: `scripts/sql/vacation_db_init.sql` (멱등). DB·역할(`vacation_app`)·
`status` 허용값: `작성중`, `제출`, `승인`, `반려`, `취소`. 워크플로: 작성중/반려 → 제출 → 승인|반려. 삭제는 기본 soft delete(`status='취소'`). 수정은 작성중/반려 상태에서 본인만.
휴가 일수는 서버(`store.compute_days`)에서 재계산: 주말 + `vacation_holidays(is_red)` 제외, 오전/오후 반차 0.5일, 시작/종료 반차는 각 0.5 차감. 클라이언트 계산은 미리보기(주말만 제외)용.
휴가 일수는 서버(`store.compute_days`)에서 재계산: 주말 + 쉬는 날 제외, 오전/오후 반차 0.5일, 시작/종료 반차는 각 0.5 차감. 클라이언트 계산은 미리보기용(같은 공휴일 표).
쉬는 날(2026-10-27) = 국경일·대체공휴일(프로젝트 `KR_HOLIDAYS`, 2026~2030) + `vacation_holidays`(is_red=true 추가·이름, is_red=false = 그 날 근무일) — `db.holiday_map`.
사용 연차 = 승인된 연차·오전반차·오후반차만, 해를 넘는 신청은 해마다 나눠 셈. 연차는 연도별(`vacation_balances.year`)이라 12/31 소멸·이월 없음.
권한: `vacation`(접근) / `vacation_approver`(승인·반려). admin 은 항상 통과. 공휴일·연차 설정은 admin 전용.
+79
View File
@@ -71,5 +71,84 @@ class VacationOptionsDBTests(unittest.TestCase):
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_national_plus_settings(self):
st = self.st
m = st.holiday_map(date_from="2027-10-01", date_to="2027-10-31") # 설정에 2027 없음 → 국경일 표
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 에 없던 날
# 설정이 덮어쓴다 — 회사 휴일 추가, 이름 바꾸기, 빨강 해제 = 근무일
st.upsert_holiday(holiday_date="2027-10-08", name="창립기념일", kind="company", is_red=True)
st.upsert_holiday(holiday_date="2027-10-09", name="한글날(회사)", kind="public", is_red=True)
st.upsert_holiday(holiday_date="2027-10-11", name="한글날 대체", kind="substitute", is_red=False)
try:
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-08": "창립기념일",
"2027-10-09": "한글날(회사)"})
self.assertEqual(st.red_holiday_set(date_from="2027-10-01", date_to="2027-10-31"), set(m))
finally:
for h in st.list_holidays(year=2027):
if h["holiday_date"] in ("2027-10-08", "2027-10-09", "2027-10-11"):
st.delete_holiday(holiday_id=h["id"])
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)
if __name__ == "__main__":
unittest.main()
+78 -3
View File
@@ -197,9 +197,12 @@ class Store:
self.req.update(status="반려", reject_reason=reason); return dict(self.req)
def list_mail_log(self, request_id):
return []
def list_holidays(self, year=None):
return [{"holiday_date": f"{year}-10-09", "name": "한글날", "is_red": True},
{"holiday_date": f"{year}-05-01", "name": "근로자의날(회사)", "is_red": False}]
def list_balances(self, year):
return []
def used_days(self, user_email, year):
return 0.0
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()
@@ -330,5 +333,77 @@ run(body)
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, year, rows):
saved.update(year=year, rows=rows); return len(rows)
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 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()
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 "2026년 · 참여자 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 + 900]
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"]})
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
# 관리자 아님 — 표 안 보임, 저장 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
# 설정 — 잔여 연차 입력 없음(옵션 안내)
who["u"] = admin
t = c.get("/vacation/settings?year=2026").text
assert "/vacation/settings/balances" not in t and "/vacation/options?year=2026#balances" in t
assert c.post("/vacation/settings/balances", data={"user_email": "a@test.local", "year": "2026", "total_days": "1"}).status_code in (404, 405)
# 달력 — 국경일·대체공휴일 이름이 날짜 아래, 그 주는 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 "2026.12.31 소멸" 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()