diff --git a/app/modules/cupang/templates/cupang/index.html b/app/modules/cupang/templates/cupang/index.html index 0e9a041..ae69010 100644 --- a/app/modules/cupang/templates/cupang/index.html +++ b/app/modules/cupang/templates/cupang/index.html @@ -2,7 +2,7 @@ {% block head_extra %} {# 출고리스트 작성 팝업의 날짜 칸은 프로젝트 화면의 날짜 팝업을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #} - + @@ -249,7 +249,7 @@ {% endblock %} {% block scripts %} - + {% endblock %} @@ -64,7 +64,7 @@ - + {% endif %} {% endblock %} diff --git a/app/modules/project/CLAUDE.md b/app/modules/project/CLAUDE.md index d1b9340..c429e24 100644 --- a/app/modules/project/CLAUDE.md +++ b/app/modules/project/CLAUDE.md @@ -138,7 +138,9 @@ 작업 칸(마이그레이션 026 `parent_task_id`) = 이미 있는 작업을 고르면 그 작업의 세부 작업으로 등록. 등록된 줄 = 줄 어디든 누르면 오른쪽 작업 창(편집, 저장 대기 — 2026-10-26 예전엔 제목만), 세부 업무 줄의 "↳ 상위" = 상위 업무 창, [크게 열기] = 같은 표를 넓은 창으로. **하위 업무 등록**(2026-10-26, 6-26) — 등록된 줄 [+](`data-quick="add-sub"`) = 바로 아래 세부 업무 초안(프로젝트·`parent_task_id` = 그 업무, 제목을 치면 POST), - 세부 업무 줄은 상위 줄 아래 들여쓰기(`displayOrder`, 서버 순서·DB 변경 없음). 예전 [2g4] "↳(줄 세부 작업)" 버튼은 표 줄끼리 묶던 다른 기능(025 parent_id). + 세부 업무 줄은 상위 줄 아래 들여쓰기(`displayOrder`, 서버 순서·DB 변경 없음). + **열 = 담당자 · 프로젝트 · 섹션 · 업무 · 제목**(2026-10-27 제목을 업무 오른쪽으로, 제목 Enter = [적용]으로 포커스). 세부 업무 줄의 섹션 = + 고른 업무의 섹션(서버 `parent_stage_name` — 세부의 세부면 섹션 있는 맨 위 업무까지 올라감, `_mt_select` LATERAL 재귀, 고칠 수 없음 회색). 예전 [2g4] "↳(줄 세부 작업)" 버튼은 표 줄끼리 묶던 다른 기능(025 parent_id). - 실적 모듈 `performance_store` 매출은 머리 카드에만 읽기 전용 — 줄(쇼핑몰)별 자동 결과·이번주 실적·연결 배지·쇼핑몰 연결 메뉴는 폐지, 지난주 결과는 늘 직접 입력. - "주요 업무" 칸 우클릭 위/아래 줄 추가 = 항목 칸은 그대로 그 항목 안에(마이그레이션 027 `label_cont`, 항목 칸 나누기). - **글 칸 하이퍼링크**(2026-10-26, 6-26) — 목표·회의록 서식 도구(`_cell_format.html`) 🔗 = 선택 글자에 주소(pj-rich 조각 `link`, http(s)만 — 서버 `store.goal_link`, diff --git a/app/modules/project/db.py b/app/modules/project/db.py index c00603f..2b38df2 100644 --- a/app/modules/project/db.py +++ b/app/modules/project/db.py @@ -3774,7 +3774,8 @@ class ProjectStore: out[k] = int(out[k]) if out[k] is not None else None out["week_start"] = r["week_start"].isoformat() out["updated_at"] = r["updated_at"].astimezone(KST).isoformat(timespec="seconds") if r.get("updated_at") else "" - for k in ("project_name", "project_status", "stage_name", "task_title", "task_project_id", "parent_task_title"): + for k in ("project_name", "project_status", "stage_name", "task_title", "task_project_id", "parent_task_title", + "parent_stage_name"): if k in r: out[k] = r[k] if "task_exists" in r: @@ -3839,12 +3840,20 @@ class ProjectStore: f"SELECT {self._mt_cols(conn, 'm.')}, " " p.name AS project_name, p.status AS project_status, s.name AS stage_name, " " t.title AS task_title, t.project_id AS task_project_id, (t.id IS NOT NULL) AS task_exists" - + (", pt.title AS parent_task_title " if v26 else " ") + + + (", pt.title AS parent_task_title, pst.name AS parent_stage_name " if v26 else " ") + "FROM goal_meeting_tasks m " "LEFT JOIN projects p ON p.id = m.project_id " "LEFT JOIN project_stages s ON s.id = m.stage_id " "LEFT JOIN tasks t ON t.id = m.task_id " - + ("LEFT JOIN tasks pt ON pt.id = m.parent_task_id " if v26 else "") + + # 세부 업무로 등록하는 줄(2026-10-27) — 섹션 = 고른 업무의 섹션(세부의 세부면 위로 올라가 섹션 있는 맨 위 업무) + + ("LEFT JOIN tasks pt ON pt.id = m.parent_task_id " + "LEFT JOIN LATERAL (" + " WITH RECURSIVE up AS (" + " SELECT u.id, u.parent_task_id, u.stage_id, 0 AS depth FROM tasks u WHERE u.id = m.parent_task_id " + " UNION ALL SELECT u2.id, u2.parent_task_id, u2.stage_id, up.depth + 1 FROM tasks u2 " + " JOIN up ON u2.id = up.parent_task_id WHERE up.stage_id IS NULL AND up.depth < 20) " + " SELECT ps.name FROM up JOIN project_stages ps ON ps.id = up.stage_id ORDER BY up.depth LIMIT 1" + ") pst ON TRUE " if v26 else "") + f"WHERE {where} ORDER BY m.sort_order, m.id", params, ).fetchall() diff --git a/app/modules/project/router.py b/app/modules/project/router.py index 2be1a15..20b8bb7 100644 --- a/app/modules/project/router.py +++ b/app/modules/project/router.py @@ -4242,7 +4242,7 @@ def _quick_view(st: Any, user: dict[str, Any], rows: list[dict[str, Any]]) -> li r = dict(r, visible=ok, registered=r.get("task_id") is not None) # 등록됨 여부는 누구에게나(작업 내용은 멤버만) if not ok: r.update(project_name="(볼 수 없는 프로젝트)", stage_name="", task_title="", task_id=None, - task_project_id=None, parent_task_id=None, parent_task_title="") + task_project_id=None, parent_task_id=None, parent_task_title="", parent_stage_name="") out.append(r) return out diff --git a/app/modules/project/templates/project/goal_meeting.html b/app/modules/project/templates/project/goal_meeting.html index afa5d6d..9c729aa 100644 --- a/app/modules/project/templates/project/goal_meeting.html +++ b/app/modules/project/templates/project/goal_meeting.html @@ -1,7 +1,7 @@ {% extends "project/_meeting_content_base.html" if meeting_embedded else "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -114,7 +114,7 @@
- +
제목담당자프로젝트섹션업무
담당자프로젝트섹션업무제목
@@ -289,5 +289,5 @@ - + {% endblock %} diff --git a/app/modules/project/templates/project/goals.html b/app/modules/project/templates/project/goals.html index 5364f22..4fa8638 100644 --- a/app/modules/project/templates/project/goals.html +++ b/app/modules/project/templates/project/goals.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -207,5 +207,5 @@ {% include "project/_member_tasks_modal.html" %} - + {% endblock %} diff --git a/app/modules/project/templates/project/help.html b/app/modules/project/templates/project/help.html index 7f80f95..48e00fa 100644 --- a/app/modules/project/templates/project/help.html +++ b/app/modules/project/templates/project/help.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -659,7 +659,8 @@

제목 아래 두 칸은 표를 스크롤해도 그대로 보입니다. 왼쪽 칸 머리 한 줄에 N월 계획과 숫자 4개(월 목표 · 누적 목표 · 누적 실적 · 목표 대비, 목표 표 매출 단위 예: 백만원 — 숫자에 마우스를 올리면 원 단위 금액과 뜻)와 결정사항 제목이 나오고, 그 아래 칸 전체가 결정사항(진행상황 수시 공유 및 완료 되어야 할 것) 입력란입니다. 오른쪽은 업무 등록 표입니다.

  1. 업무 등록(제목에 N주차 업무 등록) — 주차마다 한 표를 모두가 같이 봅니다(다른 사람이 적거나 등록한 줄도 보임, 30초마다·창을 다시 볼 때 새로 읽음). 내가 멤버가 아닌 프로젝트를 고른 남의 줄은 프로젝트 이름을 가립니다. 회의 완료면 읽기 전용입니다. - 업무 칸 — 비워 두면 고른 섹션에 새 업무로, 업무를 고르면 그 업무의 세부 업무로 등록합니다(목록 = 그 섹션의 진행 중인 메인 업무, 고르면 섹션 칸은 —). 등록된 줄(업무·세부 업무)을 누르면 줄 어디든 오른쪽에 업무 창이 열려 바로 편집할 수 있습니다(연 줄은 옅은 보라색, 다른 줄을 누르면 창이 그 업무로 바뀜, 업무 창에서 저장이 끝나야 닫히거나 다른 업무로 바뀝니다). 세부 업무 줄의 ↳ 상위 업무를 누르면 상위 업무 창이 열립니다. + 칸 순서는 담당자 · 프로젝트 · 섹션 · 업무 · 제목입니다(제목에서 Enter = 적용 버튼으로). + 업무 칸 — 비워 두면 고른 섹션에 새 업무로, 업무를 고르면 그 업무의 세부 업무로 등록합니다(목록 = 그 섹션의 진행 중인 메인 업무, 고르면 섹션 칸에 그 업무의 섹션이 회색으로 — 상위 업무를 따름). 등록된 줄(업무·세부 업무)을 누르면 줄 어디든 오른쪽에 업무 창이 열려 바로 편집할 수 있습니다(연 줄은 옅은 보라색, 다른 줄을 누르면 창이 그 업무로 바뀜, 업무 창에서 저장이 끝나야 닫히거나 다른 업무로 바뀝니다). 세부 업무 줄의 ↳ 상위 업무를 누르면 상위 업무 창이 열립니다. 하위 업무 등록 — 등록된 줄 오른쪽 add(하위 업무 추가)을 누르면 바로 아래에 그 업무의 세부 업무 줄이 생깁니다(프로젝트·↳ 상위 업무가 채워져 있음). 제목·담당자를 적고 적용하면 세부 업무로 등록되고, 세부 업무 줄에서 다시 add를 누르면 그 아래 단계도 만들 수 있습니다. 세부 업무 줄은 상위 업무 줄 아래에 들여 써서 보입니다. 크게 열기 — 같은 표를 넓은 창으로 열어 씁니다(줄·저장은 그대로, Esc·×로 닫기). 제목 칸에 업무 이름을 씁니다. 담당자·프로젝트·섹션 칸을 누르면 고를 수 있는 목록이 나옵니다(완료 프로젝트·완료 섹션은 목록에 나오지 않습니다). 목록 맨 위 새 프로젝트(Pro user 이상)·새 섹션(그 프로젝트 멤버)을 누르면 이름만 적어 바로 만들고 그 칸에 골라집니다. 새 프로젝트는 섹션 없이 시작하니 섹션 칸에서 새 섹션을 만들어 고르세요.
  2. 프로젝트는 내가 멤버인 프로젝트만 나오고, 고르면 첫 섹션이 자동으로 들어갑니다. 담당자는 그 프로젝트의 멤버·소유자 중에서 고릅니다(프로젝트를 먼저 고르면 정확합니다).
  3. diff --git a/app/modules/project/templates/project/inbox.html b/app/modules/project/templates/project/inbox.html index c63450a..c182397 100644 --- a/app/modules/project/templates/project/inbox.html +++ b/app/modules/project/templates/project/inbox.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -106,5 +106,5 @@ {% include "project/_side_modals.html" %} {% include "project/_member_tasks_modal.html" %} - + {% endblock %} diff --git a/app/modules/project/templates/project/mytasks.html b/app/modules/project/templates/project/mytasks.html index a9bcc10..e5f428d 100644 --- a/app/modules/project/templates/project/mytasks.html +++ b/app/modules/project/templates/project/mytasks.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -100,5 +100,5 @@ "today": {{ today | tojson }} } - + {% endblock %} diff --git a/app/modules/project/templates/project/notifier.html b/app/modules/project/templates/project/notifier.html index 292ddde..02655f0 100644 --- a/app/modules/project/templates/project/notifier.html +++ b/app/modules/project/templates/project/notifier.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -108,5 +108,5 @@ }); })(); - + {% endblock %} diff --git a/app/modules/project/templates/project/project.html b/app/modules/project/templates/project/project.html index 5a23a93..f36f8f9 100644 --- a/app/modules/project/templates/project/project.html +++ b/app/modules/project/templates/project/project.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + @@ -476,5 +476,5 @@ - + {% endblock %} diff --git a/app/modules/project/templates/project/trash.html b/app/modules/project/templates/project/trash.html index a99eb3b..9eace18 100644 --- a/app/modules/project/templates/project/trash.html +++ b/app/modules/project/templates/project/trash.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -70,5 +70,5 @@ {% include "project/_side_modals.html" %} {% include "project/_member_tasks_modal.html" %} - + {% endblock %} 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/project.css b/app/static/project.css index b7a5b49..8188720 100644 --- a/app/static/project.css +++ b/app/static/project.css @@ -2756,11 +2756,12 @@ html.pj-goal-selecting, html.pj-goal-selecting * { user-select: none !important; .pj-ctxmenu-ic .pj-meet-quick-face { width: 20px; height: 20px; } .pj-member-pick.is-owner { opacity: .75; } /* 제목·담당자·프로젝트·섹션·작업(세부 작업으로 넣을 작업)·버튼 */ -.pj-meet-quick-table th:nth-child(1) { width: 24%; } +/* 열 = 담당자 · 프로젝트 · 섹션 · 업무 · 제목 · 버튼(2026-10-27 제목을 업무 오른쪽으로) */ +.pj-meet-quick-table th:nth-child(1) { width: 15%; } .pj-meet-quick-table th:nth-child(2) { width: 15%; } -.pj-meet-quick-table th:nth-child(3) { width: 15%; } -.pj-meet-quick-table th:nth-child(4) { width: 12%; } -.pj-meet-quick-table th:nth-child(5) { width: 15%; } +.pj-meet-quick-table th:nth-child(3) { width: 12%; } +.pj-meet-quick-table th:nth-child(4) { width: 15%; } +.pj-meet-quick-table th:nth-child(5) { width: 24%; } .pj-meet-quick-table th:nth-child(6) { width: 19%; } .pj-meet-quick-acts { white-space: nowrap; text-align: right; } .pj-meet-quick-del { diff --git a/app/static/project.js b/app/static/project.js index 4e21fba..87a1d97 100644 --- a/app/static/project.js +++ b/app/static/project.js @@ -12140,13 +12140,14 @@ }; const blank = function () { return { id: null, title: "", assignee: "", projectId: null, projectName: "", stageId: null, stageName: "", - parentTaskId: null, parentTaskTitle: "", taskId: null, registered: false, visible: true, taskExists: true, chain: null, - unsaved: new Set(), err: "" }; + parentTaskId: null, parentTaskTitle: "", parentStageName: "", taskId: null, registered: false, visible: true, taskExists: true, + chain: null, unsaved: new Set(), err: "" }; }; function fromServer(t) { return { id: t.id, title: t.title || "", assignee: t.assignee_email || "", projectId: t.project_id, projectName: t.project_name || "", stageId: t.stage_id, stageName: t.stage_name || "", - parentTaskId: t.parent_task_id || null, parentTaskTitle: t.parent_task_title || "", taskId: t.task_id, + parentTaskId: t.parent_task_id || null, parentTaskTitle: t.parent_task_title || "", parentStageName: t.parent_stage_name || "", + taskId: t.task_id, registered: !!t.registered, visible: t.visible !== false, taskExists: t.task_exists !== false, chain: null, unsaved: new Set(), err: "" }; } @@ -12314,16 +12315,20 @@ const cls = [r.registered ? "is-done" : (r.err && r.unsaved.size ? "is-unsaved" : ""), openable ? "is-openable" : "", depth ? "is-sub" : "", openable && panelOpen() && panelTask === r.taskId ? "is-panel-selected" : ""] .filter(Boolean).join(" "); + // 열 = 담당자 · 프로젝트 · 섹션 · 업무 · 제목(2026-10-27 제목을 업무 오른쪽으로) · 버튼 return '" + - '' + titleCell + "" + "" + (r.assignee ? '" : cell("assignee", "", "담당자", ro)) + "" + "" + cell("project", r.projectName, "프로젝트", ro) + "" + - "" + (r.parentTaskId ? '—' + // 세부 업무 줄의 섹션 = 고른(상위) 업무의 섹션 — 바꿀 수 없음(상위 업무를 따름), 회색 글자(2026-10-27 예전엔 —) + "" + (r.parentTaskId + ? '' + + escapeHtml(r.parentStageName || r.stageName || "—") + "" : cell("stage", r.stageName, "섹션", ro)) + "" + "" + taskCell + "" + + '' + titleCell + "" + '
' + acts + "
"; }).join(""); } @@ -12413,10 +12418,10 @@ const all = await tasksOf(pid); const list = r.stageId ? all.filter(function (t) { return t.stage_id === r.stageId; }) : all; const set = function (t) { - r.parentTaskId = t ? t.id : null; r.parentTaskTitle = t ? t.title : ""; + r.parentTaskId = t ? t.id : null; r.parentTaskTitle = t ? t.title : ""; r.parentStageName = ""; if (t && t.stage_id) { const st = (stageCache[pid] || []).find(function (x) { return x.id === t.stage_id; }); - if (st) { r.stageId = st.id; r.stageName = st.name; } + if (st) { r.stageId = st.id; r.stageName = st.name; r.parentStageName = st.name; } } render(); persist(r, { parent_task_id: r.parentTaskId, stage_id: r.stageId }); }; @@ -12431,7 +12436,8 @@ function addSubRow(parent) { const b = blank(); Object.assign(b, { projectId: parent.projectId, projectName: parent.projectName, stageId: parent.stageId, - stageName: parent.stageName, parentTaskId: parent.taskId, parentTaskTitle: parent.title, subDraft: true }); + stageName: parent.stageName, parentTaskId: parent.taskId, parentTaskTitle: parent.title, subDraft: true, + parentStageName: parent.parentTaskId ? (parent.parentStageName || parent.stageName) : parent.stageName }); rows.push(b); render(); const inp = tbody.querySelector('tr[data-i="' + rows.indexOf(b) + '"] input[data-field="title"]'); if (inp) inp.focus(); @@ -12575,9 +12581,11 @@ tbody.addEventListener("keydown", function (e) { const inp = e.target.closest("input[data-field=title]"); if (inp && !inp.readOnly && e.key === "Enter" && !isImeEnter(e)) { + // 제목은 이제 맨 뒤 칸(2026-10-27) — Enter = 저장하고 [적용]으로(예전엔 다음 칸 담당자 목록을 열었다) e.preventDefault(); flushTitle(rowOf(inp)); - inp.closest("tr").querySelector('[data-pick="assignee"]').click(); + const ap = inp.closest("tr").querySelector('[data-quick="apply"]'); + if (ap) ap.focus(); } }); tbody.addEventListener("click", function (e) { 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/goals_meeting_ui.test.js b/tests/js/goals_meeting_ui.test.js index a612557..7f2178a 100644 --- a/tests/js/goals_meeting_ui.test.js +++ b/tests/js/goals_meeting_ui.test.js @@ -559,6 +559,7 @@ function meetServer(env, st) { return { id: r.id, title: r.title || "", assignee_email: r.assignee_email || "", project_id: r.project_id || null, project_name: r.project_name || "", stage_id: r.stage_id || null, stage_name: r.stage_name || "", task_id: r.task_id, parent_task_id: r.parent_task_id || null, parent_task_title: r.parent_task_id ? (r.parent_task_title || "상세페이지 리뉴얼") : "", + parent_stage_name: r.parent_task_id ? (r.parent_stage_name || "") : "", registered: r.task_id != null, visible: r.visible !== false, task_exists: true }; }; env.route("GET", /\/goals\/meetings\/([\d-]+)\/quick-tasks$/, function (u) { @@ -790,17 +791,20 @@ function meetServer(env, st) { await boot(env); await settle(); await wait(5); await settle(); const d = env.d; const row = function () { return d.querySelector("#pj-meet-quick tbody tr"); }; - check("[2g4] 표 머리에 '업무' 칸, 예전 ↳(줄 세부 작업) 버튼 없음", - Array.from(d.querySelectorAll("#pj-meet-quick thead th")).map(function (t) { return t.textContent; }).indexOf("업무") === 4 && - !d.querySelector('[data-quick="add-sub"]')); + // 열 = 담당자 · 프로젝트 · 섹션 · 업무 · 제목(2026-10-27 제목을 업무 오른쪽으로) + const heads = Array.from(d.querySelectorAll("#pj-meet-quick thead th")).map(function (t) { return t.textContent; }); + check("[2g4] 표 머리 = 담당자·프로젝트·섹션·업무·제목, 예전 ↳(줄 세부 작업) 버튼 없음", + heads.slice(0, 5).join("|") === "담당자|프로젝트|섹션|업무|제목" && !d.querySelector('[data-quick="add-sub"]') && + row().children[4].classList.contains("pj-meet-quick-title") && !!row().children[4].querySelector('input[data-field="title"]'), heads); row().querySelector('[data-pick="task"]').click(); await settle(); await wait(5); await settle(); const labels = Array.from(d.querySelectorAll(".pj-ctxmenu-item")).map(itemLabel); check("[2g4] 작업 칸 목록 = '새 업무(섹션에)' + 그 섹션의 진행 중 메인 작업만", labels[0] === "새 업무 (‘할 일’ 섹션에)" && labels.indexOf("상세페이지 리뉴얼") >= 0 && labels.indexOf("다른 섹션 작업") < 0 && labels.indexOf("끝난 작업") < 0 && labels.indexOf("이미 세부 작업") < 0, labels); Array.from(d.querySelectorAll(".pj-ctxmenu-item")).find(function (n) { return itemLabel(n) === "상세페이지 리뉴얼"; }).click(); await settle(); await wait(5); await settle(); - check("[2g4] 작업을 고르면 ↳ 표시·섹션 '—'·제목 칸 '세부 업무 제목'·서버 줄에 parent_task_id", - /↳ 상세페이지 리뉴얼/.test(row().querySelector('[data-pick="task"]').textContent) && /—/.test(row().children[3].textContent) && + check("[2g4] 작업을 고르면 ↳ 표시·섹션 = 그 업무의 섹션(할 일, 고칠 수 없음)·제목 칸 '세부 업무 제목'·서버 줄에 parent_task_id", + /↳ 상세페이지 리뉴얼/.test(row().querySelector('[data-pick="task"]').textContent) && + row().children[2].textContent.trim() === "할 일" && !row().children[2].querySelector('[data-pick="stage"]') && row().querySelector('input[data-field="title"]').placeholder === "세부 업무 제목" && q.rows[1].parent_task_id === 300, q.rows[1]); row().querySelector('[data-quick="apply"]').click(); await settle(); await wait(5); await settle(); check("[2g4] 적용 → 서버 [적용](고른 작업 밑 세부 작업)", q.applied.length === 1 && q.applied[0].parent_task_id === 300, q.applied); @@ -836,7 +840,8 @@ function meetServer(env, st) { const q = quickServer(env, { rows: [ { id: 1, title: "상위 업무", project_id: 7, project_name: "브랜드", stage_id: 71, stage_name: "할 일", task_id: 900 }, { id: 2, title: "다른 줄", project_id: 7, project_name: "브랜드", stage_id: 71, stage_name: "할 일" }, - { id: 3, title: "이미 세부", project_id: 7, project_name: "브랜드", task_id: 901, parent_task_id: 900, parent_task_title: "상위 업무" }] }); + { id: 3, title: "이미 세부", project_id: 7, project_name: "브랜드", task_id: 901, parent_task_id: 900, parent_task_title: "상위 업무", + parent_stage_name: "할 일" }] }); await boot(env); await settle(); await wait(5); await settle(); const d = env.d; const trs = function () { return Array.from(d.querySelectorAll("#pj-meet-quick tbody tr")); }; @@ -844,6 +849,8 @@ function meetServer(env, st) { check("[2g5] 세부 업무 줄은 상위 업무 줄 바로 아래(들여쓰기 is-sub)", titleOf(trs()[0]) === "상위 업무" && titleOf(trs()[1]) === "이미 세부" && trs()[1].classList.contains("is-sub") && titleOf(trs()[2]) === "다른 줄" && !trs()[0].classList.contains("is-sub"), trs().map(titleOf)); + check("[2g5] 세부 업무 줄의 섹션 = 상위 업무의 섹션(서버 parent_stage_name)", trs()[1].children[2].textContent.trim() === "할 일", + trs()[1].children[2].textContent); check("[2g5] 등록된 줄에만 [+](하위 업무 추가)", !!trs()[0].querySelector('[data-quick="add-sub"]') && !!trs()[1].querySelector('[data-quick="add-sub"]') && !trs()[2].querySelector('[data-quick="add-sub"]')); // 등록된 줄 — 제목이 아닌 칸(프로젝트 칸)을 눌러도 오른쪽 업무 창 @@ -864,8 +871,8 @@ function meetServer(env, st) { const calls = env.calls.length; trs()[0].querySelector('[data-quick="add-sub"]').click(); await settle(); const draft = trs()[2]; - check("[2g5] [+] → 상위 줄 아래 세부 업무 초안(↳ 상위 업무, 프로젝트 채움, 제목 칸 포커스, 요청 없음)", - draft.classList.contains("is-sub") && /↳ 상위 업무/.test(draft.textContent) && /브랜드/.test(draft.textContent) && + check("[2g5] [+] → 상위 줄 아래 세부 업무 초안(↳ 상위 업무, 프로젝트 채움, 섹션 = 상위 업무 섹션, 제목 칸 포커스, 요청 없음)", + draft.classList.contains("is-sub") && draft.children[2].textContent.trim() === "할 일" && /↳ 상위 업무/.test(draft.textContent) && /브랜드/.test(draft.textContent) && d.activeElement === draft.querySelector('input[data-field="title"]') && draft.querySelector("input").placeholder === "세부 업무 제목" && env.calls.length === calls, [trs().map(titleOf), env.calls.length - calls]); const inp = draft.querySelector('input[data-field="title"]'); 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_project_module.py b/tests/test_project_module.py index 1010281..439d0d8 100644 --- a/tests/test_project_module.py +++ b/tests/test_project_module.py @@ -1318,6 +1318,27 @@ def _clear_quick(*weeks) -> None: conn.execute("DELETE FROM goal_meeting_tasks WHERE week_start = ANY(%s)", (list(weeks),)) +def test_meeting_quick_task_parent_stage_name(): + """업무 등록 표 세부 업무 줄(2026-10-27) — 섹션 = 고른 업무의 섹션, 세부의 세부면 섹션 있는 맨 위 업무까지 올라감.""" + from app.modules.project import store + + w = store.month_weeks(2031, 11)[1][0] + _clear_quick(w) + p = _project("P-qpst", ADMIN, (BOB,)) + s = _stage(p["id"], name="기획", by=ADMIN) + top = ST.create_task(project_id=p["id"], title="상위", stage_id=s["id"], created_by=BOB) + sub = ST.create_task(project_id=p["id"], title="세부", parent_task_id=top["id"], created_by=BOB) + url = f"/project/api/goals/meetings/{w}/quick-tasks" + for parent in (top["id"], sub["id"]): + r = req("POST", url, BOB, json={"title": "새 세부", "project_id": p["id"], "parent_task_id": parent}) + assert r.status_code == 201, r.text + assert r.json()["task"]["parent_stage_name"] == "기획", r.json()["task"] + rows = req("GET", url, BOB).json()["tasks"] + assert [x["parent_stage_name"] for x in rows] == ["기획", "기획"], rows + assert all(x["parent_stage_name"] == "" for x in req("GET", url, ALICE).json()["tasks"]) # 남의 프로젝트 줄 = 가림 + _clear_quick(w) + + def test_review_meeting_quick_tasks_shared(): """작업 등록 표(025) — 주차별 한 표를 모두가 같이 본다. 남의 프로젝트 이름은 가리고, [적용]은 동시에 눌러도 작업 하나.""" from app.modules.project import store 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")