diff --git a/CLAUDE.md b/CLAUDE.md index 80cc81e..e7432eb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -63,6 +63,7 @@ - `app/integrations/google_sheets.py`(쿠팡) · `google_slides.py`(프로젝트 회의록 보드). - `app/mail.py`: 프로젝트 알림 메일. - ERP 모든 화면 스크립트: `erp-notice.js`(공지) · `erp-overdue.js`(프로젝트 마감 알림). +- 아사나식 날짜 팝업: 프로젝트(`project.js` 안) + 공용 복사본 `erp-datepop.js/css`(휴가 신청) — 바꾸면 둘 다. --- diff --git a/app/modules/project/CLAUDE.md b/app/modules/project/CLAUDE.md index 15e8f5b..d1b9340 100644 --- a/app/modules/project/CLAUDE.md +++ b/app/modules/project/CLAUDE.md @@ -17,6 +17,8 @@ - 용어는 **"업무"**(2026-10-13 "작업"에서 다시 통일 — 화면·메시지·알림 제목, 코드·DB 는 그대로)·"세부 업무"·"메인 업무 추가". ERP 메뉴 이름은 "Project"(`app/main.py` 모듈 목록 title). - 화면 기능을 바꾸면 도움말(`/project/help`)도 같이 고친다. - UI 버그는 로컬 헤드리스 크롬/엣지로 렌더·좌표 덤프해 재현 후 고칠 것. +- 날짜 팝업(`openDatePopover`·`enhanceDateInput`·`.pj-datepop` CSS)은 다른 모듈용 공용 복사본이 있다 — `app/static/erp-datepop.js`·`.css` + (2026-10-27, 휴가 신청 날짜 칸). 모양·동작을 바꾸면 그쪽도 같이 고칠 것(나중에 프로젝트도 공용 파일로 옮기면 하나가 됨). ## 권한 — 관리자 등급 4단계 (2026-10-12, 6-14) diff --git a/app/modules/vacation/CLAUDE.md b/app/modules/vacation/CLAUDE.md index 661319b..60e9237 100644 --- a/app/modules/vacation/CLAUDE.md +++ b/app/modules/vacation/CLAUDE.md @@ -5,6 +5,11 @@ - 월간 달력(구글식 bar) / 연차·반차 신청 / 승인 워크플로 / 공휴일·연차 설정. - 권한키 `vacation`(사용)·`vacation_approver`(승인). +- **신청 화면 날짜 칸 = 프로젝트와 같은 아사나식 날짜 팝업**(2026-10-27, 공용 `app/static/erp-datepop.js`·`.css` — project.js `openDatePopover`· + `enhanceDateInput` 을 떼어 낸 것). 시작일·종료일 input 은 숨긴 값 저장소, 옆 날짜 버튼 둘(`ErpDatePop.enhanceRange`) — 어느 쪽을 눌러도 같은 + 기간 팝업(누른 칸이 먼저, 시작일 고르면 종료일 칸으로, 종료일 고르면 닫힘, 지우기 없음), 반차는 하루짜리 팝업(시작=종료). 직접 입력(10/27·1027 Enter). + 공휴일 = 휴가 설정 공휴일 중 빨강(`router._red_holidays`, 작년~내년, `#vac-holidays`) — 팝업 빨강·이름 + 예상 일수에서도 뺀다(서버 compute_days 와 같은 표). + 테스트 `tests/js/vacation_datepop.browser.test.js`(`render_vacation.py`). ## 휴가 옵션 · 휴가 메일 (2026-10-27, 마이그레이션 `vacation_db_001_options_mail.sql`) diff --git a/app/modules/vacation/router.py b/app/modules/vacation/router.py index 934b8eb..b8705d2 100644 --- a/app/modules/vacation/router.py +++ b/app/modules/vacation/router.py @@ -343,9 +343,27 @@ def _form_context(request: Request, user: dict[str, Any]) -> dict[str, Any]: "vacation_types": list(VACATION_TYPES), "halves": list(HALVES), "half_labels": HALF_LABELS, + "holidays": _red_holidays(request), } +def _red_holidays(request: Request) -> dict[str, str]: + """날짜 팝업 공휴일(빨강·이름) — 휴가 설정의 공휴일(is_red) 작년~내년. 일수 계산과 같은 표.""" + 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 "" + except Exception: # noqa: BLE001 — 공휴일 표시가 신청 화면을 막지 않게 + return {} + return out + + @router.get("/new", response_class=HTMLResponse) def new_form(request: Request) -> HTMLResponse: from app.main import render_template # noqa: WPS433 diff --git a/app/modules/vacation/templates/vacation/form.html b/app/modules/vacation/templates/vacation/form.html index 118816c..4fc01ed 100644 --- a/app/modules/vacation/templates/vacation/form.html +++ b/app/modules/vacation/templates/vacation/form.html @@ -1,6 +1,9 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %} +{#- 날짜 칸 = 프로젝트와 같은 아사나식 날짜 팝업(2026-10-27, erp-datepop) -#} + +{% endblock %} {% block content %}
@@ -51,7 +54,7 @@
예상 사용 일수: — - (주말 제외 · 공휴일은 저장 시 반영) + (주말 · 공휴일 제외)
@@ -68,4 +71,6 @@
{% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %} + +{% endblock %} diff --git a/app/static/erp-datepop.css b/app/static/erp-datepop.css new file mode 100644 index 0000000..1e85478 --- /dev/null +++ b/app/static/erp-datepop.css @@ -0,0 +1,113 @@ +/* 아사나식 날짜 팝업 · 날짜 버튼 — 공용(2026-10-27, erp-datepop.js). + 프로젝트 모듈 project.css 의 .pj-date-btn · .pj-datepop · .pj-dp-* 규칙을 그대로 옮긴 것(같은 모양) — 프로젝트 화면은 아직 + project.css 쪽을 쓴다(둘을 한 화면에 같이 싣지 않음). 모양을 바꾸면 두 곳 모두 고칠 것. + 아이콘은 Material Symbols(/static/vendor/material-symbols/material-symbols.css)를 화면에서 함께 싣는다. */ +.pj-date-btn { + display: inline-flex; align-items: center; gap: 6px; margin-top: 5px; height: 36px; padding: 0 12px; + border: 1px solid #d8dce2; border-radius: 8px; background: #fff; cursor: pointer; + font-size: var(--pj-text-size, 14px); font-family: inherit; font-weight: 500; color: var(--pj-ink, #050505); white-space: nowrap; line-height: var(--pj-text-leading, 1.4); +} +.pj-date-btn .material-symbols-outlined { font-size: 19px; color: #6d6e6f; } +.pj-date-btn:hover { background: #f6f7f8; border-color: #c4c9d0; } +.pj-date-btn.is-empty { color: #9aa1a9; } +.pj-date-btn.is-overdue { color: #c22b10; } +/* 날짜가 없을 때 — 테두리 없이 점선 원 달력 아이콘만(아사나) */ +.pj-date-btn.is-icon-only { + width: 32px; height: 32px; padding: 0; justify-content: center; border: none; border-radius: 50%; + background: transparent; color: #6d6e6f; +} +.pj-date-btn.is-icon-only:hover { background: #eceef0; color: #1e1f21; } + +/* ── 아사나식 날짜 팝업(openDatePopover) — 시작일/마감일 칸 + 월 달력 + 지우기. + 앵커 아래(자리 없으면 위)에 뜨고 꼬리가 앵커를 가리킨다(--pj-dp-tail). ── */ +.pj-datepop { + position: fixed; z-index: 2300; width: 300px; box-sizing: border-box; + background: #fff; border: 1px solid #e3e5e8; border-radius: 12px; + box-shadow: 0 8px 28px rgba(15,23,42,.16), 0 1px 3px rgba(15,23,42,.08); + padding: 14px 14px 8px; font-size: 13px; color: var(--pj-ink, #050505); + animation: pj-dp-in .12s ease-out; +} +@keyframes pj-dp-in { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: none; } } +.pj-datepop::before, .pj-datepop::after { + content: ""; position: absolute; left: var(--pj-dp-tail, 50%); transform: translateX(-50%); + border: 8px solid transparent; +} +/* 아래에 뜸 → 위쪽 꼬리 */ +.pj-datepop::before { bottom: 100%; border-bottom-color: #e3e5e8; } +.pj-datepop::after { bottom: calc(100% - 1px); border-bottom-color: #fff; } +/* 위에 뜸 → 아래쪽 꼬리 */ +.pj-datepop.is-above::before { bottom: auto; top: 100%; border-bottom-color: transparent; border-top-color: #e3e5e8; } +.pj-datepop.is-above::after { bottom: auto; top: calc(100% - 1px); border-bottom-color: transparent; border-top-color: #fff; } + +.pj-dp-fields { display: flex; gap: 8px; margin-bottom: 10px; } +.pj-dp-field, .pj-dp-addstart { + flex: 1 1 0; min-width: 0; height: 36px; box-sizing: border-box; + border: 1px solid #d8dce2; border-radius: 8px; padding: 0 10px; + font: inherit; font-size: 13.5px; color: var(--pj-ink, #050505); background: #fff; +} +.pj-dp-field:focus, .pj-dp-field.is-active { outline: none; border: 2px solid #4573d2; padding: 0 9px; } +.pj-dp-field::placeholder { color: #9aa1a9; } +.pj-dp-addstart { + border-color: transparent; background: transparent; cursor: pointer; font-weight: 600; color: #525860; text-align: left; +} +.pj-dp-addstart:hover { background: #f1f2f4; } + +.pj-dp-nav { display: flex; align-items: center; justify-content: space-between; margin: 2px 0 6px; } +.pj-dp-title { font-size: 14px; font-weight: 500; color: var(--pj-ink, #050505); } +.pj-dp-navbtn { + width: 28px; height: 28px; display: inline-flex; align-items: center; justify-content: center; + border: 0; background: transparent; border-radius: 6px; color: #525860; cursor: pointer; +} +.pj-dp-navbtn:hover { background: #f1f2f4; color: var(--pj-ink, #050505); } +.pj-dp-navbtn .material-symbols-outlined { font-size: 22px; } + +.pj-dp-grid { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); row-gap: 2px; } +.pj-dp-wd { text-align: center; font-size: 12px; font-weight: 600; color: #6d6e6f; padding: 4px 0 6px; } +.pj-dp-day { + position: relative; height: 34px; border: 0; padding: 0; background: transparent; cursor: pointer; + font: inherit; font-size: 13.5px; color: var(--pj-ink, #050505); + display: flex; flex-direction: column; align-items: center; justify-content: flex-start; min-width: 0; +} +/* 원(오늘·선택·마우스)은 숫자 자리(위 34px)의 가운데 — 공휴일 이름 줄이 붙어도 그대로 */ +.pj-dp-day::before { + content: ""; position: absolute; width: 30px; height: 30px; border-radius: 50%; z-index: 0; + left: 50%; top: 17px; transform: translate(-50%, -50%); +} +.pj-dp-num { height: 34px; display: flex; align-items: center; justify-content: center; flex: none; } +/* 공휴일 이름 — 숫자 밑 작은 글씨. 이 칸이 있는 주만 줄이 높아진다(다른 칸은 34px 그대로 위에 붙음). */ +.pj-dp-day.has-hol { height: 46px; } +.pj-dp-hol { + max-width: 100%; margin-top: -3px; padding: 0 1px; box-sizing: border-box; + font-size: 9px; line-height: 1.1; letter-spacing: -.5px; font-weight: 500; + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: #d93025; +} +.pj-dp-day.is-out .pj-dp-hol { color: #efaaa3; } +.pj-dp-day { z-index: 0; } +.pj-dp-day > * { position: relative; } +.pj-dp-day:hover::before { background: #f1f2f4; } +.pj-dp-day.is-out { color: #b3b8bf; } +/* 일요일·공휴일(국경일·대체공휴일) 빨강, 토요일 파랑 — 다른 달 날짜는 옅게 */ +.pj-dp-day.is-sun, .pj-dp-wd.is-sun { color: #d93025; } +.pj-dp-day.is-sat, .pj-dp-wd.is-sat { color: #1a73e8; } +.pj-dp-day.is-out.is-sun { color: #efaaa3; } +.pj-dp-day.is-out.is-sat { color: #a8c6f3; } +/* 오늘 = 파란 테두리 원 + 굵게 */ +.pj-dp-day.is-today { font-weight: 800; } +.pj-dp-day.is-today::before { border: 1.5px solid #4573d2; } +/* 선택 = 파란 원 + 흰 글자 (숫자가 원 위에 보이도록 글자는 z 위로) */ +.pj-dp-day.is-selected, .pj-dp-day.is-selected.is-sun, .pj-dp-day.is-selected.is-sat { color: #fff; font-weight: 600; } +.pj-dp-day.is-selected::before { background: #4573d2; border: 0; } +.pj-dp-day.is-inrange { background: #e8effb; } +.pj-dp-day.is-selected .pj-dp-hol { color: #d93025; font-weight: 600; } +.pj-dp-day { isolation: isolate; } +.pj-dp-day::before { z-index: -1; } + +.pj-dp-foot { + display: flex; justify-content: space-between; align-items: center; + margin-top: 8px; padding-top: 8px; border-top: 1px solid #eef0f2; +} +.pj-dp-link { + border: 0; background: transparent; cursor: pointer; font: inherit; font-size: 13px; font-weight: 600; + color: #525860; padding: 6px 8px; border-radius: 6px; +} +.pj-dp-link:hover { background: #f1f2f4; color: var(--pj-ink, #050505); } diff --git a/app/static/erp-datepop.js b/app/static/erp-datepop.js new file mode 100644 index 0000000..7596c0e --- /dev/null +++ b/app/static/erp-datepop.js @@ -0,0 +1,294 @@ +/* 아사나식 날짜 팝업 · 날짜 버튼 — 공용(2026-10-27). + 프로젝트 모듈 project.js 의 openDatePopover · enhanceDateInput 과 같은 모양·같은 동작을 다른 모듈에서 쓰려고 떼어 낸 것 + (프로젝트 화면은 아직 project.js 안의 것을 쓴다 — 동작을 바꾸면 두 곳 모두 고칠 것). 스타일 = erp-datepop.css. + · 브라우저 기본 달력(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) } */ +(function () { + "use strict"; + + function esc(s) { + return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) { + return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]; + }); + } + function isoOf(d) { + return d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0"); + } + // 오늘 = 한국시간 날짜(브라우저 시간대와 무관 — 프로젝트 isoToday 와 같음) + function isoToday() { return new Date(Date.now() + 9 * 3600000).toISOString().slice(0, 10); } + // 'YYYY-MM-DD' → 'mm/dd(요일)' — 오늘·내일·어제는 글자로(프로젝트 날짜 버튼과 같음), 다른 해면 앞에 연도 + function fmt(iso) { + if (!iso) return ""; + const d = new Date(String(iso).slice(0, 10) + "T00:00:00"); + if (isNaN(d.getTime())) return iso; + const today = isoToday(); + const diff = Math.round((d - new Date(today + "T00:00:00")) / 86400000); + if (diff === 0) return "오늘"; + if (diff === 1) return "내일"; + if (diff === -1) return "어제"; + const wd = ["일", "월", "화", "수", "목", "금", "토"][d.getDay()]; + 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; + } + function fmtField(iso) { + if (!iso) return ""; + const d = new Date(iso + "T00:00:00"); + const same = d.getFullYear() === new Date().getFullYear(); + return (same ? "" : d.getFullYear() + "년 ") + (d.getMonth() + 1) + "월 " + d.getDate() + "일"; + } + // 직접 입력 해석 — 2026-09-30 / 2026.9.30 / 9/30 / 9월 30일 / 0930. 빈 값 = "", 해석 불가 = null. + function parseTyped(text, baseIso) { + const v = String(text || "").trim().replace(/\s+/g, ""); + if (!v) return ""; + let m = v.match(/^(\d{4})[-./년](\d{1,2})[-./월](\d{1,2})[.일]?$/); + let y, mo, d; + if (m) { y = +m[1]; mo = +m[2]; d = +m[3]; } + else if ((m = v.match(/^(\d{1,2})[-./월](\d{1,2})[.일]?$/))) { y = +baseIso.slice(0, 4); mo = +m[1]; d = +m[2]; } + else if ((m = v.match(/^(\d{2})(\d{2})$/))) { y = +baseIso.slice(0, 4); mo = +m[1]; d = +m[2]; } + else return null; + const dt = new Date(y, mo - 1, d); + if (dt.getFullYear() !== y || dt.getMonth() !== mo - 1 || dt.getDate() !== d) return null; + return isoOf(dt); + } + const HOLIDAY_SHORT = { "부처님오신날": "석가탄신일", "추석·개천절": "추석" }; + + let popEl = null, cleanup = null; + function close() { + if (cleanup) cleanup(); + cleanup = null; + if (popEl) { popEl.remove(); popEl = null; } + } + + // opts: { start, due, allowStart, active("start"|"due"), labels {start, due}, holidays {iso: 이름}, clear(bool, 기본 true), + // onChange(patch {due_date, start_date?}) } — 날짜를 누를 때마다 onChange, 마감(종료)일을 고르면 닫힘. + function open(anchor, opts) { + close(); + opts = opts || {}; + const labels = Object.assign({ start: "시작일", due: "마감일" }, opts.labels || {}); + const holidays = opts.holidays || {}; + const today = isoToday(); + let start = opts.start ? String(opts.start).slice(0, 10) : ""; + let due = opts.due ? String(opts.due).slice(0, 10) : ""; + let showStart = !!(opts.allowStart && (start || opts.active === "start")); + let active = opts.allowStart && opts.active === "start" ? "start" : "due"; + const base = new Date(((active === "start" ? start : due) || start || due || today) + "T00:00:00"); + let viewY = base.getFullYear(), viewM = base.getMonth(); + + const pop = document.createElement("div"); + pop.className = "pj-datepop"; + document.body.appendChild(pop); + popEl = pop; + + function emit() { + const patch = { due_date: due || null }; + if (opts.allowStart) patch.start_date = start || null; + if (opts.onChange) opts.onChange(patch); + } + function field(kind, val) { + return ''; + } + function render() { + const first = new Date(viewY, viewM, 1); + const gridStart = new Date(viewY, viewM, 1 - first.getDay()); + let days = ""; + for (let i = 0; i < 42; i++) { + const d = new Date(gridStart.getFullYear(), gridStart.getMonth(), gridStart.getDate() + i); + const iso = isoOf(d); + const cls = ["pj-dp-day"]; + if (d.getMonth() !== viewM) cls.push("is-out"); + const holName = holidays[iso] || ""; + if (d.getDay() === 0 || holName) cls.push("is-sun"); + else if (d.getDay() === 6) cls.push("is-sat"); + if (iso === today) cls.push("is-today"); + if (iso === due || (showStart && iso === start)) cls.push("is-selected"); + if (showStart && start && due && iso > start && iso < due) cls.push("is-inrange"); + if (holName) cls.push("has-hol"); + const holShort = /\s대체$/.test(holName) ? "대체휴일" : (HOLIDAY_SHORT[holName] || holName); + days += '"; + } + pop.innerHTML = + '
' + + (opts.allowStart ? (showStart ? field("start", start) : '") : "") + + field("due", due) + + "
" + + '
' + + '' + + '' + viewY + "년 " + (viewM + 1) + "월" + + '' + + "
" + + '
' + + ["일", "월", "화", "수", "목", "금", "토"].map(function (w, i) { + return '' + w + ""; + }).join("") + days + + "
" + + '
' + + '' + + (opts.clear === false ? "" : '') + + "
"; + wire(); + } + // 시작일 칸이 활성이면 시작일(그 뒤 마감일로), 아니면 마감일(저장하고 닫음). 시작일 > 마감일이 되지 않게 맞춘다. + function pick(iso) { + if (active === "start") { + start = iso; + if (due && due < iso) due = iso; + active = "due"; + render(); emit(); focusActive(); + return; + } + due = iso; + if (start && start > iso) start = iso; + emit(); + close(); + } + function wire() { + pop.querySelectorAll(".pj-dp-day").forEach(function (b) { + b.addEventListener("click", function () { pick(b.dataset.iso); }); + }); + 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++; } + render(); + }); + }); + const add = pop.querySelector(".pj-dp-addstart"); + if (add) add.addEventListener("click", function () { showStart = true; active = "start"; render(); focusActive(); }); + pop.querySelectorAll(".pj-dp-field").forEach(function (inp) { + inp.addEventListener("focus", function () { + active = inp.dataset.kind; + pop.querySelectorAll(".pj-dp-field").forEach(function (x) { x.classList.toggle("is-active", x === inp); }); + }); + function commit() { + const kind = inp.dataset.kind; + const cur = kind === "start" ? start : due; + const parsed = parseTyped(inp.value, today); + if (parsed === null || parsed === cur) { inp.value = fmtField(cur); return; } + if (!parsed) { + if (opts.clear === false) { inp.value = fmtField(cur); return; } + if (kind === "start") { start = ""; showStart = false; } else due = ""; + render(); emit(); return; + } + active = kind; + const d = new Date(parsed + "T00:00:00"); + viewY = d.getFullYear(); viewM = d.getMonth(); + pick(parsed); + } + inp.addEventListener("keydown", function (e) { + if (e.isComposing) return; + if (e.key === "Enter") { e.preventDefault(); commit(); } + }); + inp.addEventListener("change", commit); + }); + pop.querySelector(".pj-dp-today").addEventListener("click", function () { + const d = new Date(); viewY = d.getFullYear(); viewM = d.getMonth(); + pick(today); + }); + const clr = pop.querySelector(".pj-dp-clear"); + if (clr) clr.addEventListener("click", function () { start = ""; due = ""; emit(); close(); }); + } + function focusActive() { + const f = pop.querySelector('.pj-dp-field[data-kind="' + active + '"]'); + if (f) f.focus(); + } + function place() { + const r = anchor.getBoundingClientRect(); + const vw = document.documentElement.clientWidth, vh = document.documentElement.clientHeight; + const w = pop.offsetWidth, h = pop.offsetHeight; + const ax = r.left + r.width / 2; + const left = Math.min(Math.max(8, ax - w / 2), vw - w - 8); + const below = r.bottom + 10 + h <= vh - 8 || r.top - 10 - h < 8; + pop.classList.toggle("is-above", !below); + pop.style.left = left + "px"; + pop.style.top = (below ? r.bottom + 10 : r.top - 10 - h) + "px"; + pop.style.setProperty("--pj-dp-tail", Math.min(Math.max(ax - left, 16), w - 16) + "px"); + } + function onDown(e) { + if (pop.contains(e.target) || anchor.contains(e.target)) return; + close(); + } + function onKey(e) { if (e.key === "Escape") { e.stopPropagation(); close(); } } + render(); + place(); + setTimeout(function () { + if (popEl !== pop) return; // 그 사이 닫혔으면 걸지 않는다(남은 Esc 처리가 이후 Esc 를 삼키지 않게) + document.addEventListener("mousedown", onDown, true); + document.addEventListener("keydown", onKey, true); + }, 0); + window.addEventListener("resize", close); + cleanup = function () { + document.removeEventListener("mousedown", onDown, true); + document.removeEventListener("keydown", onKey, true); + window.removeEventListener("resize", close); + }; + focusActive(); + } + + // 시작·끝 날짜 input 두 개 → 날짜 버튼 두 개(각 input 자리), 어느 쪽을 눌러도 같은 기간 팝업(누른 쪽 칸이 먼저). + // endInput 이 숨겨져 있으면(opts.single() 이 true — 예: 반차) 하루짜리 팝업으로 시작=끝을 같이 맞춘다. + // input 은 숨겨 값 저장소로 둔다 — value 쓰기를 가로채 버튼 글자도 따라 바뀌고, 고르면 input·change 이벤트를 낸다. + function enhanceRange(startInput, endInput, opts) { + opts = opts || {}; + const labels = Object.assign({ start: "시작일", due: "종료일" }, opts.labels || {}); + const desc = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value"); + const pairs = [[startInput, "start"], [endInput, "due"]].filter(function (p) { return p[0] && !p[0].dataset.erpDate; }); + const btns = {}; + pairs.forEach(function (p) { + const inp = p[0], kind = p[1]; + inp.dataset.erpDate = "1"; + inp.style.display = "none"; + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = "pj-date-btn erp-date-btn"; + btn.dataset.kind = kind; + inp.after(btn); + btns[kind] = btn; + Object.defineProperty(inp, "value", { + configurable: true, + get: function () { return desc.get.call(this); }, + set: function (v) { desc.set.call(this, v); sync(); }, + }); + btn.addEventListener("click", function (e) { + e.preventDefault(); e.stopPropagation(); + const single = !!(opts.single && opts.single()); + open(btn, { + start: single ? "" : startInput.value, due: single ? startInput.value : endInput.value, + allowStart: !single, active: single ? "due" : kind, clear: false, holidays: opts.holidays || {}, + labels: single ? { due: opts.singleLabel || "날짜" } : labels, + onChange: function (patch) { + if (single) { set(startInput, patch.due_date); set(endInput, patch.due_date); return; } + set(startInput, patch.start_date); + set(endInput, patch.due_date); + }, + }); + }); + }); + function set(inp, v) { + if (!v || (inp.value || "") === v) return; // 필수 칸 — 비우지 않는다 + inp.value = v; + inp.dispatchEvent(new Event("input", { bubbles: true })); + inp.dispatchEvent(new Event("change", { bubbles: true })); + } + function sync() { + [["start", startInput], ["due", endInput]].forEach(function (p) { + const btn = btns[p[0]]; + if (!btn) return; + const text = fmt(p[1].value); + btn.innerHTML = 'calendar_month'; + btn.querySelector(".pj-date-btn-text").textContent = text || labels[p[0]] + " 선택"; + btn.classList.toggle("is-empty", !text); + btn.title = text ? labels[p[0]] + " 변경" : labels[p[0]] + " 지정"; + }); + } + sync(); + return { sync: sync, buttons: btns }; + } + + window.ErpDatePop = { open: open, close: close, enhanceRange: enhanceRange, fmt: fmt, parse: parseTyped }; +})(); diff --git a/app/static/vacation.js b/app/static/vacation.js index 2efda5b..099bf5c 100644 --- a/app/static/vacation.js +++ b/app/static/vacation.js @@ -1,5 +1,7 @@ /* 휴가 신청 폼 — 종류에 따른 필드 토글 + 예상 일수 미리보기. - 서버(store.compute_days)가 공휴일 포함 정확히 재계산한다. 여기선 주말만 제외한 근사치. */ + 서버(store.compute_days)가 공휴일 포함 정확히 재계산한다. 여기선 주말만 제외한 근사치. + 시작일·종료일 = 프로젝트와 같은 아사나식 날짜 팝업(2026-10-27, erp-datepop.js — 숨긴 input 옆 날짜 버튼, 둘 중 어느 쪽을 눌러도 + 같은 기간 팝업, 반차는 하루짜리 팝업). 공휴일 = 휴가 설정의 공휴일(#vac-holidays). */ (function () { "use strict"; var form = document.getElementById("vac-form"); @@ -17,6 +19,20 @@ function isHalfType(t) { return t === "오전반차" || t === "오후반차"; } + // 휴가 설정의 공휴일(빨강) {날짜: 이름} — 날짜 팝업 표시 + 예상 일수에서 제외(서버 compute_days 와 같은 표) + var holidays = {}; + try { holidays = JSON.parse((document.getElementById("vac-holidays") || {}).textContent || "{}"); } catch (_) { holidays = {}; } + function isoOf(d) { + return d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0"); + } + + if (window.ErpDatePop) { + window.ErpDatePop.enhanceRange(start, end, { + labels: { start: "시작일", due: "종료일" }, holidays: holidays, singleLabel: "날짜", + single: function () { return isHalfType(type.value); }, + }); + } + function parseDate(s) { if (!s) return null; var p = s.split("-"); @@ -28,16 +44,15 @@ var n = 0; var d = new Date(sd.getTime()); while (d <= ed) { - var wd = d.getDay(); // 0=일, 6=토 - if (wd !== 0 && wd !== 6) n++; + if (isWorking(d)) n++; d.setDate(d.getDate() + 1); } return n; } function isWorking(d) { - var wd = d.getDay(); - return wd !== 0 && wd !== 6; + var wd = d.getDay(); // 0=일, 6=토 + return wd !== 0 && wd !== 6 && !holidays[isoOf(d)]; } function recalc() { @@ -50,7 +65,8 @@ startHalfField.style.display = half ? "none" : ""; if (half) { - out.textContent = "0.5"; + var hd = parseDate(start.value); + out.textContent = hd && !isWorking(hd) ? "0" : "0.5"; return; } @@ -59,7 +75,7 @@ if (!sd || !ed || ed < sd) { out.textContent = "—"; return; } if (sd.getTime() === ed.getTime()) { - out.textContent = (startHalf.value === "am" || startHalf.value === "pm") ? "0.5" : "1"; + out.textContent = !isWorking(sd) ? "0" : (startHalf.value === "am" || startHalf.value === "pm") ? "0.5" : "1"; return; } diff --git a/tests/js/render_vacation.py b/tests/js/render_vacation.py new file mode 100644 index 0000000..86b3c23 --- /dev/null +++ b/tests/js/render_vacation.py @@ -0,0 +1,36 @@ +"""휴가 신청 화면(form.html)을 진짜 ERP 셸(erp_base.html)로 렌더 — 날짜 팝업 브라우저 테스트용(2026-10-27). + + python tests/js/render_vacation.py # → tests/js/.out/vac_form.html + +DB 없이 화면 데이터만 만든다(공휴일 = 휴가 설정 공휴일 모양 {날짜: 이름}). +""" + +from __future__ import annotations + +import os +import sys + +import jinja2 + +ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +sys.path.insert(0, ROOT) +OUT_DIR = os.path.join(ROOT, "tests", "js", ".out") + +from app.modules.vacation.store import HALF_LABELS, HALVES, VACATION_TYPES # noqa: E402 + + +def main() -> None: + os.makedirs(OUT_DIR, exist_ok=True) + env = jinja2.Environment(loader=jinja2.FileSystemLoader([ + os.path.join(ROOT, "app", "templates"), os.path.join(ROOT, "app", "modules", "vacation", "templates")]), autoescape=True) + ctx = {"user": {"email": "kim@test.local", "name": "김철수", "picture": ""}, "is_admin": False, "is_approver": False, + "nav_items": [], "page_title": "휴가 신청", "page_subtitle": "", "mode": "new", "req": None, + "default_date": "2026-10-27", "vacation_types": list(VACATION_TYPES), "halves": list(HALVES), + "half_labels": HALF_LABELS, "holidays": {"2026-10-03": "개천절", "2026-10-09": "한글날", "2026-12-25": "성탄절"}} + 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) + + +if __name__ == "__main__": + main() diff --git a/tests/js/vacation_datepop.browser.test.js b/tests/js/vacation_datepop.browser.test.js new file mode 100644 index 0000000..d46ff1b --- /dev/null +++ b/tests/js/vacation_datepop.browser.test.js @@ -0,0 +1,124 @@ +// 휴가 신청 날짜 칸 = 프로젝트와 같은 아사나식 날짜 팝업(2026-10-27, erp-datepop.js) — 실제 브라우저(Chromium). +// python tests/js/render_vacation.py +// NODE_PATH= PJ_TEST_BROWSER= node tests/js/vacation_datepop.browser.test.js +// 브라우저 기본 달력 없음(숨긴 input = 값 저장소), 시작일·종료일 날짜 버튼 → 기간 팝업(누른 칸이 먼저), 날짜를 고르면 시작 → 종료로 넘어가고 +// 종료를 고르면 닫힘, 공휴일 빨강·이름, 직접 입력(Enter), 반차 = 하루짜리, 제출하면 고른 날짜가 그대로 서버로. +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: 1300, 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: "

saved

" }); } + r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: fs.readFileSync(path.join(__dirname, ".out", "vac_form.html"), "utf8") }); + }); + await p.goto("http://erp.test/vacation/new"); + await p.waitForTimeout(200); + const state = function () { + return p.evaluate(function () { + const s = document.getElementById("vac-start"), e = document.getElementById("vac-end"); + return { start: s.value, end: e.value, startShown: getComputedStyle(s).display !== "none", endShown: getComputedStyle(e).display !== "none", + btns: Array.from(document.querySelectorAll(".erp-date-btn")).map(function (b) { return b.textContent.replace("calendar_month", "").trim(); }), + want: [ErpDatePop.fmt(s.value), ErpDatePop.fmt(e.value)], + days: document.getElementById("vac-days-out").textContent, pop: !!document.querySelector(".pj-datepop") }; + }); + }; + const s0 = await state(); + // 버튼 글자 = 프로젝트 날짜 버튼과 같은 규칙(오늘·내일·어제, 아니면 mm/dd(요일)) — 오늘 날짜에 따라 달라서 같은 함수로 비교 + const fmtCheck = await p.evaluate(function () { + return [ErpDatePop.fmt("2026-10-29"), ErpDatePop.fmt("2027-01-04")]; + }); + check("기본 달력 input 숨김 · 날짜 버튼 두 개(시작·종료)", !s0.startShown && !s0.endShown && s0.btns.length === 2 && + JSON.stringify(s0.btns) === JSON.stringify(s0.want) && s0.want[0] !== "", s0); + check("날짜 글자 mm/dd(요일), 다른 해는 연도", ["10/29(목)", "오늘", "내일", "어제"].indexOf(fmtCheck[0]) >= 0 && + ["2027/01/04(월)", "01/04(월)"].indexOf(fmtCheck[1]) >= 0, fmtCheck); + // 시작일 버튼 → 기간 팝업(시작일 칸 활성) + await p.click('.erp-date-btn[data-kind="start"]'); + const pop = await p.evaluate(function () { + const el = document.querySelector(".pj-datepop"); + const f = Array.from(el.querySelectorAll(".pj-dp-field")).map(function (x) { return [x.placeholder, x.value, x.classList.contains("is-active")]; }); + const hol = el.querySelector('.pj-dp-day[data-iso="2026-10-09"]'); + return { fields: f, title: el.querySelector(".pj-dp-title").textContent, hol: hol && hol.classList.contains("is-sun") && hol.textContent, + clear: !!el.querySelector(".pj-dp-clear"), parent: el.parentElement === document.body, + sat: document.querySelector('.pj-dp-day[data-iso="2026-10-24"]').classList.contains("is-sat") }; + }); + check("시작일 버튼 → 기간 팝업(시작일·종료일 칸, 시작일 활성, body 에, 지우기 없음)", pop.parent && !pop.clear && + JSON.stringify(pop.fields) === '[["시작일","10월 27일",true],["종료일","10월 27일",false]]' && pop.title === "2026년 10월", pop); + check("공휴일 빨강 + 이름(한글날), 토요일 파랑", pop.hol === "9한글날" && pop.sat, pop); + // 시작일 10/29 → 종료일(10/27)이 더 빨라 10/29 로 맞춤, 종료일 칸으로 넘어감(팝업 그대로) + await p.click('.pj-dp-day[data-iso="2026-10-29"]'); + const s1 = await state(); + const act = await p.evaluate(function () { const a = document.querySelector(".pj-dp-field.is-active"); return a && a.dataset.kind; }); + check("시작일 고름 → 시작·종료 10/29, 팝업은 열린 채 종료일 칸으로", s1.start === "2026-10-29" && s1.end === "2026-10-29" && s1.pop && act === "due", [s1, act]); + await p.click('.pj-dp-day[data-iso="2026-11-02"]'); + await p.waitForTimeout(50); + const s2 = await state(); + check("종료일 고름 → 11/02, 팝업 닫힘, 버튼 글자·예상 일수(주말 빼고 3)", s2.end === "2026-11-02" && !s2.pop && + s2.btns[1] === s2.want[1] && s2.days === "3", s2); + // 종료일 버튼 → 종료일 칸이 먼저, 기간 칸 옅은 파랑 + await p.click('.erp-date-btn[data-kind="due"]'); + const pop2 = await p.evaluate(function () { + const a = document.querySelector(".pj-dp-field.is-active"); + return { active: a && a.dataset.kind, inrange: document.querySelectorAll(".pj-dp-day.is-inrange").length, + selected: Array.from(document.querySelectorAll(".pj-dp-day.is-selected")).map(function (b) { return b.dataset.iso; }) }; + }); + // 종료일 달(11월)이 보인다 — 11/1 이 일요일이라 10월 날짜는 이 달력에 없음: 기간 = 11/1, 선택 = 11/2 + check("종료일 버튼 → 종료일 칸 활성·종료일 달, 기간 표시", pop2.active === "due" && pop2.inrange === 1 && + JSON.stringify(pop2.selected) === '["2026-11-02"]', pop2); + // 예상 일수는 휴가 설정 공휴일도 뺀다 — 10/8~10/12 = 8·9(한글날)·10·11(주말)·12 → 2일 + await p.click('.erp-date-btn[data-kind="start"]'); + await p.fill('.pj-dp-field[data-kind="start"]', "10/8"); + await p.press('.pj-dp-field[data-kind="start"]', "Enter"); + await p.fill('.pj-dp-field[data-kind="due"]', "10/12"); + await p.press('.pj-dp-field[data-kind="due"]', "Enter"); + const sh = await state(); + check("예상 일수 = 주말·공휴일(한글날) 빼고 2", sh.start === "2026-10-08" && sh.end === "2026-10-12" && sh.days === "2", sh); + await p.click('.erp-date-btn[data-kind="due"]'); + // 직접 입력 — 종료일 칸에 11/3 Enter + await p.fill('.pj-dp-field[data-kind="due"]', "11/3"); + await p.press('.pj-dp-field[data-kind="due"]', "Enter"); + const s3 = await state(); + check("직접 입력 11/3 Enter → 종료일 11/03, 닫힘", s3.end === "2026-11-03" && !s3.pop, s3); + // Esc 로 닫기 + await p.click('.erp-date-btn[data-kind="start"]'); + await p.waitForTimeout(50); + await p.keyboard.press("Escape"); + check("Esc → 닫힘", !(await state()).pop); + // 반차 — 종료일 칸 숨김, 날짜 버튼 하나로 하루짜리 팝업(시작=종료) + await p.selectOption("#vac-type", "오전반차"); + await p.click('.erp-date-btn[data-kind="start"]'); + const half = await p.evaluate(function () { + return Array.from(document.querySelectorAll(".pj-dp-field")).map(function (x) { return x.placeholder; }); + }); + await p.click('.pj-dp-day[data-iso="2026-11-05"]'); + const s4 = await state(); + check("반차 → 날짜 칸 하나 팝업, 고르면 시작=종료=11/05, 0.5일", JSON.stringify(half) === '["날짜"]' && + s4.start === "2026-11-05" && s4.end === "2026-11-05" && !s4.pop && s4.days === "0.5", [half, s4]); + // 제출 — 고른 날짜가 그대로 폼으로 + await p.selectOption("#vac-type", "연차"); + await p.click('button[name="action"][value="submit"]'); + await p.waitForTimeout(200); + check("제출 → start_date·end_date 가 고른 날짜로 전송", posts.length === 1 && /start_date=2026-11-05/.test(posts[0]) && /end_date=2026-11-05/.test(posts[0]), posts); + } finally { + await browser.close(); + } + if (fails.length) { console.log("\n" + fails.length + " FAILED"); process.exit(1); } + console.log("\nALL PASS"); +})().catch(function (e) { console.error(e); process.exit(1); }); diff --git a/tests/test_vacation_options_mail.py b/tests/test_vacation_options_mail.py index 768ae15..bafcfda 100644 --- a/tests/test_vacation_options_mail.py +++ b/tests/test_vacation_options_mail.py @@ -197,6 +197,9 @@ 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}] st = Store() @@ -264,6 +267,15 @@ def body(c): # 관리자는 승인자 목록에 없어도 승인 who["u"] = admin assert c.post("/vacation/r1/approve").status_code == 303 and sent[-1][:2] == ("approved", "admin@test.local") + # 휴가 신청 화면 — 날짜 칸 = 공용 날짜 팝업(erp-datepop), 공휴일(빨강만) 작년~내년을 화면에 + import json, re + from app.timezone import today_kst + r = c.get("/vacation/new") + assert r.status_code == 200, r.status_code + assert "/static/erp-datepop.js" in r.text and "/static/erp-datepop.css" in r.text and "material-symbols.css" in r.text + hol = json.loads(re.search(r'', r.text, re.S).group(1)) + y = today_kst().year + assert hol == {f"{yy}-10-09": "한글날" for yy in (y - 1, y, y + 1)}, hol # Gmail 연결 — 저장소(입출고 DB)가 없으면 옵션으로 돌아와 안내 who["u"] = kim r = c.get("/vacation/gmail/connect")