fix(project): review fixes — access leaks, open paths, save safety, concurrency

- Subproject tasks via parent /tasks are re-filtered by current access (FULL/READ kept)
- PUT /api/projects/order: every id must be manageable; bad/duplicate ids -> 400, all-or-nothing
- Inbox, web alert popup, PC notifier open tasks via /project/t/{id}; embed=1 survives redirect;
  old /p/{home}?task= redirects READ users to the linked project
- Project page / snapshot / workload include the opened archived or sub project only
- Alerts: DB-side filters + oldest-first paging (no 50-row cut); badges counted without caps;
  my tasks keep every open task (completed capped)
- Meeting results: next-week meeting open, or own meeting open when no next meeting;
  header edits + result checks under row locks (FOR UPDATE / FOR SHARE)
- Inbox panel waits for the task window save (same retry/discard flow) before switching/closing;
  read failures stay unread
- Attachment upload removes only its own file on DB failure
- New project modal: create once, retry only failed member assignments
- update_task / update_project: locked-row validation in one transaction; completion hints from real transition
- Creator added as explicit member when another owner is chosen
- _once lock lifetime managed by refcount (no leak on failure)
- Section default assignee must still be a registered project user; follower add uses can_assign
- Docs (PROJECT_MODULE 6-15, help), tests (DB-less, real PostgreSQL, jsdom, Chrome)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-12 11:08:56 +09:00
parent c07a3466a0
commit 89ad338024
29 changed files with 1849 additions and 378 deletions
+226 -102
View File
@@ -156,15 +156,15 @@ def _require_task(
def _my_visible_tasks(st: Any, user: dict[str, Any]) -> list[dict[str, Any]]:
"""내가 담당인 작업 중 지금 볼 수 있는 것만 — 권한을 잃은 프로젝트의 작업은 빠진다."""
return access.filter_visible_tasks(
st, user, st.list_my_tasks(assignee_email=user["email"], limit=1000)
)
"""내가 담당인 작업 중 지금 볼 수 있는 것만 — 권한을 잃은 프로젝트의 작업은 빠진다.
미완료는 전부, 완료는 최근 완료 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 와 같은 기준."""
return sum(1 for t in _my_visible_tasks(st, user) if not t.get("completed_at"))
"""사이드바 "내 작업" 배지 — 지금 볼 수 있는 미완료 담당 작업 수(_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:
@@ -729,23 +729,34 @@ def task_permalink(request: Request, task_id: int):
task = st.get_task(task_id=task_id)
if task is None:
return _denied("작업을 찾을 수 없습니다. 삭제되었을 수 있습니다.", 404)
level = access.task_access(st, user, task)
if level is None:
target = _task_open_project(st, user, task)
if target is None:
return _denied(
"이 작업이 속한 프로젝트의 멤버만 볼 수 있습니다. "
"프로젝트 관리자에게 멤버 배정을 요청하세요.",
403,
)
target = task["project_id"]
if level != access.FULL:
# 연결된 프로젝트에서만 볼 수 있는 작업 — 그 프로젝트 화면에서 읽기 전용으로 연다.
target = next((pid for pid in sorted(access.link_scope(st, [task_id]).get(task_id, set()))
if _can_manage(request, st, user, pid)), None)
if target is None:
return _denied("이 작업을 볼 권한이 없습니다.", 403)
# 세부 업무도 업무처럼 자기 팝업으로 연다(아사나식 — 제목 위에 상위 업무 경로).
return RedirectResponse(url=f"/project/p/{target}?task={task_id}", status_code=303)
# 수신함 오른쪽 작업 창(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)
@@ -767,6 +778,12 @@ def project_page(request: Request, project_id: int) -> HTMLResponse:
# 링크(/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",
@@ -779,13 +796,8 @@ def project_page(request: Request, project_id: int) -> HTMLResponse:
},
status_code=403,
)
all_projects = st.list_projects(
include_archived=False,
member_email=None if access.sees_all_projects(user) else user["email"],
)
members = st.list_members(project_id=project_id)
top_projects = [p for p in all_projects if not p.get("parent_id")] # 과거 서브프로젝트 제외
top_ids = [p["id"] for p in top_projects]
top_projects, top_ids = _view_scope(st, user, project)
# 좌측 트리 + 전체 집계: 4개 뷰(달력/타임라인/보드/리스트)는 '전체 프로젝트'를 보여준다.
# all_tasks : 접근 가능한 모든 프로젝트의 업무(뷰 데이터)
@@ -806,20 +818,12 @@ def project_page(request: Request, project_id: int) -> HTMLResponse:
tasks_by_ctx.setdefault(t["context_project_id"], []).append(t)
nav_projects: list[dict[str, Any]] = []
projects_meta: 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"], [])
projects_meta.append({
"id": p["id"],
"name": p["name"],
"color": p.get("color") or "#4573d2",
"icon": p.get("icon") or "",
"start_date": p.get("start_date"),
"due_date": p.get("due_date"),
"created_by": p.get("created_by") or "",
"description": p.get("description") or "",
"status": p.get("status") or "active",
})
nav_projects.append({
"id": p["id"],
"name": p["name"],
@@ -917,6 +921,28 @@ def project_page(request: Request, project_id: int) -> HTMLResponse:
# ────────────────────────────────────────────────────────────
# 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:
@@ -952,6 +978,13 @@ def _owner_for_create(user: dict[str, Any], payload: dict[str, Any]) -> str:
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}):
@@ -966,17 +999,19 @@ def api_create_project(
"""최상위 프로젝트 생성 — 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_for_create(user, payload),
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))
@@ -993,16 +1028,18 @@ def api_create_subproject(
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_for_create(user, payload),
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))
@@ -1023,13 +1060,39 @@ def api_reorder_projects(
"order" 가 project_id 로 매칭 시도되어(정수 변환 실패로 422) 이 라우트가
영영 실행되지 않는다(경로 매칭은 등록 순서, path param 특이도 무관).
"""
_require_pro(request)
user = _require_pro(request)
st = _db_or_503(request)
ids = payload.get("ordered_ids") or []
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 가 필요합니다.")
st.reorder_projects(ordered_ids=[int(i) for i in ids])
return JSONResponse({"ok": True})
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}")
@@ -1156,10 +1219,8 @@ def api_user_tasks(
tasks = st.list_tasks(project_id=project_id, assignee_email=email, limit=500)
else:
tasks = st.list_tasks(assignee_email=email, limit=500)
# 전체 대상이면 내가 볼 수 있는 프로젝트의 업무만 남긴다(비관리자).
allowed = _accessible_project_ids(st, user)
if allowed is not None:
tasks = [t for t in tasks if t["project_id"] in allowed]
# 전체 대상이면 내가 지금 볼 수 있는 업무만(원 소속 멤버 또는 연결된 프로젝트의 읽기 — 프로젝트 화면과 같은 기준).
tasks = access.filter_visible_tasks(st, user, tasks)
return JSONResponse({"tasks": tasks})
@@ -1253,11 +1314,19 @@ def _stage_default_assignee_arg(st: Any, project_id: int, payload: dict[str, Any
allowed = {m["user_email"] for m in st.list_members(project_id=project_id)}
project = st.get_project(project_id=project_id) or {}
allowed.add(store.norm_str(project.get("owner_email") or "", lower=True))
if email not in allowed:
# 담당자 지정(_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 로
하므로, 이걸 안 보면 아무 프로젝트 멤버나 남의 세션을 고칠 수 있다."""
@@ -1295,7 +1364,9 @@ def api_list_tasks(request: Request, project_id: int) -> JSONResponse:
st = _db_or_503(request)
_require_manage(request, st, user, project_id)
tasks = st.list_tasks(project_id=project_id, include_subprojects=True, limit=2000)
return JSONResponse({"tasks": tasks})
# 서브프로젝트는 프로젝트마다 멤버가 따로다 — 부모를 볼 수 있다고 자식 작업이 보이면 안 된다.
# 각 작업을 지금 권한(원 소속 멤버 또는 연결된 프로젝트의 읽기)으로 다시 거른다.
return JSONResponse({"tasks": access.filter_visible_tasks(st, user, tasks)})
@router.get("/api/projects/{project_id}/snapshot")
@@ -1317,18 +1388,18 @@ def api_project_snapshot(request: Request, project_id: int, scope: str = "projec
"stages": st.list_stages(project_id=project_id),
"members": st.list_members(project_id=project_id),
})
allowed = _accessible_project_ids(st, user)
top = [
p for p in st.list_projects(include_archived=False,
member_email=None if allowed is None else user["email"])
if not p.get("parent_id")
]
ids = [p["id"] for p in top]
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": st.get_project(project_id=project_id),
"projects": [_project_meta(p) for p in top],
"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),
@@ -1345,10 +1416,10 @@ def api_subtasks_summary(request: Request, project_id: int, scope: str = "projec
st = _db_or_503(request)
_require_manage(request, st, user, project_id)
if scope == "all":
allowed = _accessible_project_ids(st, user)
ids = [p["id"] for p in st.list_projects(include_archived=False,
member_email=None if allowed is None else user["email"])
if not p.get("parent_id")]
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)]
@@ -1414,6 +1485,7 @@ def api_create_task(
due_time=payload.get("due_time"),
created_by=user["email"],
parent_task_id=payload.get("parent_task_id"),
assignee_allowed=_registered_project_user,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
@@ -1486,7 +1558,8 @@ def api_update_task(
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"])
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:
@@ -1655,22 +1728,15 @@ def api_list_followers(request: Request, task_id: int) -> JSONResponse:
def api_add_follower(
request: Request, task_id: int, payload: dict[str, Any] = Body(default={})
) -> JSONResponse:
"""팔로워 추가. email 을 안 주면 나 자신(팔로우). 다른 사람은 그 프로젝트를
볼 수 있는 사람(멤버·owner·관리자)만 추가할 수 있다 — 못 보는 업무의 알림이
가면 안 되므로."""
from app.main import user_store # noqa: WPS433
from app.store import is_admin # noqa: WPS433
"""팔로워 추가. 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 != store.norm_str(user["email"], lower=True):
target = user_store.get(email)
allowed = (target is not None and is_admin(target)) or st.is_member(
project_id=task["project_id"], user_email=email
)
if not allowed:
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])
@@ -1904,10 +1970,16 @@ def _after_comment(
# 같은 댓글이 두 번 등록되지 않게(더블클릭·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]]] = {}
_once_key_locks: dict[tuple[str, int, str], threading.Lock] = {}
# 키별 잠금 [잠금, 쓰는 요청 수]. 쓰는 요청이 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]:
@@ -1918,17 +1990,25 @@ def _once(user: dict[str, Any], task_id: int, token: str, fn: Any) -> dict[str,
with _once_lock:
for k in [k for k, (t, _) in _once_results.items() if now - t > _ONCE_TTL_SEC]:
_once_results.pop(k, None)
_once_key_locks.pop(k, None)
klock = _once_key_locks.setdefault(key, threading.Lock())
with klock: # 같은 토큰의 동시 요청은 첫 요청이 끝날 때까지 기다렸다가 그 결과를 받는다
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:
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
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
@@ -2142,14 +2222,21 @@ def api_upload_attachment(
orig = (file.filename or "file").replace("\\", "_").replace("/", "_").strip()
suffix = Path(orig).suffix[:16]
stored = f"{uuid.uuid4().hex}{suffix}"
dest = _attach_dir(request, task_id) / stored
dest = _attach_dir(request, task_id) / stored # 요청마다 새 uuid 이름 — 기존 파일을 덮지 않는다
dest.write_bytes(data)
att = st.add_attachment(
task_id=task_id, filename=orig, stored_name=stored,
content_type=file.content_type or "application/octet-stream",
size_bytes=len(data), uploaded_by=user["email"], comment_id=comment_id,
)
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)
@@ -2317,14 +2404,44 @@ def _alerts_payload(st: Any, user: dict[str, Any], after: int) -> dict[str, Any]
out: dict[str, Any] = {"me": store.norm_str(user["email"], lower=True), "latest_id": latest, "alerts": []}
if after < 0:
return out
rows = [n for n in st.list_notifications(recipient_email=user["email"], unread_only=True, limit=50)
if n.get("type") in ("mention", "assigned") and int(n["id"]) > after]
rows = sorted(_visible_notifications(st, user, rows), key=lambda n: int(n["id"]))[:10]
# 수신자·읽지 않음·종류·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회.
@@ -2520,8 +2637,13 @@ def _safe_mentions(st: Any, user: dict[str, Any], *, limit: int = 100) -> list[d
def _safe_mention_unread(st: Any, user: dict[str, Any]) -> int:
"""수신함 배지 — 지금 볼 수 있는 작업의 미확인 태그 수(_safe_mentions 와 같은 기준)."""
return sum(int(t.get("unread_mentions") or 0) for t in _safe_mentions(st, user, limit=1000))
"""수신함 배지 — 지금 볼 수 있는 작업의 미확인 태그 수(_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]]:
@@ -2544,8 +2666,8 @@ def _visible_notifications(st: Any, user: dict[str, Any], items: list[dict[str,
def _notification_unread(st: Any, user: dict[str, Any]) -> int:
rows = st.list_notifications(recipient_email=user["email"], unread_only=True, limit=500)
return len(_visible_notifications(st, user, rows))
"""읽지 않은 알림 수 — 지금 볼 수 있는 것만, 개수 제한 없이(예전엔 최근 500건만 세었다)."""
return len(_visible_notifications(st, user, st.list_unread_refs(recipient_email=user["email"])))
@router.get("/api/mentions")
@@ -2576,12 +2698,14 @@ def api_mentions_read(
st = _db_or_503(request)
task_id = payload.get("task_id")
try:
n = st.mark_mentions_read(
mentioned_email=user["email"],
task_id=int(task_id) if task_id else None,
)
except Exception: # noqa: BLE001
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})