diff --git a/app/modules/vacation/CLAUDE.md b/app/modules/vacation/CLAUDE.md
index cf7483f..bb1f3c1 100644
--- a/app/modules/vacation/CLAUDE.md
+++ b/app/modules/vacation/CLAUDE.md
@@ -6,11 +6,24 @@
- 월간 달력(구글식 bar) / 연차·반차 신청 / 승인 워크플로 / 옵션(승인자·통보자·잔여 연차).
- **설정 화면 없음**(2026-10-27 삭제 — [설정] 버튼·공휴일 추가/삭제 기능 포함). `GET /vacation/settings` 는 옵션으로 넘김, 공휴일 저장 주소 없음.
- 권한키 `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` → `db.holiday_map`, 작년~내년, `#vac-holidays`) — 팝업 빨강·이름 + 예상 일수에서도 뺀다(서버 compute_days 와 같은 표).
- 테스트 `tests/js/vacation_datepop.browser.test.js`(`render_vacation.py`).
+- **신청 화면**(2026-11-02, `form.html`) = 위 휴가 종류 라디오(고르면 검은 배경·흰 굵은 글씨) · 왼쪽 붙박이 달력(공용 `ErpDatePop.mountRange` — 팝업과 같은 `.pj-dp-*` 서식,
+ 첫 클릭 시작일·둘째 클릭 종료일·셋째 새로, 하루 = 동그라미, 기간 = 둥근 막대, 반차 = 클릭마다 하루) · 오른쪽 시작일·종료일(읽기 전용, 달력이 채움)·구분·예상 일수·사유 · 아래 결재 라인.
+ 하루짜리는 종료 구분을 숨기고 보내지 않는다(서버 compute_days 도 시작 구분만 씀). 시작일·종료일 숨긴 칸은 브라우저 필수 검사가 안 돼 `vacation.js` 가 제출 전 확인.
+ 공휴일 = 국경일·대체공휴일(`router._red_holidays` → `db.holiday_map`, 작년~내년, `#vac-holidays`) — 달력 빨강·이름 + 예상 일수에서도 뺀다(서버 compute_days 와 같은 표).
+ 옵션의 입사일 버튼은 그대로 `ErpDatePop.enhance`(팝업). 테스트 `tests/js/vacation_datepop.browser.test.js`(`render_vacation.py`).
+
+## 협의자 결재 (2026-11-02, 마이그레이션 `vacation_db_003_consults.sql`)
+
+- 흐름: 작성중 → (협의자 있으면) **협의중** → 모두 승인 → **제출**(결재자 승인 대기) → 승인. 협의자 한 명이 반려하면 신청도 반려(`approver_email` = 그 협의자). 수정·재제출하면 협의가 처음부터(`db.submit`).
+ 협의중에는 결재자가 승인·반려 못 함(`approve`·`reject` 가 status='제출' 만). 일수·연차 차감은 그대로 승인 때만. 마지막 두 명 동시 처리는 `decide_consult` 가 신청 줄을 잠가 막음.
+- 표 `vacation_consults`(신청 삭제 시 CASCADE) — 이메일·이름·협의 내용·상태 대기|승인|반려·반려 사유·처리 시각. 003 전이면 `consults_ready()` False → 협의자 칸 잠김, 예전처럼 제출.
+- 신청 화면: [구성원 선택] = **ERP 등록 구성원 전체**(`router._people`, 휴가 권한 무관, 본인 제외) 아이콘 + 이름, 복수. 고른 사람마다 협의 내용 칸(`consult_email`·`consult_message` 같은 순서 — 빈 내용도 자리 유지).
+ [협의자 없음] 체크 = 칸 잠김·전송 안 함. 제출인데 둘 다 없으면 400(작성중 저장은 통과). 통보자·결재자 = 옵션 값, 아이콘 + 이름 표시만.
+- 메일(`notify.py`): 제출 = 협의자마다 따로 한 통(자기 내용만, `consult_request`) + 결재자·통보자(전체 협의자·내용). 모두 승인 = `consulted`(결재자·통보자·신청자). 협의 반려 = `rejected`. 한 명 승인만으로는 메일 없음.
+- 화면: 달력 위 [내 신청 내역] `/vacation/mine`(협의자별 상태 → 결재 상태), [협의 대기 N] → `/vacation/pending#consults`(이 화면은 이제 누구나, 승인 대기 표는 결재자만, 표에 협의 내용).
+ 상세 = 결재 진행·협의자별 내용·협의 승인/반려. **보기 권한**: 신청자·결재자·통보자 = 전체, 협의자 = 자기 줄만(서버가 거름, 메일 기록도 안 보임).
+- **휴가 권한 없는 협의자**: 사이드바에 휴가 메뉴가 없어 메일 링크로 상세(`_guard(consult_of=…)`)에 들어와 처리한다. 달력·내역·대기 화면은 권한이 있어야 함.
+- 테스트 `tests/test_vacation_options_mail.py`(메일 내용·폼·권한), `tests/test_vacation_db.py`(실제 PG 흐름).
## 공휴일 · 연차 (2026-10-27)
diff --git a/app/modules/vacation/db.py b/app/modules/vacation/db.py
index 2a88d47..2eaa9b8 100644
--- a/app/modules/vacation/db.py
+++ b/app/modules/vacation/db.py
@@ -337,15 +337,96 @@ class VacationDBStore:
).fetchone()
return self._req_serialize(row) if row else None
+ # ── 협의자(마이그레이션 003, 2026-11-02) — 테이블이 없으면 협의자 없음 ──
+ def consults_ready(self) -> bool:
+ with self._pool.connection() as conn:
+ row = conn.execute("SELECT to_regclass('public.vacation_consults') AS r").fetchone()
+ return bool(row and row["r"])
+
+ @staticmethod
+ def _consult_serialize(row: dict[str, Any]) -> dict[str, Any]:
+ out = dict(row)
+ if isinstance(out.get("decided_at"), datetime):
+ out["decided_at"] = out["decided_at"].astimezone(KST).isoformat(timespec="seconds")
+ return out
+
+ def consults_for(self, request_ids: list[str]) -> dict[str, list[dict[str, Any]]]:
+ """{신청 id: [협의자…]} — 지정한 순서대로."""
+ if not request_ids or not self.consults_ready():
+ return {}
+ with self._pool.connection() as conn:
+ rows = conn.execute("SELECT * FROM vacation_consults WHERE request_id = ANY(%s) ORDER BY id",
+ (list(request_ids),)).fetchall()
+ out: dict[str, list[dict[str, Any]]] = {}
+ for r in rows:
+ out.setdefault(r["request_id"], []).append(self._consult_serialize(r))
+ return out
+
+ def list_consults(self, *, request_id: str) -> list[dict[str, Any]]:
+ return self.consults_for([request_id]).get(request_id, [])
+
+ def my_consults(self, *, email: str) -> list[dict[str, Any]]:
+ """내 협의 차례인 신청(협의중 + 내 줄 대기) — 시작일 순, 줄마다 my_message."""
+ if not self.consults_ready():
+ return []
+ with self._pool.connection() as conn:
+ rows = conn.execute(
+ "SELECT r.*, c.message AS my_message FROM vacation_consults c JOIN vacation_requests r ON r.id = c.request_id "
+ "WHERE c.email = %s AND c.state = '대기' AND r.status = '협의중' ORDER BY r.start_date, r.created_at",
+ (email.lower().strip(),)).fetchall()
+ return [self._req_serialize(r) for r in rows]
+
+ @staticmethod
+ def _replace_consults(conn: Any, request_id: str, consults: list[dict[str, Any]]) -> None:
+ conn.execute("DELETE FROM vacation_consults WHERE request_id = %s", (request_id,))
+ for c in consults:
+ conn.execute("INSERT INTO vacation_consults (request_id, email, name, message) VALUES (%s, %s, %s, %s)",
+ (request_id, c["email"], c.get("name") or "", c.get("message") or ""))
+
+ def decide_consult(self, *, request_id: str, email: str, approve: bool, reason: str = "") -> tuple[dict[str, Any], str | None]:
+ """협의자 한 명의 승인·반려. 반환 (신청, 알릴 일): 모두 승인 → 제출로 넘어감("consulted"), 반려 → 신청도 반려("rejected"),
+ 아직 남은 협의자가 있으면 None. 신청 줄을 잠가 마지막 두 명이 동시에 눌러도 한 번만 넘어간다."""
+ email = email.lower().strip()
+ reason = (reason or "").strip()
+ if not approve and not reason:
+ raise ValueError("반려 사유는 필수입니다.")
+ with self._pool.connection() as conn, conn.transaction():
+ head = conn.execute("SELECT status FROM vacation_requests WHERE id = %s FOR UPDATE", (request_id,)).fetchone()
+ if not head:
+ raise KeyError(request_id)
+ mine = conn.execute("SELECT state FROM vacation_consults WHERE request_id = %s AND email = %s",
+ (request_id, email)).fetchone()
+ if not mine:
+ raise PermissionError("이 신청의 협의자만 처리할 수 있습니다.")
+ if head["status"] != "협의중" or mine["state"] != "대기":
+ raise ValueError("협의 대기 중이 아닙니다(이미 처리됨).")
+ conn.execute("UPDATE vacation_consults SET state = %s, comment = %s, decided_at = now() WHERE request_id = %s AND email = %s",
+ ("승인" if approve else "반려", reason, request_id, email))
+ event: str | None = None
+ if not approve:
+ event = "rejected"
+ row = conn.execute("UPDATE vacation_requests SET status = '반려', approver_email = %s, decided_at = now(), "
+ "reject_reason = %s WHERE id = %s RETURNING *", (email, reason, request_id)).fetchone()
+ elif conn.execute("SELECT 1 FROM vacation_consults WHERE request_id = %s AND state <> '승인' LIMIT 1", (request_id,)).fetchone():
+ row = conn.execute("SELECT * FROM vacation_requests WHERE id = %s", (request_id,)).fetchone()
+ else:
+ event = "consulted"
+ row = conn.execute("UPDATE vacation_requests SET status = '제출' WHERE id = %s RETURNING *", (request_id,)).fetchone()
+ return self._req_serialize(row), event
+
def create_request(
- self, *, owner: str, owner_name: str, payload: dict[str, Any], status: str = "작성중"
+ self, *, owner: str, owner_name: str, payload: dict[str, Any], status: str = "작성중",
+ consults: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
+ """consults = [{email, name, message}] — 제출이면서 협의자가 있으면 협의중으로 시작."""
h = self._normalize_payload(payload)
if status not in STATUSES:
status = "작성중"
+ if status == "제출" and consults:
+ status = "협의중"
days = self._calc_days(h)
req_id = uuid.uuid4().hex[:12]
- with self._pool.connection() as conn:
+ with self._pool.connection() as conn, conn.transaction():
row = conn.execute(
"""
INSERT INTO vacation_requests
@@ -368,12 +449,14 @@ class VacationDBStore:
status,
),
).fetchone()
+ if consults:
+ self._replace_consults(conn, req_id, consults)
return self._req_serialize(row)
def update_request(
- self, *, request_id: str, owner: str, payload: dict[str, Any]
+ self, *, request_id: str, owner: str, payload: dict[str, Any], consults: list[dict[str, Any]] | None = None
) -> dict[str, Any]:
- """작성중/반려 상태에서만 본인이 수정 가능."""
+ """작성중/반려 상태에서만 본인이 수정 가능. consults 를 넘기면 협의자를 그 목록으로 바꾼다(003 전이면 None)."""
owner = owner.lower().strip()
current = self.get_request(request_id=request_id)
if not current:
@@ -384,7 +467,7 @@ class VacationDBStore:
raise ValueError(f"{current['status']} 상태에서는 수정할 수 없습니다.")
h = self._normalize_payload(payload)
days = self._calc_days(h)
- with self._pool.connection() as conn:
+ with self._pool.connection() as conn, conn.transaction():
row = conn.execute(
"""
UPDATE vacation_requests
@@ -407,25 +490,32 @@ class VacationDBStore:
owner,
),
).fetchone()
+ if row and consults is not None:
+ self._replace_consults(conn, request_id, consults)
if not row:
raise KeyError(request_id)
return self._req_serialize(row)
# ── 워크플로 ──
def submit(self, *, request_id: str, owner: str) -> dict[str, Any]:
- """작성중/반려 → 제출 (본인)."""
+ """작성중/반려 → 제출(본인). 협의자가 있으면 협의중으로, 다시 제출하면 협의도 처음부터."""
owner = owner.lower().strip()
- with self._pool.connection() as conn:
+ ready = self.consults_ready() # 트랜잭션 전에 — 안에서 두 번째 연결을 잡지 않게
+ with self._pool.connection() as conn, conn.transaction():
+ has = ready and conn.execute("SELECT 1 FROM vacation_consults WHERE request_id = %s LIMIT 1", (request_id,)).fetchone()
row = conn.execute(
"""
UPDATE vacation_requests
- SET status = '제출', reject_reason = '',
+ SET status = %s, reject_reason = '',
approver_email = NULL, decided_at = NULL
WHERE id = %s AND owner = %s AND status IN ('작성중', '반려')
RETURNING *
""",
- (request_id, owner),
+ ("협의중" if has else "제출", request_id, owner),
).fetchone()
+ if row and has:
+ conn.execute("UPDATE vacation_consults SET state = '대기', comment = '', decided_at = NULL WHERE request_id = %s",
+ (request_id,))
if not row:
raise ValueError("작성중/반려 상태에서만 제출할 수 있습니다.")
return self._req_serialize(row)
@@ -487,7 +577,7 @@ class VacationDBStore:
"""완전 삭제.
- 관리자(is_admin): 모든 상태 삭제 가능.
- - 일반 사용자: 본인 + 승인 전(작성중/제출/반려)만. 승인/취소 건은 불가.
+ - 일반 사용자: 본인 + 승인 전(작성중/협의중/제출/반려)만. 승인/취소 건은 불가.
"""
user_email = user_email.lower().strip()
current = self.get_request(request_id=request_id)
@@ -496,7 +586,7 @@ class VacationDBStore:
if not is_admin:
if current["owner"] != user_email:
raise PermissionError("본인 신청만 삭제할 수 있습니다.")
- if current["status"] not in ("작성중", "제출", "반려"):
+ if current["status"] not in ("작성중", "협의중", "제출", "반려"):
raise ValueError("승인/취소된 휴가는 삭제할 수 없습니다. (관리자 문의)")
with self._pool.connection() as conn:
cur = conn.execute(
diff --git a/app/modules/vacation/notify.py b/app/modules/vacation/notify.py
index 49fa0f6..06b473e 100644
--- a/app/modules/vacation/notify.py
+++ b/app/modules/vacation/notify.py
@@ -4,7 +4,9 @@
제출 = 승인자 + 승인 통보자
승인 = 승인자 + 승인 통보자 + 신청자
반려 = 승인자 + 승인 통보자 + 신청자
+ 협의 완료(협의자 모두 승인) = 승인자 + 승인 통보자 + 신청자
승인자 = 휴가 옵션의 승인자(없으면 vacation_approver 권한자 — ERP 관리자는 자동으로 넣지 않는다).
+협의자(2026-11-02)가 있으면 제출 때 협의자마다 따로 한 통 — 자기 협의 내용만. 그 밖의 메일은 협의자 전체와 협의 내용을 싣는다.
보내는 사람 = 그 일을 한 사람(제출 = 신청자, 승인·반려 = 처리한 승인자)의 **본인 Gmail** — 입출고 발주 메일과 같은
Gmail 연결(inout_db `inout_gmail_tokens`, gmail.send 만, 사람마다 한 번 연결). 연결이 없거나 끊겼거나 Gmail 이 실패하면
회사 알림 메일(SMTP, app/mail.py)로 보내고 보낸 사람 이름·답장 주소를 그 사람으로 한다.
@@ -22,13 +24,16 @@ from .store import HALF_LABELS
logger = logging.getLogger("app.vacation.notify")
-EVENTS = ("submitted", "approved", "rejected")
-EVENT_WORD = {"submitted": "제출", "approved": "승인", "rejected": "반려"}
+EVENTS = ("submitted", "approved", "rejected", "consulted")
+EVENT_WORD = {"submitted": "제출", "approved": "승인", "rejected": "반려", "consult_request": "협의 요청", "consulted": "협의 완료"}
EVENT_LEAD = {
"submitted": "휴가 신청이 제출되었습니다. 확인 후 승인해 주세요.",
"approved": "휴가가 승인되었습니다.",
"rejected": "휴가가 반려되었습니다.",
+ "consult_request": "휴가 협의 요청이 왔습니다. 내용을 확인하고 ERP 휴가 메뉴에서 협의 결재를 진행해 주세요.",
+ "consulted": "협의가 모두 끝났습니다. 확인 후 승인해 주세요.",
}
+LEAD_WITH_CONSULTS = "휴가 신청이 제출되었습니다. 협의자가 모두 승인하면 결재할 수 있습니다."
_WEEKDAYS = "월화수목금토일"
@@ -55,7 +60,7 @@ def approver_emails(options: dict[str, Any], users: list[dict[str, Any]]) -> lis
def recipients(event: str, req: dict[str, Any], options: dict[str, Any], users: list[dict[str, Any]]) -> list[str]:
people = approver_emails(options, users) + _uniq(options.get("notifiers") or [])
- if event in ("approved", "rejected"):
+ if event in ("approved", "rejected", "consulted"):
people.append(req.get("owner") or "")
return _uniq(people)
@@ -87,29 +92,39 @@ def _days(v: Any) -> str:
def build(event: str, req: dict[str, Any], *, actor_name: str, actor_email: str, link: str,
- name_of: Any = None) -> dict[str, str]:
- """제목·글·HTML. 사용자 글(사유·반려 사유·이름)은 HTML 에서 늘 escape."""
+ name_of: Any = None, consult: dict[str, Any] | None = None) -> dict[str, str]:
+ """제목·글·HTML. 사용자 글(사유·반려 사유·이름)은 HTML 에서 늘 escape.
+ 협의 요청(consult_request)은 받는 협의자 한 명 몫(consult)만, 나머지 메일은 협의자 전체(req["consults"])와 협의 내용을 싣는다."""
name_of = name_of or (lambda e: e)
owner = req.get("owner_name") or name_of(req.get("owner") or "")
word = EVENT_WORD[event]
+ consults = req.get("consults") or []
subject = f"[휴가 {word}] {owner} · {req.get('vacation_type', '')} {period_text(req)} ({_days(req.get('days'))}일)"
rows = [("신청자", f"{owner} ({req.get('owner', '')})"), ("종류", req.get("vacation_type") or ""),
("기간", period_text(req)), ("일수", f"{_days(req.get('days'))}일"), ("사유", req.get("reason") or "-")]
- if event == "submitted":
- rows.append(("상태", "제출 — 승인 대기"))
+ if event == "consult_request":
+ rows += [("상태", "협의 대기"), ("협의 내용", (consult or {}).get("message") or "-")]
+ elif event == "consulted":
+ rows.append(("상태", "협의 완료 — 승인 대기"))
+ elif event == "submitted":
+ rows.append(("상태", "협의 진행 중" if consults else "제출 — 승인 대기"))
else:
rows.append(("상태", word))
rows.append((f"{word}자", f"{actor_name} ({actor_email})"))
if event == "rejected":
rows.append(("반려 사유", req.get("reject_reason") or "-"))
- text = "\n".join([EVENT_LEAD[event], ""] + [f"{k}: {v}" for k, v in rows] + ["", f"휴가 신청 보기: {link}"])
+ if event != "consult_request":
+ rows += [(f"협의자 {c.get('name') or name_of(c.get('email') or '')}",
+ f"{c.get('state') or '대기'} — {c.get('message') or '협의 내용 없음'}") for c in consults]
+ lead = LEAD_WITH_CONSULTS if event == "submitted" and consults else EVENT_LEAD[event]
+ text = "\n".join([lead, ""] + [f"{k}: {v}" for k, v in rows] + ["", f"휴가 신청 보기: {link}"])
tr = "".join(
f'
'
f'{escape(k)}
{escape(str(v))}
' for k, v in rows)
- color = {"submitted": "#1a56db", "approved": "#0f8a3a", "rejected": "#c22b10"}[event]
+ color = {"approved": "#0f8a3a", "rejected": "#c22b10"}.get(event, "#1a56db")
html = (
'
{% for p in line.notifiers %}{{ vm.person(p) }}{% else %}없음{% endfor %}
+
+
+ 결재자
+
{% for p in line.approvers %}{{ vm.person(p) }}{% else %}ERP 관리자{% endfor %}
+
+
+
+ {% if can_consult %}
+
+
+
+
+ {% endif %}
+
{% if is_approver and req.status == '제출' %}
@@ -91,7 +128,7 @@
{% endif %}
- {% if req.status in ('작성중', '제출', '반려') and (is_owner or is_admin) %}
+ {% if req.status in ('작성중', '협의중', '제출', '반려') and (is_owner or is_admin) %}