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
+4 -2
View File
@@ -10,8 +10,10 @@
build_project_store 는 None 을 반환하고, 라우터가 "설정 필요" 안내 페이지를
보여준다(앱은 죽지 않음).
권한: 로그인한 회사(dbxcorp.co.kr) 직원은 모듈 진입 가능. 프로젝트 생성/삭제·
사용자 배정은 ERP 관리자(is_admin)만. 배정된 멤버는 서브프로젝트/업무/단계 관리.
권한: 권한키 `project` 보유자는 모듈 진입·프로젝트 생성 가능. 삭제는 만든 사람만,
사용자 배정은 ERP 관리자(is_admin)만. 배정된 멤버(또는 owner/관리자)만 그 프로젝트를
조회하고 서브프로젝트/업무/단계를 관리한다.
마감 알림 스레드: `reminders.py` (app.main 의 startup 에서 시작).
"""
from typing import Any
+121
View File
@@ -1155,6 +1155,127 @@ class ProjectStore:
)
return cur.rowcount or 0
# ════════════════════════════════════════════════════════════
# 팔로워(task_followers, 마이그레이션 008) — 아사나의 "협업자".
# 업무 알림(완료·댓글)은 담당자 + 팔로워에게만 간다. 008 미적용이면
# psycopg_errors.UndefinedTable 이 나고, 라우터가 예전 동작으로 폴백한다.
# ════════════════════════════════════════════════════════════
def list_followers(self, *, task_id: int) -> list[str]:
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT user_email FROM task_followers WHERE task_id = %s "
"ORDER BY created_at ASC, user_email ASC",
(task_id,),
).fetchall()
return [r["user_email"] for r in rows]
def add_followers(self, *, task_id: int, emails: list[str]) -> list[str]:
"""팔로워 추가(이미 있으면 무시). 새로 추가된 이메일만 돌려준다."""
targets = store.normalize_emails(emails)
if not targets:
return []
with self._pool.connection() as conn:
rows = conn.execute(
"INSERT INTO task_followers (task_id, user_email) "
"SELECT %s, e FROM unnest(%s::text[]) AS e "
"ON CONFLICT DO NOTHING RETURNING user_email",
(task_id, targets),
).fetchall()
return [r["user_email"] for r in rows]
def remove_follower(self, *, task_id: int, user_email: str) -> None:
with self._pool.connection() as conn:
conn.execute(
"DELETE FROM task_followers WHERE task_id = %s AND user_email = %s",
(task_id, store.norm_str(user_email, lower=True)),
)
# ════════════════════════════════════════════════════════════
# 전체 검색 — 제목·설명·댓글 (008 의 pg_trgm 인덱스가 있으면 그걸 탄다)
# ════════════════════════════════════════════════════════════
def search_tasks(
self, *, query: str, project_ids: set[int] | None, limit: int = 30,
) -> list[dict[str, Any]]:
"""제목/설명/댓글에 검색어가 들어간 업무(하위 업무 포함).
project_ids 가 None 이면 전체(관리자), 아니면 그 프로젝트들만.
설명은 HTML 이라 태그 이름·속성에만 걸린 경우(예: "img")를 걸러내려고
넉넉히 가져온 뒤 라우터가 본문 텍스트로 다시 확인한다.
"""
q = store.norm_str(query)
if not q:
return []
if project_ids is not None and not project_ids:
return []
pat = "%" + q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
params: dict[str, Any] = {"pat": pat, "limit": int(limit)}
scope = ""
if project_ids is not None:
scope = "AND t.project_id = ANY(%(ids)s)"
params["ids"] = sorted(project_ids)
with self._pool.connection() as conn:
rows = conn.execute(
f"""
SELECT t.id, t.title, t.description, t.project_id, t.parent_task_id,
t.completed_at, t.due_date, t.assignee_email,
p.name AS project_name, p.color AS project_color,
pt.title AS parent_title,
(t.title ILIKE %(pat)s) AS hit_title,
(SELECT c.body FROM task_comments c
WHERE c.task_id = t.id AND c.body ILIKE %(pat)s
ORDER BY c.created_at DESC LIMIT 1) AS comment_hit
FROM tasks t
JOIN projects p ON p.id = t.project_id
LEFT JOIN tasks pt ON pt.id = t.parent_task_id
WHERE (t.title ILIKE %(pat)s
OR t.description ILIKE %(pat)s
OR t.id IN (SELECT c.task_id FROM task_comments c WHERE c.body ILIKE %(pat)s))
{scope}
ORDER BY (t.title ILIKE %(pat)s) DESC, (t.completed_at IS NULL) DESC,
t.updated_at DESC, t.id DESC
LIMIT %(limit)s
""",
params,
).fetchall()
return [self._serialize(r) for r in rows]
# ════════════════════════════════════════════════════════════
# 마감 알림 (task_reminders, 마이그레이션 008) — reminders.py 가 부른다
# ════════════════════════════════════════════════════════════
def list_open_tasks_due_between(self, *, start: date, end: date) -> list[dict[str, Any]]:
"""미완료 + 마감일이 [start, end] 인 업무(하위 업무 포함) + 팔로워 목록.
보관(archived) 프로젝트는 뺀다."""
with self._pool.connection() as conn:
rows = conn.execute(
"""
SELECT t.id, t.title, t.due_date, t.assignee_email, t.project_id,
t.parent_task_id, p.name AS project_name,
COALESCE((SELECT array_agg(f.user_email ORDER BY f.user_email)
FROM task_followers f WHERE f.task_id = t.id),
'{}'::text[]) AS followers
FROM tasks t
JOIN projects p ON p.id = t.project_id
WHERE t.completed_at IS NULL
AND t.due_date BETWEEN %s AND %s
AND p.status <> 'archived'
ORDER BY t.due_date ASC, t.id ASC
""",
(start, end),
).fetchall()
return [self._serialize(r) for r in rows]
def record_reminder(
self, *, task_id: int, kind: str, due_date: str, recipient_email: str,
) -> bool:
"""이 알림을 처음 보내는 거면 기록하고 True. 이미 보냈으면 False(중복 방지)."""
with self._pool.connection() as conn:
row = conn.execute(
"INSERT INTO task_reminders (task_id, kind, due_date, recipient_email) "
"VALUES (%s,%s,%s,%s) ON CONFLICT DO NOTHING RETURNING id",
(task_id, kind, due_date, store.norm_str(recipient_email, lower=True)),
).fetchone()
return row is not None
# ════════════════════════════════════════════════════════════
# 실시간 새로고침 — 프로젝트/업무/댓글/멤버/단계 중 가장 최근 변경 시각
# ════════════════════════════════════════════════════════════
+183
View File
@@ -0,0 +1,183 @@
"""프로젝트 업무 마감 알림 — 아사나의 "마감일 임박/지남" 알림.
매일 한 번(기본 09시 KST, 영업일만) 미완료 업무를 훑어 수신함 알림을 만든다.
· due_soon — 다음 영업일까지 마감(금요일이면 토·일·월 마감분까지)
· due_today — 오늘 마감
· overdue — 마감이 지남(최근 7일 이내 마감분만 — 첫 적용 때 오래된 업무가
한꺼번에 쏟아지지 않게, 연휴로 며칠 건너뛰어도 놓치지 않게)
수신자는 담당자. 담당자가 없으면 팔로워 전원.
중복 방지: task_reminders(업무, 종류, 마감일, 수신자) UNIQUE — 같은 알림은 한 번만
간다(재기동·여러 번 실행해도 안전). 마감일을 바꾸면 새 마감일 기준으로 다시 알린다.
실행 방식: 웹 프로세스 안의 데몬 스레드(start_reminder_thread). 5분마다 깨어나
"오늘 아직 안 돌았고, 설정 시각이 지났고, 영업일이면" 한 번 돈다. 여러 프로세스가
동시에 돌아도 위 UNIQUE 덕분에 중복 알림이 없다.
환경변수:
PROJECT_REMINDERS false 면 끈다(기본 켜짐)
PROJECT_REMINDER_HOUR 실행 시각(KST 0~23, 기본 9)
PROJECT_REMINDER_EMAIL true 면 수신자에게 메일도 보낸다(사람별 1통 요약, 기본 끔).
SMTP_* 설정이 있어야 실제로 나간다.
PUBLIC_BASE_URL 메일 속 업무 링크의 앞부분(예: https://erp.dbxcorp.co.kr)
"""
from __future__ import annotations
import logging
import os
import threading
import time
from datetime import date, timedelta
from typing import Any
from app.timezone import now_kst
from . import store
logger = logging.getLogger("project.reminders")
KIND_DUE_SOON = "due_soon"
KIND_DUE_TODAY = "due_today"
KIND_OVERDUE = "overdue"
OVERDUE_WINDOW_DAYS = 7
def _env(name: str, default: str = "") -> str:
return (os.getenv(name, "") or "").strip() or default
def _env_bool(name: str, default: bool) -> bool:
v = _env(name).lower()
if not v:
return default
return v in ("1", "true", "yes", "on")
def is_workday(d: date) -> bool:
return d.weekday() < 5 and not store.holiday_name(d.isoformat())
def next_workday(d: date) -> date:
n = d + timedelta(days=1)
while not is_workday(n):
n += timedelta(days=1)
return n
def classify(due: date, today: date) -> str | None:
"""마감일 → 알림 종류(없으면 None)."""
if due == today:
return KIND_DUE_TODAY
if today < due <= next_workday(today):
return KIND_DUE_SOON
if today - timedelta(days=OVERDUE_WINDOW_DAYS) <= due < today:
return KIND_OVERDUE
return None
def _title_for(kind: str, task: dict[str, Any], today: date) -> str:
due = date.fromisoformat(task["due_date"][:10])
if kind == KIND_DUE_TODAY:
return f"오늘 마감: {task['title']}"
if kind == KIND_DUE_SOON:
days = (due - today).days
when = "내일" if days == 1 else f"{days}일 후"
return f"마감 임박({when}): {task['title']}"
return f"마감 지남({(today - due).days}일): {task['title']}"
def run_due_reminders(st: Any, *, today: date | None = None) -> dict[str, int]:
"""한 번 실행. 새로 만든 알림 수를 종류별로 돌려준다."""
today = today or now_kst().date()
start = today - timedelta(days=OVERDUE_WINDOW_DAYS)
end = next_workday(today)
counts = {KIND_DUE_SOON: 0, KIND_DUE_TODAY: 0, KIND_OVERDUE: 0}
digest: dict[str, list[tuple[str, dict[str, Any]]]] = {}
for t in st.list_open_tasks_due_between(start=start, end=end):
due = date.fromisoformat(t["due_date"][:10])
kind = classify(due, today)
if kind is None:
continue
assignee = store.norm_str(t.get("assignee_email"), lower=True)
recipients = [assignee] if assignee else store.normalize_emails(t.get("followers") or [])
for rcpt in recipients:
if not st.record_reminder(
task_id=t["id"], kind=kind, due_date=t["due_date"][:10], recipient_email=rcpt,
):
continue # 이미 보냄
title = _title_for(kind, t, today)
try:
st.add_notification(
recipient_email=rcpt, actor_email="", project_id=t["project_id"],
task_id=t["id"], type=kind, title=title,
body=f"{t.get('project_name') or ''} · 마감 {t['due_date'][:10]}",
)
except Exception: # noqa: BLE001
logger.warning("마감 알림 생성 실패: task=%s", t["id"])
continue
counts[kind] += 1
digest.setdefault(rcpt, []).append((title, t))
if digest and _env_bool("PROJECT_REMINDER_EMAIL", False):
_send_digests(digest, today)
return counts
def _send_digests(digest: dict[str, list[tuple[str, dict[str, Any]]]], today: date) -> None:
from app.mail import send_email # noqa: WPS433
base = _env("PUBLIC_BASE_URL").rstrip("/")
for rcpt, items in digest.items():
lines = [f"{today.isoformat()} 마감 알림 — {len(items)}건", ""]
for title, t in items:
lines.append(f"· {title} [{t.get('project_name') or ''}]")
if base:
lines.append(f" {base}/project/t/{t['id']}")
send_email(
to=[rcpt],
subject=f"[DBX 프로젝트] 마감 알림 {len(items)}건 ({today.isoformat()})",
body="\n".join(lines) + "\n",
)
_started = False
_start_lock = threading.Lock()
def start_reminder_thread(st: Any) -> bool:
"""웹 프로세스 시작 시 1번. 이미 돌고 있거나 꺼져 있으면 False."""
global _started # noqa: PLW0603
if st is None or not _env_bool("PROJECT_REMINDERS", True):
return False
with _start_lock:
if _started:
return False
_started = True
try:
hour = min(23, max(0, int(_env("PROJECT_REMINDER_HOUR", "9"))))
except ValueError:
hour = 9
def _loop() -> None:
last_run: date | None = None
while True:
try:
now = now_kst()
today = now.date()
if last_run != today and now.hour >= hour and is_workday(today):
counts = run_due_reminders(st, today=today)
last_run = today
logger.info("마감 알림 실행: %s", counts)
except Exception as exc: # noqa: BLE001
if type(exc).__name__ == "UndefinedTable":
# 008 마이그레이션 미적용 — 오늘은 더 시도하지 않는다(로그 도배 방지)
logger.warning("마감 알림 skip — project_db_008 마이그레이션 필요")
last_run = now_kst().date()
else:
logger.warning("마감 알림 실패(%s) — 5분 뒤 재시도", type(exc).__name__)
time.sleep(300)
threading.Thread(target=_loop, name="project-reminders", daemon=True).start()
return True
+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"]),
+34
View File
@@ -441,6 +441,40 @@ def extract_mentions_from_html(html: str) -> list[str]:
return parser.emails
class _TextCollector(HTMLParser):
_BREAK_TAGS = frozenset({"br", "p", "div", "li", "blockquote", "pre"})
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.parts: list[str] = []
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
if tag in self._BREAK_TAGS:
self.parts.append(" ")
def handle_data(self, data: str) -> None:
self.parts.append(data)
def html_to_text(html: str) -> str:
"""설명 HTML → 한 줄 평문(검색 확인·미리보기용). 공백은 하나로 줄인다."""
parser = _TextCollector()
parser.feed(html or "")
parser.close()
return re.sub(r"\s+", " ", "".join(parser.parts)).strip()
def search_snippet(text: str, query: str, *, width: int = 60) -> str:
"""text 에서 query 주변만 잘라 보여준다(앞뒤 … 표시). 없으면 앞부분."""
t = text or ""
i = t.lower().find((query or "").lower())
if i < 0:
return t[:width * 2] + ("…" if len(t) > width * 2 else "")
start = max(0, i - width)
end = min(len(t), i + len(query) + width)
return ("…" if start else "") + t[start:end] + ("…" if end < len(t) else "")
def normalize_emails(values: Any) -> list[str]:
"""임의 입력(리스트/문자열)을 소문자 이메일 목록으로 정리한다."""
if isinstance(values, str):
@@ -11,6 +11,13 @@
프로젝트 수정/삭제(✎/×) 버튼은 그 동작을 배선하는 initProject 가 도는
프로젝트 화면에서만 그린다(current_pid 로 판별). #}
<aside class="pj-side">
<!-- 전체 검색 — 제목·설명·댓글, 내가 볼 수 있는 모든 프로젝트(하위 업무 포함).
결과를 누르면 그 업무 팝업(/project/t/{id})으로. 어디서든 "/" 키로 포커스. -->
<div class="pj-side-search">
<span class="material-symbols-outlined pj-side-search-ic">search</span>
<input type="search" id="pj-global-search" placeholder="전체 검색 ( / )" autocomplete="off" aria-label="업무 전체 검색" />
<div class="pj-search-results" id="pj-search-results" hidden></div>
</div>
<!-- 아사나처럼 맨 위에 개인 메뉴(수신함 / 내 업무). 내 업무는 접었다 펴는
패널이 아니라 오른쪽 화면 전체에 목록을 띄우는 별도 페이지다. -->
<nav class="pj-side-nav">
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260923b" />
<link rel="stylesheet" href="/static/project.css?v=20260923c" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -70,6 +70,9 @@
{% elif n.type == 'completed' %}task_alt
{% elif n.type == 'comment' %}chat_bubble
{% elif n.type == 'mention' %}alternate_email
{% elif n.type == 'due_soon' %}schedule
{% elif n.type == 'due_today' %}today
{% elif n.type == 'overdue' %}alarm
{% else %}notifications{% endif %}
</span>
<div class="pj-inbox-body">
@@ -93,5 +96,5 @@
</div>
</div>
<script src="/static/project.js?v=20260923b" defer></script>
<script src="/static/project.js?v=20260923c" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260923b" />
<link rel="stylesheet" href="/static/project.css?v=20260923c" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -34,6 +34,26 @@
</div>
<div class="pj-mytasks-summary" id="pj-mytasks-summary"></div>
</div>
<!-- 검색·필터 — 정렬은 표 머리글 클릭(마감·우선순위 등). -->
<div class="pj-filterbar" id="pj-mt-filterbar">
<label class="pj-fb-search">
<span class="material-symbols-outlined">filter_list</span>
<input type="search" id="pj-mt-q" placeholder="내 업무에서 찾기 (제목·설명·프로젝트)" autocomplete="off" />
</label>
<select id="pj-mt-due" class="pj-fb-select" title="마감일">
<option value="all">마감: 전체</option>
<option value="overdue">마감 지남</option>
<option value="today">오늘 마감</option>
<option value="week">이번 주 마감</option>
<option value="none">마감일 없음</option>
</select>
<select id="pj-mt-priority" class="pj-fb-select" title="우선순위">
<option value="all">우선순위: 전체</option>
<option value="high">높음</option>
<option value="normal">보통</option>
<option value="low">낮음</option>
</select>
</div>
<div class="pj-view pj-mytasks-pane">
<table class="pj-table pj-mytasks-table" id="pj-mytasks-table">
@@ -97,5 +117,5 @@
"today": {{ today | tojson }}
}
</script>
<script src="/static/project.js?v=20260923b" defer></script>
<script src="/static/project.js?v=20260923c" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260923b" />
<link rel="stylesheet" href="/static/project.css?v=20260923c" />
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<!-- 타임라인 vis-timeline — self-host -->
@@ -74,6 +74,49 @@
</div>
</div>
<!-- 필터 바 — 보드·리스트·달력·타임라인·대시보드 모두에 적용(이미 받은 업무를
화면에서 거른다). 설정은 프로젝트별로 이 브라우저에 기억한다.
정렬은 보드 카드 순서와 리스트 기본 순서(열 제목 클릭 정렬이 우선). -->
<div class="pj-filterbar" id="pj-filterbar">
<label class="pj-fb-search">
<span class="material-symbols-outlined">filter_list</span>
<input type="search" id="pj-fb-q" placeholder="이 화면에서 찾기 (제목·설명·담당자)" autocomplete="off" />
</label>
<select id="pj-fb-status" class="pj-fb-select" title="완료 상태">
<option value="all">상태: 전체</option>
<option value="open">미완료</option>
<option value="done">완료</option>
</select>
<select id="pj-fb-assignee" class="pj-fb-select" title="담당자">
<option value="all">담당자: 전체</option>
<option value="me">나</option>
<option value="none">담당자 없음</option>
</select>
<select id="pj-fb-due" class="pj-fb-select" title="마감일">
<option value="all">마감: 전체</option>
<option value="overdue">마감 지남</option>
<option value="today">오늘 마감</option>
<option value="week">이번 주 마감</option>
<option value="none">마감일 없음</option>
</select>
<select id="pj-fb-priority" class="pj-fb-select" title="우선순위">
<option value="all">우선순위: 전체</option>
<option value="high">높음</option>
<option value="normal">보통</option>
<option value="low">낮음</option>
</select>
<select id="pj-fb-sort" class="pj-fb-select" title="정렬">
<option value="manual">정렬: 기본</option>
<option value="due">마감일순</option>
<option value="priority">우선순위순</option>
<option value="title">제목순</option>
<option value="assignee">담당자순</option>
<option value="created">최근 생성순</option>
</select>
<span class="pj-fb-count" id="pj-fb-count" hidden></span>
<button type="button" class="pj-fb-reset" id="pj-fb-reset" hidden>초기화</button>
</div>
<!-- 달력 (휴가 모듈과 동일한 월간 그리드) -->
<div class="pj-view" data-view="calendar" hidden>
<div class="pj-cal-head">
@@ -291,6 +334,18 @@
<input type="date" id="pj-t-due" />
</span>
</div>
<!-- 팔로워(아사나의 협업자) — 완료·댓글 알림을 받는 사람. 만든 사람·담당자·
댓글 단 사람·@태그된 사람은 자동으로 들어온다. 저장 버튼과 무관하게 즉시 반영.
기존 업무에서만, 008 마이그레이션이 있어야 보인다. -->
<div class="pj-meta-row2" id="pj-followers-row" hidden>
<span class="pj-meta-label2">팔로워</span>
<span class="pj-meta-value2 pj-followers">
<span class="material-symbols-outlined pj-meta-ic">group</span>
<span class="pj-follower-chips" id="pj-follower-chips"></span>
<button type="button" class="pj-follower-add" id="pj-follower-add" title="팔로워 추가">+</button>
<button type="button" class="pj-follow-toggle" id="pj-follow-toggle">팔로우</button>
</span>
</div>
</div>
</div>
@@ -458,10 +513,11 @@
"projects": {{ projects_meta | tojson }},
"stagesByProject": {{ stages_by_project | tojson }},
"boardStages": {{ board_stage_names | tojson }},
"avatars": {{ avatars | tojson }}
"avatars": {{ avatars | tojson }},
"today": {{ today | tojson }}
}
</script>
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
<script src="/static/project.js?v=20260923b" defer></script>
<script src="/static/project.js?v=20260923c" defer></script>
{% endblock %}