Files
dbx-main/app/modules/project/router.py
T
king 20232baf06 feat(project): add font options and selected goal text formatting
Restore the board header add button to the task side panel while keeping footer quick entry. Add safe, persisted goal text formatting and self-hosted Project font preferences with shared help updates and regression coverage.
2026-10-02 17:28:54 +09:00

3287 lines
151 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 json
import logging
import threading
import time
import uuid
from datetime import date, timedelta
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, UndefinedTable
from app.timezone import KST, now_kst, today_kst
from . import access, 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 (access.can_manage_project — 지금 기준)."""
return access.can_manage_project(st, user, project_id)
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(=전체)."""
return access.visible_project_ids(st, user)
_TASK_DENIED = "이 작업을 볼 권한이 없습니다. 프로젝트 관리자에게 멤버 배정을 요청하세요."
_TASK_READ_ONLY = ("다른 프로젝트에서 연결된 작업이라 읽기만 할 수 있습니다. "
"변경은 원 소속 프로젝트 멤버만 할 수 있습니다.")
def _task_or_404(st: 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="작업을 찾을 수 없습니다.")
return task
def _require_task(
st: Any, user: dict[str, Any], task: dict[str, Any], *, write: bool = True
) -> str:
"""작업 권한 공통 검사 — write=True 면 원 소속 권한(FULL)만, False 면 연결된 프로젝트의
읽기(READ)도 허용. 권한 레벨을 돌려준다."""
level = access.task_access(st, user, task)
if level is None:
raise HTTPException(status_code=403, detail=_TASK_DENIED)
if write and level != access.FULL:
raise HTTPException(status_code=403, detail=_TASK_READ_ONLY)
return level
def _my_visible_tasks(st: Any, user: dict[str, Any]) -> list[dict[str, Any]]:
"""내가 담당인 작업 중 지금 볼 수 있는 것만 — 권한을 잃은 프로젝트의 작업은 빠진다."""
return access.filter_visible_tasks(
st, user, st.list_my_tasks(assignee_email=user["email"], limit=1000)
)
def _my_open_count(st: Any, user: dict[str, Any]) -> int:
"""사이드바 "내 작업" 배지 — _my_visible_tasks 와 같은 기준."""
return sum(1 for t in _my_visible_tasks(st, user) if not t.get("completed_at"))
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 _project_data_dir(request: Request) -> Path:
return Path(str(getattr(request.app.state, "data_dir", "."))) / "project"
def _trash_dir(request: Request, trash_id: int) -> Path:
"""휴지통으로 옮긴 첨부 폴더 자리 — DATA_DIR/project/_trash/<trash_id>/<task_id>."""
return _project_data_dir(request) / "_trash" / str(int(trash_id))
def _move_task_dirs_to_trash(request: Request, task_ids: list[int], trash_id: int) -> None:
"""지운 업무들의 첨부 폴더를 휴지통 폴더로 옮긴다(복구 시 되돌림). 실패해도
삭제는 이미 끝났으므로 로그만."""
import shutil # noqa: WPS433
base = _project_data_dir(request)
dest_root = _trash_dir(request, trash_id)
for tid in task_ids:
src = base / str(int(tid))
if not src.is_dir():
continue
try:
dest_root.mkdir(parents=True, exist_ok=True)
shutil.move(str(src), str(dest_root / str(int(tid))))
except Exception: # noqa: BLE001
logger.warning("첨부 폴더 휴지통 이동 실패: %s", src)
def _restore_task_dirs(request: Request, trash_id: int) -> None:
"""휴지통 폴더의 첨부 폴더를 원래 자리(DATA_DIR/project/<task_id>)로 되돌린다."""
import shutil # noqa: WPS433
root = _trash_dir(request, trash_id)
if not root.is_dir():
return
base = _project_data_dir(request)
for d in root.iterdir():
if not d.is_dir():
continue
dest = base / d.name
try:
if dest.exists():
logger.warning("복구 대상 첨부 폴더가 이미 있음 — 건너뜀: %s", dest)
continue
shutil.move(str(d), str(dest))
except Exception: # noqa: BLE001
logger.warning("첨부 폴더 복구 실패: %s", d)
try:
root.rmdir()
except OSError:
pass
def _purge_trash(request: Request, st: Any) -> None:
"""보관 기간(3개월)이 지난 휴지통 항목과 그 첨부 폴더를 영구 삭제. 휴지통 화면을
열거나 업무를 지울 때 가볍게 돈다. 실패해도 본 작업은 막지 않는다."""
import shutil # noqa: WPS433
try:
purged = st.purge_expired_trash()
except Exception: # noqa: BLE001 - 010 미적용 등
return
for trash_id in purged:
d = _trash_dir(request, trash_id)
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 + 멤버 전원. 멤버에서 빠진 담당자·협업자는 기록은 남아도 받지 않는다.
"""
return access.filter_recipients(st, task, _task_recipients_raw(st, project, task, exclude=exclude))
def _task_recipients_raw(
st: Any, project: dict[str, Any], task: dict[str, Any], *, exclude: str = ""
) -> list[str]:
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 = "",
) -> list[str]:
"""@태그를 기록하고 새로 태그된 사람에게만 알림을 만든다. 태그할 수 없는 사람(이 작업을
지금 볼 수 없는 직원·등록 안 된 이메일)은 기록·알림·협업자 등록 없이 건너뛰고 그 목록을
돌려준다 — 태그로 작업 정보가 새거나 접근 권한이 생기지 않게(payload 에 이메일을 직접 넣어도).
태그는 부가 기능이라 여기서 실패해도(예: 006 마이그레이션 미적용) 본
저장/등록은 막지 않는다 — 로그만 남긴다.
"""
wanted = store.normalize_emails(emails)
if not wanted:
return []
allowed = access.filter_recipients(st, task, wanted)
skipped = [e for e in wanted if e not in allowed and e != store.norm_str(actor, lower=True)]
if not allowed:
return skipped
try:
added = st.add_mentions(
task_id=task["id"], emails=allowed, actor_email=actor,
comment_id=comment_id, source=source,
)
except Exception: # noqa: BLE001
logger.warning("멘션 기록 실패: task=%s", task.get("id"))
return skipped
if not added:
return skipped
_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}",
)
return skipped
def _notify_completed(
bg: BackgroundTasks, request: Request, st: Any, *, project: dict[str, Any],
task: dict[str, Any], actor: str,
) -> None:
"""작업 완료 알림 — 관리자 메일 + 담당자·협업자 수신함(행위자 제외, 지금 볼 수 있는 사람만).
완료 섹션으로 옮김·완료로 표시·완료 섹션에 바로 만듦 모두 이 한 곳."""
project_name = project.get("name") or task.get("project_name") or ""
_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"완료 처리: {actor}\n"
),
)
_inbox(
st, recipients=_task_recipients(st, project, task, exclude=actor),
actor=actor, project_id=task["project_id"], task_id=task["id"],
ntype="completed", title=f"작업 완료: {task['title']}", body=project_name,
)
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",
"icon": p.get("icon") or "",
"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 _goal_years_nav(st: Any) -> list[int]:
"""좌측 사이드바 "목표" 아래 연도 목록(최근 연도 먼저). 올해는 목표를 아직 안
만들었어도 항상 보인다(누르면 관리자에게 "목표 만들기"). 013 미적용이면 올해만."""
this_year = today_kst().year
try:
years = st.list_goal_years()
except UndefinedTable:
years = []
except Exception: # noqa: BLE001 — 사이드바 때문에 화면 전체가 죽지 않게
logger.exception("goal years 조회 실패")
years = []
if this_year not in years:
years.append(this_year)
return sorted(set(years), reverse=True)
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]
assignee = assignee[:1].upper() + assignee[1:] # 멤버 이름은 첫 글자 대문자
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 = _my_visible_tasks(st, user)
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,
"goal_years": _goal_years_nav(st),
"my_tasks": my_tasks,
"my_open_total": my_open_total,
"mention_unread": _safe_mention_unread(st, user),
"avatars": avatars,
"priority_labels": store.PRIORITY_LABELS,
"color_palette": list(store.COLOR_PALETTE),
"project_icons": list(store.PROJECT_ICONS),
"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)
level = access.task_access(st, user, task)
if level is None:
return _denied(
"이 작업이 속한 프로젝트의 멤버만 볼 수 있습니다. "
"프로젝트 관리자에게 멤버 배정을 요청하세요.",
403,
)
target = task["project_id"]
if level != access.FULL:
# 연결된 프로젝트에서만 볼 수 있는 작업 — 그 프로젝트 화면에서 읽기 전용으로 연다.
target = next((pid for pid in sorted(access.link_scope(st, [task_id]).get(task_id, set()))
if _can_manage(request, st, user, pid)), None)
if target is None:
return _denied("이 작업을 볼 권한이 없습니다.", 403)
# 하위 업무도 업무처럼 자기 팝업으로 연다(아사나식 — 제목 위에 상위 업무 경로).
return RedirectResponse(url=f"/project/p/{target}?task={task_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",
"icon": p.get("icon") or "",
"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",
"icon": p.get("icon") or "",
"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 = _my_open_count(st, user)
mention_unread = _safe_mention_unread(st, user)
# 달력(휴가식 월간 그리드) — ?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,
"goal_years": _goal_years_nav(st),
"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),
"project_icons": list(store.PROJECT_ICONS),
"stage_color_palette": list(store.STAGE_COLOR_PALETTE),
"today": today.isoformat(),
# 타임라인 날짜 색(일요일·국경일·대체공휴일 빨강) — 캘린더와 같은 공휴일 표
"holidays": store.KR_HOLIDAYS,
"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)})
_PROJECT_ICON_MIGRATION_MSG = "프로젝트 아이콘 기능이 아직 준비되지 않았습니다(DB 마이그레이션 011 필요)."
_OWNER_ADMIN_ONLY = "프로젝트 소유자는 관리자만 지정·변경할 수 있습니다."
def _owner_for_create(user: dict[str, Any], payload: dict[str, Any]) -> str:
"""새 프로젝트 소유자 — 만든 사람. 다른 사람을 소유자로 지정하는 건 관리자만(그 사람은
등록 사용자이고 project 모듈 권한이 있어야 한다). 비관리자가 남을 지정하면 거절."""
me = store.norm_str(user["email"], lower=True)
want = store.norm_str(payload.get("owner_email") or "", lower=True)
if not want or want == me:
return me
from app.store import is_admin # noqa: WPS433
if not is_admin(user):
raise HTTPException(status_code=403, detail=_OWNER_ADMIN_ONLY)
_check_owner_candidate(want)
return want
def _check_owner_candidate(email: str) -> None:
rec = access.default_user_lookup(email)
if not rec or not access.can_use_module({**rec, "email": email}):
raise HTTPException(status_code=400,
detail="소유자는 프로젝트 관리 권한이 있는 등록 사용자여야 합니다.")
@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=_owner_for_create(user, payload),
start_date=payload.get("start_date"),
due_date=payload.get("due_date"),
created_by=user["email"],
icon=payload.get("icon"),
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except UndefinedColumn:
raise HTTPException(status_code=503, detail=_PROJECT_ICON_MIGRATION_MSG)
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=_owner_for_create(user, payload),
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:
from app.store import is_admin # noqa: WPS433
user = _require_user(request)
st = _db_or_503(request)
_require_manage(request, st, user, project_id)
fields = dict(payload)
if "owner_email" in fields:
# 소유자는 멤버 목록과 별개로 계속 관리 권한을 준다 — 스스로를 소유자로 바꿔 권한 회수를
# 피할 수 없게 관리자만. 값이 그대로면(화면이 같이 보낸 경우) 그냥 무시한다.
current = st.get_project(project_id=project_id)
if current is None:
raise HTTPException(status_code=404, detail="프로젝트를 찾을 수 없습니다.")
want = store.norm_str(fields.get("owner_email") or "", lower=True)
if want == store.norm_str(current.get("owner_email") or "", lower=True):
fields.pop("owner_email")
elif not is_admin(user):
raise HTTPException(status_code=403, detail=_OWNER_ADMIN_ONLY)
elif want:
_check_owner_candidate(want)
try:
project = st.update_project(project_id=project_id, fields=fields)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except UndefinedColumn:
raise HTTPException(status_code=503, detail=_PROJECT_ICON_MIGRATION_MSG)
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="프로젝트를 찾을 수 없습니다.")
# 만든 사람이어도 지금 그 프로젝트 권한이 없으면(멤버에서 빠짐) 지울 수 없다.
_require_manage(request, st, user, project_id)
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, task_id: int | None = None) -> JSONResponse:
"""project 모듈 권한 보유 등록 사용자 전원 — 좌측 "전체 멤버"(관리자
에게만 그린다) + 설명란/댓글 @태그 후보 목록. @태그는 일반 직원도 쓰므로
이 API 자체는 로그인 사용자 누구나 호출 가능(이름·아이디·사진만 반환).
task_id 를 주면 @태그 후보 — 그 작업을 지금 볼 수 있는 사람만(원 소속 멤버·owner·관리자,
연결된 프로젝트 멤버). 태그로 작업 정보가 새지 않게 서버도 저장할 때 다시 거른다."""
user = _require_user(request)
from app.main import user_store # noqa: WPS433
from app.store import has_module # noqa: WPS433
users = [u for u in user_store.list_all() if has_module(u, "project")]
if task_id is not None:
st = _db_or_503(request)
task = _task_or_404(st, task_id)
_require_task(st, user, task, write=False)
users = [u for u in users if access.task_access(st, u, task) is not None]
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 users
]
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, scope: str = "project") -> JSONResponse:
"""프로젝트 화면 실시간 동기화용 — 업무(이 프로젝트 + 여기 연결된 업무,
context_project_id·home_stage_id 포함)·세션·멤버를 요청 한 번에.
scope=all — 프로젝트 화면이 들고 있는 것과 같은 범위(지금 볼 수 있는 모든 최상위 프로젝트의
작업·섹션·프로젝트 목록)를 통째로 준다. 다른 프로젝트의 새 작업·삭제·섹션 변경·권한 회수까지
반영된다(예전엔 지금 연 프로젝트 것만 받아 다른 프로젝트 행이 남거나 빠졌다).
이 프로젝트 권한을 잃었으면 403 — 화면이 편집을 멈추고 안내한다.
"""
user = _require_user(request)
st = _db_or_503(request)
_require_manage(request, st, user, project_id)
if scope != "all":
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),
})
allowed = _accessible_project_ids(st, user)
top = [
p for p in st.list_projects(include_archived=False,
member_email=None if allowed is None else user["email"])
if not p.get("parent_id")
]
ids = [p["id"] for p in top]
stages_by_project = st.list_stages_for_projects(project_ids=ids)
return JSONResponse({
"scope": "all",
"project": st.get_project(project_id=project_id),
"projects": [_project_meta(p) for p in top],
"tasks": st.list_tasks_for_projects(project_ids=ids),
"stages_by_project": {str(k): v for k, v in stages_by_project.items()},
"stages": stages_by_project.get(project_id) or st.list_stages(project_id=project_id),
"members": st.list_members(project_id=project_id),
})
def _project_meta(p: dict[str, Any]) -> dict[str, Any]:
"""프로젝트 화면·스냅샷 공용 프로젝트 요약(사이드바·타임라인 그룹·보드 배지용)."""
return {
"id": p["id"],
"name": p["name"],
"color": p.get("color") or "#4573d2",
"icon": p.get("icon") or "",
"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",
}
@router.get("/api/my-tasks")
def api_my_tasks(request: Request) -> JSONResponse:
user = _require_user(request)
st = _db_or_503(request)
return JSONResponse({"tasks": _my_visible_tasks(st, user)})
@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": _my_open_count(st, user)})
@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="프로젝트를 찾을 수 없습니다.")
_check_assignee(st, payload.get("assignee_email"), project_id)
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 '-'}",
)
# 완료 섹션에 바로 만든 작업 — 완료 섹션으로 옮긴 것과 같은 완료 알림.
if task.pop("_newly_completed", False):
_notify_completed(bg, request, st, project=project, task=task, actor=user["email"])
skipped = _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, "mention_skipped": skipped}, status_code=201)
_ASSIGNEE_DENIED = "담당자는 이 프로젝트를 볼 수 있는 사람(멤버·소유자·관리자)이어야 합니다."
def _check_assignee(st: Any, email: Any, project_id: int, *, previous: str = "") -> None:
"""새로 지정하는 담당자가 그 프로젝트를 볼 수 있는지 — 권한 없는 사람에게 배정 알림(작업 제목
등)이 가지 않게. 비우거나 그대로 두는 건 검사하지 않는다(멤버에서 빠진 예전 담당자 보존)."""
em = store.norm_str(email or "", lower=True)
if not em or em == store.norm_str(previous or "", lower=True):
return
if not access.can_assign(st, em, project_id):
raise HTTPException(status_code=400, detail=_ASSIGNEE_DENIED)
@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 = _task_or_404(st, task_id)
_require_task(st, user, existing, write=True)
if "assignee_email" in payload:
_check_assignee(st, payload.get("assignee_email"), existing["project_id"],
previous=existing.get("assignee_email") or "")
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_completed(bg, request, st, project=project, task=task, actor=user["email"])
skipped: list[str] = []
if "description" in payload:
skipped = _record_mentions(
st, task=task,
emails=store.extract_mentions_from_html(payload["description"]),
actor=user["email"], project_name=project_name,
)
return JSONResponse({"task": task, "mention_skipped": skipped})
@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 = _task_or_404(st, task_id)
# 만든 사람이어도 지금 원 소속 프로젝트 권한이 없으면(멤버에서 빠짐) 지울 수 없다.
_require_task(st, user, existing, write=True)
if not _can_delete(user, existing.get("created_by")):
raise HTTPException(status_code=403, detail=_DELETE_DENIED)
try:
removed_task_ids, trash_id = st.delete_task(task_id=task_id, deleted_by=user["email"])
except KeyError:
raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.")
# 휴지통(010)이 있으면 첨부 폴더도 휴지통으로(복구 대비), 없으면 예전처럼 삭제.
if trash_id is not None:
_move_task_dirs_to_trash(request, removed_task_ids, trash_id)
else:
_remove_task_dirs(request, removed_task_ids) # 하위 업무 첨부 폴더까지
_purge_trash(request, st)
return JSONResponse({"ok": True, "trash": trash_id is not None, "count": len(removed_task_ids)})
@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 = _task_or_404(st, task_id)
# 원 소속 권한(FULL) 또는 연결된 프로젝트의 읽기 권한(READ). READ 면 화면이 읽기 전용으로 연다.
level = _require_task(st, user, task, write=False)
task["access"] = level
# 하위 업무를 팝업으로 열면 제목 위에 상위 업무 경로를 보여준다(아사나식).
if task.get("parent_task_id"):
parent = st.get_task(task_id=task["parent_task_id"])
task["parent_title"] = parent["title"] if parent else ""
task["subtasks"] = st.list_tasks(parent_task_id=task_id)
# 다른 연결 프로젝트 중 내가 볼 수 없는 곳은 이름·색도 보이지 않게 뺀다.
allowed = _accessible_project_ids(st, user)
task["links"] = [
ln for ln in st.list_task_links(task_id=task_id)
if allowed is None or int(ln["project_id"]) in allowed
]
if level != access.FULL:
task["followers"] = None # 읽기 전용 — 협업자 편집 칸을 숨긴다
else:
try:
task["followers"] = st.list_followers(task_id=task_id)
except Exception: # noqa: BLE001 - 008 미적용이면 팔로워 UI 를 숨긴다
task["followers"] = None
return JSONResponse({"task": task})
@router.put("/api/tasks/{task_id}/subtasks/order")
def api_reorder_subtasks(
request: Request, task_id: int, payload: dict[str, Any] = Body(...)
) -> JSONResponse:
"""작업 팝업의 하위 작업 목록을 드래그로 재정렬. body: {"ordered_ids": [...]}"""
user = _require_user(request)
st = _db_or_503(request)
parent = _task_or_404(st, task_id)
_require_task(st, user, parent, write=True)
ids = payload.get("ordered_ids") or []
if not isinstance(ids, list) or not ids:
raise HTTPException(status_code=400, detail="ordered_ids 가 필요합니다.")
try:
ordered = [int(i) for i in ids]
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail="ordered_ids 가 올바르지 않습니다.")
st.reorder_subtasks(parent_task_id=task_id, ordered_ids=ordered)
return JSONResponse({"ok": True})
@router.post("/api/tasks/{task_id}/move-parent")
def api_move_subtask(
request: Request,
task_id: int,
payload: dict[str, Any] = Body(...),
) -> JSONResponse:
"""하위 업무를 다른 상위 업무로 옮긴다 — 보드에서 하위 업무 줄을 다른 카드로 드래그.
body: {"parent_task_id": 받는 업무 id}. 받는 업무는 같은 프로젝트의 최상위 업무만.
"""
user = _require_user(request)
st = _db_or_503(request)
existing = _task_or_404(st, task_id)
_require_task(st, user, existing, write=True)
try:
parent_id = int(payload.get("parent_task_id"))
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail="parent_task_id 가 필요합니다.")
try:
task = st.move_subtask(task_id=task_id, parent_task_id=parent_id, actor=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({"task": task})
# ────────────────────────────────────────────────────────────
# JSON API — 팔로워 (아사나의 협업자)
# ────────────────────────────────────────────────────────────
def _task_for_followers(request: Request, st: Any, user: dict[str, Any], task_id: int) -> dict[str, Any]:
task = _task_or_404(st, task_id)
_require_task(st, user, task, write=True)
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 = _task_or_404(st, task_id)
level = _require_task(st, user, task, write=False) # 연결된 프로젝트 멤버도 읽기는 된다
# 완료 이력 줄은 "지금 완료 상태"일 때 마지막 완료 1건만 — 완료를 취소하면 사라지고,
# 예전에 완료했다가 취소한 기록도 안 보인다(이력 행 자체는 지우지 않는다).
events: list[dict[str, Any]] = []
if task.get("completed_at"):
try:
events = st.list_completion_events(task_id=task_id)[-1:]
except Exception: # noqa: BLE001 - 완료 표시는 부가 정보
logger.warning("완료 이력 조회 실패: task=%s", task_id)
return JSONResponse({
"comments": st.list_comments(task_id=task_id),
# "OO 님이 이 작업을 완료했습니다" — 댓글 사이에 시간순으로 끼워 보인다.
"events": [{"type": "completed", **e} for e in events],
"features": st.comment_features(),
# 댓글 대화창이 입력칸을 보일지 — read 면 읽기 전용(댓글·반응·답글 불가)
"access": level,
})
@router.post("/api/tasks/{task_id}/comments")
def api_add_comment(
request: Request, task_id: int, payload: dict[str, Any] = Body(...)
) -> JSONResponse:
"""글 댓글(본문 필수). 파일이 있는 댓글은 POST /comments/files(본문+파일 한 번에).
예전의 has_attachment 플래그(빈 본문 허용 후 파일을 따로 올림)는 더 받지 않는다 —
업로드가 실패하면 빈 댓글만 남았다."""
user = _require_user(request)
st = _db_or_503(request)
task = _task_or_404(st, task_id)
_require_task(st, user, task, write=True)
parent_id = _comment_parent_arg(st, payload.get("parent_id"))
token = str(payload.get("client_token") or "")[:64]
def create() -> dict[str, Any]:
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", ""),
parent_id=parent_id,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
skipped = _after_comment(st, user, task, comment, payload.get("mentions"))
return {"comment": comment, "attachments": [], "mention_skipped": skipped}
return JSONResponse(_once(user, task_id, token, create), status_code=201)
def _comment_parent_arg(st: Any, raw: Any) -> int | None:
if not raw:
return None
try:
parent_id = int(raw)
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail="parent_id 가 올바르지 않습니다.")
if not st.comment_features()["replies"]:
raise HTTPException(status_code=503, detail=_COMMENT_012_MSG)
return parent_id
def _after_comment(
st: Any, user: dict[str, Any], task: dict[str, Any], comment: dict[str, Any], mentions: Any,
*, n_files: int = 0,
) -> list[str]:
"""댓글이 만들어진 뒤 — 자동 협업자·알림·@태그. 반환: 태그하지 못한 이메일."""
comment.setdefault("parent_id", None)
comment["reactions"] = []
_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", "")}
preview = comment["body"][:120] or f"첨부 파일 {n_files}개"
_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=preview,
)
# 댓글은 평문이라 본문에서 이메일을 꺼낼 수 없다 — 화면이 고른 멤버
# 목록을 그대로 받아 기록한다(설명란은 본문 HTML 에서 직접 뽑는다).
return _record_mentions(
st, task=task, emails=store.normalize_emails(mentions),
actor=user["email"], comment_id=comment["id"], source="comment",
project_name=project.get("name", ""),
)
# 같은 댓글이 두 번 등록되지 않게(더블클릭·Enter 연타·응답을 못 받은 재전송) — 화면이 댓글마다
# 만든 client_token 으로 10분 동안 첫 결과를 돌려준다. 웹 프로세스 하나(uvicorn 단일 워커) 기준.
_ONCE_TTL_SEC = 600
_once_lock = threading.Lock()
_once_results: dict[tuple[str, int, str], tuple[float, dict[str, Any]]] = {}
_once_key_locks: dict[tuple[str, int, str], threading.Lock] = {}
def _once(user: dict[str, Any], task_id: int, token: str, fn: Any) -> dict[str, Any]:
if not token:
return fn()
key = (store.norm_str(user["email"], lower=True), int(task_id), token)
now = time.monotonic()
with _once_lock:
for k in [k for k, (t, _) in _once_results.items() if now - t > _ONCE_TTL_SEC]:
_once_results.pop(k, None)
_once_key_locks.pop(k, None)
klock = _once_key_locks.setdefault(key, threading.Lock())
with klock: # 같은 토큰의 동시 요청은 첫 요청이 끝날 때까지 기다렸다가 그 결과를 받는다
with _once_lock:
hit = _once_results.get(key)
if hit is not None:
return {**hit[1], "duplicate": True}
out = fn()
with _once_lock:
_once_results[key] = (time.monotonic(), out)
return out
_MAX_COMMENT_FILES = 20
@router.post("/api/tasks/{task_id}/comments/files")
def api_add_comment_with_files(
request: Request,
task_id: int,
files: list[UploadFile] = File(...),
body: str = Form(""),
parent_id: str = Form(""),
mentions: str = Form(""),
client_token: str = Form(""),
) -> JSONResponse:
"""파일이 있는 댓글 — 본문과 파일을 한 요청으로 받아 한 트랜잭션에 만든다. 파일 하나라도
문제가 있으면(빈 파일·20MB 초과) 아무것도 만들지 않고 어느 파일인지 돌려준다(detail.failed).
DB 저장이 실패하면 방금 쓴 파일도 지운다 — 첨부 없는 빈 댓글이 남지 않는다."""
user = _require_user(request)
st = _db_or_503(request)
task = _task_or_404(st, task_id)
_require_task(st, user, task, write=True)
pid = _comment_parent_arg(st, parent_id)
try:
mention_list = json.loads(mentions) if mentions else []
except ValueError:
mention_list = []
if not files:
raise HTTPException(status_code=400, detail="보낼 파일이 없습니다.")
if len(files) > _MAX_COMMENT_FILES:
raise HTTPException(status_code=400, detail=f"파일은 한 번에 {_MAX_COMMENT_FILES}개까지 보낼 수 있습니다.")
def create() -> dict[str, Any]:
loaded: list[tuple[str, str, bytes]] = []
failed: list[dict[str, str]] = []
for i, f in enumerate(files):
name = (f.filename or "file").replace("\\", "_").replace("/", "_").strip() or "file"
data = f.file.read(_MAX_ATTACH_BYTES + 1)
if len(data) > _MAX_ATTACH_BYTES:
failed.append({"index": str(i), "name": name, "reason": "20MB 초과"})
elif not data:
failed.append({"index": str(i), "name": name, "reason": "빈 파일"})
else:
loaded.append((name, f.content_type or "application/octet-stream", data))
if failed:
raise HTTPException(status_code=400, detail={
"message": "보낼 수 없는 파일이 있어 댓글을 등록하지 않았습니다.", "failed": failed,
})
written: list[Path] = []
metas: list[dict[str, Any]] = []
try:
d = _attach_dir(request, task_id)
for name, ctype, data in loaded:
stored = f"{uuid.uuid4().hex}{Path(name).suffix[:16]}"
(d / stored).write_bytes(data)
written.append(d / stored)
metas.append({"filename": name, "stored_name": stored, "content_type": ctype,
"size_bytes": len(data)})
comment, atts = st.add_comment_with_attachments(
task_id=task_id, author_email=user["email"],
author_name=user.get("name") or user["email"].split("@")[0],
body=body, files=metas, parent_id=pid,
)
except Exception as exc:
for w in written: # DB 에 안 들어간 파일은 디스크에도 남기지 않는다
try:
w.unlink(missing_ok=True)
except Exception: # noqa: BLE001
logger.warning("댓글 첨부 정리 실패: %s", w.name)
if isinstance(exc, ValueError):
raise HTTPException(status_code=400, detail=str(exc))
raise
skipped = _after_comment(st, user, task, comment, mention_list, n_files=len(atts))
return {"comment": comment, "attachments": atts, "mention_skipped": skipped}
return JSONResponse(_once(user, task_id, client_token[:64], create), status_code=201)
_COMMENT_012_MSG = (
"댓글 답글·반응 기능은 DB 마이그레이션 012 적용 후 사용할 수 있습니다 "
"(scripts/sql/project_db_012_comment_replies_reactions.sql)."
)
_REACTION_MAX_LEN = 16 # 이모티콘 1개(ZWJ 조합·국기 포함)면 충분한 길이
@router.post("/api/comments/{comment_id}/reactions")
def api_toggle_reaction(
request: Request, comment_id: int, payload: dict[str, Any] = Body(...)
) -> JSONResponse:
"""댓글 이모티콘 반응 켜기/끄기(아사나식). body: {"emoji": "👍"} → {"reactions": [...]}"""
user = _require_user(request)
st = _db_or_503(request)
emoji = str(payload.get("emoji") or "").strip()
if not emoji or len(emoji) > _REACTION_MAX_LEN or any(ch.isalnum() or ch in "<>&\"'" for ch in emoji):
raise HTTPException(status_code=400, detail="이모티콘이 올바르지 않습니다.")
comment = st.get_comment(comment_id=comment_id)
if comment is None:
raise HTTPException(status_code=404, detail="댓글을 찾을 수 없습니다.")
task = _task_or_404(st, comment["task_id"])
_require_task(st, user, task, write=True)
if not st.comment_features()["reactions"]:
raise HTTPException(status_code=503, detail=_COMMENT_012_MSG)
try:
reactions = st.toggle_reaction(comment_id=comment_id, user_email=user["email"], emoji=emoji)
except KeyError:
raise HTTPException(status_code=404, detail="댓글을 찾을 수 없습니다.")
return JSONResponse({"reactions": reactions})
def _comment_task_access(st: Any, user: dict[str, Any], comment_id: int) -> dict[str, Any]:
"""댓글 수정·삭제 전 — 작성자라도 지금 그 작업의 원 소속 권한이 없으면 거절(멤버에서 빠진 뒤
자기 댓글을 고치거나 지우던 경로 차단). 작성자 본인/관리자 검사는 DB 쪽이 한다."""
comment = st.get_comment(comment_id=comment_id)
if comment is None:
raise HTTPException(status_code=404, detail="댓글을 찾을 수 없습니다.")
_require_task(st, user, _task_or_404(st, comment["task_id"]), write=True)
return comment
@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)
_comment_task_access(st, user, comment_id)
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)
_comment_task_access(st, user, comment_id)
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 = _task_or_404(st, task_id)
_require_task(st, user, task, write=False)
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 를 주면 댓글 채팅 팝업의 첨부(이미지/파일)로도 등록 —
같은 표에 저장되므로 업무 "첨부파일" 패널에도 그대로 함께 나온다."""
from app.store import is_admin # noqa: WPS433
user = _require_user(request)
st = _db_or_503(request)
task = _task_or_404(st, task_id)
_require_task(st, user, task, write=True)
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="잘못된 댓글입니다.")
# 남의 댓글에 파일을 붙일 수 없다(작성자 본인·관리자만).
if not is_admin(user) and store.norm_str(comment.get("author_email") or "", lower=True) != \
store.norm_str(user["email"], lower=True):
raise HTTPException(status_code=403, 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="첨부 파일을 찾을 수 없습니다.")
_require_task(st, user, _task_or_404(st, att["task_id"]), write=False)
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="첨부 파일을 찾을 수 없습니다.")
_require_task(st, user, _task_or_404(st, att["task_id"]), write=False)
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="첨부 파일을 찾을 수 없습니다.")
_require_task(st, user, _task_or_404(st, att["task_id"]), write=True)
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 = _visible_notifications(st, user, st.list_notifications(
recipient_email=user["email"], unread_only=unread_only, limit=100
))
return JSONResponse({"notifications": items, "unread": _notification_unread(st, user)})
@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": _notification_unread(st, user)})
@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, user: dict[str, Any], *, limit: int = 100) -> list[dict[str, Any]]:
"""나를 태그한 작업 중 지금 볼 수 있는 것만(권한을 잃은 작업의 옛 태그는 숨김).
006 마이그레이션 미적용 환경에서도 화면이 죽지 않게."""
try:
rows = st.list_mentioned_tasks(mentioned_email=user["email"], limit=1000)
except Exception: # noqa: BLE001
logger.warning("멘션 조회 실패 — project_db_006 마이그레이션 확인 필요")
return []
return access.filter_visible_tasks(st, user, rows)[:limit]
def _safe_mention_unread(st: Any, user: dict[str, Any]) -> int:
"""수신함 배지 — 지금 볼 수 있는 작업의 미확인 태그 수(_safe_mentions 와 같은 기준)."""
return sum(int(t.get("unread_mentions") or 0) for t in _safe_mentions(st, user, limit=1000))
def _visible_notifications(st: Any, user: dict[str, Any], items: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""알림 중 지금 볼 수 있는 프로젝트·작업의 것만. 작업 알림은 작업 기준(연결된 프로젝트의
읽기 권한 포함), 프로젝트 알림은 프로젝트 관리 권한, 둘 다 없는 알림은 그대로."""
allowed = access.visible_project_ids(st, user)
if allowed is None:
return items
scope = access.link_scope(st, [int(n["task_id"]) for n in items if n.get("task_id")])
out = []
for n in items:
pid, tid = n.get("project_id"), n.get("task_id")
if pid is None and tid is None:
out.append(n)
elif pid is not None and int(pid) in allowed:
out.append(n)
elif tid is not None and scope.get(int(tid), set()) & allowed:
out.append(n)
return out
def _notification_unread(st: Any, user: dict[str, Any]) -> int:
rows = st.list_notifications(recipient_email=user["email"], unread_only=True, limit=500)
return len(_visible_notifications(st, user, rows))
@router.get("/api/mentions")
def api_mentions(request: Request) -> JSONResponse:
"""나를 태그한 업무 목록 + 미확인 개수."""
user = _require_user(request)
st = _db_or_503(request)
tasks = _safe_mentions(st, user)
return JSONResponse({
"tasks": tasks,
"unread": _safe_mention_unread(st, user),
})
@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)})
@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("/trash", response_class=HTMLResponse)
def trash_page(request: Request) -> HTMLResponse:
"""휴지통 — 관리자 전용. 지운 업무(하위 업무 포함)를 3개월 보관, 복구."""
from app.main import build_erp_nav, render_template # noqa: WPS433
from app.store import is_admin # noqa: WPS433
user = _require_user(request)
if not is_admin(user):
raise HTTPException(status_code=403, detail="관리자만 볼 수 있습니다.")
st = _store(request)
if st is None:
return _render_config_needed(request, user)
_purge_trash(request, st)
enabled = st.trash_enabled()
return render_template(
request,
"project/trash.html",
{
"user": user,
"is_admin": True,
"nav_items": build_erp_nav(user, active="project"),
"nav_projects": _nav_projects(st, user, True),
"goal_years": _goal_years_nav(st),
"my_open_total": _my_open_count(st, user),
"mention_unread": _safe_mention_unread(st, user),
"page_title": "휴지통",
"page_subtitle": "삭제한 작업 — 3개월 보관, 관리자만 복구",
"force_sidebar_collapsed": True,
"color_palette": list(store.COLOR_PALETTE),
"project_icons": list(store.PROJECT_ICONS),
"trash_enabled": enabled,
"items": _trash_view_items(st.list_trash()) if enabled else [],
},
)
def _trash_view_items(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""휴지통 화면용 — 삭제 시각(KST 문자열)·남은 보관 일수."""
from datetime import datetime # noqa: WPS433
now = now_kst()
for it in items:
try:
deleted = datetime.fromisoformat(str(it["deleted_at"])).astimezone(KST)
it["deleted_label"] = deleted.strftime("%Y-%m-%d %H:%M")
except (TypeError, ValueError):
it["deleted_label"] = str(it.get("deleted_at") or "")[:16]
try:
expires = datetime.fromisoformat(str(it["expires_at"])).astimezone(KST)
it["days_left"] = max(0, (expires - now).days)
except (TypeError, ValueError):
it["days_left"] = None
did = (it.get("deleted_by") or "").split("@")[0]
it["deleted_by_id"] = did[:1].upper() + did[1:] # 멤버 이름은 첫 글자 대문자
return items
@router.post("/api/trash/{trash_id}/restore")
def api_restore_trash(request: Request, trash_id: int) -> JSONResponse:
"""휴지통 항목 복구 — 관리자 전용. 업무·하위 업무·댓글 등 원래 id 그대로."""
user = _require_admin(request)
st = _db_or_503(request)
try:
result = st.restore_trash(trash_id=trash_id, restored_by=user["email"])
except KeyError:
raise HTTPException(status_code=404, detail="휴지통 항목을 찾을 수 없습니다.")
except ValueError as exc:
raise HTTPException(status_code=409, detail=str(exc))
_restore_task_dirs(request, trash_id)
return JSONResponse({"ok": True, **result})
@router.get("/help", response_class=HTMLResponse)
def help_page(request: Request) -> HTMLResponse:
"""프로젝트 관리 도움말 — 상단 바 ? 아이콘(새 탭). 처음 쓰는 사람을 위한 기능 설명.
DB 없이 그리는 정적 안내라 DB 설정 전에도 열린다."""
from app.main import build_erp_nav, render_template # noqa: WPS433
from app.store import is_admin # noqa: WPS433
user = _require_user(request)
return render_template(
request,
"project/help.html",
{
"user": user,
"is_admin": is_admin(user),
"nav_items": build_erp_nav(user, active="project"),
"page_title": "프로젝트 관리 도움말",
"page_subtitle": "처음 쓰는 분을 위한 기능 안내",
},
)
@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 = _visible_notifications(st, user, st.list_notifications(recipient_email=user["email"], limit=100))
mentioned = _safe_mentions(st, user)
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 = _my_open_count(st, user)
return render_template(
request,
"project/inbox.html",
{
"user": user,
"is_admin": admin,
"nav_items": build_erp_nav(user, active="project"),
"nav_projects": nav_projects,
"goal_years": _goal_years_nav(st),
"my_open_total": my_open_total,
"page_title": "수신함",
"page_subtitle": "나를 태그한 작업과 프로젝트 알림",
"force_sidebar_collapsed": True,
"color_palette": list(store.COLOR_PALETTE),
"project_icons": list(store.PROJECT_ICONS),
"notifications": items,
"mentioned_tasks": mentioned,
"mention_unread": _safe_mention_unread(st, user),
},
)
# ────────────────────────────────────────────────────────────
# 연간 목표 (마이그레이션 013) — 사이드바 "목표" → 연도 → 목표 표
# 조회: project 권한자 전원 · 입력/구조 변경: 관리자(is_admin) 전용
# ────────────────────────────────────────────────────────────
_GOALS_MIGRATION_MSG = "연간 목표 기능이 아직 준비되지 않았습니다(DB 마이그레이션 013 필요)."
_GOALS_014_MSG = "분기 칸과 칸 병합은 DB 마이그레이션 014 가 필요합니다."
_GOALS_017_MSG = "2·4분기 칸은 DB 마이그레이션 017 이 필요합니다."
_GOALS_015_MSG = "세로 병합·연간/반기 칸 병합과 주간 회의록은 DB 마이그레이션 015 가 필요합니다."
_GOALS_016_MSG = "같은 항목 칸 안에 줄 추가(3열)는 DB 마이그레이션 016 이 필요합니다."
def _fmt_goal_num(v: float | None) -> str:
"""지표 숫자 표시 — 천 단위 쉼표, 소수는 필요한 만큼만(12.50 → 12.5)."""
if v is None:
return ""
if float(v).is_integer():
return f"{int(v):,}"
return f"{v:,.2f}".rstrip("0").rstrip(".")
def _goal_label(metric: str, v: float | None) -> str:
"""지표 칸 표기 — 로아스는 % 단위(499 → "499%"). 입력칸도 이 표기로 보이고, 저장 때 % 는 떼고 읽는다."""
s = _fmt_goal_num(v)
return f"{s}%" if s and metric == "roas" else s
def _goal_area_layout(rows: list[dict[str, Any]], this_month: int) -> None:
"""업무 영역 줄마다 칸 배치(row["layout"]) — 연간 · 1~3월 · 1분기 · 4~6월 · 2분기 … 4분기 순서, 엑셀식 사각형 병합.
병합(row["merges"] = {시작 칸: (가로 칸 수, 세로 줄 수)})의 시작 칸은 {"span", "rspan"}(colspan/rowspan),
병합에 가려진 칸은 빼고 그린다. 칸 = {"m", "kind": year|month|quarter, "h"(분기 1~4), "span", "rspan", "now"}.
가로는 같은 분기 월 칸 안(예전 반기 병합이 분기를 넘으면 여기서 잘림), 세로는 영역 끝까지로 자른다.
겹치는 병합(있을 수 없지만)은 나중 것을 무시."""
order = store.GOAL_COL_ORDER
covered: set[tuple[int, int]] = set()
anchors: dict[tuple[int, int], tuple[int, int]] = {}
for ri, row in enumerate(rows):
for start, (span, rspan) in sorted((row.get("merges") or {}).items()):
if start not in order:
continue
ci = order.index(start)
cols = [c for c in range(ci, min(len(order), ci + span))
if store.goal_col_group(order[c]) == store.goal_col_group(start)]
rr = list(range(ri, min(len(rows), ri + max(1, rspan))))
cells = {(r, c) for r in rr for c in cols}
if (ri, ci) in covered or cells & set(anchors) - {(ri, ci)} or cells & covered:
continue
anchors[(ri, ci)] = (len(cols), len(rr))
covered |= cells - {(ri, ci)}
for ri, row in enumerate(rows):
out: list[dict[str, Any]] = []
for ci, m in enumerate(order):
if (ri, ci) in covered:
continue
span, rspan = anchors.get((ri, ci), (1, 1))
kind = "year" if m == store.GOAL_YEAR else "quarter" if m in store.GOAL_COL_QUARTER else "month"
h = 0 if kind == "year" else store.GOAL_COL_QUARTER[m] if kind == "quarter" else store.goal_quarter_of(m)
out.append({"m": m, "kind": kind, "h": h, "span": span, "rspan": rspan,
"now": kind == "month" and m <= this_month <= m + span - 1,
"html": store.goal_text_html(row.get("cells", {}).get(m, ""))})
row["layout"] = out
def _goal_label_spans(rows: list[dict[str, Any]]) -> None:
"""항목 칸(2열) 묶음(016) — 묶음 첫 줄 label_span = 이어 붙은 줄 수 + 1, 이어 붙은 줄은 label_span 0(2열을 그리지 않음).
영역 첫 줄은 늘 묶음 첫 줄."""
for k, row in enumerate(rows):
if k == 0 or not row.get("label_cont"):
row["label_cont"] = False
n = 1
while k + n < len(rows) and rows[k + n].get("label_cont"):
n += 1
row["label_span"] = n
else:
row["label_span"] = 0
def _goal_call(fn: Any, *args: Any, **kwargs: Any) -> Any:
"""목표 DB 호출 공통 — 013 미적용 503, 없는 대상 404, 입력 오류 400."""
try:
return fn(*args, **kwargs)
except store.GoalMigration014Needed:
raise HTTPException(status_code=503, detail=_GOALS_014_MSG)
except store.GoalMigration015Needed:
raise HTTPException(status_code=503, detail=_GOALS_015_MSG)
except store.GoalMigration016Needed:
raise HTTPException(status_code=503, detail=_GOALS_016_MSG)
except store.GoalMigration017Needed:
raise HTTPException(status_code=503, detail=_GOALS_017_MSG)
except UndefinedTable:
raise HTTPException(status_code=503, detail=_GOALS_MIGRATION_MSG)
except KeyError:
raise HTTPException(status_code=404, detail="대상을 찾을 수 없습니다. 새로고침해 주세요.")
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
@router.get("/goals")
def goals_home(request: Request) -> RedirectResponse:
"""사이드바 "목표" 자체 주소 — 가장 최근 연도(없으면 올해)로."""
_require_user(request)
st = _store(request)
years = _goal_years_nav(st) if st is not None else [today_kst().year]
return RedirectResponse(url=f"/project/goals/{years[0]}", status_code=303)
@router.get("/goals/{year}", response_class=HTMLResponse)
def goals_page(request: Request, year: 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)
if not 2000 <= year <= 2100:
raise HTTPException(status_code=404, detail="연도가 올바르지 않습니다.")
admin = is_admin(user)
enabled = st.goals_enabled()
board = st.get_goal_board(year=year) if enabled else None
today = today_kst()
this_month = today.month if today.year == year else 0
if board:
for metric, m in board["metrics"].items():
for kind in list(m):
m[kind + "_label"] = {mo: _goal_label(metric, v) for mo, v in m[kind].items()}
for area in board["areas"]:
_goal_area_layout(area["rows"], this_month)
_goal_label_spans(area["rows"])
return render_template(
request,
"project/goals.html",
{
"user": user,
"is_admin": admin,
"nav_items": build_erp_nav(user, active="project"),
"nav_projects": _nav_projects(st, user, admin),
"goal_years": _goal_years_nav(st),
"goal_year_active": year,
"my_open_total": _my_open_count(st, user),
"mention_unread": _safe_mention_unread(st, user),
"page_title": f"{year}년 목표",
"page_subtitle": "한 해 전체 목표와 업무 영역별 계획",
"force_sidebar_collapsed": True,
"color_palette": list(store.COLOR_PALETTE),
"project_icons": list(store.PROJECT_ICONS),
"goals_enabled": enabled,
"goal_year": year,
"board": board,
"months": list(range(1, 13)),
# 분기 — (분기, 그 분기 월, 분기 글 칸 번호, 이름). 분기 칸은 그 분기 월 바로 오른쪽
"quarters": [(q, list(range(q * 3 - 2, q * 3 + 1)), store.GOAL_QUARTER_COL[q], f"{q}분기")
for q in (1, 2, 3, 4)],
"this_month": this_month,
"goal_area_colors": list(store.GOAL_AREA_COLORS),
},
)
@router.post("/api/goals/years")
def api_create_goal_year(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""연도 추가(관리자) — 가장 가까운 이전 연도의 영역·줄 구조를 글 없이 복사."""
user = _require_admin(request)
st = _db_or_503(request)
y = _goal_call(store.validate_goal_year, payload.get("year"))
_goal_call(st.create_goal_year, year=y, created_by=user["email"])
return JSONResponse({"ok": True, "year": y}, status_code=201)
@router.put("/api/goals/{year}")
def api_update_goal_year(request: Request, year: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
_require_admin(request)
st = _db_or_503(request)
_goal_call(st.update_goal_year, year=year, sales_unit=payload.get("sales_unit", ""))
return JSONResponse({"ok": True})
@router.delete("/api/goals/{year}")
def api_delete_goal_year(request: Request, year: int) -> JSONResponse:
_require_admin(request)
st = _db_or_503(request)
_goal_call(st.delete_goal_year, year=year)
return JSONResponse({"ok": True})
@router.put("/api/goals/{year}/metrics")
def api_set_goal_metric(request: Request, year: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""매출/로아스 목표·실적 한 칸 — {metric, kind, month, value}. value 빈값 = 지움."""
user = _require_admin(request)
st = _db_or_503(request)
value = _goal_call(store.validate_goal_value, payload.get("value"))
_goal_call(
st.set_goal_metric, year=year, metric=str(payload.get("metric") or ""),
kind=str(payload.get("kind") or ""), month=payload.get("month"),
value=value, updated_by=user["email"],
)
return JSONResponse({"ok": True, "value": value, "label": _goal_label(str(payload.get("metric") or ""), value)})
@router.post("/api/goals/{year}/areas")
def api_add_goal_area(request: Request, year: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
_require_admin(request)
st = _db_or_503(request)
aid = _goal_call(st.add_goal_area, year=year, name=payload.get("name", ""), color=payload.get("color", ""))
return JSONResponse({"ok": True, "id": aid}, status_code=201)
@router.put("/api/goals/areas/{area_id}")
def api_update_goal_area(request: Request, area_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
_require_admin(request)
st = _db_or_503(request)
fields = {k: payload[k] for k in ("name", "color") if k in payload}
_goal_call(st.update_goal_area, area_id=area_id, fields=fields)
return JSONResponse({"ok": True})
@router.delete("/api/goals/areas/{area_id}")
def api_delete_goal_area(request: Request, area_id: int) -> JSONResponse:
_require_admin(request)
st = _db_or_503(request)
_goal_call(st.delete_goal_area, area_id=area_id)
return JSONResponse({"ok": True})
@router.post("/api/goals/areas/{area_id}/move")
def api_move_goal_area(request: Request, area_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
_require_admin(request)
st = _db_or_503(request)
_goal_call(st.move_goal_area, area_id=area_id, direction=int(payload.get("direction") or 0))
return JSONResponse({"ok": True})
@router.post("/api/goals/areas/{area_id}/rows")
def api_add_goal_row(request: Request, area_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
_require_admin(request)
st = _db_or_503(request)
# ref_row_id + place(above|below) 가 있으면 그 줄 위/아래에, 없으면 영역 맨 끝에
ref = payload.get("ref_row_id")
try:
ref_id = int(ref) if ref not in (None, "") else None
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail="ref_row_id 가 올바르지 않습니다.")
rid = _goal_call(st.add_goal_row, area_id=area_id, label=payload.get("label", ""),
ref_row_id=ref_id, place=payload.get("place") or "below",
same_label=bool(payload.get("same_label")))
return JSONResponse({"ok": True, "id": rid}, status_code=201)
@router.put("/api/goals/rows/{row_id}")
def api_update_goal_row(request: Request, row_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
_require_admin(request)
st = _db_or_503(request)
_goal_call(st.update_goal_row, row_id=row_id, label=payload.get("label", ""))
return JSONResponse({"ok": True})
@router.delete("/api/goals/rows/{row_id}")
def api_delete_goal_row(request: Request, row_id: int) -> JSONResponse:
_require_admin(request)
st = _db_or_503(request)
_goal_call(st.delete_goal_row, row_id=row_id)
return JSONResponse({"ok": True})
@router.post("/api/goals/rows/{row_id}/split-label")
def api_split_goal_label(request: Request, row_id: int) -> JSONResponse:
"""항목 칸 나누기 — 묶음 첫 줄 아래 이어 붙은 줄들을 각자 항목 칸으로(016)."""
_require_admin(request)
st = _db_or_503(request)
n = _goal_call(st.split_goal_label, row_id=row_id)
return JSONResponse({"ok": True, "split": n})
@router.post("/api/goals/rows/{row_id}/move")
def api_move_goal_row(request: Request, row_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
_require_admin(request)
st = _db_or_503(request)
_goal_call(st.move_goal_row, row_id=row_id, direction=int(payload.get("direction") or 0))
return JSONResponse({"ok": True})
@router.put("/api/goals/rows/{row_id}/cells/{month}")
def api_set_goal_cell(
request: Request, row_id: int, month: int, payload: dict[str, Any] = Body(...)
) -> JSONResponse:
"""업무 영역 칸 글 — month 0 = 연간, 1~12 = 월, 분기 칸 13 = 1분기 · 15 = 2분기 · 14 = 3분기 · 16 = 4분기
(014, 15·16 은 017). 빈 글 = 지움."""
user = _require_admin(request)
st = _db_or_503(request)
_goal_call(
st.set_goal_cell, row_id=row_id, month=month,
body=payload.get("body", ""), updated_by=user["email"],
)
return JSONResponse({"ok": True})
@router.post("/api/goals/areas/{area_id}/merge")
def api_merge_goal_rect(request: Request, area_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""엑셀식 병합 {row_from, row_to(줄 id), col_from, col_to(칸 번호 0·1~12·13~16)} — 같은 영역 안 사각형,
가로는 같은 분기 월 칸끼리. 걸친 병합은 흡수, 글은 왼쪽 위부터 이어서 왼쪽 위 칸에."""
user = _require_admin(request)
st = _db_or_503(request)
res = _goal_call(
st.merge_goal_rect, area_id=area_id, row_from=payload.get("row_from"), row_to=payload.get("row_to"),
col_from=payload.get("col_from"), col_to=payload.get("col_to"), updated_by=user["email"],
)
return JSONResponse({"ok": True, **res})
@router.delete("/api/goals/rows/{row_id}/merge/{start}")
def api_unmerge_goal_cells(request: Request, row_id: int, start: int) -> JSONResponse:
"""병합 해제 — 글은 왼쪽 위(시작) 칸에 남는다(엑셀과 같음)."""
_require_admin(request)
st = _db_or_503(request)
_goal_call(st.unmerge_goal_cells, row_id=row_id, start=start)
return JSONResponse({"ok": True})
# ════════════════════════════════════════════════════════════
# 주간 회의록 (마이그레이션 015) — 목표 표 월 머리 → /project/goals/{연도}/meetings/{월}?week=월요일
# 주 = 월요일~일요일. 지난주 목표·결과 리뷰 → 월 목표 달성을 위한 이번주 목표·할 일.
# 쇼핑몰 연결(유통 줄) 결과·전주/금주 매출·월 누적은 실적 모듈(performance_db)에서 읽기만 한다.
# ════════════════════════════════════════════════════════════
def _perf_sales(request: Request) -> Any:
"""실적 모듈 저장소(읽기 전용). 없거나 오류면 None — 회의록은 직접 입력만으로도 동작한다."""
return getattr(request.app.state, "performance_store", None)
class _MeetingPerf:
"""회의록이 읽는 실적(읽기 전용) — 값과 상태를 따로 둔다. 조회 장애를 0 원으로 바꾸지 않는다.
state: ``off``(실적 모듈 미연결) · ``error``(쇼핑몰 목록 조회 실패) · ``empty``(매출 집계 쇼핑몰 없음) · ``ok``.
``sum``/``total`` 은 알 수 없으면 None(목록 장애·매출 조회 실패), 정상 조회 결과 0 건이면 0.
매출 조회가 실패할 때마다 ``failures`` 가 늘어난다(부분 실패 — 머리 숫자마다 따로 미확인)."""
def __init__(self, perf: Any) -> None:
self.perf = perf
self.markets: list[dict[str, Any]] = []
self.failures = 0
if perf is None:
self.state = "off"
else:
try:
self.markets = [m for m in perf.list_marketplaces() if m.get("enabled")]
self.state = "ok"
except Exception: # noqa: BLE001 — 실적 DB 장애가 회의록을 막지 않게
logger.warning("performance marketplaces unavailable for meeting", exc_info=True)
self.state = "error"
self.names = {m["code"]: m["name"] for m in self.markets}
self.sales_codes = [m["code"] for m in self.markets if m.get("include_in_sales")]
if self.state == "ok" and not self.sales_codes:
self.state = "empty"
@property
def readable(self) -> bool:
"""쇼핑몰 목록을 읽었는가(ok·empty) — 연결 쇼핑몰이 "사용 중이 아님"을 판단할 수 있는가."""
return self.state in ("ok", "empty")
def sum(self, start: date, end: date, codes: list[str]) -> dict[str, int] | None:
"""기간 쇼핑몰별 매출 합(원, 취소·반품 차감 = 대시보드 총매출과 같은 값). 알 수 없으면 None."""
if not self.readable:
return None
if not codes or end < start:
return {}
try:
out: dict[str, int] = {}
for (_, code), amount in self.perf.daily_amounts(start, end, codes).items():
out[code] = out.get(code, 0) + int(amount)
return out
except Exception: # noqa: BLE001
self.failures += 1
logger.warning("performance sales unavailable for meeting", exc_info=True)
return None
def total(self, start: date, end: date) -> int | None:
"""매출 집계 쇼핑몰 합계. 매출 집계 쇼핑몰이 없으면(empty) None — 0 원으로 보이지 않게."""
if self.state != "ok":
return None
r = self.sum(start, end, self.sales_codes)
return None if r is None else sum(r.values())
def freshness(self) -> dict[str, Any] | None:
"""매출 집계 쇼핑몰별 마지막 갱신 성공 시각(실적 모듈 perf_connection_status — 서버가 기록한 값만).
oldest = 가장 오래된 쇼핑몰 기준(자료가 적어도 이 시각까지는 갱신됨), never = 한 번도 성공 못 한 쇼핑몰."""
if self.state != "ok" or not hasattr(self.perf, "statuses"):
return None
try:
stats = self.perf.statuses() or {}
except Exception: # noqa: BLE001
logger.warning("performance statuses unavailable for meeting", exc_info=True)
return None
shops, never = [], []
for code in self.sales_codes:
t = (stats.get(code) or {}).get("last_success_sync_at")
if t:
shops.append({"name": self.names.get(code, code), "at": str(t)})
else:
never.append(self.names.get(code, code))
oldest = min((s["at"] for s in shops), default="")
return {"shops": shops, "never": never, "oldest": oldest}
def _kst_short(iso: str) -> str:
"""'2026-10-01T14:20:00+09:00' → '10/01 14:20'(서버가 준 시각을 한국시간으로)."""
if not iso:
return ""
try:
from datetime import datetime # noqa: WPS433
d = datetime.fromisoformat(str(iso))
if d.tzinfo is not None:
d = d.astimezone(KST)
return d.strftime("%m/%d %H:%M")
except ValueError:
return str(iso)[:16]
def _meeting_view(request: Request, st: Any, *, year: int, month: int, week: date) -> dict[str, Any]:
"""회의록 화면 데이터 — 머리(월 목표·누적·남은 주 필요 매출·전주/금주 목표·결과) + 줄(지난주 리뷰 포함).
"지난주"는 정확히 7일 전 주(prev_week)만 — 머리 전주 목표·전주 결과·줄의 지난주 칸·결과·달성률이 같은 주다
(db.get_meeting 이 7일 전 주 회의록에서 같은 연결키 줄만 prev 로 준다). 실적은 _MeetingPerf — 알 수 없는 값은
None + head.unknown 에 이름(0 원·0% 로 보이지 않게, 그 값에 기대는 달성률·필요 매출도 계산하지 않는다)."""
today = today_kst()
meeting = st.get_meeting(week_start=week)
targets = st.goal_month_targets(year=year, month=month)
mult = store.sales_unit_multiplier(targets["sales_unit"])
perf = _MeetingPerf(_perf_sales(request))
names = perf.names
week_end = week + timedelta(days=6)
prev_start, prev_end = week - timedelta(days=7), week - timedelta(days=1)
first = date(year, month, 1)
last = date(year + (month == 12), month % 12 + 1, 1) - timedelta(days=1)
unknown: list[str] = []
def total(key: str, a: date, b: date) -> int | None:
v = perf.total(a, min(b, today))
if v is None and perf.state in ("error", "ok"):
unknown.append(key) # 목록 장애(error) 또는 이 기간 매출 조회 실패(ok 인데 None)
return v
# 월 누적 = 이 주 앞까지(지난주 일요일까지) — 남은 목표를 이번 주 포함 남은 주로 나눠 "주당 필요 매출"
mtd_end = min(last, today, prev_end)
month_target_won = int(round(targets["sales_target"] * mult)) if targets["sales_target"] is not None and mult else None
mtd = total("mtd", first, mtd_end) if mtd_end >= first else 0 # 1주차 앞에는 지난 날이 없다(정말 0)
weeks_left = sum(1 for mon, _ in store.month_weeks(year, month) if mon >= week)
pm = meeting.get("prev_meeting") if meeting else None # 정확히 7일 전 주 회의록이어야 "전주 목표"
need = None
if month_target_won is not None and mtd is not None and weeks_left:
need = max(0, month_target_won - mtd) // weeks_left
fresh = perf.freshness()
head = {
"sales_unit": targets["sales_unit"], "sales_target": targets["sales_target"],
"roas_target": targets["roas_target"], "month_target_won": month_target_won,
"mtd": mtd, "mtd_end": mtd_end.isoformat() if mtd_end >= first else "", "weeks_left": weeks_left,
"need_per_week": need,
"prev_target": pm["week_target"] if pm and pm["week_start"] == prev_start.isoformat() else None,
"prev_exists": bool(pm and pm["week_start"] == prev_start.isoformat()),
"prev_result": total("prev_result", prev_start, prev_end) if prev_start <= today else None,
"week_result": total("week_result", week, week_end) if week <= today else None,
# perf = 실적 모듈 연결 여부(예전 뜻 그대로 — 갱신 상자·안내 문구 조건), 조회 성공 여부는 perf_state·unknown
"perf": perf.state != "off",
"perf_state": perf.state,
"unknown": unknown,
"fresh_oldest": _kst_short(fresh["oldest"]) if fresh else "",
"fresh_tip": ("매출 자료(실적 모듈) 쇼핑몰별 마지막 갱신 성공 — " +
" · ".join(f"{s['name']} {_kst_short(s['at'])}" for s in fresh["shops"]) +
(f" · 갱신 성공 기록 없음: {', '.join(fresh['never'])}" if fresh["never"] else "")) if fresh else "",
}
if meeting:
# 줄마다 지난주 결과 — 쇼핑몰 연결이면 그 주 실적(자동), 아니면 직접 입력한 결과(지난주 줄에 저장)
all_codes = [m["code"] for m in perf.markets]
by_week: dict[str, dict[str, int] | None] = {}
def week_sales(ws: str) -> dict[str, int] | None:
"""그 주(월~일, 오늘까지) 쇼핑몰별 실적 — 조회 실패면 None(시작 전 주는 부르지 않는다)."""
if ws not in by_week:
a = date.fromisoformat(ws)
by_week[ws] = perf.sum(a, min(a + timedelta(days=6), today), all_codes)
return by_week[ws]
for it in meeting["items"]:
prev = it.get("prev")
if not prev:
continue
auto = None
code = prev.get("marketplace_code") or ""
a = date.fromisoformat(prev["week_start"])
prev["period"] = f"{a.month}/{a.day}~{(a + timedelta(days=6)).month}/{(a + timedelta(days=6)).day}"
prev["not_started"] = bool(code) and a > today
# 쇼핑몰 목록을 못 읽었으면 연결 쇼핑몰이 사용 중인지 알 수 없다 → 결과 미확인(직접 입력 칸·0 으로 바꾸지 않음)
prev["auto_error"] = bool(code) and not prev["not_started"] and perf.state == "error"
# 실적 모듈에서 사용 중이 아닌 쇼핑몰(설정에서 사용 OFF·없는 코드)은 늘 0 이라 자동으로 보지 않고 직접 입력
prev["market_off"] = bool(code) and perf.state != "error" and code not in names
if code and perf.readable and not prev["not_started"] and not prev["market_off"]:
got = week_sales(prev["week_start"])
if got is None:
prev["auto_error"] = True
else:
auto = got.get(code, 0)
prev["auto_result"] = auto
prev["result"] = auto if auto is not None else (None if prev["auto_error"] else prev.get("result_amount"))
prev["market_name"] = names.get(code, code)
for it in meeting["items"]:
code = it["marketplace_code"]
it["market_name"] = names.get(code, code) if code else ""
it["market_off"] = bool(code) and perf.state != "error" and code not in names
it["market_unknown"] = bool(code) and perf.state == "error"
# 이번 주 진행 중 실적(쇼핑몰 연결 줄) — 정량 목표 칸 아래에 "이번주 실적"
it["week_auto"], it["week_error"] = None, False
if code and week <= today and not it["market_off"]:
got = week_sales(meeting["week_start"]) if perf.readable else None
if got is None:
it["week_error"] = perf.state != "off"
else:
it["week_auto"] = got.get(code, 0)
p = it.get("prev")
it["rate"] = (round(p["result"] / p["target_amount"] * 100, 1)
if p and p.get("result") is not None and p.get("target_amount") else None)
# 구역 묶음 — 이어진 같은 구역 줄을 한 덩어리로(표의 구역 칸 rowspan)
sections: list[dict[str, Any]] = []
for it in meeting["items"]:
if not sections or sections[-1]["name"] != it["section"]:
sections.append({"name": it["section"], "color": it["section_color"], "rows": []})
sections[-1]["rows"].append(it) # 키 이름 rows — 템플릿의 sec.items 는 dict.items 메서드가 된다
meeting["sections"] = sections
prev_items = [it["prev"] for it in meeting["items"] if it.get("prev")]
head["prev_items_target"] = sum(p["target_amount"] or 0 for p in prev_items) if prev_items else None
return {"meeting": meeting, "head": head,
"markets": [{"code": m["code"], "name": m["name"]} for m in perf.markets]}
def _month_plan(st: Any, year: int, month: int) -> list[dict[str, Any]] | None:
"""회의록 위 "N월 계획" — 연간 목표 표의 그 달 열 글을 업무 영역별로(빈 칸은 뺌). 목표 표가 없으면 None.
가로 병합(예: 9~10월 칸)에 적은 글도 그 달 계획으로, 세로 병합은 한 번만. 항목 이름이 묶인 줄(016)은 묶음 이름."""
try:
board = st.get_goal_board(year=year) if st.goals_enabled() else None
except Exception: # noqa: BLE001 — 목표 표를 못 읽어도 회의록은 열린다
logger.warning("goal board unavailable for meeting plan", exc_info=True)
return None
if not board:
return None
out = []
for area in board["areas"]:
rows = area["rows"]
_goal_area_layout(rows, 0)
_goal_label_spans(rows)
items, label = [], ""
for row in rows:
if not row.get("label_cont"):
label = row.get("label") or ""
cell = next((c for c in row["layout"] if c["kind"] == "month" and c["m"] <= month <= c["m"] + c["span"] - 1), None)
text = store.goal_text_plain(row["cells"].get(cell["m"], "") if cell else "").strip()
if not text:
continue
rng = f"{cell['m']}~{cell['m'] + cell['span'] - 1}월" if cell["span"] > 1 else ""
items.append({"label": label, "text": text, "range": rng})
if items:
out.append({"name": area["name"], "color": area["color"], "lines": items}) # 키 lines — 템플릿의 a.items 는 dict.items 메서드
return out
def _meet_members() -> list[dict[str, str]]:
"""회의 참석자 후보 = 전체 멤버(project 모듈 권한 보유 등록 사용자) — 이름·이메일·사진."""
try:
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], "avatar": u.get("picture") or ""}
for u in user_store.list_all() if has_module(u, "project")]
except Exception: # noqa: BLE001 — 사용자 목록이 없어도 회의록은 열린다
logger.warning("meeting members unavailable", exc_info=True)
return []
return sorted(out, key=lambda m: m["name"])
def _parse_attendees(text: str, members: list[dict[str, str]]) -> list[dict[str, str]]:
"""참석자 칸(쉼표로 이은 이메일 — 예전엔 자유 입력 글자) → 칩 목록. 멤버 이메일이면 이름·사진, 아니면 글자 그대로."""
by_email = {m["email"].lower(): m for m in members}
out, seen = [], set()
for tok in str(text or "").replace("\n", ",").split(","):
t = tok.strip()
if not t or t.lower() in seen:
continue
seen.add(t.lower())
m = by_email.get(t.lower())
out.append({"key": m["email"] if m else t, "email": m["email"] if m else "", "name": m["name"] if m else t,
"avatar": m["avatar"] if m else ""})
return out
@router.get("/goals/{year}/meetings/{month}", response_class=HTMLResponse)
def goal_meeting_page(request: Request, year: int, month: int, week: str | None = None) -> HTMLResponse:
"""주간 회의록 — 그 달과 겹치는 주(월~일) 탭, 주마다 회의록 하나. 입력은 관리자만(목표 표와 같음)."""
from app.main import build_erp_nav, render_template # noqa: WPS433
from app.store import has_module, is_admin # noqa: WPS433
user = _require_user(request)
st = _store(request)
if st is None:
return _render_config_needed(request, user)
if not 2000 <= year <= 2100 or not 1 <= month <= 12:
raise HTTPException(status_code=404, detail="연도·월이 올바르지 않습니다.")
weeks = store.month_weeks(year, month)
today = today_kst()
sel = None
if week:
try:
sel = store.validate_week_start(week)
except ValueError:
sel = None
if sel is not None and (sel.year, sel.month) != (year, month):
# 다른 달의 주(주는 월요일이 속한 달의 것) — 그 달 회의록 주소로
return RedirectResponse(url=f"/project/goals/{sel.year}/meetings/{sel.month}?week={sel.isoformat()}",
status_code=303)
if sel is None or sel not in [w for w, _ in weeks]:
sel = next((w for w, e in weeks if w <= today <= e), weeks[0][0])
enabled = st.meetings_enabled()
cal = store.calendar_weeks(year, month)
existing = set(st.meeting_weeks(start=cal[0][0], end=cal[-1][0])) if enabled else set()
view = _meeting_view(request, st, year=year, month=month, week=sel) if enabled else {}
members = _meet_members()
admin = is_admin(user)
return render_template(
request,
"project/goal_meeting.html",
{
"user": user,
"is_admin": admin,
"nav_items": build_erp_nav(user, active="project"),
"nav_projects": _nav_projects(st, user, admin),
"goal_years": _goal_years_nav(st),
"goal_year_active": year,
"my_open_total": _my_open_count(st, user),
"mention_unread": _safe_mention_unread(st, user),
"page_title": f"{year}년 {month}월 주간 회의록",
"page_subtitle": "지난주 리뷰와 이번주 목표",
"force_sidebar_collapsed": True,
"color_palette": list(store.COLOR_PALETTE),
"project_icons": list(store.PROJECT_ICONS),
"goal_year": year,
"goal_month": month,
"meetings_enabled": enabled,
"weeks": [{"start": w.isoformat(), "end": e.isoformat(), "n": i + 1, "label": f"{w.month}/{w.day}~{e.month}/{e.day}",
"has": w.isoformat() in existing, "now": w <= today <= e,
# 작은 달력(월요일 시작) 한 줄 — 날짜·그 달 여부·오늘·요일(5 토, 6 일)·공휴일
"days": [{"d": (w + timedelta(days=k)).day, "iso": (w + timedelta(days=k)).isoformat(),
"in": (w + timedelta(days=k)).month == month, "today": w + timedelta(days=k) == today,
"wd": k, "hol": store.KR_HOLIDAYS.get((w + timedelta(days=k)).isoformat(), "")}
for k in range(7)]}
for i, (w, e) in enumerate(weeks)],
# 작은 달력 — 그 달 날짜가 든 주 전부(앞뒤 달에 속한 주는 흐리게, 누르면 그 달 회의록)
"cal_weeks": [{"start": w.isoformat(), "own": (w.year, w.month) == (year, month),
"href": (f"?week={w.isoformat()}" if (w.year, w.month) == (year, month)
else f"/project/goals/{w.year}/meetings/{w.month}?week={w.isoformat()}"),
"title": (f"{next(i + 1 for i, (x, _) in enumerate(weeks) if x == w)}주차"
if (w.year, w.month) == (year, month) else f"{w.month}월 주")
+ f" ({w.month}/{w.day}~{e.month}/{e.day})",
"has": w.isoformat() in existing,
"days": [{"d": (w + timedelta(days=k)).day, "in": (w + timedelta(days=k)).month == month,
"today": w + timedelta(days=k) == today, "wd": k,
"hol": store.KR_HOLIDAYS.get((w + timedelta(days=k)).isoformat(), "")}
for k in range(7)]}
for w, e in store.calendar_weeks(year, month)],
"week": sel.isoformat(),
"week_n": next(i + 1 for i, (w, _) in enumerate(weeks) if w == sel),
"week_end": (sel + timedelta(days=6)).isoformat(),
"prev_week": (sel - timedelta(days=7)).isoformat(),
"prev_week_end": (sel - timedelta(days=1)).isoformat(),
# 주차를 열면 다시 받을 매출 기간(실적 모듈 매출 업데이트) — 지난주 월요일 ~ 이번 주 일요일(오늘까지)
"sync_from": (sel - timedelta(days=7)).isoformat() if sel - timedelta(days=7) <= today else "",
"sync_to": min(sel + timedelta(days=6), today).isoformat(),
# 쇼핑몰 매출 갱신(실적 모듈 POST /performance/api/sync)은 실적 모듈 권한자만 — 없으면 화면이 부르지 않는다
"can_sync": has_module(user, "performance"),
"meeting_status": store.MEETING_STATUS,
"meet_members": members,
"month_plan": _month_plan(st, year, month),
"attendee_list": _parse_attendees((view.get("meeting") or {}).get("attendees", ""), members),
**view,
},
)
@router.get("/api/goals/meetings/{week_start}")
def api_get_meeting(request: Request, week_start: str, year: int, month: int) -> JSONResponse:
"""회의록 다시 읽기(저장 뒤 머리 숫자·달성률 갱신용) — 화면과 같은 계산."""
_require_user(request)
st = _db_or_503(request)
ws = _goal_call(store.validate_week_start, week_start)
if not 1 <= month <= 12:
raise HTTPException(status_code=400, detail="월이 올바르지 않습니다.")
view = _goal_call(_meeting_view, request, st, year=year, month=month, week=ws)
return JSONResponse(view)
@router.post("/api/goals/meetings/{week_start}")
def api_create_meeting(request: Request, week_start: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
"""회의록 만들기(관리자) — 앞선 회의록 줄을 이어받거나, 처음이면 그 해 목표 표 업무 영역 + 기본 양식 줄."""
user = _require_admin(request)
st = _db_or_503(request)
ws = _goal_call(store.validate_week_start, week_start)
year = _goal_call(store.validate_goal_year, payload.get("year") or ws.year)
created = _goal_call(st.create_meeting, week_start=ws, sections=st.goal_area_sections(year=year),
created_by=user["email"])
return JSONResponse({"ok": True, "created": created}, status_code=201 if created else 200)
@router.put("/api/goals/meetings/{week_start}")
def api_update_meeting(request: Request, week_start: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
user = _require_admin(request)
st = _db_or_503(request)
ws = _goal_call(store.validate_week_start, week_start)
fields = {k: payload[k] for k in ("week_target", "attendees", "notes") if k in payload}
_goal_call(st.update_meeting, week_start=ws, fields=fields, updated_by=user["email"])
out: dict[str, Any] = {"ok": True}
if "week_target" in fields: # 화면이 서버 확정값(원 정수)으로 칸을 맞춘다
out["week_target"] = store.validate_meeting_amount(fields["week_target"])
return JSONResponse(out)
@router.delete("/api/goals/meetings/{week_start}")
def api_delete_meeting(request: Request, week_start: str) -> JSONResponse:
_require_admin(request)
st = _db_or_503(request)
ws = _goal_call(store.validate_week_start, week_start)
_goal_call(st.delete_meeting, week_start=ws)
return JSONResponse({"ok": True})
@router.post("/api/goals/meetings/{week_start}/items")
def api_add_meeting_item(request: Request, week_start: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""줄 추가 {section, label?, ref_item_id?, place?: above|below} — 기준 줄 위/아래, 없으면 구역 끝(새 구역이면 맨 끝)."""
user = _require_admin(request)
st = _db_or_503(request)
ws = _goal_call(store.validate_week_start, week_start)
ref = payload.get("ref_item_id")
try:
ref_id = int(ref) if ref not in (None, "") else None
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail="ref_item_id 가 올바르지 않습니다.")
item_id = _goal_call(
st.add_meeting_item, week_start=ws, section=payload.get("section", ""), label=payload.get("label", ""),
ref_item_id=ref_id, place=payload.get("place") or "below", updated_by=user["email"],
)
return JSONResponse({"ok": True, "id": item_id}, status_code=201)
@router.put("/api/goals/meeting-items/{item_id}")
def api_update_meeting_item(request: Request, item_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""줄 칸 하나 — label·content·target_amount·result_amount·status·marketplace_code. 전주 결과·평가는
이번 회의 화면에서 지난주 줄(prev)의 result_amount·status 로 저장한다."""
user = _require_admin(request)
st = _db_or_503(request)
keys = ("label", "content", "target_amount", "result_amount", "status", "marketplace_code")
item = _goal_call(st.update_meeting_item, item_id=item_id,
fields={k: payload[k] for k in keys if k in payload}, updated_by=user["email"])
return JSONResponse({"ok": True, "item": item})
@router.delete("/api/goals/meeting-items/{item_id}")
def api_delete_meeting_item(request: Request, item_id: int) -> JSONResponse:
_require_admin(request)
st = _db_or_503(request)
_goal_call(st.delete_meeting_item, item_id=item_id)
return JSONResponse({"ok": True})
@router.post("/api/goals/meeting-items/{item_id}/move")
def api_move_meeting_item(request: Request, item_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
_require_admin(request)
st = _db_or_503(request)
_goal_call(st.move_meeting_item, item_id=item_id, direction=int(payload.get("direction") or 0))
return JSONResponse({"ok": True})