feat(휴가): 협의자 결재·신청 화면 개편(라디오·붙박이 달력·결재 라인)·내 신청 내역

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-02 15:46:19 +09:00
parent f7a3afcebf
commit 97f4a904cd
22 changed files with 1200 additions and 246 deletions
+101 -11
View File
@@ -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(