"""프로젝트 관리(아사나식) 모듈 라우터. - 경로: /project - 권한: · 모듈 진입: 로그인한 회사 직원 전원(도메인 게이트는 OAuth 단에서 처리). · 프로젝트 생성/삭제·사용자 배정: ERP 관리자(is_admin) 전용. · 서브프로젝트/업무/단계 관리: 해당 프로젝트 멤버(또는 owner) 또는 관리자. - 데이터: ProjectStore (project_db / PostgreSQL) 전용. PROJECT_DB_URL 미설정 시 store 가 None 이며, 각 페이지는 "설정 필요" 안내. - 메일: 업무가 직원에게 '배정'되거나 '완료'되면 관리자에게 알림(BackgroundTasks). 뷰: 메인은 달력(FullCalendar)/타임라인(vis-timeline) 토글. 추가로 보드(칸반)·리스트. """ from __future__ import annotations import calendar as _calendar import logging import uuid from datetime import date from pathlib import Path from typing import Any from fastapi import ( APIRouter, BackgroundTasks, Body, Depends, File, Form, HTTPException, Request, UploadFile, ) from fastapi.responses import ( FileResponse, HTMLResponse, JSONResponse, RedirectResponse, ) from app.timezone import today_kst from . import store # 첨부 업로드 제한 _MAX_ATTACH_BYTES = 20 * 1024 * 1024 # 20MB logger = logging.getLogger("project.router") router = APIRouter(prefix="/project", tags=["project"]) # ──────────────────────────────────────────────────────────── # 공용 헬퍼 # ──────────────────────────────────────────────────────────── def _store(request: Request) -> Any: return getattr(request.app.state, "project_store", None) def _require_user(request: Request) -> dict[str, Any]: from app.main import get_current_user_record # noqa: WPS433 from app.store import has_module # noqa: WPS433 user = get_current_user_record(request) if user is None: raise HTTPException(status_code=401, detail="로그인이 필요합니다.") if not has_module(user, "project"): raise HTTPException(status_code=403, detail="프로젝트 관리 모듈 권한이 없습니다.") return user def _require_admin(request: Request) -> dict[str, Any]: from app.store import is_admin # noqa: WPS433 user = _require_user(request) if not is_admin(user): raise HTTPException(status_code=403, detail="관리자만 할 수 있는 작업입니다.") return user def _can_manage(request: Request, st: Any, user: dict[str, Any], project_id: int) -> bool: """프로젝트 단위 관리 권한: 관리자이거나 멤버/owner.""" from app.store import is_admin # noqa: WPS433 if is_admin(user): return True return bool(st.is_member(project_id=project_id, user_email=user["email"])) def _require_manage(request: Request, st: Any, user: dict[str, Any], project_id: int) -> None: if not _can_manage(request, st, user, project_id): raise HTTPException(status_code=403, detail="이 프로젝트에 대한 권한이 없습니다.") def _can_delete(user: dict[str, Any], created_by: str | None) -> bool: """삭제는 '만든 사람'만. 슈퍼관리자는 예외 허용. 생성자 정보가 없는 과거 데이터는 관리자에게 허용(잠김 방지).""" from app.store import SUPER_ADMIN_EMAIL, is_admin # noqa: WPS433 me = store.norm_str(user.get("email", ""), lower=True) cb = store.norm_str(created_by or "", lower=True) if me == SUPER_ADMIN_EMAIL: return True if not cb: return is_admin(user) return me == cb _DELETE_DENIED = "삭제는 만든 사람만 할 수 있습니다." def _admin_emails(request: Request) -> list[str]: """알림 수신 관리자 이메일 목록. PROJECT_NOTIFY_EMAIL(쉼표구분)이 있으면 우선, 없으면 user_store 의 admin 전원. """ import os override = (os.getenv("PROJECT_NOTIFY_EMAIL", "") or "").strip() if override: return [e.strip() for e in override.split(",") if e.strip()] from app.main import user_store # noqa: WPS433 from app.store import is_admin # noqa: WPS433 return [u["email"] for u in user_store.list_all() if is_admin(u)] def _notify( bg: BackgroundTasks, request: Request, *, subject: str, body: str ) -> None: """관리자에게 백그라운드 메일 발송 예약. 수신자 없거나 SMTP 미설정 시 조용히 skip.""" from app.mail import send_email # noqa: WPS433 recipients = _admin_emails(request) if not recipients: return bg.add_task(send_email, to=recipients, subject=subject, body=body) def _task_recipients( st: Any, project: dict[str, Any], task: dict[str, Any], *, exclude: str = "" ) -> list[str]: """업무 관련 인앱 알림 수신자 = 담당자 + 프로젝트 owner + 멤버 (행위자 제외).""" emails: set[str] = set() if task.get("assignee_email"): emails.add(store.norm_str(task["assignee_email"], lower=True)) if project.get("owner_email"): emails.add(store.norm_str(project["owner_email"], lower=True)) try: for m in st.list_members(project_id=project["id"]): emails.add(store.norm_str(m["user_email"], lower=True)) except Exception: # noqa: BLE001 pass emails.discard(store.norm_str(exclude, lower=True)) return [e for e in emails if e] def _inbox( st: Any, *, recipients: list[str], actor: str, project_id: int | None, task_id: int | None, ntype: str, title: str, body: str = "", ) -> None: """인앱 알림(알림센터) 생성. 실패해도 본 작업을 막지 않는다.""" for r in recipients: try: st.add_notification( recipient_email=r, actor_email=actor, project_id=project_id, task_id=task_id, type=ntype, title=title, body=body, ) except Exception: # noqa: BLE001 logger.warning("알림 생성 실패: %s", r) def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLResponse: from app.main import build_erp_nav, render_template # noqa: WPS433 from app.store import is_admin # noqa: WPS433 return render_template( request, "denied.html", { "reason": "프로젝트 관리 모듈이 아직 설정되지 않았습니다. " "PROJECT_DB_URL 환경변수를 설정하고 " "scripts/sql/project_db_init.sql 로 project_db 를 초기화한 뒤 " "컨테이너를 재기동하세요.", "user": user, "is_admin": is_admin(user), "nav_items": build_erp_nav(user, active="project"), }, status_code=503, ) _WEEKDAYS_KR = ["월", "화", "수", "목", "금", "토", "일"] def _fmt_date_kr(d: str | None) -> str: """'YYYY-MM-DD' → 'mm/dd(요일)'. 형식이 아니면 원본 그대로.""" if not d: return "" try: dd = date.fromisoformat(d[:10]) except (ValueError, TypeError): return d return dd.strftime("%m/%d") + f"({_WEEKDAYS_KR[dd.weekday()]})" def _build_tree(projects: list[dict[str, Any]]) -> list[dict[str, Any]]: """평면 프로젝트 목록 → parent_id 기준 트리(children 키).""" by_id: dict[int, dict[str, Any]] = {} roots: list[dict[str, Any]] = [] for p in projects: p = {**p, "children": []} by_id[p["id"]] = p for p in by_id.values(): parent_id = p.get("parent_id") if parent_id and parent_id in by_id: by_id[parent_id]["children"].append(p) else: roots.append(p) return roots # ──────────────────────────────────────────────────────────── # 월간 달력 레이아웃 (휴가 모듈과 동일한 구글식 bar 레인 배치) # ──────────────────────────────────────────────────────────── def _assign_lanes(bars: list[dict[str, Any]]) -> int: """주(week) 내 bar 들에 겹치지 않는 lane(행)을 그리디 배정. 사용 lane 수 반환.""" bars.sort(key=lambda b: (b["start_col"], -b["span"])) lane_end: list[int] = [] # lane 별 마지막 점유 col(포함) for b in bars: placed = False for li, end_col in enumerate(lane_end): if b["start_col"] > end_col: b["lane"] = li lane_end[li] = b["start_col"] + b["span"] - 1 placed = True break if not placed: b["lane"] = len(lane_end) lane_end.append(b["start_col"] + b["span"] - 1) return len(lane_end) def _task_span(task: dict[str, Any]) -> tuple[date, date] | None: """업무의 달력 표시 기간(start..due). 둘 중 하나만 있으면 단일일. 없으면 None.""" s = task.get("start_date") d = task.get("due_date") try: sd = date.fromisoformat(s[:10]) if s else None dd = date.fromisoformat(d[:10]) if d else None except (ValueError, TypeError): return None if sd and dd: return (sd, dd) if sd <= dd else (dd, sd) if sd: return (sd, sd) if dd: return (dd, dd) return None def _build_task_calendar( tasks: list[dict[str, Any]], year: int, month: int ) -> list[dict[str, Any]]: """업무 리스트 → 월간 달력 주(week) 데이터(휴가 _build_calendar 와 동일 구조).""" cal = _calendar.Calendar(firstweekday=6) # 일요일 시작 weeks_dates = cal.monthdatescalendar(year, month) today = today_kst() spans: list[tuple[date, date, dict[str, Any]]] = [] for t in tasks: sp = _task_span(t) if sp: spans.append((sp[0], sp[1], t)) weeks: list[dict[str, Any]] = [] for week in weeks_dates: w_start, w_end = week[0], week[-1] days = [ { "date": d.isoformat(), "day": d.day, "in_month": d.month == month, "is_today": d == today, "is_sunday": d.weekday() == 6, "is_saturday": d.weekday() == 5, "holiday_name": store.holiday_name(d.isoformat()), } for d in week ] bars: list[dict[str, Any]] = [] for rs, re_, t in spans: if re_ < w_start or rs > w_end: continue seg_start = max(rs, w_start) seg_end = min(re_, w_end) # bar 라벨: [프로젝트명] 제목 · 담당자(아이디) assignee = (t.get("assignee_email") or "").split("@")[0] proj = t.get("project_name") or "" parts = [] if proj: parts.append(f"[{proj}]") parts.append(t["title"]) if assignee: parts.append(f"· {assignee}") bars.append( { "id": t["id"], "label": " ".join(parts), "color": t.get("project_color") or "#4573d2", "completed": bool(t.get("completed_at")), "start_col": (seg_start - w_start).days, "span": (seg_end - seg_start).days + 1, "continues_left": rs < w_start, "continues_right": re_ > w_end, } ) lane_count = _assign_lanes(bars) weeks.append({"days": days, "bars": bars, "lane_count": lane_count}) return weeks # ──────────────────────────────────────────────────────────── # 페이지 # ──────────────────────────────────────────────────────────── @router.get("/health") async def health(request: Request) -> JSONResponse: st = _store(request) if st is None: return JSONResponse({"status": "not_configured"}, status_code=503) try: st.list_projects(include_archived=False) return JSONResponse({"status": "ok"}) except Exception as exc: # noqa: BLE001 return JSONResponse({"status": "error", "detail": str(exc)}, status_code=500) @router.get("/api/live-version") async def api_live_version(request: Request) -> JSONResponse: """프로젝트/업무/댓글/멤버/단계 중 가장 최근 변경 시각. 페이지를 열어둔 클라이언트가 주기적으로 조회해 값이 바뀌면 새로고침한다 (다른 사용자가 프로젝트·업무·댓글을 추가/수정했을 때 실시간 반영용). """ _require_user(request) st = _db_or_503(request) return JSONResponse({"ts": st.latest_version()}) @router.get("/", response_class=HTMLResponse) async def index(request: Request) -> HTMLResponse: from app.main import build_erp_nav, render_template # noqa: WPS433 from app.store import is_admin # noqa: WPS433 user = _require_user(request) st = _store(request) if st is None: return _render_config_needed(request, user) admin = is_admin(user) projects = st.list_projects( include_archived=False, member_email=None if admin else user["email"], ) tree = _build_tree(projects) # 진행중/완료 프로젝트를 구분해 별도 섹션으로 표시. active_projects = [p for p in tree if p.get("status") != "completed"] done_projects = [p for p in tree if p.get("status") == "completed"] # 아바타 맵: 이메일(소문자) → 구글 프로필 이미지 URL (홈 카드 업무 담당자 표시용) from app.main import user_store # noqa: WPS433 avatars = { store.norm_str(u["email"], lower=True): u.get("picture") or "" for u in user_store.list_all() if u.get("picture") } # 프로젝트 카드에 업무 미리보기(담당자·마감일·진행률) 붙이기 — 한눈에 현황 파악용. # 완료 업무도 취소선으로 계속 보이도록 목록에 포함하되, 미완료를 먼저 보여준다. today_iso = today_kst().isoformat() for p in tree: p_tasks = st.list_tasks(project_id=p["id"], include_subprojects=True, limit=500) total = len(p_tasks) open_tasks = [t for t in p_tasks if not t.get("completed_at")] done_tasks = [t for t in p_tasks if t.get("completed_at")] open_tasks.sort(key=lambda t: (t.get("due_date") is None, t.get("due_date") or "", t["id"])) done_tasks.sort(key=lambda t: t.get("completed_at") or "", reverse=True) ordered_tasks = open_tasks + done_tasks for t in ordered_tasks: t["assignee_display"] = ( t.get("assignee_name") or (t["assignee_email"].split("@")[0] if t.get("assignee_email") else "") ) d = t.get("due_date") t["due_overdue"] = bool(d and d[:10] < today_iso and not t.get("completed_at")) t["due_label"] = _fmt_date_kr(d) p["task_total"] = total p["task_done"] = len(done_tasks) p["task_percent"] = round(len(done_tasks) * 100 / total) if total else 0 p["task_preview"] = ordered_tasks[:8] p["task_more"] = max(0, len(ordered_tasks) - 8) p["due_label"] = _fmt_date_kr(p.get("due_date")) # 프로젝트 이름 아래 표시할 멤버(아이콘+이름) + 업무추가 버튼 노출 권한 # (관리자 또는 해당 프로젝트 멤버/owner). p_members = st.list_members(project_id=p["id"]) p["members"] = [ { "email": m["user_email"], "name": m.get("user_name") or m["user_email"].split("@")[0], "avatar": avatars.get(store.norm_str(m["user_email"], lower=True), ""), } for m in p_members ] member_emails = {store.norm_str(m["user_email"], lower=True) for m in p_members} p["can_add_task"] = ( admin or store.norm_str(user["email"], lower=True) in member_emails or store.norm_str(p.get("owner_email"), lower=True) == store.norm_str(user["email"], lower=True) ) # 세션이 하나도 없으면 업무를 넣을 곳이 없다 — "업무 추가" 버튼 비활성화용. p["has_stages"] = bool(st.list_stages(project_id=p["id"])) my_tasks = st.list_tasks(assignee_email=user["email"], limit=500) for t in my_tasks: t["start_label"] = _fmt_date_kr(t.get("start_date")) t["due_label"] = _fmt_date_kr(t.get("due_date")) # 내 업무를 프로젝트별로 묶어 트리로 표시 my_groups: dict[int, dict[str, Any]] = {} for t in my_tasks: pid = t.get("project_id") g = my_groups.get(pid) if g is None: g = { "id": pid, "name": t.get("project_name") or "프로젝트", "color": t.get("project_color") or "#4573d2", "tasks": [], } my_groups[pid] = g g["tasks"].append(t) my_projects = list(my_groups.values()) # 홈 화면 카드/내업무에 노출된 업무 전체(id→업무) — 클릭 시 페이지 이동 없이 # 팝업으로 편집하기 위해 필요한 원본 데이터를 그대로 클라이언트에 넘긴다. home_tasks: dict[str, Any] = {} for p in tree: for t in p.get("task_preview", []): home_tasks[str(t["id"])] = t for t in my_tasks: home_tasks[str(t["id"])] = t return render_template( request, "project/index.html", { "user": user, "is_admin": admin, "nav_items": build_erp_nav(user, active="project"), "page_title": "프로젝트 관리", "page_subtitle": "달력·타임라인·보드로 프로젝트를 관리하세요.", "force_sidebar_collapsed": True, "active_projects": active_projects, "done_projects": done_projects, "my_projects": my_projects, "avatars": avatars, "home_tasks": home_tasks, "today": today_kst().isoformat(), }, ) @router.get("/p/{project_id}", response_class=HTMLResponse) async def project_page(request: Request, project_id: int) -> HTMLResponse: from app.main import build_erp_nav, render_template # noqa: WPS433 from app.store import is_admin # noqa: WPS433 user = _require_user(request) st = _store(request) if st is None: return _render_config_needed(request, user) project = st.get_project(project_id=project_id) if project is None: raise HTTPException(status_code=404, detail="프로젝트를 찾을 수 없습니다.") admin = is_admin(user) all_projects = st.list_projects( include_archived=False, member_email=None if admin else user["email"], ) stages = st.list_stages(project_id=project_id) tasks = st.list_tasks(project_id=project_id, limit=2000) members = st.list_members(project_id=project_id) can_manage = _can_manage(request, st, user, project_id) # 좌측 트리 + 전체 집계: 4개 뷰(달력/타임라인/보드/리스트)는 '전체 프로젝트'를 보여준다. # all_tasks : 접근 가능한 모든 프로젝트의 업무(뷰 데이터) # stages_by_project : 프로젝트별 단계(보드 이름→단계 매핑 + 모달 단계 선택용) # projects_meta : 프로젝트 메타(타임라인 그룹/보드 카드 배지용) nav_projects: list[dict[str, Any]] = [] all_tasks: list[dict[str, Any]] = [] stages_by_project: dict[int, list[dict[str, Any]]] = {} projects_meta: list[dict[str, Any]] = [] for p in all_projects: if p.get("parent_id"): continue # 과거 서브프로젝트는 트리에서 제외 p_tasks = ( tasks if p["id"] == project_id else st.list_tasks(project_id=p["id"], limit=2000) ) # 이 업무가 '어느 프로젝트를 보다가' 담겼는지 표시 — 멀티호밍된 업무는 # 원 프로젝트(t.project_id)와 연결된 프로젝트(p.id) 양쪽에서 각각 한 번씩 # 나온다(각 프로젝트 화면에 보여야 하므로). "전체 프로젝트" 집계 화면은 # context_project_id == project_id(원 소속)인 것만 세어 중복을 없앤다. for t in p_tasks: t["context_project_id"] = p["id"] all_tasks.extend(p_tasks) stages_by_project[p["id"]] = st.list_stages(project_id=p["id"]) projects_meta.append({ "id": p["id"], "name": p["name"], "color": p.get("color") or "#4573d2", "start_date": p.get("start_date"), "due_date": p.get("due_date"), "created_by": p.get("created_by") or "", "description": p.get("description") or "", "status": p.get("status") or "active", }) nav_projects.append({ "id": p["id"], "name": p["name"], "color": p.get("color") or "#4573d2", "created_by": p.get("created_by") or "", "description": p.get("description") or "", "start_date": p.get("start_date"), "due_date": p.get("due_date"), "status": p.get("status") or "active", "tasks": [ {"id": t["id"], "title": t["title"], "color": t.get("project_color") or p.get("color") or "#4573d2", "completed": bool(t.get("completed_at"))} for t in p_tasks ], }) # 보드 컬럼 = 전체 프로젝트의 단계 '이름' 묶음(기본 4단계 순서를 우선). _order = {n: i for i, (n, _d) in enumerate(store.DEFAULT_STAGES)} board_stage_names: list[str] = [] for slist in stages_by_project.values(): for s in slist: if s["name"] not in board_stage_names: board_stage_names.append(s["name"]) board_stage_names.sort(key=lambda n: (_order.get(n, 999), n)) # 아바타 맵: 이메일(소문자) → 구글 프로필 이미지 URL (담당자/댓글 작성자 표시용) from app.main import user_store # noqa: WPS433 avatars = { store.norm_str(u["email"], lower=True): u.get("picture") or "" for u in user_store.list_all() if u.get("picture") } # 우측 "내 업무" 패널 — 홈 화면과 동일한 쿼리/그룹핑(프로젝트별)을 재사용. my_tasks = st.list_tasks(assignee_email=user["email"], limit=500) for t in my_tasks: t["start_label"] = _fmt_date_kr(t.get("start_date")) t["due_label"] = _fmt_date_kr(t.get("due_date")) my_groups: dict[int, dict[str, Any]] = {} for t in my_tasks: pid = t.get("project_id") g = my_groups.get(pid) if g is None: g = { "id": pid, "name": t.get("project_name") or "프로젝트", "color": t.get("project_color") or "#4573d2", "tasks": [], } my_groups[pid] = g g["tasks"].append(t) my_projects = list(my_groups.values()) # 달력(휴가식 월간 그리드) — ?y=&m= 로 월 이동, 기본 이번 달 today = today_kst() try: year = int(request.query_params.get("y") or today.year) month = int(request.query_params.get("m") or today.month) if not (1 <= month <= 12): year, month = today.year, today.month except (TypeError, ValueError): year, month = today.year, today.month weeks = _build_task_calendar(all_tasks, year, month) prev_y, prev_m = (year - 1, 12) if month == 1 else (year, month - 1) next_y, next_m = (year + 1, 1) if month == 12 else (year, month + 1) return render_template( request, "project/project.html", { "user": user, "is_admin": admin, "can_manage": can_manage, "nav_items": build_erp_nav(user, active="project"), "page_title": project["name"], "page_subtitle": project.get("description") or "프로젝트 보드", "force_sidebar_collapsed": True, "project": project, "current_project_id": project_id, "my_projects": my_projects, "my_tasks": my_tasks, "nav_projects": nav_projects, "stages": stages, "tasks": all_tasks, "members": members, "projects_meta": projects_meta, "stages_by_project": stages_by_project, "board_stage_names": board_stage_names, "avatars": avatars, "priority_labels": store.PRIORITY_LABELS, "color_palette": list(store.COLOR_PALETTE), "stage_color_palette": list(store.STAGE_COLOR_PALETTE), "today": today.isoformat(), "year": year, "month": month, "prev_y": prev_y, "prev_m": prev_m, "next_y": next_y, "next_m": next_m, "weekdays": ["일", "월", "화", "수", "목", "금", "토"], "weeks": weeks, }, ) # ──────────────────────────────────────────────────────────── # JSON API — 프로젝트 # ──────────────────────────────────────────────────────────── def _db_or_503(request: Request) -> Any: st = _store(request) if st is None: raise HTTPException(status_code=503, detail="프로젝트 모듈이 설정되지 않았습니다.") return st @router.get("/api/projects") async def api_list_projects(request: Request) -> JSONResponse: from app.store import is_admin # noqa: WPS433 user = _require_user(request) st = _db_or_503(request) admin = is_admin(user) projects = st.list_projects( include_archived=False, member_email=None if admin else user["email"], ) return JSONResponse({"projects": projects, "tree": _build_tree(projects)}) @router.post("/api/projects") async def api_create_project( request: Request, payload: dict[str, Any] = Body(...) ) -> JSONResponse: """최상위 프로젝트 생성 — 로그인해 프로젝트 모듈에 접근할 수 있는 사용자 누구나.""" user = _require_user(request) st = _db_or_503(request) try: project = st.create_project( name=payload.get("name", ""), parent_id=None, description=payload.get("description", ""), color=payload.get("color", ""), owner_email=payload.get("owner_email", "") or user["email"], start_date=payload.get("start_date"), due_date=payload.get("due_date"), created_by=user["email"], ) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) return JSONResponse({"project": project}, status_code=201) @router.post("/api/projects/{project_id}/subprojects") async def api_create_subproject( request: Request, project_id: int, payload: dict[str, Any] = Body(...) ) -> JSONResponse: """서브프로젝트 생성 — 멤버(또는 관리자).""" user = _require_user(request) st = _db_or_503(request) _require_manage(request, st, user, project_id) try: project = st.create_project( name=payload.get("name", ""), parent_id=project_id, description=payload.get("description", ""), color=payload.get("color", ""), owner_email=payload.get("owner_email", "") or user["email"], start_date=payload.get("start_date"), due_date=payload.get("due_date"), created_by=user["email"], ) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) except KeyError as exc: raise HTTPException(status_code=404, detail=str(exc)) return JSONResponse({"project": project}, status_code=201) @router.put("/api/projects/order") async def api_reorder_projects( request: Request, payload: dict[str, Any] = Body(...) ) -> JSONResponse: """홈 화면 프로젝트 카드 드래그 순서 변경. 최상위 프로젝트만 대상이며, 순서는 이 화면을 보는 모든 사용자에게 공유되므로(세션 재정렬과 동일 원칙) 관리자 전용으로 제한한다. ⚠️ 반드시 `PUT /api/projects/{project_id}` 보다 먼저 등록해야 한다 — 아니면 "order" 가 project_id 로 매칭 시도되어(정수 변환 실패로 422) 이 라우트가 영영 실행되지 않는다(경로 매칭은 등록 순서, path param 특이도 무관). """ _require_admin(request) st = _db_or_503(request) ids = payload.get("ordered_ids") or [] if not isinstance(ids, list) or not ids: raise HTTPException(status_code=400, detail="ordered_ids 가 필요합니다.") st.reorder_projects(ordered_ids=[int(i) for i in ids]) return JSONResponse({"ok": True}) @router.put("/api/projects/{project_id}") async def api_update_project( request: Request, project_id: int, payload: dict[str, Any] = Body(...) ) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) _require_manage(request, st, user, project_id) try: project = st.update_project(project_id=project_id, fields=payload) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) except KeyError: raise HTTPException(status_code=404, detail="프로젝트를 찾을 수 없습니다.") return JSONResponse({"project": project}) @router.delete("/api/projects/{project_id}") async def api_delete_project(request: Request, project_id: int) -> JSONResponse: """프로젝트 삭제 — '만든 사람'만(슈퍼관리자 예외). 안의 업무도 CASCADE.""" user = _require_user(request) st = _db_or_503(request) project = st.get_project(project_id=project_id) if project is None: raise HTTPException(status_code=404, detail="프로젝트를 찾을 수 없습니다.") if not _can_delete(user, project.get("created_by")): raise HTTPException(status_code=403, detail=_DELETE_DENIED) st.delete_project(project_id=project_id) return JSONResponse({"ok": True}) # ──────────────────────────────────────────────────────────── # JSON API — 멤버 (관리자가 사용자 배정) # ──────────────────────────────────────────────────────────── @router.get("/api/assignable-users") async def api_assignable_users(request: Request) -> JSONResponse: """배정 후보 = 등록된 사용자 중 프로젝트 권한(project 모듈) 보유자. 관리자 전용. 관리자 페이지의 '프로젝트 관리' 토글을 켠 직원이 자동으로 후보가 된다. """ _require_admin(request) from app.main import user_store # noqa: WPS433 from app.store import has_module # noqa: WPS433 out = [ { "email": u["email"], "name": u.get("name") or u["email"].split("@")[0], "id": u["email"].split("@")[0], "avatar": u.get("picture") or "", } for u in user_store.list_all() if has_module(u, "project") ] out.sort(key=lambda x: x["id"]) return JSONResponse({"users": out}) @router.get("/api/all-users") async def api_all_users(request: Request) -> JSONResponse: """프로젝트 화면 좌측 "전체 멤버" 표시용 — project 모듈 권한 보유 등록 사용자 전원. assignable-users 와 후보군은 같지만, 이건 멤버 배정(쓰기)이 아니라 단순 열람용이라 관리자가 아니어도 볼 수 있다.""" _require_user(request) from app.main import user_store # noqa: WPS433 from app.store import has_module # noqa: WPS433 out = [ { "email": u["email"], "name": u.get("name") or u["email"].split("@")[0], "id": u["email"].split("@")[0], "avatar": u.get("picture") or "", } for u in user_store.list_all() if has_module(u, "project") ] out.sort(key=lambda x: x["id"]) return JSONResponse({"users": out}) @router.get("/api/users/tasks") async def api_user_tasks( request: Request, email: str, project_id: int | None = None ) -> JSONResponse: """'전체 멤버'/사이드바 '프로젝트 멤버' 아이콘 클릭 팝업 — 지정한 사용자가 담당자인 업무 목록(프로젝트/세션/마감일). project_id 를 주면 그 프로젝트 안에서 담당하는 업무만(멀티호밍으로 연결된 업무 포함, list_tasks 의 project_id 단일 조회 경로 재사용). 안 주면 전체 프로젝트 대상.""" _require_user(request) st = _db_or_503(request) if project_id is not None: tasks = st.list_tasks(project_id=project_id, assignee_email=email, limit=500) else: tasks = st.list_tasks(assignee_email=email, limit=500) return JSONResponse({"tasks": tasks}) @router.get("/api/projects/{project_id}/members") async def api_list_members(request: Request, project_id: int) -> JSONResponse: _require_user(request) st = _db_or_503(request) return JSONResponse({"members": st.list_members(project_id=project_id)}) @router.post("/api/projects/{project_id}/members") async def api_add_member( request: Request, project_id: int, payload: dict[str, Any] = Body(...) ) -> JSONResponse: """사용자를 프로젝트에 배정 — 관리자 전용.""" _require_admin(request) st = _db_or_503(request) try: member = st.add_member( project_id=project_id, user_email=payload.get("user_email", ""), user_name=payload.get("user_name", ""), role=payload.get("role", "member"), ) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) return JSONResponse({"member": member}, status_code=201) @router.delete("/api/projects/{project_id}/members/{user_email}") async def api_remove_member( request: Request, project_id: int, user_email: str ) -> JSONResponse: _require_admin(request) st = _db_or_503(request) st.remove_member(project_id=project_id, user_email=user_email) return JSONResponse({"ok": True}) # ──────────────────────────────────────────────────────────── # JSON API — 단계 (stages) # ──────────────────────────────────────────────────────────── @router.get("/api/projects/{project_id}/stages") async def api_list_stages(request: Request, project_id: int) -> JSONResponse: _require_user(request) st = _db_or_503(request) return JSONResponse({"stages": st.list_stages(project_id=project_id)}) @router.post("/api/projects/{project_id}/stages") async def api_add_stage( request: Request, project_id: int, payload: dict[str, Any] = Body(...) ) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) _require_manage(request, st, user, project_id) try: stage = st.add_stage( project_id=project_id, name=payload.get("name", ""), is_done_stage=bool(payload.get("is_done_stage", False)), color=payload.get("color"), created_by=user["email"], ) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) return JSONResponse({"stage": stage}, status_code=201) @router.delete("/api/projects/{project_id}/stages/{stage_id}") async def api_delete_stage( request: Request, project_id: int, stage_id: int ) -> JSONResponse: """세션(단계) 삭제 — 만든 사람만(슈퍼관리자 예외). 생성자 정보가 없는 과거 데이터는 관리자에게 허용(잠김 방지) — `_can_delete` 규칙 그대로 재사용.""" user = _require_user(request) st = _db_or_503(request) _require_manage(request, st, user, project_id) stage = st.get_stage(stage_id=stage_id) if stage is None: raise HTTPException(status_code=404, detail="세션을 찾을 수 없습니다.") if not _can_delete(user, stage.get("created_by")): raise HTTPException(status_code=403, detail=_DELETE_DENIED) try: st.delete_stage(stage_id=stage_id) except KeyError: raise HTTPException(status_code=404, detail="세션을 찾을 수 없습니다.") return JSONResponse({"ok": True}) # ──────────────────────────────────────────────────────────── # JSON API — 업무 (tasks) # ──────────────────────────────────────────────────────────── @router.get("/api/projects/{project_id}/tasks") async def api_list_tasks(request: Request, project_id: int) -> JSONResponse: _require_user(request) st = _db_or_503(request) tasks = st.list_tasks(project_id=project_id, include_subprojects=True, limit=2000) return JSONResponse({"tasks": tasks}) @router.get("/api/my-tasks") async def api_my_tasks(request: Request) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) return JSONResponse({"tasks": st.list_tasks(assignee_email=user["email"], limit=1000)}) @router.post("/api/projects/{project_id}/tasks") async def api_create_task( request: Request, project_id: int, bg: BackgroundTasks, payload: dict[str, Any] = Body(...), ) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) _require_manage(request, st, user, project_id) project = st.get_project(project_id=project_id) if project is None: raise HTTPException(status_code=404, detail="프로젝트를 찾을 수 없습니다.") try: task = st.create_task( project_id=project_id, title=payload.get("title", ""), stage_id=payload.get("stage_id"), description=store.sanitize_description_html(payload.get("description", "")), assignee_email=payload.get("assignee_email", ""), assignee_name=payload.get("assignee_name", ""), priority=payload.get("priority", "normal"), start_date=payload.get("start_date"), due_date=payload.get("due_date"), start_time=payload.get("start_time"), due_time=payload.get("due_time"), created_by=user["email"], parent_task_id=payload.get("parent_task_id"), ) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) except KeyError as exc: raise HTTPException(status_code=404, detail=str(exc)) # 생성과 동시에 담당자 지정 시 관리자 메일 + 담당자 인앱 알림 if task.get("assignee_email"): _notify( bg, request, subject=store.build_subject_assigned( project_name=project["name"], task_title=task["title"], assignee=task["assignee_email"], ), body=( f"프로젝트: {project['name']}\n" f"업무: {task['title']}\n" f"담당자: {task.get('assignee_name') or task['assignee_email']} " f"({task['assignee_email']})\n" f"마감일: {task.get('due_date') or '-'}\n" f"등록자: {user['email']}\n" ), ) _inbox( st, recipients=[task["assignee_email"]], actor=user["email"], project_id=project_id, task_id=task["id"], ntype="assigned", title=f"업무 배정: {task['title']}", body=f"{project['name']} · 마감 {task.get('due_date') or '-'}", ) return JSONResponse({"task": task}, status_code=201) @router.put("/api/tasks/{task_id}") async def api_update_task( request: Request, task_id: int, bg: BackgroundTasks, payload: dict[str, Any] = Body(...), ) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) existing = st.get_task(task_id=task_id) if existing is None: raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.") _require_manage(request, st, user, existing["project_id"]) if "description" in payload: payload["description"] = store.sanitize_description_html(payload["description"]) try: task = st.update_task(task_id=task_id, fields=payload, actor=user["email"]) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) except KeyError: raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.") project_name = task.get("project_name") or "" project = st.get_project(project_id=existing["project_id"]) or {"id": existing["project_id"], "name": project_name} if task.get("_newly_assigned"): _notify( bg, request, subject=store.build_subject_assigned( project_name=project_name, task_title=task["title"], assignee=task["_newly_assigned"], ), body=( f"프로젝트: {project_name}\n" f"업무: {task['title']}\n" f"담당자: {task.get('assignee_name') or task['_newly_assigned']} " f"({task['_newly_assigned']})\n" f"마감일: {task.get('due_date') or '-'}\n" f"변경자: {user['email']}\n" ), ) _inbox( st, recipients=[task["_newly_assigned"]], actor=user["email"], project_id=existing["project_id"], task_id=task_id, ntype="assigned", title=f"업무 배정: {task['title']}", body=f"{project_name} · 마감 {task.get('due_date') or '-'}", ) if task.get("_newly_completed"): _notify( bg, request, subject=store.build_subject_completed( project_name=project_name, task_title=task["title"] ), body=( f"프로젝트: {project_name}\n" f"완료된 업무: {task['title']}\n" f"담당자: {task.get('assignee_name') or task.get('assignee_email') or '-'}\n" f"완료 처리: {user['email']}\n" ), ) _inbox( st, recipients=_task_recipients(st, project, task, exclude=user["email"]), actor=user["email"], project_id=existing["project_id"], task_id=task_id, ntype="completed", title=f"업무 완료: {task['title']}", body=project_name, ) return JSONResponse({"task": task}) @router.delete("/api/tasks/{task_id}") async def api_delete_task(request: Request, task_id: int) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) existing = st.get_task(task_id=task_id) if existing is None: raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.") if not _can_delete(user, existing.get("created_by")): raise HTTPException(status_code=403, detail=_DELETE_DENIED) st.delete_task(task_id=task_id) return JSONResponse({"ok": True}) @router.get("/api/tasks/{task_id}") async def api_get_task(request: Request, task_id: int) -> JSONResponse: """업무 상세 — 하위 업무·연결된 프로젝트 포함. 업무 편집 팝업을 열 때 쓴다.""" user = _require_user(request) st = _db_or_503(request) task = st.get_task(task_id=task_id) if task is None: raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.") _require_manage(request, st, user, task["project_id"]) task["subtasks"] = st.list_tasks(parent_task_id=task_id) task["links"] = st.list_task_links(task_id=task_id) return JSONResponse({"task": task}) # ──────────────────────────────────────────────────────────── # JSON API — 업무 멀티호밍 (다른 프로젝트/세션에 연결) # ──────────────────────────────────────────────────────────── @router.post("/api/tasks/{task_id}/links") async def api_add_task_link( request: Request, task_id: int, payload: dict[str, Any] = Body(...) ) -> JSONResponse: """업무를 다른 프로젝트(의 한 세션)에도 연결한다(아사나의 멀티호밍). 최초 연결은 원래 소속(프로젝트)과 연결할 대상 프로젝트 양쪽에 대한 관리 권한이 필요하다(안 그러면 접근 권한 없는 프로젝트의 업무를 아무나 자기 프로젝트로 끌어와 제목 등을 노출시킬 수 있다). 이미 연결된 업무를 그 프로젝트 안에서 다른 세션으로 옮기는 것(보드 드래그)은 대상 프로젝트 권한만 있으면 된다 — 매번 원 프로젝트 권한까지 다시 확인하면 원 프로젝트 멤버가 아닌 사람은 이미 허용된 카드조차 못 옮기게 된다. """ user = _require_user(request) st = _db_or_503(request) task = st.get_task(task_id=task_id) if task is None: raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.") try: target_project_id = int(payload.get("project_id")) except (TypeError, ValueError): raise HTTPException(status_code=400, detail="project_id 가 필요합니다.") if target_project_id == task["project_id"]: raise HTTPException(status_code=400, detail="이미 이 업무의 기본 프로젝트입니다.") _require_manage(request, st, user, target_project_id) already_linked = any( link["project_id"] == target_project_id for link in st.list_task_links(task_id=task_id) ) if not already_linked: _require_manage(request, st, user, task["project_id"]) stage_id = payload.get("stage_id") link = st.add_task_link( task_id=task_id, project_id=target_project_id, stage_id=int(stage_id) if stage_id else None, created_by=user["email"], ) return JSONResponse({"link": link}, status_code=201) @router.delete("/api/tasks/{task_id}/links/{project_id}") async def api_remove_task_link(request: Request, task_id: int, project_id: int) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) task = st.get_task(task_id=task_id) if task is None: raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.") _require_manage(request, st, user, task["project_id"]) _require_manage(request, st, user, project_id) st.remove_task_link(task_id=task_id, project_id=project_id) return JSONResponse({"ok": True}) @router.get("/api/projects/{project_id}/activity") async def api_activity(request: Request, project_id: int) -> JSONResponse: _require_user(request) st = _db_or_503(request) return JSONResponse({"activity": st.list_activity(project_id=project_id, limit=100)}) # ──────────────────────────────────────────────────────────── # JSON API — 댓글 # ──────────────────────────────────────────────────────────── @router.get("/api/tasks/{task_id}/comments") async def api_list_comments(request: Request, task_id: int) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) task = st.get_task(task_id=task_id) if task is None: raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.") _require_manage(request, st, user, task["project_id"]) return JSONResponse({"comments": st.list_comments(task_id=task_id)}) @router.post("/api/tasks/{task_id}/comments") async def api_add_comment( request: Request, task_id: int, payload: dict[str, Any] = Body(...) ) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) task = st.get_task(task_id=task_id) if task is None: raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.") _require_manage(request, st, user, task["project_id"]) try: comment = st.add_comment( task_id=task_id, author_email=user["email"], author_name=user.get("name") or user["email"].split("@")[0], body=payload.get("body", ""), allow_empty=bool(payload.get("has_attachment")), ) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) project = st.get_project(project_id=task["project_id"]) or {"id": task["project_id"], "name": task.get("project_name", "")} _inbox( st, recipients=_task_recipients(st, project, task, exclude=user["email"]), actor=user["email"], project_id=task["project_id"], task_id=task_id, ntype="comment", title=f"새 댓글: {task['title']}", body=comment["body"][:120], ) return JSONResponse({"comment": comment}, status_code=201) @router.put("/api/comments/{comment_id}") async def api_update_comment( request: Request, comment_id: int, payload: dict[str, Any] = Body(...) ) -> JSONResponse: from app.store import is_admin # noqa: WPS433 user = _require_user(request) st = _db_or_503(request) try: comment = st.update_comment( comment_id=comment_id, requester=user["email"], is_admin=is_admin(user), body=payload.get("body", ""), ) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) except KeyError: raise HTTPException(status_code=404, detail="댓글을 찾을 수 없습니다.") except PermissionError as exc: raise HTTPException(status_code=403, detail=str(exc)) return JSONResponse({"comment": comment}) @router.delete("/api/comments/{comment_id}") async def api_delete_comment(request: Request, comment_id: int) -> JSONResponse: from app.store import is_admin # noqa: WPS433 user = _require_user(request) st = _db_or_503(request) try: st.delete_comment(comment_id=comment_id, requester=user["email"], is_admin=is_admin(user)) except KeyError: raise HTTPException(status_code=404, detail="댓글을 찾을 수 없습니다.") except PermissionError as exc: raise HTTPException(status_code=403, detail=str(exc)) return JSONResponse({"ok": True}) # ──────────────────────────────────────────────────────────── # JSON API — 첨부파일 # ──────────────────────────────────────────────────────────── def _attach_dir(request: Request, task_id: int) -> Path: base = Path(str(getattr(request.app.state, "data_dir", "."))) d = base / "project" / str(task_id) d.mkdir(parents=True, exist_ok=True) return d @router.get("/api/tasks/{task_id}/attachments") async def api_list_attachments(request: Request, task_id: int) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) task = st.get_task(task_id=task_id) if task is None: raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.") _require_manage(request, st, user, task["project_id"]) return JSONResponse({"attachments": st.list_attachments(task_id=task_id)}) @router.post("/api/tasks/{task_id}/attachments") async def api_upload_attachment( request: Request, task_id: int, file: UploadFile = File(...), comment_id: int | None = Form(None), ) -> JSONResponse: """comment_id 를 주면 댓글 채팅 팝업의 첨부(이미지/파일)로도 등록 — 같은 표에 저장되므로 업무 "첨부파일" 패널에도 그대로 함께 나온다.""" user = _require_user(request) st = _db_or_503(request) task = st.get_task(task_id=task_id) if task is None: raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.") _require_manage(request, st, user, task["project_id"]) if comment_id is not None: comment = st.get_comment(comment_id=comment_id) if comment is None or comment["task_id"] != task_id: raise HTTPException(status_code=400, detail="잘못된 댓글입니다.") data = await file.read() if len(data) > _MAX_ATTACH_BYTES: raise HTTPException(status_code=413, detail="파일이 너무 큽니다(최대 20MB).") if not data: raise HTTPException(status_code=400, detail="빈 파일입니다.") orig = (file.filename or "file").replace("\\", "_").replace("/", "_").strip() suffix = Path(orig).suffix[:16] stored = f"{uuid.uuid4().hex}{suffix}" dest = _attach_dir(request, task_id) / stored dest.write_bytes(data) att = st.add_attachment( task_id=task_id, filename=orig, stored_name=stored, content_type=file.content_type or "application/octet-stream", size_bytes=len(data), uploaded_by=user["email"], comment_id=comment_id, ) return JSONResponse({"attachment": att}, status_code=201) @router.get("/api/attachments/{attachment_id}/download") async def api_download_attachment(request: Request, attachment_id: int): user = _require_user(request) st = _db_or_503(request) att = st.get_attachment(attachment_id=attachment_id) if att is None: raise HTTPException(status_code=404, detail="첨부를 찾을 수 없습니다.") task = st.get_task(task_id=att["task_id"]) if task is None: raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.") _require_manage(request, st, user, task["project_id"]) path = _attach_dir(request, att["task_id"]) / att["stored_name"] if not path.exists(): raise HTTPException(status_code=404, detail="파일이 디스크에 없습니다.") return FileResponse( str(path), filename=att["filename"], media_type=att.get("content_type") or "application/octet-stream", ) @router.get("/api/attachments/{attachment_id}/inline") async def api_inline_attachment(request: Request, attachment_id: int): """설명란에 붙여넣은/업로드한 이미지를 `` 로 바로 보여주기 위한 서빙. `/download` 는 `filename=` 을 줘서 강제 다운로드(Content-Disposition: attachment)가 걸리므로 이미지 삽입에는 못 쓴다 — filename 을 안 주면 브라우저가 그대로 렌더링한다.""" user = _require_user(request) st = _db_or_503(request) att = st.get_attachment(attachment_id=attachment_id) if att is None: raise HTTPException(status_code=404, detail="첨부를 찾을 수 없습니다.") task = st.get_task(task_id=att["task_id"]) if task is None: raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.") _require_manage(request, st, user, task["project_id"]) path = _attach_dir(request, att["task_id"]) / att["stored_name"] if not path.exists(): raise HTTPException(status_code=404, detail="파일이 디스크에 없습니다.") return FileResponse(str(path), media_type=att.get("content_type") or "application/octet-stream") @router.delete("/api/attachments/{attachment_id}") async def api_delete_attachment(request: Request, attachment_id: int) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) att = st.get_attachment(attachment_id=attachment_id) if att is None: raise HTTPException(status_code=404, detail="첨부를 찾을 수 없습니다.") task = st.get_task(task_id=att["task_id"]) if task is not None: _require_manage(request, st, user, task["project_id"]) removed = st.delete_attachment(attachment_id=attachment_id) try: (_attach_dir(request, removed["task_id"]) / removed["stored_name"]).unlink(missing_ok=True) except Exception: # noqa: BLE001 logger.warning("첨부 파일 삭제 실패: %s", removed.get("stored_name")) return JSONResponse({"ok": True}) # ──────────────────────────────────────────────────────────── # JSON API — 단계 이름/순서 편집 # ──────────────────────────────────────────────────────────── @router.put("/api/projects/{project_id}/stages/order") async def api_reorder_stages( request: Request, project_id: int, payload: dict[str, Any] = Body(...) ) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) _require_manage(request, st, user, project_id) ids = payload.get("ordered_ids") or [] if not isinstance(ids, list) or not ids: raise HTTPException(status_code=400, detail="ordered_ids 가 필요합니다.") st.reorder_stages(project_id=project_id, ordered_ids=[int(i) for i in ids]) return JSONResponse({"stages": st.list_stages(project_id=project_id)}) @router.put("/api/projects/{project_id}/stages/{stage_id}/tasks/order") async def api_reorder_tasks( request: Request, project_id: int, stage_id: int, payload: dict[str, Any] = Body(...) ) -> JSONResponse: """보드에서 카드를 같은 세션 안에서 드래그로 재정렬.""" user = _require_user(request) st = _db_or_503(request) _require_manage(request, st, user, project_id) ids = payload.get("ordered_ids") or [] if not isinstance(ids, list) or not ids: raise HTTPException(status_code=400, detail="ordered_ids 가 필요합니다.") st.reorder_tasks(stage_id=stage_id, ordered_ids=[int(i) for i in ids]) return JSONResponse({"ok": True}) @router.put("/api/projects/{project_id}/stages/{stage_id}") async def api_update_stage( request: Request, project_id: int, stage_id: int, payload: dict[str, Any] = Body(...) ) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) _require_manage(request, st, user, project_id) try: stage = st.update_stage( stage_id=stage_id, name=payload.get("name"), is_done_stage=payload.get("is_done_stage"), color=payload.get("color", ...), ) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) except KeyError: raise HTTPException(status_code=404, detail="단계를 찾을 수 없습니다.") return JSONResponse({"stage": stage}) # ──────────────────────────────────────────────────────────── # 알림센터 (인앱) # ──────────────────────────────────────────────────────────── @router.get("/api/notifications") async def api_notifications(request: Request) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) unread_only = request.query_params.get("unread") in ("1", "true") items = st.list_notifications( recipient_email=user["email"], unread_only=unread_only, limit=100 ) return JSONResponse({"notifications": items, "unread": st.count_unread(recipient_email=user["email"])}) @router.get("/api/notifications/unread-count") async def api_notif_count(request: Request) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) return JSONResponse({"unread": st.count_unread(recipient_email=user["email"])}) @router.post("/api/notifications/{notification_id}/read") async def api_notif_read(request: Request, notification_id: int) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) st.mark_read(notification_id=notification_id, recipient_email=user["email"]) return JSONResponse({"ok": True}) @router.post("/api/notifications/read-all") async def api_notif_read_all(request: Request) -> JSONResponse: user = _require_user(request) st = _db_or_503(request) n = st.mark_all_read(recipient_email=user["email"]) return JSONResponse({"ok": True, "marked": n}) @router.get("/inbox", response_class=HTMLResponse) async def inbox_page(request: Request) -> HTMLResponse: from app.main import build_erp_nav, render_template # noqa: WPS433 from app.store import is_admin # noqa: WPS433 user = _require_user(request) st = _store(request) if st is None: return _render_config_needed(request, user) items = st.list_notifications(recipient_email=user["email"], limit=100) return render_template( request, "project/inbox.html", { "user": user, "is_admin": is_admin(user), "nav_items": build_erp_nav(user, active="project"), "page_title": "알림센터", "page_subtitle": "내게 온 프로젝트 알림", "force_sidebar_collapsed": True, "notifications": items, }, )