feat(project): 검색·필터·정렬 + 팔로워 + 마감 알림

검색·필터·정렬
- 좌측 사이드바 전체 검색(/api/search): 제목·설명·댓글, 볼 수 있는
  프로젝트의 업무(하위 업무 포함). 설명 HTML 태그에만 걸린 결과는 본문
  텍스트로 재확인해 제거. 어디서 걸렸는지 + 미리보기, 키보드(/ ↑↓ Enter).
- 프로젝트 화면 필터 바: 찾기·상태·담당자·마감·우선순위·정렬. visibleTasks()
  에서 걸러 보드/리스트/달력/타임라인/대시보드 모두 적용, 프로젝트별 기억.
  필터·정렬 중엔 보드 카드 순서 드래그 차단.
- 내 업무 화면에도 찾기·마감·우선순위 필터.

팔로워 · 알림
- task_followers(008): 만든 사람·담당자·댓글 작성자·@태그된 사람 자동 팔로우,
  기존 업무 백필. 업무 팝업에서 추가/빼기/내 팔로우 토글.
- 완료·댓글 인앱 알림 수신자: 프로젝트 멤버 전원 → 담당자 + 팔로워.
  008 미적용이면 예전 방식 폴백.
- 마감 알림(reminders.py, lifespan 에서 데몬 스레드): 영업일(주말·공휴일
  skip) 09시 KST 1회, 다음 영업일까지 마감/오늘 마감/지남(7일 이내).
  수신자 담당자(없으면 팔로워). task_reminders UNIQUE 로 중복 방지, 마감일
  바뀌면 재알림. PROJECT_REMINDER_EMAIL=true 면 요약 메일.
- 008: pg_trgm GIN 인덱스(제목·설명·댓글), 미완료 마감일 부분 인덱스.

버그
- 업무 팝업 담당자 선택지가 프로젝트 멤버뿐이라, 멤버 목록에 없는 담당자
  (프로젝트 owner, 멤버에서 빠진 사람)의 업무를 열고 저장하면 담당자가
  지워지던 문제 수정.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-23 13:28:19 +09:00
parent b74f92523d
commit 78b6e8df11
16 changed files with 1141 additions and 24 deletions
+146 -1
View File
@@ -177,13 +177,33 @@ def _notify(
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]:
"""업무 관련 인앱 알림 수신자 = 담당자 + 프로젝트 owner + 멤버 (행위자 제외)."""
"""업무 관련 인앱 알림 수신자 (행위자 제외).
= 담당자 + 팔로워(아사나의 협업자). 예전엔 프로젝트 멤버 전원에게 갔는데
알림이 너무 많아 정작 중요한 게 묻혔다. 팔로워 표(008)가 없으면 예전처럼
담당자 + owner + 멤버 전원.
"""
emails: set[str] = set()
if task.get("assignee_email"):
emails.add(store.norm_str(task["assignee_email"], lower=True))
try:
emails.update(st.list_followers(task_id=task["id"]))
emails.discard(store.norm_str(exclude, lower=True))
return [e for e in emails if e]
except Exception: # noqa: BLE001 - 008 미적용 → 예전 방식
pass
if project.get("owner_email"):
emails.add(store.norm_str(project["owner_email"], lower=True))
try:
@@ -232,6 +252,7 @@ def _record_mentions(
return
if not added:
return
_follow(st, task["id"], added) # 태그된 사람은 이후 소식도 받도록 팔로워로
where = "댓글" if source == "comment" else "설명"
_inbox(
st, recipients=added, actor=actor,
@@ -1090,6 +1111,8 @@ def api_create_task(
raise HTTPException(status_code=400, detail=str(exc))
except KeyError as exc:
raise HTTPException(status_code=404, detail=str(exc))
# 만든 사람·담당자는 자동 팔로워(아사나와 같은 규칙)
_follow(st, task["id"], [user["email"], task.get("assignee_email") or ""])
# 생성과 동시에 담당자 지정 시 관리자 메일 + 담당자 인앱 알림
if task.get("assignee_email"):
_notify(
@@ -1147,6 +1170,7 @@ def api_update_task(
project_name = task.get("project_name") or ""
project = st.get_project(project_id=existing["project_id"]) or {"id": existing["project_id"], "name": project_name}
if task.get("_newly_assigned"):
_follow(st, task_id, [task["_newly_assigned"]])
_notify(
bg, request,
subject=store.build_subject_assigned(
@@ -1224,9 +1248,129 @@ def api_get_task(request: Request, task_id: int) -> JSONResponse:
_require_manage(request, st, user, task["project_id"])
task["subtasks"] = st.list_tasks(parent_task_id=task_id)
task["links"] = st.list_task_links(task_id=task_id)
try:
task["followers"] = st.list_followers(task_id=task_id)
except Exception: # noqa: BLE001 - 008 미적용이면 팔로워 UI 를 숨긴다
task["followers"] = None
return JSONResponse({"task": task})
# ────────────────────────────────────────────────────────────
# JSON API — 팔로워 (아사나의 협업자)
# ────────────────────────────────────────────────────────────
def _task_for_followers(request: Request, st: Any, user: dict[str, Any], task_id: int) -> dict[str, Any]:
task = st.get_task(task_id=task_id)
if task is None:
raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.")
_require_manage(request, st, user, task["project_id"])
return task
def _followers_response(st: Any, task_id: int) -> JSONResponse:
try:
return JSONResponse({"followers": st.list_followers(task_id=task_id)})
except Exception: # noqa: BLE001
raise HTTPException(status_code=503, detail="팔로워 기능은 project_db_008 마이그레이션 후 사용할 수 있습니다.")
@router.get("/api/tasks/{task_id}/followers")
def api_list_followers(request: Request, task_id: int) -> JSONResponse:
user = _require_user(request)
st = _db_or_503(request)
_task_for_followers(request, st, user, task_id)
return _followers_response(st, task_id)
@router.post("/api/tasks/{task_id}/followers")
def api_add_follower(
request: Request, task_id: int, payload: dict[str, Any] = Body(default={})
) -> JSONResponse:
"""팔로워 추가. email 을 안 주면 나 자신(팔로우). 다른 사람은 그 프로젝트를
볼 수 있는 사람(멤버·owner·관리자)만 추가할 수 있다 — 못 보는 업무의 알림이
가면 안 되므로."""
from app.main import user_store # noqa: WPS433
from app.store import is_admin # noqa: WPS433
user = _require_user(request)
st = _db_or_503(request)
task = _task_for_followers(request, st, user, task_id)
email = store.norm_str(payload.get("email") or user["email"], lower=True)
if email != store.norm_str(user["email"], lower=True):
target = user_store.get(email)
allowed = (target is not None and is_admin(target)) or st.is_member(
project_id=task["project_id"], user_email=email
)
if not allowed:
raise HTTPException(status_code=400, detail="이 프로젝트 멤버만 팔로워로 추가할 수 있습니다.")
try:
st.add_followers(task_id=task_id, emails=[email])
except Exception: # noqa: BLE001
raise HTTPException(status_code=503, detail="팔로워 기능은 project_db_008 마이그레이션 후 사용할 수 있습니다.")
return _followers_response(st, task_id)
@router.delete("/api/tasks/{task_id}/followers/{email}")
def api_remove_follower(request: Request, task_id: int, email: str) -> JSONResponse:
user = _require_user(request)
st = _db_or_503(request)
_task_for_followers(request, st, user, task_id)
try:
st.remove_follower(task_id=task_id, user_email=email)
except Exception: # noqa: BLE001
raise HTTPException(status_code=503, detail="팔로워 기능은 project_db_008 마이그레이션 후 사용할 수 있습니다.")
return _followers_response(st, task_id)
# ────────────────────────────────────────────────────────────
# JSON API — 전체 검색 (좌측 사이드바 검색창)
# ────────────────────────────────────────────────────────────
@router.get("/api/search")
def api_search(request: Request, q: str = "", limit: int = 20) -> JSONResponse:
"""제목·설명·댓글 검색 — 내가 볼 수 있는 프로젝트의 업무(하위 업무 포함).
설명은 HTML 이라 DB 에서는 넉넉히 가져온 뒤 본문 텍스트에 실제로 검색어가
있는지 다시 확인한다(태그 이름·속성에만 걸린 결과 제거). 결과마다 어디서
걸렸는지(match: title/description/comment)와 미리보기(snippet)를 붙인다.
"""
user = _require_user(request)
st = _db_or_503(request)
query = store.norm_str(q)[:100]
if len(query) < 2:
return JSONResponse({"results": [], "query": query})
limit = max(1, min(int(limit), 50))
rows = st.search_tasks(
query=query, project_ids=_accessible_project_ids(st, user), limit=limit * 3,
)
ql = query.lower()
out: list[dict[str, Any]] = []
for r in rows:
desc_text = store.html_to_text(r.get("description") or "")
if r.get("hit_title"):
match, snippet = "title", store.search_snippet(desc_text, query) if ql in desc_text.lower() else ""
elif ql in desc_text.lower():
match, snippet = "description", store.search_snippet(desc_text, query)
elif r.get("comment_hit"):
match, snippet = "comment", store.search_snippet(r["comment_hit"], query)
else:
continue # 설명 HTML 태그에만 걸린 경우
out.append({
"id": r["id"],
"title": r["title"],
"project_id": r["project_id"],
"project_name": r.get("project_name") or "",
"project_color": r.get("project_color") or "#4573d2",
"parent_title": r.get("parent_title") or "",
"completed": bool(r.get("completed_at")),
"due_date": r.get("due_date"),
"assignee_email": r.get("assignee_email") or "",
"match": match,
"snippet": snippet,
})
if len(out) >= limit:
break
return JSONResponse({"results": out, "query": query})
# ────────────────────────────────────────────────────────────
# JSON API — 업무 멀티호밍 (다른 프로젝트/세션에 연결)
# ────────────────────────────────────────────────────────────
@@ -1328,6 +1472,7 @@ def api_add_comment(
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
_follow(st, task_id, [user["email"]]) # 댓글 단 사람은 이후 소식도 받는다
project = st.get_project(project_id=task["project_id"]) or {"id": task["project_id"], "name": task.get("project_name", "")}
_inbox(
st, recipients=_task_recipients(st, project, task, exclude=user["email"]),