Files
dbx-main/app/modules/project/router.py
T
king 96f54db0b1 feat(project): 섹션째 다른 프로젝트로 · 회의록 글 칸 하이퍼링크 · 업무 등록 표 하위 업무·줄 클릭 업무 창
- 보드 섹션 머리를 왼쪽 프로젝트 목록에 놓으면 확인 창 → POST /api/stages/{id}/move-project
  (db.move_stage_to_project 한 트랜잭션: 섹션 + 업무 + 세부 업무, 대상 맨 끝, 원·대상 멤버만, 남의 연결은 원 프로젝트에 섹션 없음)
- 목표·회의록 글 칸 서식 도구 🔗 — pj-rich 조각 link(http(s)만, 서버 store.goal_link), 주소 붙여넣기 = 링크, Ctrl+클릭 = 새 탭
- 회의록 업무 등록 표: 등록된 줄 [+] = 바로 아래 세부 업무 초안, 세부 업무 줄은 상위 줄 아래 들여쓰기,
  등록된 줄 어디든 클릭 = 오른쪽 업무 창, ↳ 상위 = 상위 업무 창
- 도움말·CLAUDE.md·PROJECT_MODULE.md 6-26, 정적 파일 버전 20261026a
- 테스트: test_move_stage_to_other_project(실제 PG), 링크 서버 검증, project_ui [섹션 이동], goals_meeting_ui [2g5],
  goal_text_link.browser.test.js

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 12:29:14 +09:00

4359 lines
213 KiB
Python

"""프로젝트 관리(아사나식) 모듈 라우터.
- 경로: /project
- 권한:
· 모듈 진입: 로그인한 회사 직원 전원(도메인 게이트는 OAuth 단에서 처리).
· 등급(수퍼관리자 > Admin > Pro user > User)별 권한은 access.py 머리 표 — 새 프로젝트·프로젝트 수정·
멤버 배정·휴지통·목표 입력·회의 완료 등은 Pro user 이상(_require_pro / access.is_pro),
남이 만든 프로젝트·섹션 삭제는 Admin 이상(access.is_project_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 _page_user(request: Request) -> Any:
"""화면(HTML) 주소용 — 로그인 전이면 오류 JSON 대신 로그인 화면으로 보냈다가 이 주소로 되돌아온다
(공유한 회의록·업무 링크를 로그인 안 된 브라우저에서 열 때, 2026-10-14). 로그인했으면 _require_user 와 같다."""
from urllib.parse import quote # noqa: WPS433
from app.main import get_current_user_record # noqa: WPS433
if get_current_user_record(request) is None:
here = str(request.url.path) + ("?" + request.url.query if request.url.query else "")
return RedirectResponse(url="/login?next=" + quote(here, safe=""), status_code=303)
return _require_user(request)
def _require_pro(request: Request) -> dict[str, Any]:
"""Pro user 이상(수퍼관리자·Admin·Pro user) — access.is_pro."""
user = _require_user(request)
if not access.is_pro(user):
raise HTTPException(status_code=403, detail="Pro user 이상만 할 수 있는 작업입니다.")
return user
def _role_ctx(user: dict[str, Any]) -> dict[str, Any]:
"""화면 공용 등급 값 — is_admin 은 ERP 공통(상단 관리자 메뉴), pj_pro·pj_admin 은 프로젝트 모듈 버튼용."""
from app.store import is_admin # noqa: WPS433
return {"is_admin": is_admin(user), "pj_pro": access.is_pro(user),
"pj_admin": access.is_project_admin(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:
"""프로젝트·섹션 삭제 — 수퍼관리자·Admin 은 누구 것이든, Pro user·User 는 '만든 사람'만.
생성자 정보가 없는 과거 데이터는 Admin 이상만(잠김 방지). 작업 삭제는 멤버 누구나(이 검사 안 함)."""
if access.is_project_admin(user):
return True
me = store.norm_str(user.get("email", ""), lower=True)
cb = store.norm_str(created_by or "", lower=True)
return bool(cb) and 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]]:
"""내가 담당인 작업 중 지금 볼 수 있는 것만 — 권한을 잃은 프로젝트의 작업은 빠진다.
미완료는 전부, 완료는 최근 완료 1000건까지(db.list_my_tasks)."""
return access.filter_visible_tasks(st, user, st.list_my_tasks(assignee_email=user["email"]))
def _my_open_count(st: Any, user: dict[str, Any]) -> int:
"""사이드바 "내 작업" 배지 — 지금 볼 수 있는 미완료 담당 작업 수(_my_visible_tasks 와 같은 권한 기준).
목록 전체를 읽지 않고 (id, project_id) 만 읽어 개수 제한 없이 센다."""
return len(access.filter_visible_tasks(st, user, st.list_my_open_refs(assignee_email=user["email"])))
def _remove_task_dirs(request: Request, task_ids: list[int]) -> None:
"""삭제된 업무들의 첨부 폴더(DATA_DIR/project/<task_id>)를 지운다.
DB 행은 CASCADE 로 사라지지만 디스크 파일은 남아 계속 쌓였다. 실패해도
삭제 자체는 이미 끝났으므로 로그만 남긴다.
"""
import shutil # noqa: WPS433
base = Path(str(getattr(request.app.state, "data_dir", "."))) / "project"
for tid in task_ids:
d = base / str(int(tid))
if d.is_dir():
try:
shutil.rmtree(d)
except Exception: # noqa: BLE001
logger.warning("첨부 폴더 삭제 실패: %s", d)
def _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
return render_template(
request,
"denied.html",
{
"reason": "프로젝트 관리 모듈이 아직 설정되지 않았습니다. "
"PROJECT_DB_URL 환경변수를 설정하고 "
"scripts/sql/project_db_init.sql 로 project_db 를 초기화한 뒤 "
"컨테이너를 재기동하세요.",
"user": user,
**_role_ctx(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)의 프로젝트 트리 데이터.
내 업무 · 수신함 · 프로젝트 화면이 같은 사이드바를 쓰므로 한 곳에서 만든다.
내가 owner·멤버인 프로젝트만(관리자도 마찬가지, 슈퍼관리자만 전체 — access.sees_all_projects).
"""
projects = st.list_projects(
include_archived=False,
member_email=None if access.sees_all_projects(user) 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 = _page_user(request)
if not isinstance(user, dict):
return user
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,
**_role_ctx(user),
"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),
"project_asana_icons": list(store.PROJECT_ASANA_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 # 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,
**_role_ctx(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)
target = _task_open_project(st, user, task)
if target is None:
return _denied(
"이 업무가 속한 프로젝트의 멤버만 볼 수 있습니다. "
"프로젝트 관리자에게 멤버 배정을 요청하세요.",
403,
)
# 세부 업무도 업무처럼 자기 팝업으로 연다(아사나식 — 제목 위에 상위 업무 경로).
# 수신함 오른쪽 작업 창(iframe, ?embed=1)은 옮겨 간 뒤에도 embed 화면이어야 한다.
return RedirectResponse(url=_task_page_url(target, task_id, request), status_code=303)
def _task_open_project(st: Any, user: dict[str, Any], task: dict[str, Any]) -> int | None:
"""작업을 열 프로젝트 화면 — 지금 권한 기준. FULL 이면 원 소속, READ 면 내가 볼 수 있는 연결된
프로젝트(id 가 작은 것부터), 권한이 없으면 None. 공유 링크·수신함·알림 팝업·PC 알림이 같이 쓴다."""
level = access.task_access(st, user, task)
if level is None:
return None
if level == access.FULL:
return int(task["project_id"])
tid = int(task["id"])
return next((pid for pid in sorted(access.link_scope(st, [tid]).get(tid, set()))
if access.can_manage_project(st, user, pid)), None)
def _task_page_url(project_id: int, task_id: int, request: Request) -> str:
embed = "&embed=1" if request.query_params.get("embed") == "1" else ""
return f"/project/p/{int(project_id)}?task={int(task_id)}{embed}"
@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 = _page_user(request)
if not isinstance(user, dict):
return user
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:
# 예전 주소(/p/{원 소속}?task=)로 연결된 작업을 연 경우 — 읽기 권한이 있는 연결된 프로젝트 화면으로.
# (옛 PC 알림 프로그램·북마크가 원 소속 주소를 쓴다. 새 주소는 /project/t/{id})
target = _redirect_target_for_task(st, user, request.query_params.get("task"))
if target is not None and target != project_id:
return RedirectResponse(
url=_task_page_url(target, int(request.query_params["task"]), request), status_code=303)
return render_template(
request,
"denied.html",
{
"reason": "이 프로젝트의 멤버만 볼 수 있습니다. "
"프로젝트 관리자에게 멤버 배정을 요청하세요.",
"user": user,
**_role_ctx(user),
"nav_items": build_erp_nav(user, active="project"),
},
status_code=403,
)
members = st.list_members(project_id=project_id)
top_projects, top_ids = _view_scope(st, user, project)
# 좌측 트리 + 전체 집계: 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]] = [_project_meta(p) for p in top_projects]
if project_id not in {int(p["id"]) for p in top_projects}:
# 보관된 프로젝트·서브프로젝트를 직접 연 경우 — 화면용 메타에만 넣고 사이드바 목록엔 넣지 않는다.
projects_meta.append({**_project_meta(project), "view_only": True})
for p in top_projects:
p_tasks = tasks_by_ctx.get(p["id"], [])
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,
**_role_ctx(user),
"pj_options": _project_options(st),
"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),
"project_asana_icons": list(store.PROJECT_ASANA_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 _view_scope(st: Any, user: dict[str, Any], project: dict[str, Any]) -> tuple[list[dict[str, Any]], list[int]]:
"""프로젝트 화면·스냅샷(scope=all)·담당자별 합계가 같이 쓰는 조회 범위.
(내가 볼 수 있는 활성 최상위 프로젝트, 작업·섹션을 읽을 프로젝트 id). 지금 연 프로젝트가 보관됐거나
서브프로젝트여서 목록에 없으면 그 프로젝트 하나만 더한다 — 다른 보관 프로젝트까지 읽지는 않는다."""
top = [p for p in st.list_projects(
include_archived=False,
member_email=None if access.sees_all_projects(user) else user["email"],
) if not p.get("parent_id")] # 과거 서브프로젝트 제외
ids = [int(p["id"]) for p in top]
if int(project["id"]) not in ids:
ids.append(int(project["id"]))
return top, ids
def _redirect_target_for_task(st: Any, user: dict[str, Any], raw_task_id: Any) -> int | None:
try:
task = st.get_task(task_id=int(raw_task_id)) if raw_task_id else None
except (TypeError, ValueError):
return None
return _task_open_project(st, user, task) if task else None
def _db_or_503(request: Request) -> Any:
st = _store(request)
if st is None:
raise HTTPException(status_code=503, detail="프로젝트 모듈이 설정되지 않았습니다.")
return st
def _project_options(st: Any) -> dict[str, Any]:
"""시스템 Project 옵션(처음 여는 탭·보드 카드 표지) — 읽기 실패해도 화면은 기본값으로 연다."""
if st is None:
return store.normalize_project_options(None)
try:
return store.normalize_project_options(st.get_project_options())
except Exception: # noqa: BLE001 — 옵션 때문에 프로젝트 화면이 안 열리면 안 된다
logger.warning("Project 옵션 읽기 실패 — 기본값 사용", exc_info=True)
return store.normalize_project_options(None)
@router.get("/api/options")
def api_get_options(request: Request) -> JSONResponse:
"""Project 옵션 창 — 시스템 전체 설정(모든 사용자에게 적용)과 내가 바꿀 수 있는지(Admin 이상)."""
user = _require_user(request)
st = _db_or_503(request)
return JSONResponse({"options": _project_options(st), "can_edit": access.is_project_admin(user)})
@router.put("/api/options")
def api_put_options(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""시스템 Project 옵션 저장 — 수퍼관리자·Admin 만. 보낸 키만 바꾼다. 029 미적용이면 503."""
user = _require_user(request)
if not access.is_project_admin(user):
raise HTTPException(status_code=403, detail="수퍼관리자·Admin 만 바꿀 수 있습니다.")
st = _db_or_503(request)
try:
values = store.validate_project_options(payload)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
try:
st.set_project_options(values=values, updated_by=user.get("email", ""))
except UndefinedTable:
raise HTTPException(status_code=503, detail="DB 마이그레이션 029(Project 옵션)가 아직 적용되지 않았습니다.")
return JSONResponse({"options": _project_options(st)})
@router.get("/api/projects")
def api_list_projects(request: Request) -> JSONResponse:
user = _require_user(request)
st = _db_or_503(request)
projects = st.list_projects(
include_archived=False,
member_email=None if access.sees_all_projects(user) else user["email"],
)
return JSONResponse({"projects": projects, "tree": _build_tree(projects)})
_PROJECT_ICON_MIGRATION_MSG = "프로젝트 아이콘 기능이 아직 준비되지 않았습니다(DB 마이그레이션 011 필요)."
_OWNER_ADMIN_ONLY = "프로젝트 소유자는 Pro user 이상만 지정·변경할 수 있습니다."
def _owner_for_create(user: dict[str, Any], payload: dict[str, Any]) -> str:
"""새 프로젝트 소유자 — 만든 사람. 다른 사람을 소유자로 지정하는 건 Pro user 이상만(그 사람은
등록 사용자이고 project 모듈 권한이 있어야 한다). User 가 남을 지정하면 거절."""
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
if not access.is_pro(user):
raise HTTPException(status_code=403, detail=_OWNER_ADMIN_ONLY)
_check_owner_candidate(want)
return want
def _creator_member(user: dict[str, Any], owner: str) -> list[str]:
"""남을 소유자로 지정해 만들면 만든 사람을 일반 멤버로 같이 넣는다 — 만든 직후 자기 프로젝트를
못 여는 일이 없게. created_by 로 권한을 주는 게 아니라 멤버 행이라, 나중에 멤버에서 빼면 권한도 없어진다."""
me = store.norm_str(user["email"], lower=True)
return [] if owner == me else [me]
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:
"""최상위 프로젝트 생성 — Pro user 이상(만든 사람이 owner). User 는 서브프로젝트만."""
user = _require_pro(request)
st = _db_or_503(request)
owner = _owner_for_create(user, payload)
try:
project = st.create_project(
name=payload.get("name", ""),
parent_id=None,
description=payload.get("description", ""),
color=payload.get("color", ""),
owner_email=owner,
start_date=payload.get("start_date"),
due_date=payload.get("due_date"),
created_by=user["email"],
icon=payload.get("icon"),
member_emails=_creator_member(user, owner),
)
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)
owner = _owner_for_create(user, payload)
try:
project = st.create_project(
name=payload.get("name", ""),
parent_id=project_id,
description=payload.get("description", ""),
color=payload.get("color", ""),
owner_email=owner,
start_date=payload.get("start_date"),
due_date=payload.get("due_date"),
created_by=user["email"],
member_emails=_creator_member(user, owner),
)
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:
"""홈 화면 프로젝트 카드 드래그 순서 변경. 최상위 프로젝트만 대상이며,
순서는 이 화면을 보는 모든 사용자에게 공유되므로(세션 재정렬과 동일 원칙)
Pro user 이상으로 제한한다.
⚠️ 반드시 `PUT /api/projects/{project_id}` 보다 먼저 등록해야 한다 — 아니면
"order" 가 project_id 로 매칭 시도되어(정수 변환 실패로 422) 이 라우트가
영영 실행되지 않는다(경로 매칭은 등록 순서, path param 특이도 무관).
"""
user = _require_pro(request)
st = _db_or_503(request)
ids = _ordered_ids_arg(payload)
# 보낸 id 가 모두 지금 내가 관리할 수 있는 프로젝트여야 한다(없는 id 도 같은 403 — 다른 프로젝트가
# 있는지 알려 주지 않는다). 하나라도 아니면 아무것도 바꾸지 않는다(UPDATE 는 한 문장이라 전부 아니면 전무).
allowed = _accessible_project_ids(st, user)
if allowed is None: # 수퍼관리자 — 있는 프로젝트인지만
allowed = {int(p["id"]) for p in st.list_projects(include_archived=True)}
if any(i not in allowed for i in ids):
raise HTTPException(status_code=403, detail="순서를 바꿀 권한이 없는 프로젝트가 들어 있습니다.")
st.reorder_projects(ordered_ids=ids)
return JSONResponse({"ok": True})
def _ordered_ids_arg(payload: Any) -> list[int]:
"""{"ordered_ids": [정수, ...]} — 비었거나 정수가 아니거나(참/거짓·소수·글자) 겹치면 400."""
ids = payload.get("ordered_ids") if isinstance(payload, dict) else None
if not isinstance(ids, list) or not ids:
raise HTTPException(status_code=400, detail="ordered_ids 가 필요합니다.")
out: list[int] = []
for v in ids:
if isinstance(v, bool) or not isinstance(v, (int, str)):
raise HTTPException(status_code=400, detail="ordered_ids 가 올바르지 않습니다.")
try:
n = int(v)
except ValueError:
raise HTTPException(status_code=400, detail="ordered_ids 가 올바르지 않습니다.")
if n <= 0:
raise HTTPException(status_code=400, detail="ordered_ids 가 올바르지 않습니다.")
out.append(n)
if len(set(out)) != len(out):
raise HTTPException(status_code=400, detail="ordered_ids 에 같은 프로젝트가 두 번 들어 있습니다.")
return out
@router.put("/api/projects/{project_id}")
def api_update_project(
request: Request, project_id: int, payload: dict[str, Any] = Body(...)
) -> JSONResponse:
"""프로젝트 이름·설명·색·아이콘·날짜·완료·소유자 — Pro user 이상, 그 프로젝트 멤버(owner)일 때."""
user = _require_pro(request)
st = _db_or_503(request)
_require_manage(request, st, user, project_id)
fields = dict(payload)
if "owner_email" in fields:
# 소유자는 멤버 목록과 별개로 계속 관리 권한을 준다 — Pro user 이상만(위 _require_pro).
# 값이 그대로면(화면이 같이 보낸 경우) 그냥 무시한다.
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 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:
"""프로젝트 삭제 — Admin 이상은 누구 것이든, Pro user·User 는 '만든 사람'만. 안의 업무도 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 모듈) 보유자. Pro user 이상.
관리자 페이지의 '프로젝트 관리' 토글을 켠 직원이 자동으로 후보가 된다.
"""
_require_pro(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)
# 전체 대상이면 내가 지금 볼 수 있는 업무만(원 소속 멤버 또는 연결된 프로젝트의 읽기 — 프로젝트 화면과 같은 기준).
tasks = access.filter_visible_tasks(st, user, tasks)
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:
"""사용자를 프로젝트에 배정 — Pro user 이상, 자기가 멤버(owner)인 프로젝트만."""
user = _require_pro(request)
st = _db_or_503(request)
_require_manage(request, st, user, project_id)
try:
member = st.add_member(
project_id=project_id,
user_email=payload.get("user_email", ""),
user_name=payload.get("user_name", ""),
role="member", # 역할 구분 없음(2026-10-07) — 배정된 멤버는 모두 보기·수정, 예전 manager 값은 그대로 둔다
)
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:
user = _require_pro(request)
st = _db_or_503(request)
_require_manage(request, st, user, project_id)
project = st.get_project(project_id=project_id) or {}
if store.norm_str(user_email, lower=True) == store.norm_str(project.get("owner_email") or "", lower=True):
# 소유자는 멤버로 늘 등록(2026-10-20) — 빼려면 소유자를 먼저 바꾼다(화면도 소유자 체크를 잠근다)
raise HTTPException(status_code=400, detail="소유자는 멤버에서 뺄 수 없습니다 — 소유자를 먼저 바꾸세요.")
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))
# 담당자 지정(_check_assignee)과 같은 지금 권한 — 멤버이고, 등록된 project 권한 사용자
if email not in allowed or not _registered_project_user(email):
raise HTTPException(status_code=400, detail="기본 담당자는 이 프로젝트 멤버여야 합니다.")
return email
def _registered_project_user(email: str) -> bool:
"""지금 등록돼 있고 project 모듈 권한이 있는 사용자인가 — 섹션 기본 담당자 자동 배정 전 확인(DB 밖,
사용자 목록만 본다 — 작업 행을 잠근 트랜잭션 안에서 불려도 다른 DB 연결을 빌리지 않는다)."""
rec = access.default_user_lookup(email)
return bool(rec) and access.can_use_module({**rec, "email": rec.get("email") or 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:
"""세션(단계) 삭제 — Admin 이상은 누구 것이든, 그 밖은 만든 사람만. 생성자 정보가 없는 과거
데이터는 Admin 이상(잠김 방지) — `_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": access.filter_visible_tasks(st, user, 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),
})
project = st.get_project(project_id=project_id)
if project is None:
raise HTTPException(status_code=404, detail="프로젝트를 찾을 수 없습니다.")
top, ids = _view_scope(st, user, project) # 첫 화면(project_page)과 같은 범위
stages_by_project = st.list_stages_for_projects(project_ids=ids)
metas = [_project_meta(p) for p in top]
if project_id not in {int(p["id"]) for p in top}:
metas.append({**_project_meta(project), "view_only": True})
return JSONResponse({
"scope": "all",
"project": project,
"projects": metas,
"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),
})
@router.get("/api/projects/{project_id}/subtasks-summary")
def api_subtasks_summary(request: Request, project_id: int, scope: str = "project") -> JSONResponse:
"""대시보드 "담당자별 작업 합계" — 화면 업무 목록엔 세부 업무가 없어서(보드에 카드로 안 뜨게) 세부 업무만 따로.
scope=project → 이 프로젝트(+여기 연결된) 최상위 업무의 세부 업무, scope=all → 볼 수 있는 모든 최상위 프로젝트(스냅샷과 같은 범위).
사람별 업무량 표라 Pro user 이상만."""
user = _require_pro(request)
st = _db_or_503(request)
_require_manage(request, st, user, project_id)
if scope == "all":
project = st.get_project(project_id=project_id)
if project is None:
raise HTTPException(status_code=404, detail="프로젝트를 찾을 수 없습니다.")
ids = _view_scope(st, user, project)[1] # 화면·스냅샷과 같은 범위
else:
ids = [project_id]
parents = [t["id"] for t in st.list_tasks_for_projects(project_ids=ids)]
return JSONResponse({"subtasks": st.list_subtasks_of(parent_ids=parents)})
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-overdue")
def api_my_overdue(request: Request) -> JSONResponse:
"""마감이 지난 내 미완료 업무(마감일이 오늘(한국시간) 이전) — ERP 모든 화면 위쪽 알림(static/erp-overdue.js)이 쓴다.
지금 볼 수 있는 업무만, 마감이 오래된 것부터."""
user = _require_user(request)
st = _db_or_503(request)
today = today_kst()
rows = access.filter_visible_tasks(st, user, st.list_my_overdue(assignee_email=user["email"], today=today))
keys = ("id", "title", "due_date", "project_id", "project_name", "project_color", "parent_task_id", "parent_title")
return JSONResponse({"today": today.isoformat(), "tasks": [{k: t.get(k) for k in keys} for t in rows]})
@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)
task, skipped = _create_task_for(request, st, user, project_id, payload, bg)
return JSONResponse({"task": task, "mention_skipped": skipped}, status_code=201)
def _create_task_for(
request: Request, st: Any, user: dict[str, Any], project_id: int, payload: dict[str, Any],
bg: BackgroundTasks,
) -> tuple[dict[str, Any], list[str]]:
"""작업 만들기 공통(작업 창 등) — 권한(멤버)·담당자 확인·만들기·자동 협업자·배정/완료 알림·@태그.
돌려주는 값: (작업, 태그하지 못한 이메일). 회의록 [적용]은 같은 확인·후처리를 쓰되 만들기만 줄 잠금 트랜잭션 안에서."""
project, followers = _task_create_checks(request, st, user, project_id, payload)
try:
task = st.create_task(**_task_create_fields(user, project_id, payload))
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 task, _task_created_effects(request, st, user, project, task, followers, bg)
def _task_create_checks(request: Request, st: Any, user: dict[str, Any], project_id: int,
payload: dict[str, Any]) -> tuple[dict[str, Any], list[str]]:
"""만들기 전 확인 — 권한(멤버)·프로젝트·담당자·협업자. (프로젝트, 협업자). DB 쓰기·잠금 없음."""
_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)
followers = _check_followers(st, payload.get("followers"), project_id)
return project, followers
def _task_create_fields(user: dict[str, Any], project_id: int, payload: dict[str, Any]) -> dict[str, Any]:
"""db.create_task / db._insert_task 인자."""
return {
"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"),
"assignee_allowed": _registered_project_user,
}
def _task_created_effects(request: Request, st: Any, user: dict[str, Any], project: dict[str, Any],
task: dict[str, Any], followers: list[str], bg: BackgroundTasks) -> list[str]:
"""업무를 만든(커밋된) 뒤의 부가 처리 — 자동 협업자·배정/완료 알림·관리자 메일(백그라운드)·@태그. 태그 못 한 이메일."""
project_id = int(task["project_id"])
# 만든 사람은 자동 협업자 + 만들 때 고른 협업자(세부 업무 추가 칸 등). 담당자는 협업자가 아니다(2026-10-13,
# db.add_followers 가 담당자를 거른다 — 만든 사람이 담당자여도 빠진다).
# 세부 업무는 만든 사람을 자동으로 넣지 않는다 — 고른 협업자만(2026-10-14 사용자 요청).
_follow(st, task["id"], ([] if task.get("parent_task_id") else [user["email"]]) + followers)
# 생성과 동시에 담당자 지정 시 관리자 메일 + 담당자 인앱 알림
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"])
return _record_mentions(
st, task=task,
emails=store.extract_mentions_from_html(task.get("description") or ""),
actor=user["email"], project_name=project["name"],
)
_ASSIGNEE_DENIED = "담당자는 이 프로젝트를 볼 수 있는 사람(멤버·소유자·관리자)이어야 합니다."
def _check_followers(st: Any, raw: Any, project_id: int) -> list[str]:
"""업무를 만들 때 같이 고른 협업자 — 협업자 추가 API 와 같은 기준(그 프로젝트를 볼 수 있는 사람만, 아니면 400)."""
if not raw:
return []
if not isinstance(raw, list):
raise HTTPException(status_code=400, detail="협업자 목록이 올바르지 않습니다.")
emails = store.normalize_emails([str(e) for e in raw])
for em in emails:
if not access.can_assign(st, em, project_id):
raise HTTPException(status_code=400, detail="이 프로젝트 멤버만 협업자로 추가할 수 있습니다.")
return emails
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"],
assignee_allowed=_registered_project_user)
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"): # 담당자는 협업자가 아니다 — db.update_task 가 협업자에서 뺐다(2026-10-13)
_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:
# 드라이브 파일 링크를 지우면 그 파일을 휴지통으로 / 되살리면 꺼낸다(2026-10-19, 백그라운드)
from app.integrations.google_drive import file_ids_in # noqa: WPS433
before, after = file_ids_in(existing.get("description") or ""), file_ids_in(payload["description"])
if before != after:
bg.add_task(_sync_drive_links, st, task_id, before - after, after - before)
skipped = _record_mentions(
st, task=task,
emails=store.extract_mentions_from_html(payload["description"]),
actor=user["email"], project_name=project_name,
)
if _drive_path_changed(existing, task): # 섹션·프로젝트·상위 업무가 바뀜 → 드라이브 파일도 새 폴더로
bg.add_task(_relocate_drive_files, st, task_id)
return JSONResponse({"task": task, "mention_skipped": skipped})
def _drive_path_changed(before: dict[str, Any], after: dict[str, Any]) -> bool:
"""드라이브 폴더 경로(프로젝트/섹션/상위 업무)가 바뀌었나."""
return any(str(before.get(k) or "") != str(after.get(k) or "")
for k in ("project_id", "stage_id", "parent_task_id") if k in after)
@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)
# 작업 삭제(휴지통으로)는 원 소속 프로젝트 멤버 누구나(2026-10-12, 등급 무관) — 멤버에서 빠지면 못 지운다.
_require_task(st, user, existing, write=True)
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)
# 세부 업무 줄의 협업자 아이콘(담당자 오른쪽) — 줄마다 다시 묻지 않게 한 번에.
by_sub = st.list_followers_of(task_ids=[s["id"] for s in task["subtasks"]])
for s in task["subtasks"]:
s["followers"] = by_sub.get(int(s["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,
bg: BackgroundTasks,
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))
if _drive_path_changed(existing, task): # 드라이브 파일도 새 상위 업무 폴더로(백그라운드)
bg.add_task(_relocate_drive_files, st, task_id)
return JSONResponse({"task": task})
@router.post("/api/tasks/{task_id}/move-project")
def api_move_task_project(
request: Request,
task_id: int,
bg: BackgroundTasks,
payload: dict[str, Any] = Body(...),
) -> JSONResponse:
"""메인 업무를 다른 프로젝트로 옮긴다 — 보드 카드·목록 줄을 왼쪽 프로젝트 목록으로 드래그 → 섹션 선택 창.
body: {"project_id": 대상, "stage_id": 대상 섹션 또는 null}. 원 소속 권한(FULL) + 대상 프로젝트 멤버여야 한다.
세부 업무는 함께 옮겨진다. 응답의 `unseen` = 대상 프로젝트를 볼 수 없는 담당자·협업자(화면이 안내).
"""
user = _require_user(request)
st = _db_or_503(request)
existing = _task_or_404(st, task_id)
_require_task(st, user, existing, write=True)
try:
target = int(payload.get("project_id"))
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail="옮길 프로젝트(project_id)가 필요합니다.")
_require_manage(request, st, user, target)
project = st.get_project(project_id=target)
if project is None:
raise HTTPException(status_code=404, detail="프로젝트를 찾을 수 없습니다.")
try:
task = st.move_task_to_project(
task_id=task_id, project_id=target, stage_id=payload.get("stage_id"),
actor=user["email"], assignee_allowed=_registered_project_user,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except KeyError as exc:
raise HTTPException(status_code=404, detail=str(exc))
task.pop("_moved_ids", None)
if _drive_path_changed(existing, task): # 세부 업무까지 드라이브 파일도 새 프로젝트/섹션 폴더로(백그라운드)
bg.add_task(_relocate_drive_files, st, task_id)
newly_assigned = task.pop("_newly_assigned", None)
if newly_assigned: # 대상 섹션 기본 담당자가 자동 배정됨 — 일반 배정과 같은 알림(담당자는 협업자가 아님)
_inbox(
st, recipients=[newly_assigned], actor=user["email"], project_id=target, 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"])
people = [task.get("assignee_email") or ""]
try:
people += st.list_followers(task_id=task_id)
except Exception: # noqa: BLE001 - 008 미적용
pass
unseen = sorted({store.norm_str(e, lower=True) for e in people if e} -
set(access.filter_recipients(st, task, [e for e in people if e])))
return JSONResponse({"task": task, "unseen": unseen})
@router.post("/api/stages/{stage_id}/move-project")
def api_move_stage_project(
request: Request,
stage_id: int,
bg: BackgroundTasks,
payload: dict[str, Any] = Body(...),
) -> JSONResponse:
"""섹션을 통째로 다른 프로젝트로 옮긴다(2026-10-26) — 보드 섹션 머리를 왼쪽 프로젝트 목록으로 드래그 → 확인 창.
body: {"project_id": 대상}. 원 프로젝트 멤버 + 대상 프로젝트 멤버여야 한다. 섹션의 업무·세부 업무가 함께 옮겨지고
섹션은 대상 프로젝트 섹션 맨 끝. 응답의 `unseen` = 대상 프로젝트를 볼 수 없는 담당자(화면이 안내 — 담당자는 그대로).
"""
user = _require_user(request)
st = _db_or_503(request)
stage = st.get_stage(stage_id=stage_id)
if stage is None:
raise HTTPException(status_code=404, detail="섹션을 찾을 수 없습니다.")
_require_manage(request, st, user, int(stage["project_id"]))
try:
target = int(payload.get("project_id"))
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail="옮길 프로젝트(project_id)가 필요합니다.")
_require_manage(request, st, user, target)
try:
moved = st.move_stage_to_project(stage_id=stage_id, project_id=target, 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))
tops = moved.pop("_moved_task_ids", [])
moved.pop("_moved_ids", None)
for tid in tops: # 세부 업무까지 드라이브 파일도 새 프로젝트 폴더로(백그라운드)
bg.add_task(_relocate_drive_files, st, tid)
unseen: set[str] = set()
for tid in tops:
task = st.get_task(task_id=tid)
email = (task or {}).get("assignee_email") or ""
if email and not access.filter_recipients(st, task, [email]):
unseen.add(store.norm_str(email, lower=True))
return JSONResponse({"stage": moved, "task_count": len(tops), "unseen": sorted(unseen)})
# ────────────────────────────────────────────────────────────
# 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, 수퍼관리자 — 담당자 후보와 같은 access.can_assign)만 — 못 보는 업무의 알림이 가면
안 되므로. 관리자도 멤버가 아니면 안 된다(2026-10-07 — 예전엔 관리자는 멤버가 아니어도 넣을 수 있었다)."""
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 and email == store.norm_str(task.get("assignee_email") or "", lower=True):
raise HTTPException(status_code=400, detail="담당자는 협업자로 지정할 수 없습니다(협업자는 담당자 외의 멤버).")
if email != store.norm_str(user["email"], lower=True):
if not access.can_assign(st, email, task["project_id"]):
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 단일 워커) 기준.
#
# 보장 범위: 이 기록은 **웹 프로세스 메모리**에 있다. 같은 프로세스 안에서는 동시 요청·응답 유실 후 재전송이
# 한 번만 만든다. 웹 워커가 여럿이면(uvicorn --workers N·컨테이너 여러 개) 다른 워커로 간 재전송은 막지 못하고,
# 프로세스를 다시 띄우면 기록도 사라진다(지금 운영은 web 컨테이너 1개·워커 1개).
_ONCE_TTL_SEC = 600
_once_lock = threading.Lock()
_once_results: dict[tuple[str, int, str], tuple[float, dict[str, Any]]] = {}
# 키별 잠금 [잠금, 쓰는 요청 수]. 쓰는 요청이 0 이 되면 바로 뺀다 — 결과가 있으면 다음 요청은 결과로
# 답하고(결과를 먼저 저장한 뒤 잠금을 푼다), 실패해 결과가 없으면 다음 요청이 새로 만든다(재시도).
_once_key_locks: dict[tuple[str, int, str], list[Any]] = {}
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)
entry = _once_key_locks.get(key)
if entry is None:
entry = _once_key_locks[key] = [threading.Lock(), 0]
entry[1] += 1
try:
with entry[0]: # 같은 토큰의 동시 요청은 첫 요청이 끝날 때까지 기다렸다가 그 결과를 받는다
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
finally:
with _once_lock:
entry[1] -= 1
if entry[1] <= 0 and _once_key_locks.get(key) is entry:
_once_key_locks.pop(key, None)
_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="댓글을 찾을 수 없습니다.")
me = store.norm_str(user["email"], lower=True)
if any(r["emoji"] == emoji and me in r["users"] for r in reactions): # 켤 때만(끌 때는 알림 없음)
_notify_reaction(st, task=task, comment=comment, actor=user["email"], emoji=emoji)
return JSONResponse({"reactions": reactions})
def _notify_reaction(
st: Any, *, task: dict[str, Any], comment: dict[str, Any], actor: str, emoji: str,
) -> None:
"""댓글 이모티콘 반응 알림 — 그 댓글을 쓴 사람에게 어떤 이모티콘인지(자기 댓글·지금 볼 수 없는 사람은 제외)."""
author = store.norm_str(comment.get("author_email"), lower=True)
if not author or author == store.norm_str(actor, lower=True):
return
recipients = access.filter_recipients(st, task, [author])
if not recipients:
return
project = st.get_project(project_id=task["project_id"]) or {}
preview = (comment.get("body") or "").strip().replace("\n", " ")[:80] or "첨부 파일"
_inbox(
st, recipients=recipients, actor=actor, project_id=task["project_id"], task_id=task["id"],
ntype="reaction", title=f"내 댓글에 {emoji} 반응: {task['title']}",
body=f"{project.get('name') or task.get('project_name') or ''} · “{preview}”",
)
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:
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=access.is_pro(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:
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=access.is_pro(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 를 주면 댓글 채팅 팝업의 첨부(이미지/파일)로도 등록 —
같은 표에 저장되므로 업무 "첨부파일" 패널에도 그대로 함께 나온다."""
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="잘못된 댓글입니다.")
# 남의 댓글에 파일을 붙일 수 없다(작성자 본인·Pro user 이상만 — 댓글 수정 권한과 같음).
if not access.is_pro(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 # 요청마다 새 uuid 이름 — 기존 파일을 덮지 않는다
dest.write_bytes(data)
try:
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,
)
except Exception:
# DB 에 안 들어간 파일은 디스크에도 남기지 않는다(댓글+첨부 일괄 등록과 같은 원칙) — 이 요청이 쓴 파일만.
try:
dest.unlink(missing_ok=True)
except Exception: # noqa: BLE001
logger.warning("첨부 정리 실패: %s", dest.name)
raise
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})
# ────────────────────────────────────────────────────────────
# 업무 파일 → 구글 드라이브(2026-10-19) — 설명란·보드 카드·세부 업무 줄에 파일을 끌어 놓으면
# 드라이브 `프로젝트/섹션/업무/세부 업무` 폴더에 올리고 설명란에 "파일 이름.확장자" 링크.
# 설명에서 링크를 지우면 그 파일을 드라이브 휴지통으로(api_update_task → _sync_drive_links).
# ────────────────────────────────────────────────────────────
_MAX_DRIVE_BYTES = 200 * 1024 * 1024 # 200MB
def _drive_folder_names(st: Any, task: dict[str, Any]) -> list[str]:
"""[프로젝트, 섹션, 업무, (세부 업무…)] — 섹션은 맨 위 업무의 섹션(세부 업무는 섹션이 없을 수 있다)."""
chain = [task]
seen = {int(task["id"])}
while chain[-1].get("parent_task_id") and len(chain) < 10:
parent = st.get_task(task_id=chain[-1]["parent_task_id"])
if parent is None or int(parent["id"]) in seen:
break
seen.add(int(parent["id"]))
chain.append(parent)
chain.reverse()
top = chain[0]
return [top.get("project_name") or "", top.get("stage_name") or "섹션 없음"] + [t.get("title") or "" for t in chain]
def drive_link_html(url: str, name: str) -> str:
"""설명란 링크 — 제목 = 파일 이름.확장자, 새 탭에서 열기."""
import html as _html # noqa: WPS433
return (f'<a href="{_html.escape(url, quote=True)}" target="_blank" rel="noopener noreferrer">'
f"{_html.escape(name)}</a>")
@router.post("/api/tasks/{task_id}/drive-files")
def api_upload_drive_file(
request: Request, task_id: int, file: UploadFile = File(...), append: bool = Form(False),
) -> JSONResponse:
"""파일 하나를 구글 드라이브 업무 폴더에 올린다 → {file: {id, name, url}, link_html}.
append=true 면 서버가 그 업무 설명 끝에 링크 줄을 붙이고 바뀐 업무를 같이 돌려준다(보드 카드·세부 업무 줄에 놓을 때 —
설명란을 열어 둔 업무는 화면이 커서 자리에 직접 넣고 평소처럼 저장)."""
from app.integrations import google_drive # 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)
client = google_drive.get_client()
if not client.enabled:
raise HTTPException(status_code=503, detail=f"구글 드라이브 연동이 꺼져 있습니다({client.reason}).")
stream = file.file
stream.seek(0, 2)
size = stream.tell()
stream.seek(0)
if size > _MAX_DRIVE_BYTES:
raise HTTPException(status_code=413, detail="파일이 너무 큽니다(최대 200MB).")
if size <= 0:
raise HTTPException(status_code=400, detail="빈 파일입니다.")
name = (file.filename or "file").replace("\\", "_").replace("/", "_").strip() or "file"
try:
folder = client.ensure_folder_path(_drive_folder_names(st, task))
up = client.upload(folder_id=folder, name=name, stream=stream,
mimetype=file.content_type or "application/octet-stream", task_id=task_id)
except google_drive.GoogleDriveError as exc:
raise HTTPException(status_code=502, detail=str(exc))
link = drive_link_html(up["url"], up["name"])
out: dict[str, Any] = {"file": up, "link_html": link}
if append:
cur = st.get_task(task_id=task_id) or task
desc = store.sanitize_description_html((cur.get("description") or "") + f"<p>{link}</p>")
try:
out["task"] = st.update_task(task_id=task_id, fields={"description": desc}, actor=user["email"],
assignee_allowed=_registered_project_user)
except (ValueError, KeyError):
# 파일은 올라갔다 — 링크만 못 붙임(화면이 링크를 알려 준다)
out["append_failed"] = True
return JSONResponse(out, status_code=201)
def _sync_drive_links(st: Any, task_id: int, removed: set[str], added: set[str]) -> None:
"""설명란 드라이브 링크가 빠지면 그 파일을 휴지통으로, 다시 생기면 휴지통에서 꺼낸다(백그라운드).
우리가 올린 파일(appProperties dbxTaskId)만, 그리고 다른 업무 설명에 같은 링크가 남아 있으면 휴지통에 넣지 않는다."""
from app.integrations import google_drive # noqa: WPS433
client = google_drive.get_client()
if not client.enabled:
return
for fid in removed:
try:
if st.description_mentions(text=fid, exclude_task_id=task_id):
continue
info = client.ours(fid)
if info and not info["trashed"]:
client.set_trashed(fid, True)
except Exception: # noqa: BLE001 — 저장은 이미 끝났다(파일만 남음)
logger.warning("드라이브 파일 휴지통 이동 실패: task=%s file=%s", task_id, fid)
for fid in added:
try:
info = client.ours(fid)
if info and info["trashed"]:
client.set_trashed(fid, False)
except Exception: # noqa: BLE001
logger.warning("드라이브 파일 복구 실패: task=%s file=%s", task_id, fid)
def _relocate_drive_files(st: Any, task_id: int) -> None:
"""업무가 다른 섹션·프로젝트·상위 업무로 옮겨지면 설명란 링크 속 드라이브 파일도 새 `프로젝트/섹션/업무/세부 업무`
폴더로 옮긴다(2026-10-20, 백그라운드). 하위 세부 업무도 경로가 바뀌므로 함께. 그 업무가 올린 파일만
(appProperties dbxTaskId — 다른 업무 링크를 붙여 넣은 것·남의 파일은 그대로). 예전 폴더는 지우지 않는다."""
from app.integrations import google_drive # noqa: WPS433
client = google_drive.get_client()
if not client.enabled:
return
try:
ids = st.task_subtree_ids(task_id=task_id)
except Exception: # noqa: BLE001
logger.warning("드라이브 파일 이동 — 하위 업무 조회 실패: task=%s", task_id)
return
for tid in ids:
task = st.get_task(task_id=tid)
files = google_drive.file_ids_in((task or {}).get("description") or "")
if not files:
continue
try:
folder = client.ensure_folder_path(_drive_folder_names(st, task))
except Exception: # noqa: BLE001 — 이동은 이미 끝났다(파일만 예전 폴더에 남음)
logger.warning("드라이브 폴더 준비 실패: task=%s", tid)
continue
for fid in files:
try:
client.move_to(fid, folder, task_id=tid)
except Exception: # noqa: BLE001
logger.warning("드라이브 파일 이동 실패: task=%s file=%s", tid, fid)
# ────────────────────────────────────────────────────────────
# 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/alerts")
def api_notification_alerts(request: Request, after: int = -1) -> JSONResponse:
"""화면 가운데 아래 큰 팝업용(2026-10-07) — 나를 태그(mention)하거나 작업을 배정(assigned)한, 읽지 않은 알림 중
id 가 after 보다 큰 것(오래된 것부터 최대 10, 지금 볼 수 있는 작업만). after 없이 부르면 기준점(latest_id)만 —
처음 쓰는 브라우저가 쌓인 옛 알림을 한꺼번에 띄우지 않게."""
user = _require_user(request)
st = _db_or_503(request)
# PC 알림 프로그램이 돌고 있으면(023, 최근 3분 안에 확인) 웹 팝업은 띄우지 않는다 — 기준점(latest_id)만 주고
# desktop=True. 웹은 그 번호까지 본 것으로 두어, 프로그램을 끄면 그 뒤에 온 알림부터 다시 웹에 뜬다.
if _notifier_active(st, user):
out = _alerts_payload(st, user, -1)
out["desktop"] = True
return JSONResponse(out)
return JSONResponse(_alerts_payload(st, user, after))
def _notifier_active(st: Any, user: dict[str, Any]) -> bool:
try:
return bool(st.notifier_active(email=user["email"]))
except Exception: # noqa: BLE001 — 확인 실패면 웹 팝업을 그대로(알림을 놓치지 않게)
return False
def _alerts_payload(st: Any, user: dict[str, Any], after: int) -> dict[str, Any]:
"""큰 팝업 알림 — 웹 화면(initTaskAlerts)과 PC 알림 프로그램이 같이 쓴다."""
newest = st.list_notifications(recipient_email=user["email"], limit=1)
latest = int(newest[0]["id"]) if newest else 0
out: dict[str, Any] = {"me": store.norm_str(user["email"], lower=True), "latest_id": latest, "alerts": []}
if after < 0:
return out
# 수신자·읽지 않음·종류·after 는 DB 에서 먼저(오래된 것부터), 지금 권한은 여기서 — 페이지를 넘기며
# 볼 수 있는 것 10건을 모은다. 예전엔 최신 50건을 먼저 자른 뒤 걸러서, 그 뒤에 댓글 알림이 50건
# 쌓이거나 배정이 60건을 넘거나 볼 수 없는 작업 알림이 앞을 채우면 팝업이 빠졌다.
rows: list[dict[str, Any]] = []
cursor = int(after)
for _ in range(_ALERT_SCAN_PAGES):
page = st.list_unread_after(recipient_email=user["email"], after_id=cursor,
types=_ALERT_TYPES, limit=_ALERT_PAGE)
if not page:
break
rows.extend(_visible_notifications(st, user, page))
cursor = max(int(n["id"]) for n in page)
if len(rows) >= _ALERT_MAX or len(page) < _ALERT_PAGE:
break
rows = sorted(rows, key=lambda n: int(n["id"]))[:_ALERT_MAX]
out["alerts"] = [{k: n.get(k) for k in ("id", "type", "title", "body", "task_id", "project_id", "actor_email", "created_at")}
for n in rows]
for a in out["alerts"]:
a["href"] = _alert_href(a)
return out
_ALERT_TYPES = ("mention", "assigned")
_ALERT_MAX = 10 # 한 번에 띄우는 최대 건수(오래된 것부터 — 닫으면 그 뒤 것)
_ALERT_PAGE = 200
_ALERT_SCAN_PAGES = 25 # 한 번 확인에 읽는 최대 행(200 × 25) — 볼 수 없는 알림이 아주 많아도 요청이 끝나게
def _alert_href(n: dict[str, Any]) -> str:
"""알림을 열 주소 — 작업 알림은 /project/t/{id}(지금 권한으로 열 수 있는 프로젝트를 서버가 고른다 —
연결된 프로젝트에서만 읽을 수 있는 작업도 403 이 나지 않게), 작업 없는 프로젝트 알림은 그 프로젝트."""
if n.get("task_id"):
return f"/project/t/{int(n['task_id'])}"
if n.get("project_id"):
return f"/project/p/{int(n['project_id'])}"
return "/project/inbox"
# ────────────────────────────────────────────────────────────
# PC 알림 프로그램(desktop/notifier, 023) — 브라우저 쿠키 대신 PC별 연결 토큰(Authorization: Bearer).
# 연결: 프로그램 POST link/start → 사용자가 브라우저 /project/notifier?code= 에서 [연결] → 프로그램 POST link/poll 로 토큰 1회.
# ────────────────────────────────────────────────────────────
_NOTIFIER_MIGRATION_MSG = "PC 알림 연결이 아직 준비되지 않았습니다(project_db 023 마이그레이션 필요)."
def _notifier_call(fn: Any, **kwargs: Any) -> Any:
try:
return fn(**kwargs)
except UndefinedTable:
raise HTTPException(status_code=503, detail=_NOTIFIER_MIGRATION_MSG)
def _notifier_token(request: Request) -> str:
auth = request.headers.get("authorization", "")
return auth[7:].strip() if auth.lower().startswith("bearer ") else ""
def _user_by_email(email: str) -> dict[str, Any] | None:
from app.main import user_store # noqa: WPS433
return user_store.get(email)
def _notifier_user(request: Request, st: Any) -> dict[str, Any]:
"""토큰 → 지금 사용자 레코드(권한 포함). 토큰 해제·사용자 삭제·프로젝트 권한 회수면 401."""
from app.store import has_module # noqa: WPS433
email = _notifier_call(st.notifier_token_email, token=_notifier_token(request))
user = _user_by_email(email) if email else None
if user is None or not has_module(user, "project"):
raise HTTPException(status_code=401, detail="연결이 해제되었습니다. 다시 연결하세요.")
return user
@router.post("/api/notifier/link/start")
def api_notifier_link_start(request: Request, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
"""연결 요청(로그인 없이) — 화면 코드 + poll 비밀값. 사용자는 /project/notifier?code= 에서 승인."""
st = _db_or_503(request)
device = store.norm_str(payload.get("device") or "")[:80]
try:
link = _notifier_call(st.notifier_start_link, device_name=device)
except OverflowError as exc:
raise HTTPException(status_code=429, detail=str(exc))
return JSONResponse({**link, "approve_path": "/project/notifier?code=" + link["code"]})
@router.post("/api/notifier/link/poll")
def api_notifier_link_poll(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
st = _db_or_503(request)
poll = store.norm_str(payload.get("poll") or "")
if not poll:
raise HTTPException(status_code=400, detail="poll 이 필요합니다.")
return JSONResponse(_notifier_call(st.notifier_poll_link, poll=poll))
@router.post("/api/notifier/link/approve")
def api_notifier_link_approve(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""브라우저(로그인 사용자)가 [연결] — 이 코드의 PC 를 내 알림에 연결."""
user = _require_user(request)
st = _db_or_503(request)
if not _notifier_call(st.notifier_approve_link, code=str(payload.get("code") or ""), email=user["email"]):
raise HTTPException(status_code=404, detail="연결 코드가 없거나 만료되었습니다. 프로그램에서 다시 연결하세요.")
return JSONResponse({"ok": True})
@router.post("/api/notifier/devices/{device_id}/revoke")
def api_notifier_revoke_device(request: Request, device_id: int) -> JSONResponse:
user = _require_user(request)
st = _db_or_503(request)
if not _notifier_call(st.notifier_revoke_device, device_id=device_id, email=user["email"]):
raise HTTPException(status_code=404, detail="연결된 PC 를 찾을 수 없습니다.")
return JSONResponse({"ok": True})
@router.get("/api/notifier/alerts")
def api_notifier_alerts(request: Request, after: int = -1) -> JSONResponse:
"""PC 알림 프로그램 — 웹 큰 팝업과 같은 알림. name = 표시 이름(트레이 메뉴용)."""
st = _db_or_503(request)
user = _notifier_user(request, st)
out = _alerts_payload(st, user, after)
out["name"] = user.get("name") or user["email"]
return JSONResponse(out)
@router.post("/api/notifier/alerts/{notification_id}/read")
def api_notifier_alert_read(request: Request, notification_id: int) -> JSONResponse:
st = _db_or_503(request)
user = _notifier_user(request, st)
st.mark_read(notification_id=notification_id, recipient_email=user["email"])
return JSONResponse({"ok": True})
@router.post("/api/notifier/logout")
def api_notifier_logout(request: Request) -> JSONResponse:
st = _db_or_503(request)
_notifier_call(st.notifier_revoke_token, token=_notifier_token(request))
return JSONResponse({"ok": True})
@router.get("/notifier/download")
def notifier_download(request: Request) -> Any:
"""PC 알림 프로그램 내려받기 — 서버 DATA_DIR/notifier/DBXNotifier.exe 를 그대로(없으면 404)."""
from app.main import DATA_DIR # noqa: WPS433
_require_user(request)
exe = Path(DATA_DIR) / "notifier" / "DBXNotifier.exe"
if not exe.is_file():
raise HTTPException(status_code=404, detail="아직 서버에 프로그램 파일이 없습니다. 관리자에게 문의하세요.")
return FileResponse(exe, filename="DBXNotifier.exe", media_type="application/octet-stream")
@router.get("/notifier", response_class=HTMLResponse)
def notifier_page(request: Request) -> Any:
"""PC 알림 프로그램 — 연결 승인(?code=)·연결된 PC 목록·내려받기."""
from app.main import DATA_DIR, build_erp_nav, get_current_user_record, render_template # noqa: WPS433
from app.store import is_admin # noqa: WPS433
from urllib.parse import quote # noqa: WPS433
if get_current_user_record(request) is None:
return RedirectResponse(url="/login?next=" + quote(str(request.url.path) + (
"?" + request.url.query if request.url.query else ""), safe=""), status_code=303)
user = _require_user(request)
st = _store(request)
if st is None:
return _render_config_needed(request, user)
admin = is_admin(user)
enabled = st.notifier_enabled()
code = store.norm_str(request.query_params.get("code") or "").upper()[:9]
link = st.notifier_get_link(code=code) if enabled and code else None
return render_template(
request,
"project/notifier.html",
{
"user": user,
**_role_ctx(user),
"nav_items": build_erp_nav(user, active="project"),
"nav_projects": _nav_projects(st, user, admin),
"goal_years": _goal_years_nav(st),
"my_open_total": _my_open_count(st, user),
"mention_unread": _safe_mention_unread(st, user),
"page_title": "PC 알림 프로그램",
"page_subtitle": "브라우저가 뒤에 있어도 태그·업무 배정 알림을 화면 위에 크게",
"force_sidebar_collapsed": True,
"color_palette": list(store.COLOR_PALETTE),
"project_icons": list(store.PROJECT_ICONS),
"project_asana_icons": list(store.PROJECT_ASANA_ICONS),
"notifier_enabled": enabled,
"code": code,
"link": link,
"devices": st.notifier_list_devices(email=user["email"]) if enabled else [],
"download_ready": (Path(DATA_DIR) / "notifier" / "DBXNotifier.exe").is_file(),
},
)
@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 와 같은 기준). 미확인 태그가 있는
작업만 가볍게 읽어 개수 제한 없이 센다(예전엔 태그된 작업 최근 1000개 안에서만)."""
try:
rows = st.list_unread_mention_refs(mentioned_email=user["email"])
except Exception: # noqa: BLE001 - 006 미적용
return 0
return sum(int(t.get("unread_mentions") or 0) for t in access.filter_visible_tasks(st, user, rows))
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:
"""읽지 않은 알림 수 — 지금 볼 수 있는 것만, 개수 제한 없이(예전엔 최근 500건만 세었다)."""
return len(_visible_notifications(st, user, st.list_unread_refs(recipient_email=user["email"])))
@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:
tid = int(task_id) if task_id else None
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail="task_id 가 올바르지 않습니다.")
try:
n = st.mark_mentions_read(mentioned_email=user["email"], task_id=tid)
except UndefinedTable: # 006 미적용 — 태그 기록이 없다
n = 0
# 그 밖의 DB 오류는 실패로 돌려준다 — 예전엔 성공처럼 답해 화면이 확인한 것으로 지웠다.
return JSONResponse({"ok": True, "marked": n})
@router.get("/trash", response_class=HTMLResponse)
def trash_page(request: Request) -> HTMLResponse:
"""휴지통 — Pro user 이상. 지운 업무(세부 업무 포함)를 3개월 보관, 복구(멤버인 프로젝트 것만)."""
from app.main import build_erp_nav, render_template # noqa: WPS433
user = _page_user(request)
if not isinstance(user, dict):
return user
if not access.is_pro(user):
raise HTTPException(status_code=403, detail="Pro user 이상만 볼 수 있습니다.")
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,
**_role_ctx(user),
"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개월 보관, Pro user 이상만 복구",
"force_sidebar_collapsed": True,
"color_palette": list(store.COLOR_PALETTE),
"project_icons": list(store.PROJECT_ICONS),
"project_asana_icons": list(store.PROJECT_ASANA_ICONS),
"trash_enabled": enabled,
# 휴지통도 내가 볼 수 있는 프로젝트(owner·멤버, 슈퍼관리자는 전체)의 것만
"items": _trash_view_items(_visible_trash(st, user)) if enabled else [],
},
)
def _visible_trash(st: Any, user: dict[str, Any]) -> list[dict[str, Any]]:
allowed = _accessible_project_ids(st, user)
items = st.list_trash()
return items if allowed is None else [it for it in items if it.get("project_id") in allowed]
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:
"""휴지통 항목 복구 — Pro user 이상. 업무·세부 업무·댓글 등 원래 id 그대로."""
user = _require_pro(request)
st = _db_or_503(request)
if not any(int(it["id"]) == trash_id for it in _visible_trash(st, user)):
raise HTTPException(status_code=404, detail="휴지통 항목을 찾을 수 없습니다.") # 멤버가 아닌 프로젝트 것은 없는 것처럼
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
user = _page_user(request)
if not isinstance(user, dict):
return user
return render_template(
request,
"project/help.html",
{
"user": user,
**_role_ctx(user),
"nav_items": build_erp_nav(user, active="project"),
"page_title": "프로젝트 관리 도움말",
"page_subtitle": "처음 쓰는 분을 위한 기능 안내",
},
)
_DBX_PAGE = Path(__file__).resolve().parent / "dbx.html"
@router.get("/dbx", response_class=HTMLResponse)
def dbx_page(request: Request) -> HTMLResponse:
"""수신함 [성공하기] — 모듈 폴더의 dbx.html 을 그대로(별도 창, 닫기 버튼만). DB 없이 열린다."""
user = _page_user(request)
if not isinstance(user, dict):
return user
try:
html = _DBX_PAGE.read_text(encoding="utf-8")
except OSError:
raise HTTPException(status_code=404, detail="페이지를 찾을 수 없습니다.")
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
@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 = _page_user(request)
if not isinstance(user, dict):
return user
st = _store(request)
if st is None:
return _render_config_needed(request, user)
admin = is_admin(user)
# 수신함 = 아직 확인 안 한 것만(2026-10-08) — 누르면 읽음/확인 처리되고 목록에서 빠진다.
items = _visible_notifications(st, user, st.list_notifications(recipient_email=user["email"], unread_only=True, limit=100))
mentioned = [t for t in _safe_mentions(st, user) if t.get("unread_mentions")]
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,
**_role_ctx(user),
"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),
"project_asana_icons": list(store.PROJECT_ASANA_ICONS),
"notifications": items,
"mentioned_tasks": mentioned,
"mention_unread": _safe_mention_unread(st, user),
},
)
# ────────────────────────────────────────────────────────────
# 연간 목표 (마이그레이션 013) — 사이드바 "목표" → 연도 → 목표 표
# 조회: project 권한자 전원 · 입력/구조 변경: Pro user 이상(_require_pro)
# ────────────────────────────────────────────────────────────
_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 _meeting_label_spans(rows: list[dict[str, Any]]) -> None:
"""회의록 구역 한 덩어리의 항목 칸 묶음(027) — 이어 붙은 줄(label_cont, 구역 첫 줄 제외)은 항목 칸을 그리지 않고
(label_hidden) 묶음 첫 줄이 rowspan(label_span). label_shown = 그 줄이 속한 항목 이름(칸 이름표·접근성용)."""
grp: dict[str, Any] | None = None
for i, it in enumerate(rows):
if i and it.get("label_cont") and grp is not None:
it["label_hidden"] = True
grp["label_span"] += 1
else:
grp = it
it["label_hidden"], it["label_span"] = False, 1
it["label_shown"] = grp["label"]
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 store.MeetingCellMigrationNeeded:
raise HTTPException(status_code=503, detail="회의록 셀 병합은 project_db 마이그레이션 019 적용 후 사용할 수 있습니다.")
except store.MeetingLocked:
raise HTTPException(status_code=409, detail="회의가 완료되어 수정할 수 없습니다. 관리자가 [완료 해제]하면 다시 고칠 수 있습니다.")
except store.MeetingMigration022Needed:
raise HTTPException(status_code=503, detail="회의 완료 기능은 project_db 마이그레이션 022 적용 후 사용할 수 있습니다.")
except store.MeetingMigration027Needed:
raise HTTPException(status_code=503, detail="같은 항목 칸 안 줄 추가·항목 칸 나누기는 project_db 마이그레이션 027 적용 후 사용할 수 있습니다.")
except store.MeetingParentTaskMigrationNeeded:
raise HTTPException(status_code=503, detail="업무 칸(이미 있는 업무의 세부 업무로 등록)은 project_db 마이그레이션 026 적용 후 사용할 수 있습니다.")
except store.MeetingTaskMigrationNeeded:
raise HTTPException(status_code=503, detail="업무 등록 표(모두가 같이 보는 주차별 표)는 project_db 마이그레이션 025 적용 후 사용할 수 있습니다.")
except store.MeetingMigration030Needed:
raise HTTPException(status_code=503, detail="주차 목표 두 칸(유통·인플 / 카페24·네이버)은 project_db 마이그레이션 030 적용 후 사용할 수 있습니다.")
except store.MeetingMigration020Needed:
raise HTTPException(status_code=503, detail="새 주차·결과 글·주차별 목표는 project_db 마이그레이션 020 적용 후 사용할 수 있습니다.")
except store.GoalCellConflict as exc:
raise HTTPException(status_code=409, detail=str(exc))
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:
"""사이드바 "목표" 자체 주소 — 가장 최근 연도(없으면 올해)로."""
user = _page_user(request)
if not isinstance(user, dict):
return user
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:
"""한 해 전체 목표 — 매출(목표·실적·달성)·로아스(목표·실적) 월별 숫자 +
업무 영역(상품·마케팅·컨텐츠·유통 …)별 연간·월별 글. 입력은 Pro user 이상."""
from app.main import build_erp_nav, render_template # noqa: WPS433
from app.store import is_admin # noqa: WPS433
user = _page_user(request)
if not isinstance(user, dict):
return user
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"])
# 주차별 매출 목표(020) — 월 매출 목표 칸을 누르면 그 달 월 목표·주차별 입력 창(월 목표는 직접 입력)
week_targets = None
week_split = False
if board and st.week_targets_enabled():
week_split = st.week_split_enabled()
parts = st.goal_week_target_parts(start=date(year, 1, 1), end=date(year, 12, 31))
def part(a: date, key: str) -> str:
p_ = parts.get(a.isoformat()) or {}
v = p_.get(key)
# 030 전에 한 칸으로 넣은 주차(두 칸 비고 합계만) — 합계를 유통·인플 칸에 미리 넣어 보여 준다
if key == "dist" and v is None and p_.get("mall") is None:
v = p_.get("total")
return _goal_label("sales", v)
# 기간 표기 — 11/1(일)~11/8(일), days = 그 주차 날 수. 두 칸(030) = dist 유통·인플 · mall 카페24·네이버
week_targets = {mo: [{"start": a.isoformat(), "n": i + 1, "days": (b - a).days + 1,
"label": f"{a.month}/{a.day}({_WEEKDAYS_KR[a.weekday()]})~{b.month}/{b.day}({_WEEKDAYS_KR[b.weekday()]})",
"value": _goal_label("sales", (parts.get(a.isoformat()) or {}).get("total")),
"dist": part(a, "dist"), "mall": part(a, "mall")}
for i, (a, b) in enumerate(store.month_weeks(year, mo))] for mo in range(1, 13)}
return render_template(
request,
"project/goals.html",
{
"user": user,
**_role_ctx(user),
"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),
"project_asana_icons": list(store.PROJECT_ASANA_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),
"week_targets": week_targets,
"week_split": week_split,
},
)
@router.put("/api/goals/{year}/week-targets/{month}")
def api_set_goal_week_targets(request: Request, year: int, month: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""그 달 주차별 매출 목표 {month: 월 목표|"", weeks: {주차 시작일: 값|""}} — 월 목표는 직접 입력(Pro user 이상).
month 가 없으면(예전 화면) 주차 합계를 월 목표로."""
user = _require_pro(request)
st = _db_or_503(request)
raw = payload.get("weeks")
if not isinstance(raw, dict) or len(raw) > 6:
raise HTTPException(status_code=400, detail="weeks 가 올바르지 않습니다.")
# 주차 값 = 숫자 하나(예전) 또는 {dist: 유통·인플, mall: 카페24·네이버}(030, 2026-10-19)
values: dict[date, Any] = {}
for k, v in raw.items():
d = _goal_call(store.validate_period_start, k)
if isinstance(v, dict):
values[d] = (_goal_call(store.validate_goal_value, v.get("dist")), _goal_call(store.validate_goal_value, v.get("mall")))
else:
values[d] = _goal_call(store.validate_goal_value, v)
def tot(v: Any) -> float | None:
if isinstance(v, tuple):
return None if v[0] is None and v[1] is None else (v[0] or 0) + (v[1] or 0)
return v
if "month" in payload:
month_value = _goal_call(store.validate_goal_value, payload.get("month"))
else:
filled = [tot(v) for v in values.values() if tot(v) is not None]
month_value = sum(filled) if filled else None
week_total = _goal_call(st.set_goal_week_targets, year=year, month=month, values=values,
month_value=month_value, updated_by=user["email"])
return JSONResponse({"ok": True, "value": month_value, "label": _goal_label("sales", month_value),
"week_total": week_total,
"weeks": {k.isoformat(): _goal_label("sales", tot(v)) for k, v in values.items()},
"parts": {k.isoformat(): {"dist": _goal_label("sales", v[0]), "mall": _goal_label("sales", v[1])}
for k, v in values.items() if isinstance(v, tuple)}})
@router.post("/api/goals/years")
def api_create_goal_year(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""연도 추가(Pro user 이상) — 가장 가까운 이전 연도의 영역·줄 구조를 글 없이 복사."""
user = _require_pro(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.get("/api/goals/meeting-nav")
def api_goal_meeting_nav(request: Request) -> JSONResponse:
"""왼쪽 메뉴용: 저장된 회의록만 연도·월로 묶는다. 화면 조회로 회의록을 만들지 않는다."""
_require_user(request)
st = _db_or_503(request)
years = _goal_years_nav(st)
# 연도마다 DB를 읽지 않고, 메뉴에 있는 전체 연도 범위를 한 번에 조회한다.
weeks = _goal_call(st.meeting_weeks, start=date(min(years), 1, 1), end=date(max(years), 12, 31))
grouped: dict[int, dict[int, list[dict[str, Any]]]] = {}
for value in sorted(set(weeks)):
mon = store.validate_week_start(value)
if mon.year not in years:
continue
# 주차는 달을 넘지 않는다(020) — 회의록 시작일이 든 주차
a, end = store.week_period(mon)
number = store.week_number(mon)
grouped.setdefault(mon.year, {}).setdefault(mon.month, []).append({
"start": mon.isoformat(), "label": f"{number}주차 ({a.month}/{a.day}~{end.month}/{end.day})",
"href": f"/project/goals/{mon.year}/meetings/{mon.month}?week={mon.isoformat()}",
})
return JSONResponse({"years": [
{"year": y, "months": [{"month": m, "weeks": grouped[y][m]} for m in sorted(grouped[y])]}
for y in years if y in grouped
]})
@router.put("/api/goals/{year}")
def api_update_goal_year(request: Request, year: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
_require_pro(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_pro(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_pro(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_pro(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_pro(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_pro(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_pro(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_pro(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_pro(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_pro(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_pro(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_pro(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_pro(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/cells/move")
def api_move_goal_cell(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""내용·글자 서식만 원자적으로 이동. 원본·대상의 예상값이 바뀌면 409, 병합 배치는 유지."""
user = _require_pro(request)
st = _db_or_503(request)
if any(not isinstance(payload.get(k), str) for k in ("source_body", "target_body", "body")):
raise HTTPException(status_code=400, detail="이동할 내용과 두 칸의 현재 내용을 보내 주세요.")
body = _goal_call(
st.move_goal_cell, source_row=payload.get("source_row"), source_month=payload.get("source_month"),
target_row=payload.get("target_row"), target_month=payload.get("target_month"),
source_body=payload["source_body"], target_body=payload["target_body"], body=payload["body"],
updated_by=user["email"],
)
return JSONResponse({"ok": True, "body": body})
@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_pro(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_pro(request)
st = _db_or_503(request)
_goal_call(st.unmerge_goal_cells, row_id=row_id, start=start)
return JSONResponse({"ok": True})
# ════════════════════════════════════════════════════════════
# 주간 회의록 (마이그레이션 015·020) — 목표 표 월 머리 → /project/goals/{연도}/meetings/{월}?week=주차 시작일
# 주차 = store.month_weeks(그 달 안, 1주차는 1일부터). 지난 주차 업무·결과 리뷰 → 이번 주차 주요 업무·목표.
# 월 누적 실적은 실적 모듈(performance_db)에서 읽기만, 월 누적 목표는 목표 표 주차별 목표(goal_week_targets) 합.
# ════════════════════════════════════════════════════════════
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]:
"""회의록 화면 데이터 — 머리(월 목표 매출 · 월 누적 목표 · 월 누적 실적 · 누적 목표 대비 차액·%) + 줄(지난주 리뷰 포함).
"지난주"는 바로 앞 주차(store.prev_week_period)만 — 줄의 지난주 칸이 그 주차 회의록의 같은 연결키 줄이다.
월 누적 목표 = 1주차~이 주차의 주차별 목표 합(목표 표 매출 단위 → 원), 월 누적 실적 = 1일~오늘(지난 주차면 그 끝날).
실적은 _MeetingPerf — 알 수 없는 값은 None + head.unknown 에 이름(0 원·0% 로 보이지 않게)."""
today = today_kst()
week_end = store.week_period(week)[1]
prev_start, _prev_end = store.prev_week_period(week)
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
first = date(year, month, 1)
last = store.month_last_day(year, month)
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
month_target_won = int(round(targets["sales_target"] * mult)) if targets["sales_target"] is not None and mult else None
try:
wt = st.goal_week_targets(start=first, end=last)
except Exception: # noqa: BLE001 — 주차 목표를 못 읽어도 회의록은 열린다
logger.warning("goal week targets unavailable for meeting", exc_info=True)
wt = {}
cum_unit = sum(v for k, v in wt.items() if k <= week.isoformat()) if wt else None
cum_target_won = int(round(cum_unit * mult)) if cum_unit is not None and mult else None
mtd_end = min(last, today, week_end)
mtd = total("mtd", first, mtd_end) if mtd_end >= first else None # 아직 시작 전 달은 비움
gap = mtd - cum_target_won if mtd is not None and cum_target_won is not None else None
rate = round(mtd / cum_target_won * 100, 1) if mtd is not None and cum_target_won else None
pm = meeting.get("prev_meeting") if meeting else None
fresh = perf.freshness()
head = {
"sales_unit": targets["sales_unit"], "sales_target": targets["sales_target"],
"month_target_won": month_target_won, "unit_mult": mult, # 머리 숫자를 목표 표 매출 단위(예: 백만원)로 보여 줄 배수
"week_targets_set": bool(wt), "cum_target": cum_unit, "cum_target_won": cum_target_won,
"mtd": mtd, "mtd_end": mtd_end.isoformat() if mtd_end >= first else "", "gap": gap, "rate": rate,
"prev_exists": bool(pm and pm["week_start"] == prev_start.isoformat()),
# 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:
# 줄마다 지난주 결과 — 늘 직접 입력한 결과(지난주 줄에 저장). 쇼핑몰별 자동 결과·이번주 실적 표시는 2026-10-06 요청으로 폐지.
for it in meeting["items"]:
prev = it.get("prev")
if prev:
prev["result"] = prev.get("result_amount")
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
# 구역 묶음 — 이어진 같은 구역 줄을 한 덩어리로(표의 구역 칸 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
for sec in sections:
covered = 0
_meeting_label_spans(sec["rows"])
for i, it in enumerate(sec["rows"]):
it["content_html"] = store.goal_text_html(it["content"])
it["content_hidden"] = covered > 0
it["content_span"] = min(int(it.get("content_row_span") or 1), len(sec["rows"]) - i)
covered = covered - 1 if covered else it["content_span"] - 1
if it.get("prev"):
it["prev"]["content_html"] = store.goal_text_html(it["prev"]["content"])
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)
body = row["cells"].get(cell["m"], "") if cell else ""
text = store.goal_text_plain(body).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, "text_html": store.goal_text_html(body, include_size=False), "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, content: bool = False) -> HTMLResponse:
"""주간 회의록 — 그 달과 겹치는 주(월~일) 탭, 주마다 회의록 하나. 글 수정은 누구나(완료 전까지), 완료·삭제는 Pro user 이상."""
from app.main import build_erp_nav, render_template # noqa: WPS433
from app.store import has_module, is_admin # noqa: WPS433
user = _page_user(request)
if not isinstance(user, dict):
return user
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.week_period(store.validate_week_start(week))[0] # 예전 월요일 주소도 그 날짜가 든 주차로
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()}" + ("&content=1" if content else ""),
status_code=303)
if sel is None:
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][1])) if enabled else set()
first = date(year, month, 1)
sel_end = store.week_period(sel)[1]
prev_start, prev_end = store.prev_week_period(sel)
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,
**_role_ctx(user),
"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),
"project_asana_icons": list(store.PROJECT_ASANA_ICONS),
"goal_year": year,
"goal_month": month,
"meeting_embedded": content,
"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}
for i, (w, e) in enumerate(weeks)],
# 작은 달력(월요일 시작 줄) — 줄을 누르면 그 줄의 이 달 날짜가 든 주차 회의록(주차는 줄과 꼭 같지 않다)
"cal_weeks": [{"start": p[0].isoformat(), "own": True, "href": f"?week={p[0].isoformat()}",
"title": f"{store.week_number(p[0])}주차 ({p[0].month}/{p[0].day}~{p[1].month}/{p[1].day})",
"has": p[0].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 cal for p in [store.week_period(max(w, first))]],
"week": sel.isoformat(),
"week_n": store.week_number(sel),
"week_end": sel_end.isoformat(),
"prev_week": prev_start.isoformat(),
"prev_week_end": prev_end.isoformat(),
# 주차를 열면 다시 받을 매출 기간(실적 모듈 매출 업데이트) — 지난 주차 시작 ~ 이 주차 끝(오늘까지)
"sync_from": prev_start.isoformat() if prev_start <= today else "",
"sync_to": min(sel_end, 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_user(request)
st = _db_or_503(request)
ws = _goal_call(store.validate_period_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_user(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)
def meeting_board_title(ws: date) -> str:
"""회의록 보드 파일 이름 — 그 주차의 월 + 주차 + 기간. 예: 10월 2주차 (10/5~10/11)."""
a, b = store.week_period(ws)
return f"{a.month}월 {store.week_number(a)}주차 ({a.month}/{a.day}~{b.month}/{b.day})"
@router.post("/api/goals/meetings/{week_start}/board")
def api_open_meeting_board(request: Request, week_start: str) -> JSONResponse:
"""회의록 보드 — 그 주차의 빈 Google 슬라이드(공유 드라이브 MEETING_BOARD_FOLDER_ID)를 찾거나 만들어 주소를 돌려준다.
회의록을 볼 수 있는 사람 누구나(빈 슬라이드 하나라 관리자 전용으로 막지 않음). 같은 주차는 늘 같은 파일."""
from app.integrations.google_slides import GoogleSlidesError, board_folder_id, get_client # noqa: WPS433
_require_user(request)
ws = _goal_call(store.validate_period_start, week_start)
title = meeting_board_title(ws)
try:
board = get_client().open_week_board(folder_id=board_folder_id(), week_key=ws.isoformat(), title=title)
except GoogleSlidesError as exc:
logger.warning("meeting board unavailable: %s", exc) # 사유 문구만(비밀값 없음)
raise HTTPException(status_code=503, detail=str(exc))
return JSONResponse({"ok": True, "url": board["url"], "created": board["created"], "title": title})
@router.post("/api/goals/meetings/{week_start}/complete")
def api_complete_meeting(request: Request, week_start: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
"""회의 완료(수정 잠금) {done: true} · 완료 해제 {done: false} — Pro user 이상(2026-10-12, 마이그레이션 022)."""
user = _require_pro(request)
st = _db_or_503(request)
ws = _goal_call(store.validate_week_start, week_start)
done = payload.get("done", True) is not False
out = _goal_call(st.set_meeting_completed, week_start=ws, done=done, by=user["email"])
return JSONResponse({"ok": True, **out})
@router.delete("/api/goals/meetings/{week_start}")
def api_delete_meeting(request: Request, week_start: str) -> JSONResponse:
_require_pro(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, same_label?} — 기준 줄 위/아래, 없으면 구역 끝(새 구역이면 맨 끝).
same_label = 주요 업무 칸에서 추가 — 기준 줄과 같은 항목 칸 안에(027)."""
user = _require_user(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"],
same_label=bool(payload.get("same_label")),
)
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(숫자 아니면 글 — 021)·result_note(020)·status·marketplace_code.
지난주 결과(글·금액)는 이번 회의 화면에서 지난 주차 줄(prev)에 저장한다."""
user = _require_user(request)
st = _db_or_503(request)
keys = ("label", "content", "target_amount", "result_amount", "result_note", "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_user(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-cells/move")
def api_move_meeting_cell(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
user = _require_user(request)
st = _db_or_503(request)
if not all(k in payload for k in ("source_item", "target_item", "source_body", "target_body")):
raise HTTPException(status_code=400, detail="원본·대상 셀과 예상 내용을 함께 보내 주세요.")
body = _goal_call(st.move_meeting_cell, source_item=payload["source_item"], target_item=payload["target_item"],
source_body=payload["source_body"], target_body=payload["target_body"], updated_by=user["email"])
return JSONResponse({"ok": True, "body": body})
@router.post("/api/goals/meeting-cells/merge")
def api_merge_meeting_cells(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
user = _require_user(request)
result = _goal_call(_db_or_503(request).merge_meeting_cells, item_from=payload.get("item_from"),
item_to=payload.get("item_to"), updated_by=user["email"])
return JSONResponse({"ok": True, **result})
@router.delete("/api/goals/meeting-items/{item_id}/cell-merge")
def api_unmerge_meeting_cell(request: Request, item_id: int) -> JSONResponse:
user = _require_user(request)
_goal_call(_db_or_503(request).unmerge_meeting_cell, item_id=item_id, updated_by=user["email"])
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_user(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})
@router.post("/api/goals/meeting-items/{item_id}/move-to")
def api_move_meeting_group(request: Request, item_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""항목 칸 끌어 옮기기 {before_item_id: 그 묶음 앞 | null = 구역 맨 끝} — 묶인 줄·병합은 통째로, 같은 구역 안만.
줄 순서와 같은 권한(누구나, 회의 완료 전까지)."""
_require_user(request)
st = _db_or_503(request)
before = payload.get("before_item_id")
try:
before = None if before in (None, "") else int(before)
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail="before_item_id 가 올바르지 않습니다.")
moved = _goal_call(st.move_meeting_group, item_id=item_id, before_item_id=before)
return JSONResponse({"ok": True, "moved": bool(moved)})
@router.post("/api/goals/meeting-items/{item_id}/split-label")
def api_split_meeting_label(request: Request, item_id: int) -> JSONResponse:
"""항목 칸 나누기(027) — item_id = 묶음 첫 줄. 이어 붙은 줄들이 각자 항목 칸(이름 빈 칸)으로. 줄 순서와 같은 권한."""
_require_user(request)
n = _goal_call(_db_or_503(request).split_meeting_label, item_id=item_id)
return JSONResponse({"ok": True, "split": n})
# ── 회의록 작업 등록 표(025) — 주차별 한 표를 서버에(예전엔 각자 브라우저에만 있어 다른 사람 줄이 안 보였다) ──
# 보기·고치기: 회의록을 볼 수 있는 사람 누구나(회의 완료면 잠금). 줄에 고른 프로젝트는 내가 멤버인 것만 고를 수 있고,
# 내가 멤버가 아닌 프로젝트를 가리키는 남의 줄은 프로젝트·섹션 이름·만든 작업을 가린다. [적용] = 그 프로젝트 멤버만.
def _quick_view(st: Any, user: dict[str, Any], rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
seen: dict[int, bool] = {}
out = []
for r in rows:
pid = r.get("project_id")
ok = True if pid is None else seen.setdefault(pid, access.can_manage_project(st, user, pid))
r = dict(r, visible=ok, registered=r.get("task_id") is not None) # 등록됨 여부는 누구에게나(작업 내용은 멤버만)
if not ok:
r.update(project_name="(볼 수 없는 프로젝트)", stage_name="", task_title="", task_id=None,
task_project_id=None, parent_task_id=None, parent_task_title="")
out.append(r)
return out
def _quick_fields(st: Any, user: dict[str, Any], payload: dict[str, Any]) -> dict[str, Any]:
fields = {k: payload[k] for k in ("title", "assignee_email", "project_id", "stage_id", "parent_task_id") if k in payload}
pid = fields.get("project_id")
if pid not in (None, ""):
try:
pid = int(pid)
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail="프로젝트 값이 올바르지 않습니다.")
if not access.can_manage_project(st, user, pid):
raise HTTPException(status_code=403, detail="내가 멤버인 프로젝트만 고를 수 있습니다.")
return fields
@router.get("/api/goals/meetings/{week_start}/quick-tasks")
def api_list_quick_tasks(request: Request, week_start: str) -> JSONResponse:
user = _require_user(request)
st = _db_or_503(request)
ws = _goal_call(store.validate_week_start, week_start)
rows = _goal_call(st.list_meeting_tasks, week_start=ws)
return JSONResponse({"tasks": _quick_view(st, user, rows)})
@router.post("/api/goals/meetings/{week_start}/quick-tasks")
def api_add_quick_task(request: Request, week_start: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
"""줄 추가 {title?, assignee_email?, project_id?, stage_id?, parent_task_id?(작업 칸 — 그 작업의 세부 작업으로),
task_id?(예전 브라우저 표의 등록된 줄)}."""
user = _require_user(request)
st = _db_or_503(request)
ws = _goal_call(store.validate_week_start, week_start)
fields = _quick_fields(st, user, payload)
task_id = None
if payload.get("task_id") not in (None, ""):
# 옮겨 오는 등록된 줄 — 그 작업을 지금 내가 원 소속으로 다룰 수 있을 때만 이어 붙인다(남의 작업 id 를 끌어오지 못하게)
try:
t = st.get_task(task_id=int(payload["task_id"]))
except (TypeError, ValueError):
t = None
if t is not None and access.task_access(st, user, t) == access.FULL:
task_id = int(t["id"])
row = _goal_call(st.add_meeting_task, week_start=ws, fields=fields, by=user["email"], task_id=task_id)
return JSONResponse({"task": _quick_view(st, user, [row])[0]}, status_code=201)
@router.put("/api/goals/meeting-quick-tasks/{item_id}")
def api_update_quick_task(request: Request, item_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
user = _require_user(request)
st = _db_or_503(request)
fields = _quick_fields(st, user, payload)
row = _goal_call(st.update_meeting_task, item_id=item_id, fields=fields, by=user["email"])
return JSONResponse({"task": _quick_view(st, user, [row])[0]})
@router.delete("/api/goals/meeting-quick-tasks/{item_id}")
def api_delete_quick_task(request: Request, item_id: int) -> JSONResponse:
"""줄 지우기. 이미 만든 작업은 화면이 따로 지운다(DELETE /api/tasks/{id} — 그 프로젝트 멤버만, 휴지통)."""
_require_user(request)
st = _db_or_503(request)
_goal_call(st.delete_meeting_task, item_id=item_id)
return JSONResponse({"ok": True})
@router.post("/api/goals/meeting-quick-tasks/{item_id}/apply")
def api_apply_quick_task(request: Request, item_id: int, bg: BackgroundTasks) -> JSONResponse:
"""[적용] — 그 줄로 프로젝트에 작업을 만든다(작업 창과 같은 권한·알림). 줄을 잠그고 한 번만 — 이미 만들었으면 그 결과.
순서(2026-10-15 검토 F02): ① 잠그기 전에 줄을 읽어 권한·담당자·협업자를 확인(DB 잠금 없이) ② DB 한 트랜잭션에서
줄 잠금 → 이미 만들었으면 그대로 / 줄이 그사이 바뀌었으면 409 → 업무 INSERT → 줄에 task_id(같은 연결 — 실패하면 둘 다
롤백, 재시도·동시 클릭에도 업무 하나) ③ 커밋된 뒤에만 협업자·알림·메일."""
user = _require_user(request)
st = _db_or_503(request)
snap = _goal_call(st.get_meeting_task, item_id=item_id)
if snap is None:
raise HTTPException(status_code=404, detail="업무 등록 줄을 찾을 수 없습니다.")
project = followers = fields = None
if snap["task_id"] is None:
if not (snap["title"] or "").strip():
raise HTTPException(status_code=400, detail="업무 제목을 쓰세요.")
if snap["project_id"] is None:
raise HTTPException(status_code=400, detail="프로젝트를 고르세요.")
parent_task_id = snap.get("parent_task_id")
rec = access.default_user_lookup(snap["assignee_email"]) if snap["assignee_email"] else None
# 작업 칸을 골랐으면 그 작업의 세부 작업(섹션 없음) — 확인은 작업 창과 같이 프로젝트 멤버, 같은 프로젝트는 DB 가 잠근 뒤
payload = {"title": snap["title"].strip(), "stage_id": None if parent_task_id else snap["stage_id"],
"assignee_email": snap["assignee_email"],
"assignee_name": (rec or {}).get("name") or (snap["assignee_email"].split("@")[0] if snap["assignee_email"] else ""),
"parent_task_id": parent_task_id}
pid = int(snap["project_id"])
project, followers = _task_create_checks(request, st, user, pid, payload)
fields = _task_create_fields(user, pid, payload)
row, made, task = _goal_call(st.apply_meeting_task, item_id=item_id, task_fields=fields, expect=snap)
if made and task is not None:
_task_created_effects(request, st, user, project, task, followers or [], bg) # 커밋 뒤에만
return JSONResponse({"task": _quick_view(st, user, [row])[0], "created": made}, status_code=201 if made else 200)
@router.post("/api/goals/meeting-items/{item_id}/move-section")
def api_move_meeting_section(request: Request, item_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""구역(첫 열 "구분") 통째로 위/아래 {direction: -1|1} — item_id = 그 구역의 아무 줄. 줄 순서와 같은 권한(누구나,
회의 완료 전까지). 다음 회의록은 이 순서를 이어받는다."""
_require_user(request)
st = _db_or_503(request)
try:
direction = int(payload.get("direction") or 0)
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail="direction 이 올바르지 않습니다.")
if direction not in (-1, 1):
raise HTTPException(status_code=400, detail="direction 은 -1(위) 또는 1(아래)입니다.")
_goal_call(st.move_meeting_section, item_id=item_id, direction=direction)
return JSONResponse({"ok": True})