"""프로젝트 관리(아사나식) 모듈 라우터. - 경로: /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, ) 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, } 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("/", 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"], ) # 완료된 프로젝트는 비활성으로 맨 끝에 (홈 카드 정렬). 안정 정렬. projects = sorted(projects, key=lambda p: 1 if p.get("status") == "completed" else 0) tree = _build_tree(projects) my_tasks = st.list_tasks(assignee_email=user["email"], limit=500) # 내 업무를 프로젝트별로 묶어 트리로 표시 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()) return render_template( request, "project/index.html", { "user": user, "is_admin": admin, "nav_items": build_erp_nav(user, active="project"), "page_title": "프로젝트 관리", "page_subtitle": "달력·타임라인·보드로 프로젝트를 관리하세요.", "tree": tree, "my_projects": my_projects, "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) ) 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 "", }) nav_projects.append({ "id": p["id"], "name": p["name"], "color": p.get("color") or "#4573d2", "created_by": p.get("created_by") or "", "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") } # 달력(휴가식 월간 그리드) — ?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 "프로젝트 보드", "project": project, "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), "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_admin(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/{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], } 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/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)), ) 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: user = _require_user(request) st = _db_or_503(request) _require_manage(request, st, user, project_id) 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=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"], ) except ValueError as exc: raise HTTPException(status_code=400, 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"]) 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/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", ""), ) 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(...) ) -> 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"]) 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"], ) 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.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}") 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"), ) 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": "내게 온 프로젝트 알림", "notifications": items, }, )