Files
dbx-main/app/modules/project/router.py
T
king 3dbb613092 feat(project): 세션 기본 담당자
세션 편집 창에서 기본 담당자(프로젝트 멤버·owner)를 지정하면, 그 세션에
업무를 만들거나 다른 세션에서 옮겨올 때 담당자가 빈 업무만 자동 배정.
이미 담당자가 있으면 그대로. 보드 세션 머리에 담당자 아바타 표시,
새 업무 팝업은 기본 담당자를 미리 채움. 자동 배정도 일반 배정처럼
알림·팔로워·메일 처리.

DB: project_db_009 (project_stages.default_assignee_email). 미적용이어도
to_jsonb 로 읽어 동작, 지정 시도만 503 안내.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 23:51:38 +09:00

1880 lines
80 KiB
Python

"""프로젝트 관리(아사나식) 모듈 라우터.
- 경로: /project
- 권한:
· 모듈 진입: 로그인한 회사 직원 전원(도메인 게이트는 OAuth 단에서 처리).
· 프로젝트 생성/삭제·사용자 배정: ERP 관리자(is_admin) 전용.
· 서브프로젝트/업무/단계 관리: 해당 프로젝트 멤버(또는 owner) 또는 관리자.
- 데이터: ProjectStore (project_db / PostgreSQL) 전용.
PROJECT_DB_URL 미설정 시 store 가 None 이며, 각 페이지는 "설정 필요" 안내.
- 메일: 업무가 직원에게 '배정'되거나 '완료'되면 관리자에게 알림(BackgroundTasks).
뷰: 메인은 달력(FullCalendar)/타임라인(vis-timeline) 토글. 추가로 보드(칸반)·리스트.
핸들러는 전부 `def`(sync)다. DB 드라이버(psycopg ConnectionPool)가 동기라서
`async def` 안에서 부르면 쿼리 도는 동안 이벤트 루프(=앱 전체 요청 처리)가
멈춘다. `def` 로 두면 FastAPI 가 스레드풀에서 돌린다.
"""
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 psycopg.errors import UndefinedColumn
from app.timezone import today_kst
from . import store
# 첨부 업로드 제한
_MAX_ATTACH_BYTES = 20 * 1024 * 1024 # 20MB
# 첨부 응답 공통 헤더 — 브라우저가 내용을 보고 형식을 추측(sniff)해 HTML 로
# 실행하지 못하게 하고, 혹시 문서로 열려도 스크립트를 막는다.
_ATTACH_HEADERS = {
"X-Content-Type-Options": "nosniff",
"Content-Security-Policy": "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox",
}
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 _accessible_project_ids(st: Any, user: dict[str, Any]) -> set[int] | None:
"""사용자가 볼 수 있는 프로젝트 id 집합. 관리자는 None(=전체)."""
from app.store import is_admin # noqa: WPS433
if is_admin(user):
return None
return {
p["id"] for p in st.list_projects(include_archived=True, member_email=user["email"])
}
def _remove_task_dirs(request: Request, task_ids: list[int]) -> None:
"""삭제된 업무들의 첨부 폴더(DATA_DIR/project/<task_id>)를 지운다.
DB 행은 CASCADE 로 사라지지만 디스크 파일은 남아 계속 쌓였다. 실패해도
삭제 자체는 이미 끝났으므로 로그만 남긴다.
"""
import shutil # noqa: WPS433
base = Path(str(getattr(request.app.state, "data_dir", "."))) / "project"
for tid in task_ids:
d = base / str(int(tid))
if d.is_dir():
try:
shutil.rmtree(d)
except Exception: # noqa: BLE001
logger.warning("첨부 폴더 삭제 실패: %s", d)
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 _follow(st: Any, task_id: int, emails: list[str]) -> None:
"""자동 팔로우(만든 사람·담당자·댓글 작성자·@태그된 사람). 부가 기능이라
실패해도(008 미적용 등) 본 작업은 막지 않는다."""
try:
st.add_followers(task_id=task_id, emails=emails)
except Exception: # noqa: BLE001
pass
def _task_recipients(
st: Any, project: dict[str, Any], task: dict[str, Any], *, exclude: str = ""
) -> list[str]:
"""업무 관련 인앱 알림 수신자 (행위자 제외).
= 담당자 + 팔로워(아사나의 협업자). 예전엔 프로젝트 멤버 전원에게 갔는데
알림이 너무 많아 정작 중요한 게 묻혔다. 팔로워 표(008)가 없으면 예전처럼
담당자 + owner + 멤버 전원.
"""
emails: set[str] = set()
if task.get("assignee_email"):
emails.add(store.norm_str(task["assignee_email"], lower=True))
try:
emails.update(st.list_followers(task_id=task["id"]))
emails.discard(store.norm_str(exclude, lower=True))
return [e for e in emails if e]
except Exception: # noqa: BLE001 - 008 미적용 → 예전 방식
pass
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 _record_mentions(
st: Any, *, task: dict[str, Any], emails: list[str], actor: str,
comment_id: int | None = None, source: str = "description",
project_name: str = "",
) -> None:
"""@태그를 기록하고 새로 태그된 사람에게만 알림을 만든다.
태그는 부가 기능이라 여기서 실패해도(예: 006 마이그레이션 미적용) 본
저장/등록은 막지 않는다 — 로그만 남긴다.
"""
if not emails:
return
try:
added = st.add_mentions(
task_id=task["id"], emails=emails, actor_email=actor,
comment_id=comment_id, source=source,
)
except Exception: # noqa: BLE001
logger.warning("멘션 기록 실패: task=%s", task.get("id"))
return
if not added:
return
_follow(st, task["id"], added) # 태그된 사람은 이후 소식도 받도록 팔로워로
where = "댓글" if source == "comment" else "설명"
_inbox(
st, recipients=added, actor=actor,
project_id=task["project_id"], task_id=task["id"], ntype="mention",
title=f"나를 태그함: {task['title']}",
body=f"{project_name or task.get('project_name') or ''} · {where}",
)
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 _nav_projects(st: Any, user: dict[str, Any], admin: bool) -> list[dict[str, Any]]:
"""좌측 사이드바(project/_side.html)의 프로젝트 트리 데이터.
내 업무 · 수신함 · 프로젝트 화면이 같은 사이드바를 쓰므로 한 곳에서 만든다.
"""
projects = st.list_projects(
include_archived=False,
member_email=None if admin else user["email"],
)
return [
{
"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",
}
for p in projects
if not p.get("parent_id")
]
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")
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")
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)
def my_tasks_page(request: Request) -> HTMLResponse:
"""프로젝트 모듈의 첫 화면 = 내 업무.
예전 홈(프로젝트 카드 그리드)은 없앴다 — 좌측 "내 업무" 메뉴와 같은
화면이며, 좌측 사이드바는 프로젝트 화면과 공용(project/_side.html)이다.
"""
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)
nav_projects = _nav_projects(st, user, admin)
today_iso = today_kst().isoformat()
my_tasks = st.list_my_tasks(assignee_email=user["email"], limit=1000)
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"))
d = t.get("due_date")
t["due_overdue"] = bool(d and d[:10] < today_iso and not t.get("completed_at"))
my_open_total = sum(1 for t in my_tasks if not t.get("completed_at"))
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")
}
return render_template(
request,
"project/mytasks.html",
{
"user": user,
"is_admin": admin,
"nav_items": build_erp_nav(user, active="project"),
"page_title": "내 업무",
"page_subtitle": "내가 담당자인 업무를 한 곳에서 봅니다.",
"force_sidebar_collapsed": True,
"nav_projects": nav_projects,
"my_tasks": my_tasks,
"my_open_total": my_open_total,
"mention_unread": _safe_mention_unread(st, user["email"]),
"avatars": avatars,
"priority_labels": store.PRIORITY_LABELS,
"color_palette": list(store.COLOR_PALETTE),
"today": today_iso,
},
)
@router.get("/t/{task_id}")
def task_permalink(request: Request, task_id: int):
"""업무 공유 링크(퍼머링크) — 업무 편집 팝업의 "링크 복사"가 만드는 주소.
누구에게 주소가 가더라도 **회사 계정으로 로그인한 그 프로젝트 멤버(또는
관리자)만** 열 수 있다. 로그인 전이면 로그인 뒤 이 주소로 되돌아온다.
실제 화면은 기존 경로(`/p/{project_id}?task=`)가 그리므로 여기서는
권한만 확인하고 넘긴다 — 업무가 다른 프로젝트로 옮겨가도 링크는 살아 있다.
"""
from urllib.parse import quote # noqa: WPS433
from app.main import build_erp_nav, get_current_user_record, render_template # noqa: WPS433
from app.store import has_module, is_admin # noqa: WPS433
user = get_current_user_record(request)
if user is None:
return RedirectResponse(
url="/login?next=" + quote(f"/project/t/{task_id}", safe=""),
status_code=303,
)
def _denied(reason: str, status: int) -> HTMLResponse:
return render_template(
request,
"denied.html",
{
"reason": reason,
"user": user,
"is_admin": is_admin(user),
"nav_items": build_erp_nav(user, active="project"),
},
status_code=status,
)
if not has_module(user, "project"):
return _denied("프로젝트 관리 모듈 권한이 없습니다.", 403)
st = _store(request)
if st is None:
return _render_config_needed(request, user)
task = st.get_task(task_id=task_id)
if task is None:
return _denied("업무를 찾을 수 없습니다. 삭제되었을 수 있습니다.", 404)
if not _can_manage(request, st, user, task["project_id"]):
return _denied(
"이 업무가 속한 프로젝트의 멤버만 볼 수 있습니다. "
"프로젝트 관리자에게 멤버 배정을 요청하세요.",
403,
)
# 하위 업무는 목록에 따로 뜨지 않고 부모 팝업 안에서만 보인다 — 부모를 연다.
open_id = task.get("parent_task_id") or task_id
return RedirectResponse(
url=f"/project/p/{task['project_id']}?task={open_id}", status_code=303
)
@router.get("/p/{project_id}", response_class=HTMLResponse)
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)
# 멤버(또는 owner/관리자)가 아니면 이 프로젝트 화면을 열 수 없다 — 공유
# 링크(/project/t/{id})와 같은 원칙. 예전엔 세션·멤버 목록이 그대로 보였다.
can_manage = _can_manage(request, st, user, project_id)
if not can_manage:
return render_template(
request,
"denied.html",
{
"reason": "이 프로젝트의 멤버만 볼 수 있습니다. "
"프로젝트 관리자에게 멤버 배정을 요청하세요.",
"user": user,
"is_admin": admin,
"nav_items": build_erp_nav(user, active="project"),
},
status_code=403,
)
all_projects = st.list_projects(
include_archived=False,
member_email=None if admin else user["email"],
)
members = st.list_members(project_id=project_id)
top_projects = [p for p in all_projects if not p.get("parent_id")] # 과거 서브프로젝트 제외
top_ids = [p["id"] for p in top_projects]
# 좌측 트리 + 전체 집계: 4개 뷰(달력/타임라인/보드/리스트)는 '전체 프로젝트'를 보여준다.
# all_tasks : 접근 가능한 모든 프로젝트의 업무(뷰 데이터)
# stages_by_project : 프로젝트별 단계(보드 이름→단계 매핑 + 모달 단계 선택용)
# projects_meta : 프로젝트 메타(타임라인 그룹/보드 카드 배지용)
# 업무·세션은 프로젝트 수와 상관없이 각각 쿼리 한 번으로 받는다(예전엔
# 프로젝트마다 2번씩 — N+1). 행마다 context_project_id(어느 프로젝트를 보다가
# 담겼는지)가 붙어 있다 — 멀티호밍된 업무는 원 프로젝트와 연결된 프로젝트
# 양쪽에서 한 번씩 나오고, "전체 프로젝트" 집계는 원 소속 행만 센다.
all_tasks = st.list_tasks_for_projects(project_ids=top_ids)
stages_by_project = st.list_stages_for_projects(project_ids=top_ids)
stages = (
stages_by_project[project_id] if project_id in stages_by_project
else st.list_stages(project_id=project_id) # 보관된 프로젝트 등 목록 밖
)
tasks_by_ctx: dict[int, list[dict[str, Any]]] = {}
for t in all_tasks:
tasks_by_ctx.setdefault(t["context_project_id"], []).append(t)
nav_projects: list[dict[str, Any]] = []
projects_meta: list[dict[str, Any]] = []
for p in top_projects:
p_tasks = tasks_by_ctx.get(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_open_total = st.count_my_open(assignee_email=user["email"])
mention_unread = _safe_mention_unread(st, user["email"])
# 달력(휴가식 월간 그리드) — ?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_open_total": my_open_total,
"mention_unread": mention_unread,
"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")
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")
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")
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")
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}")
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}")
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)
try:
removed_task_ids = st.delete_project(project_id=project_id)
except KeyError:
raise HTTPException(status_code=404, detail="프로젝트를 찾을 수 없습니다.")
_remove_task_dirs(request, removed_task_ids)
return JSONResponse({"ok": True})
# ────────────────────────────────────────────────────────────
# JSON API — 멤버 (관리자가 사용자 배정)
# ────────────────────────────────────────────────────────────
@router.get("/api/assignable-users")
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")
def api_all_users(request: Request) -> JSONResponse:
"""project 모듈 권한 보유 등록 사용자 전원 — 좌측 "전체 멤버"(관리자
에게만 그린다) + 설명란/댓글 @태그 후보 목록. @태그는 일반 직원도 쓰므로
이 API 자체는 로그인 사용자 누구나 호출 가능(이름·아이디·사진만 반환)."""
_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")
def api_user_tasks(
request: Request, email: str, project_id: int | None = None
) -> JSONResponse:
"""'전체 멤버'/사이드바 '프로젝트 멤버' 아이콘 클릭 팝업 — 지정한 사용자가
담당자인 업무 목록(프로젝트/세션/마감일). project_id 를 주면 그 프로젝트
안에서 담당하는 업무만(멀티호밍으로 연결된 업무 포함, list_tasks 의
project_id 단일 조회 경로 재사용). 안 주면 전체 프로젝트 대상."""
user = _require_user(request)
st = _db_or_503(request)
if project_id is not None:
_require_manage(request, st, user, project_id)
tasks = st.list_tasks(project_id=project_id, assignee_email=email, limit=500)
else:
tasks = st.list_tasks(assignee_email=email, limit=500)
# 전체 대상이면 내가 볼 수 있는 프로젝트의 업무만 남긴다(비관리자).
allowed = _accessible_project_ids(st, user)
if allowed is not None:
tasks = [t for t in tasks if t["project_id"] in allowed]
return JSONResponse({"tasks": tasks})
@router.get("/api/projects/{project_id}/members")
def api_list_members(request: Request, project_id: int) -> JSONResponse:
user = _require_user(request)
st = _db_or_503(request)
_require_manage(request, st, user, project_id)
return JSONResponse({"members": st.list_members(project_id=project_id)})
@router.post("/api/projects/{project_id}/members")
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}")
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")
def api_list_stages(request: Request, project_id: int) -> JSONResponse:
user = _require_user(request)
st = _db_or_503(request)
_require_manage(request, st, user, project_id)
return JSONResponse({"stages": st.list_stages(project_id=project_id)})
@router.post("/api/projects/{project_id}/stages")
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)
dae = _stage_default_assignee_arg(st, project_id, payload)
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"],
default_assignee_email="" if dae is ... else dae,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except UndefinedColumn:
raise HTTPException(status_code=503, detail=_STAGE_ASSIGNEE_MIGRATION_MSG)
return JSONResponse({"stage": stage}, status_code=201)
_STAGE_ASSIGNEE_MIGRATION_MSG = (
"세션 기본 담당자 기능이 아직 준비되지 않았습니다(DB 마이그레이션 009 필요)."
)
def _stage_default_assignee_arg(st: Any, project_id: int, payload: dict[str, Any]) -> Any:
"""payload 의 세션 기본 담당자 — 키가 없으면 `...`(변경 안 함), 빈 값이면 ''
(해제). 값이 있으면 그 프로젝트 멤버 또는 owner 여야 한다(업무 담당자
후보와 같은 기준)."""
if "default_assignee_email" not in payload:
return ...
email = store.norm_str(payload.get("default_assignee_email") or "", lower=True)
if email:
allowed = {m["user_email"] for m in st.list_members(project_id=project_id)}
project = st.get_project(project_id=project_id) or {}
allowed.add(store.norm_str(project.get("owner_email") or "", lower=True))
if email not in allowed:
raise HTTPException(status_code=400, detail="기본 담당자는 이 프로젝트 멤버여야 합니다.")
return email
def _stage_of_project(st: Any, stage_id: int, project_id: int) -> dict[str, Any]:
"""URL 의 세션이 URL 의 프로젝트 것인지 확인. 권한 검사는 project_id 로
하므로, 이걸 안 보면 아무 프로젝트 멤버나 남의 세션을 고칠 수 있다."""
stage = st.get_stage(stage_id=stage_id)
if stage is None or stage["project_id"] != project_id:
raise HTTPException(status_code=404, detail="세션을 찾을 수 없습니다.")
return stage
@router.delete("/api/projects/{project_id}/stages/{stage_id}")
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 = _stage_of_project(st, stage_id, project_id)
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")
def api_list_tasks(request: Request, project_id: int) -> JSONResponse:
user = _require_user(request)
st = _db_or_503(request)
_require_manage(request, st, user, project_id)
tasks = st.list_tasks(project_id=project_id, include_subprojects=True, limit=2000)
return JSONResponse({"tasks": tasks})
@router.get("/api/projects/{project_id}/snapshot")
def api_project_snapshot(request: Request, project_id: int) -> JSONResponse:
"""프로젝트 화면 실시간 동기화용 — 업무(이 프로젝트 + 여기 연결된 업무,
context_project_id·home_stage_id 포함)·세션·멤버를 요청 한 번에.
예전엔 API 3개를 따로 불렀고, 업무 API 는 연결 업무를 빼고 돌려줘서
화면의 연결 업무 행과 맞지 않았다.
"""
user = _require_user(request)
st = _db_or_503(request)
_require_manage(request, st, user, project_id)
return JSONResponse({
"tasks": st.list_tasks_for_projects(project_ids=[project_id]),
"stages": st.list_stages(project_id=project_id),
"members": st.list_members(project_id=project_id),
})
@router.get("/api/my-tasks")
def api_my_tasks(request: Request) -> JSONResponse:
user = _require_user(request)
st = _db_or_503(request)
return JSONResponse({"tasks": st.list_my_tasks(assignee_email=user["email"], limit=1000)})
@router.get("/api/my-tasks/open-count")
def api_my_open_count(request: Request) -> JSONResponse:
"""사이드바 "내 업무" 배지 숫자만 — 목록 전체를 받지 않는다."""
user = _require_user(request)
st = _db_or_503(request)
return JSONResponse({"open": st.count_my_open(assignee_email=user["email"])})
@router.post("/api/projects/{project_id}/tasks")
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))
# 만든 사람·담당자는 자동 팔로워(아사나와 같은 규칙)
_follow(st, task["id"], [user["email"], task.get("assignee_email") or ""])
# 생성과 동시에 담당자 지정 시 관리자 메일 + 담당자 인앱 알림
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 '-'}",
)
_record_mentions(
st, task=task,
emails=store.extract_mentions_from_html(task.get("description") or ""),
actor=user["email"], project_name=project["name"],
)
return JSONResponse({"task": task}, status_code=201)
@router.put("/api/tasks/{task_id}")
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"):
_follow(st, task_id, [task["_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,
)
if "description" in payload:
_record_mentions(
st, task=task,
emails=store.extract_mentions_from_html(payload["description"]),
actor=user["email"], project_name=project_name,
)
return JSONResponse({"task": task})
@router.delete("/api/tasks/{task_id}")
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)
try:
removed_task_ids = st.delete_task(task_id=task_id)
except KeyError:
raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.")
_remove_task_dirs(request, removed_task_ids) # 하위 업무 첨부 폴더까지
return JSONResponse({"ok": True})
@router.get("/api/tasks/{task_id}")
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)
try:
task["followers"] = st.list_followers(task_id=task_id)
except Exception: # noqa: BLE001 - 008 미적용이면 팔로워 UI 를 숨긴다
task["followers"] = None
return JSONResponse({"task": task})
# ────────────────────────────────────────────────────────────
# JSON API — 팔로워 (아사나의 협업자)
# ────────────────────────────────────────────────────────────
def _task_for_followers(request: Request, st: Any, user: dict[str, Any], task_id: int) -> dict[str, Any]:
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 task
def _followers_response(st: Any, task_id: int) -> JSONResponse:
try:
return JSONResponse({"followers": st.list_followers(task_id=task_id)})
except Exception: # noqa: BLE001
raise HTTPException(status_code=503, detail="팔로워 기능은 project_db_008 마이그레이션 후 사용할 수 있습니다.")
@router.get("/api/tasks/{task_id}/followers")
def api_list_followers(request: Request, task_id: int) -> JSONResponse:
user = _require_user(request)
st = _db_or_503(request)
_task_for_followers(request, st, user, task_id)
return _followers_response(st, task_id)
@router.post("/api/tasks/{task_id}/followers")
def api_add_follower(
request: Request, task_id: int, payload: dict[str, Any] = Body(default={})
) -> JSONResponse:
"""팔로워 추가. email 을 안 주면 나 자신(팔로우). 다른 사람은 그 프로젝트를
볼 수 있는 사람(멤버·owner·관리자)만 추가할 수 있다 — 못 보는 업무의 알림이
가면 안 되므로."""
from app.main import user_store # noqa: WPS433
from app.store import is_admin # noqa: WPS433
user = _require_user(request)
st = _db_or_503(request)
task = _task_for_followers(request, st, user, task_id)
email = store.norm_str(payload.get("email") or user["email"], lower=True)
if email != store.norm_str(user["email"], lower=True):
target = user_store.get(email)
allowed = (target is not None and is_admin(target)) or st.is_member(
project_id=task["project_id"], user_email=email
)
if not allowed:
raise HTTPException(status_code=400, detail="이 프로젝트 멤버만 팔로워로 추가할 수 있습니다.")
try:
st.add_followers(task_id=task_id, emails=[email])
except Exception: # noqa: BLE001
raise HTTPException(status_code=503, detail="팔로워 기능은 project_db_008 마이그레이션 후 사용할 수 있습니다.")
return _followers_response(st, task_id)
@router.delete("/api/tasks/{task_id}/followers/{email}")
def api_remove_follower(request: Request, task_id: int, email: str) -> JSONResponse:
user = _require_user(request)
st = _db_or_503(request)
_task_for_followers(request, st, user, task_id)
try:
st.remove_follower(task_id=task_id, user_email=email)
except Exception: # noqa: BLE001
raise HTTPException(status_code=503, detail="팔로워 기능은 project_db_008 마이그레이션 후 사용할 수 있습니다.")
return _followers_response(st, task_id)
# ────────────────────────────────────────────────────────────
# JSON API — 전체 검색 (좌측 사이드바 검색창)
# ────────────────────────────────────────────────────────────
@router.get("/api/search")
def api_search(request: Request, q: str = "", limit: int = 20) -> JSONResponse:
"""제목·설명·댓글 검색 — 내가 볼 수 있는 프로젝트의 업무(하위 업무 포함).
설명은 HTML 이라 DB 에서는 넉넉히 가져온 뒤 본문 텍스트에 실제로 검색어가
있는지 다시 확인한다(태그 이름·속성에만 걸린 결과 제거). 결과마다 어디서
걸렸는지(match: title/description/comment)와 미리보기(snippet)를 붙인다.
"""
user = _require_user(request)
st = _db_or_503(request)
query = store.norm_str(q)[:100]
if len(query) < 2:
return JSONResponse({"results": [], "query": query})
limit = max(1, min(int(limit), 50))
rows = st.search_tasks(
query=query, project_ids=_accessible_project_ids(st, user), limit=limit * 3,
)
ql = query.lower()
out: list[dict[str, Any]] = []
for r in rows:
desc_text = store.html_to_text(r.get("description") or "")
if r.get("hit_title"):
match, snippet = "title", store.search_snippet(desc_text, query) if ql in desc_text.lower() else ""
elif ql in desc_text.lower():
match, snippet = "description", store.search_snippet(desc_text, query)
elif r.get("comment_hit"):
match, snippet = "comment", store.search_snippet(r["comment_hit"], query)
else:
continue # 설명 HTML 태그에만 걸린 경우
out.append({
"id": r["id"],
"title": r["title"],
"project_id": r["project_id"],
"project_name": r.get("project_name") or "",
"project_color": r.get("project_color") or "#4573d2",
"parent_title": r.get("parent_title") or "",
"completed": bool(r.get("completed_at")),
"due_date": r.get("due_date"),
"assignee_email": r.get("assignee_email") or "",
"match": match,
"snippet": snippet,
})
if len(out) >= limit:
break
return JSONResponse({"results": out, "query": query})
# ────────────────────────────────────────────────────────────
# JSON API — 업무 멀티호밍 (다른 프로젝트/세션에 연결)
# ────────────────────────────────────────────────────────────
@router.post("/api/tasks/{task_id}/links")
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"])
try:
stage_id = st.stage_in_project(
stage_id=payload.get("stage_id") or None, project_id=target_project_id
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
link = st.add_task_link(
task_id=task_id, project_id=target_project_id,
stage_id=stage_id, created_by=user["email"],
)
return JSONResponse({"link": link}, status_code=201)
@router.delete("/api/tasks/{task_id}/links/{project_id}")
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")
def api_activity(request: Request, project_id: int) -> JSONResponse:
user = _require_user(request)
st = _db_or_503(request)
_require_manage(request, st, user, project_id)
return JSONResponse({"activity": st.list_activity(project_id=project_id, limit=100)})
# ────────────────────────────────────────────────────────────
# JSON API — 댓글
# ────────────────────────────────────────────────────────────
@router.get("/api/tasks/{task_id}/comments")
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")
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))
_follow(st, task_id, [user["email"]]) # 댓글 단 사람은 이후 소식도 받는다
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],
)
# 댓글은 평문이라 본문에서 이메일을 꺼낼 수 없다 — 화면이 고른 멤버
# 목록을 그대로 받아 기록한다(설명란은 본문 HTML 에서 직접 뽑는다).
_record_mentions(
st, task=task, emails=store.normalize_emails(payload.get("mentions")),
actor=user["email"], comment_id=comment["id"], source="comment",
project_name=project.get("name", ""),
)
return JSONResponse({"comment": comment}, status_code=201)
@router.put("/api/comments/{comment_id}")
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}")
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:
files = 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))
# 댓글 첨부 행은 CASCADE 로 사라졌다 — 디스크 파일도 치운다.
for f in files:
try:
(_attach_dir(request, f["task_id"]) / f["stored_name"]).unlink(missing_ok=True)
except Exception: # noqa: BLE001
logger.warning("댓글 첨부 파일 삭제 실패: %s", f.get("stored_name"))
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")
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")
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="잘못된 댓글입니다.")
# 한도+1 바이트까지만 읽는다 — 20MB 를 넘는 파일을 끝까지 메모리에 올린 뒤에야
# 거절하던 것을 막는다(핸들러가 sync def 라 스레드풀에서 동기 읽기).
data = file.file.read(_MAX_ATTACH_BYTES + 1)
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")
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",
headers=_ATTACH_HEADERS,
)
@router.get("/api/attachments/{attachment_id}/inline")
def api_inline_attachment(request: Request, attachment_id: int):
"""설명란에 붙여넣은/업로드한 이미지를 `<img src=...>` 로 바로 보여주기 위한
서빙. `/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="파일이 디스크에 없습니다.")
content_type = att.get("content_type") or "application/octet-stream"
if not store.inline_safe_content_type(content_type):
# 형식은 업로드한 쪽이 정한 값이라 믿을 수 없다 — text/html·svg 등을 같은
# 도메인에서 그대로 띄우면 스크립트가 로그인 세션으로 돈다(저장형 XSS).
# 안전한 이미지가 아니면 항상 다운로드로 내려준다.
return FileResponse(
str(path), filename=att["filename"],
media_type="application/octet-stream", headers=_ATTACH_HEADERS,
)
return FileResponse(str(path), media_type=content_type, headers=_ATTACH_HEADERS)
@router.delete("/api/attachments/{attachment_id}")
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")
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")
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)
_stage_of_project(st, stage_id, 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}")
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)
_stage_of_project(st, stage_id, project_id)
dae = _stage_default_assignee_arg(st, project_id, payload)
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", ...),
default_assignee_email=dae,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except UndefinedColumn:
raise HTTPException(status_code=503, detail=_STAGE_ASSIGNEE_MIGRATION_MSG)
except KeyError:
raise HTTPException(status_code=404, detail="단계를 찾을 수 없습니다.")
return JSONResponse({"stage": stage})
# ────────────────────────────────────────────────────────────
# 알림센터 (인앱)
# ────────────────────────────────────────────────────────────
@router.get("/api/notifications")
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")
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")
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")
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})
# ────────────────────────────────────────────────────────────
# 수신함 — 나를 @태그한 업무 (아사나 Inbox)
# ────────────────────────────────────────────────────────────
def _safe_mentions(st: Any, email: str, *, limit: int = 100) -> list[dict[str, Any]]:
"""task_mentions 조회. 006 마이그레이션 미적용 환경에서도 화면이 죽지 않게."""
try:
return st.list_mentioned_tasks(mentioned_email=email, limit=limit)
except Exception: # noqa: BLE001
logger.warning("멘션 조회 실패 — project_db_006 마이그레이션 확인 필요")
return []
def _safe_mention_unread(st: Any, email: str) -> int:
try:
return st.count_unread_mentions(mentioned_email=email)
except Exception: # noqa: BLE001
return 0
@router.get("/api/mentions")
def api_mentions(request: Request) -> JSONResponse:
"""나를 태그한 업무 목록 + 미확인 개수."""
user = _require_user(request)
st = _db_or_503(request)
tasks = _safe_mentions(st, user["email"])
return JSONResponse({
"tasks": tasks,
"unread": _safe_mention_unread(st, user["email"]),
})
@router.get("/api/mentions/unread-count")
def api_mentions_unread(request: Request) -> JSONResponse:
user = _require_user(request)
st = _db_or_503(request)
return JSONResponse({"unread": _safe_mention_unread(st, user["email"])})
@router.post("/api/mentions/read")
def api_mentions_read(
request: Request, payload: dict[str, Any] = Body(default={})
) -> JSONResponse:
"""태그 확인 처리. task_id 를 주면 그 업무만, 없으면 전부."""
user = _require_user(request)
st = _db_or_503(request)
task_id = payload.get("task_id")
try:
n = st.mark_mentions_read(
mentioned_email=user["email"],
task_id=int(task_id) if task_id else None,
)
except Exception: # noqa: BLE001
n = 0
return JSONResponse({"ok": True, "marked": n})
@router.get("/inbox", response_class=HTMLResponse)
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)
admin = is_admin(user)
items = st.list_notifications(recipient_email=user["email"], limit=100)
mentioned = _safe_mentions(st, user["email"])
for t in mentioned:
t["due_label"] = _fmt_date_kr(t.get("due_date"))
# 좌측 사이드바(project/_side.html)는 세 화면 공용 — 같은 데이터가 필요하다.
nav_projects = _nav_projects(st, user, admin)
my_open_total = st.count_my_open(assignee_email=user["email"])
return render_template(
request,
"project/inbox.html",
{
"user": user,
"is_admin": admin,
"nav_items": build_erp_nav(user, active="project"),
"nav_projects": nav_projects,
"my_open_total": my_open_total,
"page_title": "수신함",
"page_subtitle": "나를 태그한 업무와 프로젝트 알림",
"force_sidebar_collapsed": True,
"notifications": items,
"mentioned_tasks": mentioned,
"mention_unread": _safe_mention_unread(st, user["email"]),
},
)