"""project_db PostgreSQL 저장소. - 드라이버: psycopg 3 (`psycopg[binary,pool]`) — 다른 모듈과 동일 패턴. - 연결 정보: 환경변수 `PROJECT_DB_URL` (예: postgresql://project_app:@postgres-db:5432/project_db) - 스키마는 앱이 만들지 않는다. `scripts/sql/project_db_init.sql` 을 superuser 가 사전 적용한다. 앱 계정(project_app)은 CRUD 권한만 받는다. - 연결 풀은 lazy open. 순수 검증/상수는 store.py 에 있고, 여기서는 DB I/O 와 직렬화만 담당한다. """ from __future__ import annotations import logging import time from datetime import date, datetime from datetime import time as dtime from typing import Any from psycopg import errors as psycopg_errors from psycopg.rows import dict_row from psycopg.types.json import Jsonb from psycopg_pool import ConnectionPool from app.timezone import KST, now_kst from . import store logger = logging.getLogger("project.db") class ProjectStore: def __init__(self, dsn: str, *, min_size: int = 1, max_size: int = 5): self._pool = ConnectionPool( conninfo=dsn, min_size=min_size, max_size=max_size, kwargs={"row_factory": dict_row, "autocommit": True}, open=False, ) self._pool.open(wait=False) self._live_retry_at = 0.0 # latest_version: 007 카운터 테이블 재시도 시각 def close(self) -> None: self._pool.close() # ════════════════════════════════════════════════════════════ # 프로젝트 / 서브프로젝트 # ════════════════════════════════════════════════════════════ def list_projects( self, *, include_archived: bool = False, member_email: str | None = None ) -> list[dict[str, Any]]: """전체 프로젝트(서브 포함) 평면 목록. member_email 지정 시 그 사용자가 멤버이거나 owner 인 프로젝트만(관리자는 라우터에서 None 으로 전체 조회). """ clauses: list[str] = [] params: list[Any] = [] if not include_archived: clauses.append("p.status <> 'archived'") if member_email: clauses.append( "(p.owner_email = %s OR EXISTS (" " SELECT 1 FROM project_members m " " WHERE m.project_id = p.id AND m.user_email = %s))" ) params.extend([member_email, member_email]) where = ("WHERE " + " AND ".join(clauses)) if clauses else "" with self._pool.connection() as conn: rows = conn.execute( f"SELECT p.* FROM projects p {where} " "ORDER BY p.parent_id NULLS FIRST, p.sort_order ASC, p.id ASC", params, ).fetchall() return [self._serialize(r) for r in rows] def get_project(self, *, project_id: int) -> dict[str, Any] | None: with self._pool.connection() as conn: row = conn.execute( "SELECT * FROM projects WHERE id = %s", (project_id,) ).fetchone() return self._serialize(row) if row else None def create_project( self, *, name: str, parent_id: int | None = None, description: str = "", color: str = "", owner_email: str = "", start_date: str | None = None, due_date: str | None = None, created_by: str = "", seed_stages: bool = False, ) -> dict[str, Any]: nm = store.validate_project_name(name) col = store.validate_color(color) sd = store.validate_date(start_date) dd = store.validate_date(due_date) with self._pool.connection() as conn: with conn.transaction(): if parent_id is not None: parent = conn.execute( "SELECT id FROM projects WHERE id = %s", (parent_id,) ).fetchone() if not parent: raise KeyError(f"상위 프로젝트를 찾을 수 없습니다: {parent_id}") row = conn.execute( """ INSERT INTO projects (parent_id, name, description, color, owner_email, start_date, due_date, created_by) VALUES (%s,%s,%s,%s,%s,%s,%s,%s) RETURNING * """, ( parent_id, nm, store.norm_str(description), col, store.norm_str(owner_email, lower=True), sd, dd, store.norm_str(created_by, lower=True), ), ).fetchone() pid = row["id"] if seed_stages: for i, (stage_name, is_done) in enumerate(store.DEFAULT_STAGES): conn.execute( "INSERT INTO project_stages " "(project_id, name, sort_order, is_done_stage, created_by) " "VALUES (%s,%s,%s,%s,%s)", (pid, stage_name, i, is_done, store.norm_str(created_by, lower=True)), ) self._log(conn, project_id=pid, actor=created_by, action=store.ACTION_CREATED, detail=nm) return self._serialize(row) def update_project(self, *, project_id: int, fields: dict[str, Any]) -> dict[str, Any]: allowed = { "name": lambda v: store.validate_project_name(v), "description": lambda v: store.norm_str(v), "color": lambda v: store.validate_color(v), "owner_email": lambda v: store.norm_str(v, lower=True), "start_date": lambda v: store.validate_date(v), "due_date": lambda v: store.validate_date(v), "status": lambda v: (store.norm_str(v, lower=True) if store.norm_str(v, lower=True) in store.PROJECT_STATUSES else "active"), } sets: list[str] = [] params: list[Any] = [] for key, fn in allowed.items(): if key in fields: sets.append(f"{key} = %s") params.append(fn(fields[key])) if not sets: existing = self.get_project(project_id=project_id) if existing is None: raise KeyError(project_id) return existing params.append(project_id) with self._pool.connection() as conn: row = conn.execute( f"UPDATE projects SET {', '.join(sets)} WHERE id = %s RETURNING *", params, ).fetchone() if not row: raise KeyError(project_id) return self._serialize(row) def delete_project(self, *, project_id: int) -> list[int]: """프로젝트(서브프로젝트·단계·업무 CASCADE) 삭제. 같이 지워진 업무 id 목록을 돌려준다 — DB 행은 CASCADE 로 사라지지만 디스크의 첨부 폴더(DATA_DIR/project/)는 라우터가 치워야 한다. """ with self._pool.connection() as conn: with conn.transaction(): rows = conn.execute( "WITH RECURSIVE tree AS (" " SELECT id FROM projects WHERE id = %s " " UNION ALL " " SELECT p.id FROM projects p JOIN tree ON p.parent_id = tree.id" ") SELECT t.id FROM tasks t WHERE t.project_id IN (SELECT id FROM tree)", (project_id,), ).fetchall() cur = conn.execute("DELETE FROM projects WHERE id = %s", (project_id,)) if cur.rowcount == 0: raise KeyError(project_id) return [int(r["id"]) for r in rows] # ════════════════════════════════════════════════════════════ # 멤버 # ════════════════════════════════════════════════════════════ def list_members(self, *, project_id: int) -> list[dict[str, Any]]: with self._pool.connection() as conn: rows = conn.execute( "SELECT * FROM project_members WHERE project_id = %s " "ORDER BY role DESC, user_email ASC", (project_id,), ).fetchall() return [self._serialize(r) for r in rows] def is_member(self, *, project_id: int, user_email: str) -> bool: email = store.norm_str(user_email, lower=True) with self._pool.connection() as conn: row = conn.execute( "SELECT 1 FROM projects p " "LEFT JOIN project_members m " " ON m.project_id = p.id AND m.user_email = %s " "WHERE p.id = %s AND (p.owner_email = %s OR m.id IS NOT NULL) LIMIT 1", (email, project_id, email), ).fetchone() return bool(row) def add_member( self, *, project_id: int, user_email: str, user_name: str = "", role: str = "member" ) -> dict[str, Any]: email = store.norm_str(user_email, lower=True) if not email or "@" not in email: raise ValueError("올바른 이메일이 아닙니다.") rl = store.validate_role(role) with self._pool.connection() as conn: row = conn.execute( """ INSERT INTO project_members (project_id, user_email, user_name, role) VALUES (%s,%s,%s,%s) ON CONFLICT (project_id, user_email) DO UPDATE SET role = EXCLUDED.role, user_name = EXCLUDED.user_name RETURNING * """, (project_id, email, store.norm_str(user_name), rl), ).fetchone() return self._serialize(row) def remove_member(self, *, project_id: int, user_email: str) -> None: email = store.norm_str(user_email, lower=True) with self._pool.connection() as conn: conn.execute( "DELETE FROM project_members WHERE project_id = %s AND user_email = %s", (project_id, email), ) # ════════════════════════════════════════════════════════════ # 단계 (stages) # ════════════════════════════════════════════════════════════ def list_stages(self, *, project_id: int) -> list[dict[str, Any]]: with self._pool.connection() as conn: rows = conn.execute( "SELECT * FROM project_stages WHERE project_id = %s " "ORDER BY sort_order ASC, id ASC", (project_id,), ).fetchall() return [self._serialize(r) for r in rows] def list_stages_for_projects(self, *, project_ids: list[int]) -> dict[int, list[dict[str, Any]]]: """여러 프로젝트의 세션을 한 번에 — {project_id: [stage, ...]} (세션 없는 프로젝트도 빈 목록).""" ids = [int(i) for i in project_ids] out: dict[int, list[dict[str, Any]]] = {i: [] for i in ids} if not ids: return out with self._pool.connection() as conn: rows = conn.execute( "SELECT * FROM project_stages WHERE project_id = ANY(%s) " "ORDER BY project_id, sort_order ASC, id ASC", (ids,), ).fetchall() for r in rows: s = self._serialize(r) out.setdefault(s["project_id"], []).append(s) return out def add_stage( self, *, project_id: int, name: str, is_done_stage: bool = False, color: str | None = None, created_by: str = "", default_assignee_email: str = "", ) -> dict[str, Any]: nm = store.norm_str(name) if not nm: raise ValueError("세션 이름은 필수입니다.") col = store.validate_stage_color(color) dae = store.norm_str(default_assignee_email or "", lower=True) with self._pool.connection() as conn: nxt = conn.execute( "SELECT COALESCE(MAX(sort_order), -1) + 1 AS n " "FROM project_stages WHERE project_id = %s", (project_id,), ).fetchone() # 기본 담당자 컬럼(009)은 값이 있을 때만 넣는다 — 009 미적용 # 환경에서도 담당자 없는 세션 추가는 그대로 되게. cols = "project_id, name, sort_order, is_done_stage, color, created_by" vals: list[Any] = [project_id, nm, int(nxt["n"]), bool(is_done_stage), col, store.norm_str(created_by, lower=True)] if dae: cols += ", default_assignee_email" vals.append(dae) row = conn.execute( f"INSERT INTO project_stages ({cols}) " f"VALUES ({','.join(['%s'] * len(vals))}) RETURNING *", vals, ).fetchone() return self._serialize(row) def get_stage(self, *, stage_id: int) -> dict[str, Any] | None: with self._pool.connection() as conn: row = conn.execute( "SELECT * FROM project_stages WHERE id = %s", (stage_id,) ).fetchone() return self._serialize(row) if row else None @staticmethod def _stage_default_assignee(conn: Any, stage_id: Any, project_id: int) -> tuple[str, str]: """세션 기본 담당자(마이그레이션 009) → (email, name). 미지정·009 미적용· 그 사람이 이제 프로젝트 멤버가 아니면 ('', ''). 컬럼이 없어도 에러가 나지 않게 to_jsonb(행) 에서 키로 읽는다.""" if stage_id in (None, ""): return "", "" row = conn.execute( "SELECT to_jsonb(s) ->> 'default_assignee_email' AS e " "FROM project_stages s WHERE id = %s", (stage_id,), ).fetchone() email = store.norm_str((row or {}).get("e") or "", lower=True) if not email: return "", "" # 멤버 또는 프로젝트 owner(멤버 행이 없을 수 있다)만 — 업무 담당자 # 후보와 같은 기준. m = conn.execute( "SELECT user_name FROM project_members WHERE project_id = %s AND user_email = %s " "UNION ALL " "SELECT '' FROM projects WHERE id = %s AND owner_email = %s " "LIMIT 1", (project_id, email, project_id, email), ).fetchone() if not m: return "", "" return email, m["user_name"] or "" @staticmethod def _check_stage_in_project(conn: Any, stage_id: Any, project_id: int) -> int | None: """세션이 그 프로젝트 것인지 확인하고 int 로 돌려준다(None 은 그대로). 확인 안 하면 다른 프로젝트의 세션 id 를 넣어 업무를 엉뚱한 세션에 묶거나(보드에서 사라짐) 남의 세션 완료 여부로 완료 처리가 될 수 있다. """ if stage_id in (None, ""): return None try: sid = int(stage_id) except (TypeError, ValueError): raise ValueError("세션 값이 올바르지 않습니다.") row = conn.execute( "SELECT 1 FROM project_stages WHERE id = %s AND project_id = %s", (sid, project_id), ).fetchone() if not row: raise ValueError("이 프로젝트의 세션이 아닙니다.") return sid def stage_in_project(self, *, stage_id: Any, project_id: int) -> int | None: with self._pool.connection() as conn: return self._check_stage_in_project(conn, stage_id, project_id) def delete_stage(self, *, stage_id: int) -> None: with self._pool.connection() as conn: cur = conn.execute("DELETE FROM project_stages WHERE id = %s", (stage_id,)) if cur.rowcount == 0: raise KeyError(stage_id) # ════════════════════════════════════════════════════════════ # 업무 (tasks) # ════════════════════════════════════════════════════════════ # 업무 목록에 함께 붙이는 하위업무 집계(댓글수와 같은 방식). 여러 쿼리에서 # 재사용하므로 상수로 뽑아둔다. _SUBTASK_COUNTS_SQL = ( "(SELECT COUNT(*) FROM tasks st WHERE st.parent_task_id = t.id) AS subtask_total, " "(SELECT COUNT(*) FROM tasks st WHERE st.parent_task_id = t.id " " AND st.completed_at IS NOT NULL) AS subtask_done" ) def list_tasks( self, *, project_id: int | None = None, assignee_email: str | None = None, include_subprojects: bool = False, parent_task_id: int | None = None, top_level_only: bool = True, include_links: bool = True, limit: int = 1000, ) -> list[dict[str, Any]]: """업무 목록. 기본은 최상위 업무만(`parent_task_id IS NULL`) — 하위 업무는 부모 안에서만 보인다(아사나와 동일, 보드/캘린더/리스트 카드로 따로 뜨지 않는다). `parent_task_id` 를 주면 그 부모의 하위 업무만 받는다. `project_id` 하나만 지정하고(`include_subprojects=False`, 최상위 조회일 때) `include_links=True`(기본값)이면, 그 프로젝트에 멀티호밍 (`task_project_links`)으로 연결된 다른 프로젝트의 업무도 함께 반환한다. 프로젝트 상세 화면이 '이 프로젝트만' 보여줄 때 쓰는 경로가 이 조합이다. 다른 조합(홈 전체보기·내 업무 등, `project_id=None`)은 연결 업무를 섞지 않는다 — 같은 업무가 여러 곳에서 중복으로 집계되는 것을 막기 위함이다. """ link_mode = ( include_links and project_id is not None and not include_subprojects and parent_task_id is None ) if link_mode: return self._list_tasks_for_project_with_links( project_id=project_id, assignee_email=assignee_email, limit=limit, ) clauses: list[str] = [] params: list[Any] = [] if project_id is not None: if include_subprojects: clauses.append( "t.project_id IN (" " WITH RECURSIVE tree AS (" " SELECT id FROM projects WHERE id = %s " " UNION ALL " " SELECT p.id FROM projects p JOIN tree ON p.parent_id = tree.id" " ) SELECT id FROM tree)" ) params.append(project_id) else: clauses.append("t.project_id = %s") params.append(project_id) if assignee_email: clauses.append("t.assignee_email = %s") params.append(store.norm_str(assignee_email, lower=True)) if parent_task_id is not None: clauses.append("t.parent_task_id = %s") params.append(parent_task_id) elif top_level_only: clauses.append("t.parent_task_id IS NULL") where = ("WHERE " + " AND ".join(clauses)) if clauses else "" params.append(int(limit)) with self._pool.connection() as conn: rows = conn.execute( f"SELECT t.*, p.name AS project_name, p.color AS project_color, " f" s.name AS stage_name, s.is_done_stage, " f" (SELECT COUNT(*) FROM task_comments c WHERE c.task_id = t.id) AS comment_count, " f" {self._SUBTASK_COUNTS_SQL} " f"FROM tasks t " f"JOIN projects p ON p.id = t.project_id " f"LEFT JOIN project_stages s ON s.id = t.stage_id " f"{where} " "ORDER BY t.sort_order ASC, t.id ASC LIMIT %s", params, ).fetchall() return [self._serialize(r) for r in rows] def _list_tasks_for_project_with_links( self, *, project_id: int, assignee_email: str | None, limit: int, ) -> list[dict[str, Any]]: """`list_tasks` 의 "이 프로젝트 + 여기 연결된 업무" 경로.""" return self.list_tasks_for_projects( project_ids=[project_id], assignee_email=assignee_email, limit=limit, ) def list_tasks_for_projects( self, *, project_ids: list[int], assignee_email: str | None = None, limit: int = 20000, ) -> list[dict[str, Any]]: """여러 프로젝트의 최상위 업무(+ 각 프로젝트에 연결된 업무)를 쿼리 한 번에. 프로젝트 화면은 접근 가능한 모든 프로젝트의 업무를 그리는데, 예전엔 프로젝트마다 쿼리를 따로 날렸다(N+1). 행마다 붙는 값: context_project_id : 어느 프로젝트 맥락의 행인지(연결 업무는 연결된 쪽) is_linked : 다른 프로젝트에서 연결돼 온 행인지 stage_id : 그 맥락에서의 세션(연결이면 link.stage_id — 없으면 NULL) home_stage_id : 원래 소속 세션(tasks.stage_id). 업무 편집 팝업의 "세션" 선택은 항상 이 값을 쓴다. `t.*` 뒤에 같은 이름(`stage_id`)을 다시 셀렉트해 덮어쓴다 — dict_row 는 중복 컬럼명이면 마지막 값을 쓴다. 원래 소속 배지(`project_name`/`color`)는 `t.project_id` 기준 그대로 둬 "다른 프로젝트에서 온 업무"임을 보인다. """ ids = [int(i) for i in project_ids] if not ids: return [] params: dict[str, Any] = {"ids": ids, "limit": int(limit)} extra = "" if assignee_email: extra = "AND t.assignee_email = %(assignee)s" params["assignee"] = store.norm_str(assignee_email, lower=True) with self._pool.connection() as conn: rows = conn.execute( f""" SELECT t.*, p.name AS project_name, p.color AS project_color, (SELECT COUNT(*) FROM task_comments c WHERE c.task_id = t.id) AS comment_count, {self._SUBTASK_COUNTS_SQL}, x.context_project_id, x.is_linked, t.stage_id AS home_stage_id, CASE WHEN x.is_linked THEN es.name ELSE s.name END AS stage_name, CASE WHEN x.is_linked THEN es.is_done_stage ELSE s.is_done_stage END AS is_done_stage, CASE WHEN x.is_linked THEN x.link_stage_id ELSE t.stage_id END AS stage_id FROM ( SELECT id AS task_id, project_id AS context_project_id, FALSE AS is_linked, NULL::bigint AS link_stage_id FROM tasks WHERE parent_task_id IS NULL AND project_id = ANY(%(ids)s) UNION ALL SELECT l.task_id, l.project_id, TRUE, l.stage_id FROM task_project_links l JOIN tasks lt ON lt.id = l.task_id WHERE l.project_id = ANY(%(ids)s) AND lt.parent_task_id IS NULL AND lt.project_id <> l.project_id ) x JOIN tasks t ON t.id = x.task_id JOIN projects p ON p.id = t.project_id LEFT JOIN project_stages s ON s.id = t.stage_id LEFT JOIN project_stages es ON es.id = x.link_stage_id WHERE TRUE {extra} ORDER BY x.context_project_id, t.sort_order ASC, t.id ASC LIMIT %(limit)s """, params, ).fetchall() return [self._serialize(r) for r in rows] def count_my_open(self, *, assignee_email: str) -> int: """사이드바 "내 업무" 배지 — 내가 담당인 미완료 업무 수(하위 업무 포함, 내 업무 화면 목록과 같은 기준).""" with self._pool.connection() as conn: row = conn.execute( "SELECT COUNT(*) AS n FROM tasks " "WHERE assignee_email = %s AND completed_at IS NULL", (store.norm_str(assignee_email, lower=True),), ).fetchone() return int(row["n"] or 0) def list_my_tasks(self, *, assignee_email: str, limit: int = 1000) -> list[dict[str, Any]]: """"내 업무" 화면 전용 — 내가 담당자인 업무를 레벨(최상위/하위) 상관없이 전부 반환한다. 하위 업무 행에는 부모 업무 정보(`parent_title` 등)를 같이 붙여서, 부모가 내 업무가 아니어도(다른 사람 담당) 화면에서 트리로 묶어 보여줄 수 있게 한다. """ email = store.norm_str(assignee_email, lower=True) with self._pool.connection() as conn: rows = conn.execute( f"SELECT t.*, p.name AS project_name, p.color AS project_color, " f" s.name AS stage_name, s.is_done_stage, " f" (SELECT COUNT(*) FROM task_comments c WHERE c.task_id = t.id) AS comment_count, " f" {self._SUBTASK_COUNTS_SQL}, " f" pt.title AS parent_title, pt.completed_at AS parent_completed_at, " f" pt.assignee_email AS parent_assignee_email " f"FROM tasks t " f"JOIN projects p ON p.id = t.project_id " f"LEFT JOIN project_stages s ON s.id = t.stage_id " f"LEFT JOIN tasks pt ON pt.id = t.parent_task_id " f"WHERE t.assignee_email = %s " "ORDER BY t.sort_order ASC, t.id ASC LIMIT %s", (email, int(limit)), ).fetchall() return [self._serialize(r) for r in rows] def get_task(self, *, task_id: int) -> dict[str, Any] | None: with self._pool.connection() as conn: row = conn.execute( f"SELECT t.*, p.name AS project_name, p.color AS project_color, " f" s.name AS stage_name, s.is_done_stage, " f" (SELECT COUNT(*) FROM task_comments c WHERE c.task_id = t.id) AS comment_count, " f" {self._SUBTASK_COUNTS_SQL} " f"FROM tasks t JOIN projects p ON p.id = t.project_id " f"LEFT JOIN project_stages s ON s.id = t.stage_id " f"WHERE t.id = %s", (task_id,), ).fetchone() return self._serialize(row) if row else None def create_task( self, *, project_id: int, title: str, stage_id: int | None = None, description: str = "", assignee_email: str = "", assignee_name: str = "", priority: str = "normal", start_date: str | None = None, due_date: str | None = None, start_time: str | None = None, due_time: str | None = None, created_by: str = "", parent_task_id: int | None = None, ) -> dict[str, Any]: ttl = store.validate_task_title(title) pr = store.validate_priority(priority) sd = store.validate_date(start_date) dd = store.validate_date(due_date) sti = store.validate_time(start_time) dti = store.validate_time(due_time) assignee = store.norm_str(assignee_email, lower=True) with self._pool.connection() as conn: with conn.transaction(): if parent_task_id is not None: # 하위 업무는 부모와 같은 프로젝트에 속하고(담당자 선택지 등이 # 맞아떨어지게), 보드에는 안 보이므로 세션을 갖지 않는다. parent = conn.execute( "SELECT project_id FROM tasks WHERE id = %s", (parent_task_id,) ).fetchone() if not parent: raise KeyError(f"상위 업무를 찾을 수 없습니다: {parent_task_id}") # 권한은 URL 의 project_id 로 검사했으므로, 부모가 다른 프로젝트 # 업무면 거부한다(예전엔 부모 프로젝트로 조용히 바꿔 권한 없는 # 프로젝트에 하위 업무를 만들 수 있었다). if int(parent["project_id"]) != int(project_id): raise ValueError("상위 업무가 이 프로젝트에 속하지 않습니다.") stage_id = None elif stage_id not in (None, ""): stage_id = self._check_stage_in_project(conn, stage_id, project_id) else: # stage 미지정 시 프로젝트의 첫 세션으로 st = conn.execute( "SELECT id FROM project_stages WHERE project_id = %s " "ORDER BY sort_order ASC, id ASC LIMIT 1", (project_id,), ).fetchone() stage_id = st["id"] if st else None # 담당자 없이 만들면 그 세션의 기본 담당자를 배정(하위 업무는 # 세션이 없어 해당 없음). if not assignee and stage_id is not None: assignee, assignee_name = self._stage_default_assignee(conn, stage_id, project_id) nxt = conn.execute( "SELECT COALESCE(MAX(sort_order), -1) + 1 AS n FROM tasks " "WHERE project_id = %s", (project_id,), ).fetchone() row = conn.execute( """ INSERT INTO tasks (project_id, stage_id, parent_task_id, title, description, assignee_email, assignee_name, priority, start_date, due_date, start_time, due_time, sort_order, created_by) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING * """, ( project_id, stage_id, parent_task_id, ttl, store.norm_str(description), assignee, store.norm_str(assignee_name), pr, sd, dd, sti, dti, int(nxt["n"]), store.norm_str(created_by, lower=True), ), ).fetchone() if assignee: self._log(conn, project_id=project_id, task_id=row["id"], actor=created_by, action=store.ACTION_ASSIGNED, detail=f"{ttl} → {assignee}") return self.get_task(task_id=row["id"]) def update_task( self, *, task_id: int, fields: dict[str, Any], actor: str = "" ) -> dict[str, Any]: """업무 수정. 반환에 알림 힌트를 담는다(라우터가 메일 발송 판단). 반환 dict 에 추가되는 키: _newly_assigned: 새 담당자 이메일 or None _newly_completed: 완료로 전환됐으면 True """ prev = self.get_task(task_id=task_id) if prev is None: raise KeyError(task_id) sets: list[str] = [] params: list[Any] = [] newly_assigned: str | None = None newly_completed = False new_stage: Any = None if "stage_id" in fields: new_stage = self.stage_in_project( stage_id=fields["stage_id"], project_id=prev["project_id"] ) # 다른 세션으로 옮겨왔고 (옮긴 뒤에도) 담당자가 비어 있으면 그 세션의 # 기본 담당자를 배정한다. 이미 담당자가 있으면 그대로 둔다. if new_stage is not None and new_stage != prev.get("stage_id"): final_assignee = ( store.norm_str(fields["assignee_email"], lower=True) if "assignee_email" in fields else (prev.get("assignee_email") or "") ) if not final_assignee: with self._pool.connection() as conn: dae, dan = self._stage_default_assignee(conn, new_stage, prev["project_id"]) if dae: fields = {**fields, "assignee_email": dae, "assignee_name": dan} if "title" in fields: sets.append("title = %s") params.append(store.validate_task_title(fields["title"])) if "description" in fields: sets.append("description = %s") params.append(store.norm_str(fields["description"])) if "priority" in fields: sets.append("priority = %s") params.append(store.validate_priority(fields["priority"])) if "start_date" in fields: sets.append("start_date = %s") params.append(store.validate_date(fields["start_date"])) if "due_date" in fields: sets.append("due_date = %s") params.append(store.validate_date(fields["due_date"])) if "start_time" in fields: sets.append("start_time = %s") params.append(store.validate_time(fields["start_time"])) if "due_time" in fields: sets.append("due_time = %s") params.append(store.validate_time(fields["due_time"])) if "assignee_email" in fields: new_assignee = store.norm_str(fields["assignee_email"], lower=True) sets.append("assignee_email = %s") params.append(new_assignee) if "assignee_name" in fields: sets.append("assignee_name = %s") params.append(store.norm_str(fields["assignee_name"])) if new_assignee and new_assignee != (prev.get("assignee_email") or ""): newly_assigned = new_assignee elif "assignee_name" in fields: sets.append("assignee_name = %s") params.append(store.norm_str(fields["assignee_name"])) # 단계 변경 → 완료단계 진입 시 completed_at 자동 세팅. 단, 실제로 단계가 # 바뀐 경우에만 판정한다 — 업무 편집 모달의 "저장"은 매번 현재 stage_id # 를 그대로 다시 보내는데, 여기서 무조건 판정하면 방금 "완료로 표시"로 # 켠 completed_at 을(단계는 그대로인데) 다시 꺼버리는 버그가 있었다. if "stage_id" in fields: sets.append("stage_id = %s") params.append(new_stage) if new_stage != prev.get("stage_id"): done = self._stage_is_done(new_stage) if done and not prev.get("completed_at"): sets.append("completed_at = %s") params.append(now_kst()) newly_completed = True elif not done and prev.get("completed_at"): sets.append("completed_at = NULL") # 직접 완료 토글 — 하위 업무는 세션(칸반 컬럼)이 없어 위 자동 세팅이 # 적용되지 않는다. "stage_id" 를 같이 보냈으면 그쪽 판정이 우선한다. elif "completed" in fields: if fields["completed"] and not prev.get("completed_at"): sets.append("completed_at = %s") params.append(now_kst()) newly_completed = True elif not fields["completed"] and prev.get("completed_at"): sets.append("completed_at = NULL") if not sets: return {**prev, "_newly_assigned": None, "_newly_completed": False} params.append(task_id) with self._pool.connection() as conn: with conn.transaction(): conn.execute( f"UPDATE tasks SET {', '.join(sets)} WHERE id = %s", params ) if newly_assigned: self._log(conn, project_id=prev["project_id"], task_id=task_id, actor=actor, action=store.ACTION_ASSIGNED, detail=f"{prev['title']} → {newly_assigned}") if newly_completed: self._log(conn, project_id=prev["project_id"], task_id=task_id, actor=actor, action=store.ACTION_COMPLETED, detail=prev["title"]) out = self.get_task(task_id=task_id) out["_newly_assigned"] = newly_assigned out["_newly_completed"] = newly_completed return out # ════════════════════════════════════════════════════════════ # 휴지통 (마이그레이션 010) — 지우기 직전 스냅샷, 관리자 복구, 3개월 보관 # ════════════════════════════════════════════════════════════ # 업무에 딸린 테이블(task_id 로 묶임). 복구 때 이 순서대로 다시 넣는다 — # task_mentions·task_attachments 의 comment_id 가 댓글을 가리키므로 댓글 먼저. # 알림(project_notifications)은 되살리면 수신함에 옛 알림이 다시 쌓여 제외. TRASH_CHILD_TABLES = ( "task_comments", "task_followers", "task_mentions", "task_attachments", "task_project_links", "project_activity", "task_reminders", ) @staticmethod def _table_exists(conn: Any, name: str) -> bool: row = conn.execute("SELECT to_regclass(%s) AS r", (f"public.{name}",)).fetchone() return bool(row and row["r"]) def _trash_snapshot(self, conn: Any, ids: list[int]) -> dict[str, list[dict[str, Any]]]: """업무 id 묶음과 딸린 행 전부를 JSON 으로(to_jsonb). 없는 테이블은 건너뜀.""" payload: dict[str, list[dict[str, Any]]] = {} row = conn.execute( "SELECT COALESCE(jsonb_agg(to_jsonb(x) ORDER BY x.id), '[]'::jsonb) AS j " "FROM tasks x WHERE x.id = ANY(%s)", (ids,), ).fetchone() payload["tasks"] = row["j"] for table in self.TRASH_CHILD_TABLES: if not self._table_exists(conn, table): continue row = conn.execute( f"SELECT COALESCE(jsonb_agg(to_jsonb(x)), '[]'::jsonb) AS j " f"FROM {table} x WHERE x.task_id = ANY(%s)", (ids,), ).fetchone() payload[table] = row["j"] return payload def delete_task(self, *, task_id: int, deleted_by: str = "") -> tuple[list[int], int | None]: """업무(+하위 업무 CASCADE) 삭제 → (지워진 업무 id 목록, 휴지통 id). 휴지통 테이블(010)이 있으면 지우기 직전 스냅샷을 같은 트랜잭션에서 남긴다 (스냅샷 저장이 실패하면 삭제도 취소). 없으면 휴지통 id 는 None — 예전처럼 영구 삭제. 첨부 폴더는 라우터가 휴지통으로 옮기거나 지운다.""" with self._pool.connection() as conn: with conn.transaction(): rows = conn.execute( "WITH RECURSIVE sub AS (" " SELECT id FROM tasks WHERE id = %s " " UNION ALL " " SELECT t.id FROM tasks t JOIN sub ON t.parent_task_id = sub.id" ") SELECT id FROM sub", (task_id,), ).fetchall() ids = [int(r["id"]) for r in rows] if not ids: raise KeyError(task_id) trash_id: int | None = None if self._table_exists(conn, "project_trash"): root = conn.execute( "SELECT t.title, t.project_id, p.name AS project_name " "FROM tasks t LEFT JOIN projects p ON p.id = t.project_id WHERE t.id = %s", (task_id,), ).fetchone() payload = self._trash_snapshot(conn, ids) trow = conn.execute( "INSERT INTO project_trash " "(task_id, project_id, project_name, title, task_count, deleted_by, payload) " "VALUES (%s,%s,%s,%s,%s,%s,%s) RETURNING id", (task_id, root["project_id"], root["project_name"] or "", root["title"] or "", len(ids), store.norm_str(deleted_by, lower=True), Jsonb(payload)), ).fetchone() trash_id = int(trow["id"]) cur = conn.execute("DELETE FROM tasks WHERE id = %s", (task_id,)) if cur.rowcount == 0: raise KeyError(task_id) return ids, trash_id def trash_enabled(self) -> bool: with self._pool.connection() as conn: return self._table_exists(conn, "project_trash") def list_trash(self) -> list[dict[str, Any]]: """휴지통 목록(최근 삭제순). payload 는 빼고 요약만.""" with self._pool.connection() as conn: rows = conn.execute( "SELECT id, task_id, project_id, project_name, title, task_count, deleted_by, " " deleted_at, expires_at, " " jsonb_array_length(COALESCE(payload->'task_comments', '[]'::jsonb)) AS comment_count, " " jsonb_array_length(COALESCE(payload->'task_attachments', '[]'::jsonb)) AS attachment_count " "FROM project_trash ORDER BY deleted_at DESC, id DESC" ).fetchall() return [self._serialize(r) for r in rows] def purge_expired_trash(self) -> list[int]: """보관 기간(expires_at)이 지난 휴지통 항목 영구 삭제 → 지운 휴지통 id 목록 (라우터가 그 휴지통 폴더를 지운다).""" with self._pool.connection() as conn: rows = conn.execute( "DELETE FROM project_trash WHERE expires_at < now() RETURNING id" ).fetchall() return [int(r["id"]) for r in rows] def _insert_snapshot_rows(self, conn: Any, table: str, rows: list[dict[str, Any]]) -> None: """스냅샷 행을 원래 id 그대로 다시 넣는다. 지금 테이블에 있는 열만(이후 추가된 열은 기본값). table 은 TRASH_CHILD_TABLES/tasks 화이트리스트에서만 온다.""" if not rows: return live = { r["column_name"] for r in conn.execute( "SELECT column_name FROM information_schema.columns " "WHERE table_schema = 'public' AND table_name = %s", (table,), ).fetchall() } cols = [c for c in rows[0].keys() if c in live] collist = ", ".join(f'"{c}"' for c in cols) conflict = "" if table == "tasks" else " ON CONFLICT DO NOTHING" conn.execute( f"INSERT INTO {table} ({collist}) " f"SELECT {collist} FROM jsonb_populate_recordset(NULL::{table}, %s){conflict}", (Jsonb(rows),), ) def restore_trash(self, *, trash_id: int, restored_by: str = "") -> dict[str, Any]: """휴지통 항목 복구 → {"task_id", "project_id", "task_ids"}. 성공하면 휴지통 행은 지운다. 복구할 수 없으면 ValueError(사유), 없으면 KeyError. - 같은 id 의 업무가 이미 있으면 거부(두 번 복구 방지). - 프로젝트가 지워졌으면 거부. 하위 업무만 지웠던 경우 상위 업무가 없으면 거부. - 세션이 지워졌으면 세션 없이(미지정), 연결/이력 중 지워진 프로젝트를 가리키는 행은 뺀다.""" with self._pool.connection() as conn: with conn.transaction(): tr = conn.execute( "SELECT * FROM project_trash WHERE id = %s FOR UPDATE", (trash_id,) ).fetchone() if not tr: raise KeyError(trash_id) payload = tr["payload"] or {} tasks = list(payload.get("tasks") or []) if not tasks: raise ValueError("복구할 업무 데이터가 없습니다.") ids = [int(t["id"]) for t in tasks] clash = conn.execute( "SELECT id FROM tasks WHERE id = ANY(%s) LIMIT 1", (ids,) ).fetchone() if clash: raise ValueError(f"이미 같은 업무(id {clash['id']})가 있어 복구할 수 없습니다.") project_ids = {int(r["id"]) for r in conn.execute("SELECT id FROM projects").fetchall()} stage_ids = {int(r["id"]) for r in conn.execute("SELECT id FROM project_stages").fetchall()} root = next((t for t in tasks if int(t["id"]) == int(tr["task_id"])), tasks[0]) if int(root["project_id"]) not in project_ids: raise ValueError("업무가 속했던 프로젝트가 삭제되어 복구할 수 없습니다.") parent = root.get("parent_task_id") if parent and int(parent) not in ids: ok = conn.execute("SELECT 1 FROM tasks WHERE id = %s", (int(parent),)).fetchone() if not ok: raise ValueError("상위 업무가 없어 복구할 수 없습니다 — 상위 업무를 먼저 복구하세요.") for t in tasks: if t.get("stage_id") is not None and int(t["stage_id"]) not in stage_ids: t["stage_id"] = None self._insert_snapshot_rows(conn, "tasks", tasks) for table in self.TRASH_CHILD_TABLES: rows = list(payload.get(table) or []) if not rows or not self._table_exists(conn, table): continue kept = [] for r in rows: pid = r.get("project_id") if pid is not None and int(pid) not in project_ids: continue if table == "task_project_links" and r.get("stage_id") is not None \ and int(r["stage_id"]) not in stage_ids: r["stage_id"] = None kept.append(r) self._insert_snapshot_rows(conn, table, kept) self._log(conn, project_id=int(root["project_id"]), task_id=int(root["id"]), actor=restored_by, action="restored", detail=f"휴지통에서 복구: {root.get('title') or ''}") conn.execute("DELETE FROM project_trash WHERE id = %s", (trash_id,)) return {"task_id": int(root["id"]), "project_id": int(root["project_id"]), "task_ids": ids} def _stage_is_done(self, stage_id: Any) -> bool: if stage_id is None: return False with self._pool.connection() as conn: row = conn.execute( "SELECT is_done_stage FROM project_stages WHERE id = %s", (stage_id,) ).fetchone() return bool(row and row["is_done_stage"]) # ════════════════════════════════════════════════════════════ # 멀티호밍 (task_project_links) — 업무 1개가 여러 프로젝트/세션에 동시 소속. # 원래 소속(tasks.project_id/stage_id)은 여기서 건드리지 않는다("기본 홈"은 # 업무 삭제로만 없어진다). 같은 프로젝트에 중복 연결하면 세션만 갱신한다. # ════════════════════════════════════════════════════════════ def add_task_link( self, *, task_id: int, project_id: int, stage_id: int | None = None, created_by: str = "", ) -> dict[str, Any]: with self._pool.connection() as conn: row = conn.execute( """ INSERT INTO task_project_links (task_id, project_id, stage_id, created_by) VALUES (%s,%s,%s,%s) ON CONFLICT (task_id, project_id) DO UPDATE SET stage_id = EXCLUDED.stage_id RETURNING * """, (task_id, project_id, stage_id, store.norm_str(created_by, lower=True)), ).fetchone() return self._serialize(row) def remove_task_link(self, *, task_id: int, project_id: int) -> None: with self._pool.connection() as conn: conn.execute( "DELETE FROM task_project_links WHERE task_id = %s AND project_id = %s", (task_id, project_id), ) def list_task_links(self, *, task_id: int) -> list[dict[str, Any]]: with self._pool.connection() as conn: rows = conn.execute( """ SELECT l.*, p.name AS project_name, p.color AS project_color, s.name AS stage_name FROM task_project_links l JOIN projects p ON p.id = l.project_id LEFT JOIN project_stages s ON s.id = l.stage_id WHERE l.task_id = %s ORDER BY l.created_at ASC """, (task_id,), ).fetchall() return [self._serialize(r) for r in rows] # ════════════════════════════════════════════════════════════ # 활동 이력 # ════════════════════════════════════════════════════════════ def list_activity(self, *, project_id: int, limit: int = 100) -> list[dict[str, Any]]: with self._pool.connection() as conn: rows = conn.execute( "SELECT * FROM project_activity WHERE project_id = %s " "ORDER BY created_at DESC, id DESC LIMIT %s", (project_id, int(limit)), ).fetchall() return [self._serialize(r) for r in rows] @staticmethod def _log( conn: Any, *, project_id: int | None = None, task_id: int | None = None, actor: str = "", action: str = "", detail: str = "", ) -> None: conn.execute( "INSERT INTO project_activity " "(project_id, task_id, actor_email, action, detail) " "VALUES (%s,%s,%s,%s,%s)", (project_id, task_id, store.norm_str(actor, lower=True), action, store.norm_str(detail)), ) # ════════════════════════════════════════════════════════════ # 댓글 (task_comments) # ════════════════════════════════════════════════════════════ def list_comments(self, *, task_id: int) -> list[dict[str, Any]]: with self._pool.connection() as conn: rows = conn.execute( "SELECT * FROM task_comments WHERE task_id = %s " "ORDER BY created_at ASC, id ASC", (task_id,), ).fetchall() return [self._serialize(r) for r in rows] def get_comment(self, *, comment_id: int) -> dict[str, Any] | None: with self._pool.connection() as conn: row = conn.execute( "SELECT * FROM task_comments WHERE id = %s", (comment_id,) ).fetchone() return self._serialize(row) if row else None def add_comment( self, *, task_id: int, author_email: str, author_name: str, body: str, allow_empty: bool = False, ) -> dict[str, Any]: """allow_empty — 채팅 팝업에서 파일/이미지만 보내는 메시지(본문 없음)를 허용할 때 True. 일반 댓글 입력은 여전히 빈 값을 막는다.""" text = store.norm_str(body) if not text and not allow_empty: raise ValueError("댓글 내용이 비었습니다.") with self._pool.connection() as conn: row = conn.execute( "INSERT INTO task_comments (task_id, author_email, author_name, body) " "VALUES (%s,%s,%s,%s) RETURNING *", (task_id, store.norm_str(author_email, lower=True), store.norm_str(author_name), text), ).fetchone() return self._serialize(row) def update_comment( self, *, comment_id: int, requester: str, is_admin: bool, body: str ) -> dict[str, Any]: text = store.norm_str(body) if not text: raise ValueError("댓글 내용이 비었습니다.") with self._pool.connection() as conn: row = conn.execute( "SELECT author_email FROM task_comments WHERE id = %s", (comment_id,) ).fetchone() if not row: raise KeyError(comment_id) if not is_admin and row["author_email"] != store.norm_str(requester, lower=True): raise PermissionError("본인 댓글만 수정할 수 있습니다.") out = conn.execute( "UPDATE task_comments SET body = %s WHERE id = %s RETURNING *", (text, comment_id), ).fetchone() return self._serialize(out) def delete_comment( self, *, comment_id: int, requester: str, is_admin: bool ) -> list[dict[str, Any]]: """댓글 삭제. 댓글에 딸린 첨부 행은 CASCADE 로 같이 지워지므로, 디스크 파일을 치울 수 있게 그 첨부(task_id, stored_name) 목록을 돌려준다.""" with self._pool.connection() as conn: with conn.transaction(): row = conn.execute( "SELECT author_email FROM task_comments WHERE id = %s", (comment_id,) ).fetchone() if not row: raise KeyError(comment_id) if not is_admin and row["author_email"] != store.norm_str(requester, lower=True): raise PermissionError("본인 댓글만 삭제할 수 있습니다.") files = conn.execute( "SELECT task_id, stored_name FROM task_attachments WHERE comment_id = %s", (comment_id,), ).fetchall() conn.execute("DELETE FROM task_comments WHERE id = %s", (comment_id,)) return [dict(f) for f in files] # ════════════════════════════════════════════════════════════ # 첨부 (task_attachments) — 메타만 저장. 파일은 라우터가 디스크 처리. # ════════════════════════════════════════════════════════════ def list_attachments(self, *, task_id: int) -> list[dict[str, Any]]: with self._pool.connection() as conn: rows = conn.execute( "SELECT * FROM task_attachments WHERE task_id = %s " "ORDER BY created_at DESC, id DESC", (task_id,), ).fetchall() return [self._serialize(r) for r in rows] def add_attachment( self, *, task_id: int, filename: str, stored_name: str, content_type: str, size_bytes: int, uploaded_by: str, comment_id: int | None = None, ) -> dict[str, Any]: with self._pool.connection() as conn: row = conn.execute( "INSERT INTO task_attachments " "(task_id, filename, stored_name, content_type, size_bytes, uploaded_by, comment_id) " "VALUES (%s,%s,%s,%s,%s,%s,%s) RETURNING *", (task_id, store.norm_str(filename), stored_name, store.norm_str(content_type), int(size_bytes), store.norm_str(uploaded_by, lower=True), comment_id), ).fetchone() return self._serialize(row) def get_attachment(self, *, attachment_id: int) -> dict[str, Any] | None: with self._pool.connection() as conn: row = conn.execute( "SELECT * FROM task_attachments WHERE id = %s", (attachment_id,) ).fetchone() return self._serialize(row) if row else None def delete_attachment(self, *, attachment_id: int) -> dict[str, Any]: """삭제 후 행(파일 경로 정리용 stored_name 포함)을 반환.""" with self._pool.connection() as conn: row = conn.execute( "DELETE FROM task_attachments WHERE id = %s RETURNING *", (attachment_id,) ).fetchone() if not row: raise KeyError(attachment_id) return self._serialize(row) # ════════════════════════════════════════════════════════════ # 단계 순서/이름 편집 # ════════════════════════════════════════════════════════════ def update_stage( self, *, stage_id: int, name: str | None = None, is_done_stage: bool | None = None, color: Any = ..., default_assignee_email: Any = ..., ) -> dict[str, Any]: """color·default_assignee_email 은 지정 안 함(기본 `...`)과 명시적으로 지우기(`None`/'')를 구분해야 해서 `is None` 이 아니라 `is not ...` 로 검사한다. 기본 담당자가 프로젝트 멤버인지는 라우터가 검사한다.""" sets: list[str] = [] params: list[Any] = [] if name is not None: nm = store.norm_str(name) if not nm: raise ValueError("단계 이름은 필수입니다.") sets.append("name = %s") params.append(nm) if is_done_stage is not None: sets.append("is_done_stage = %s") params.append(bool(is_done_stage)) if color is not ...: sets.append("color = %s") params.append(store.validate_stage_color(color)) if default_assignee_email is not ...: sets.append("default_assignee_email = %s") params.append(store.norm_str(default_assignee_email or "", lower=True)) if not sets: raise ValueError("변경할 내용이 없습니다.") params.append(stage_id) with self._pool.connection() as conn: row = conn.execute( f"UPDATE project_stages SET {', '.join(sets)} WHERE id = %s RETURNING *", params, ).fetchone() if not row: raise KeyError(stage_id) return self._serialize(row) def reorder_projects(self, *, ordered_ids: list[int]) -> None: """홈 화면 프로젝트 카드 드래그 순서 변경. 최상위 프로젝트(parent_id IS NULL)만 대상 — 서브프로젝트 정렬(부모 안에서의 순서)은 건드리지 않는다.""" # 순서 재배정은 전부 UPDATE 한 번으로 — unnest(...) WITH ORDINALITY 가 # 배열 순서(1부터)를 매겨준다. 예전엔 항목 수만큼 UPDATE 를 날렸다. with self._pool.connection() as conn: conn.execute( "UPDATE projects p SET sort_order = v.ord - 1 " "FROM unnest(%s::bigint[]) WITH ORDINALITY AS v(id, ord) " "WHERE p.id = v.id AND p.parent_id IS NULL", ([int(i) for i in ordered_ids],), ) def reorder_stages(self, *, project_id: int, ordered_ids: list[int]) -> None: """주어진 순서대로 sort_order 재배정. 해당 프로젝트 단계만 갱신.""" with self._pool.connection() as conn: conn.execute( "UPDATE project_stages s SET sort_order = v.ord - 1 " "FROM unnest(%s::bigint[]) WITH ORDINALITY AS v(id, ord) " "WHERE s.id = v.id AND s.project_id = %s", ([int(i) for i in ordered_ids], project_id), ) def reorder_tasks(self, *, stage_id: int, ordered_ids: list[int]) -> None: """보드 카드 드래그로 같은 세션 안에서 순서 바꾸기. sort_order 는 업무 생성 시 프로젝트 전체 기준으로 매겨지지만(다른 세션과 섞여도 무방 — 화면은 항상 세션으로 먼저 필터링한 뒤 이 값으로 정렬한다), 여기서는 이 세션 소속 업무만 골라 0부터 다시 매긴다.""" with self._pool.connection() as conn: conn.execute( "UPDATE tasks t SET sort_order = v.ord - 1 " "FROM unnest(%s::bigint[]) WITH ORDINALITY AS v(id, ord) " "WHERE t.id = v.id AND t.stage_id = %s", ([int(i) for i in ordered_ids], stage_id), ) # ════════════════════════════════════════════════════════════ # 알림센터 (project_notifications) # ════════════════════════════════════════════════════════════ def add_notification( self, *, recipient_email: str, actor_email: str = "", project_id: int | None = None, task_id: int | None = None, type: str = "", title: str = "", body: str = "", ) -> None: rcpt = store.norm_str(recipient_email, lower=True) if not rcpt: return # 본인이 본인에게 보내는 알림은 생략(아사나도 자기 행동은 알림 안 함) if rcpt == store.norm_str(actor_email, lower=True): return with self._pool.connection() as conn: conn.execute( "INSERT INTO project_notifications " "(recipient_email, actor_email, project_id, task_id, type, title, body) " "VALUES (%s,%s,%s,%s,%s,%s,%s)", (rcpt, store.norm_str(actor_email, lower=True), project_id, task_id, type, store.norm_str(title), store.norm_str(body)), ) def list_notifications( self, *, recipient_email: str, unread_only: bool = False, limit: int = 100 ) -> list[dict[str, Any]]: rcpt = store.norm_str(recipient_email, lower=True) clause = "WHERE recipient_email = %s" params: list[Any] = [rcpt] if unread_only: clause += " AND is_read = FALSE" params.append(int(limit)) with self._pool.connection() as conn: rows = conn.execute( f"SELECT * FROM project_notifications {clause} " "ORDER BY created_at DESC, id DESC LIMIT %s", params, ).fetchall() return [self._serialize(r) for r in rows] def count_unread(self, *, recipient_email: str) -> int: with self._pool.connection() as conn: row = conn.execute( "SELECT COUNT(*) AS n FROM project_notifications " "WHERE recipient_email = %s AND is_read = FALSE", (store.norm_str(recipient_email, lower=True),), ).fetchone() return int(row["n"] or 0) def mark_read(self, *, notification_id: int, recipient_email: str) -> None: with self._pool.connection() as conn: conn.execute( "UPDATE project_notifications SET is_read = TRUE " "WHERE id = %s AND recipient_email = %s", (notification_id, store.norm_str(recipient_email, lower=True)), ) def mark_all_read(self, *, recipient_email: str) -> int: with self._pool.connection() as conn: cur = conn.execute( "UPDATE project_notifications SET is_read = TRUE " "WHERE recipient_email = %s AND is_read = FALSE", (store.norm_str(recipient_email, lower=True),), ) return cur.rowcount or 0 # ════════════════════════════════════════════════════════════ # 멘션(@태그) — task_mentions # # 설명란/댓글에서 @로 지정된 사람. 수신함의 "나를 태그한 업무" 목록이 # 이걸 읽는다. 같은 자리(설명란=comment_id NULL, 또는 같은 댓글)에서 같은 # 사람을 두 번 저장하지 않는다(마이그레이션 006 의 UNIQUE 인덱스). # ════════════════════════════════════════════════════════════ def add_mentions( self, *, task_id: int, emails: list[str], actor_email: str = "", comment_id: int | None = None, source: str = "description", ) -> list[str]: """멘션을 기록하고 '이번에 새로 추가된' 이메일만 돌려준다(알림 대상).""" actor = store.norm_str(actor_email, lower=True) targets = [e for e in store.normalize_emails(emails) if e != actor] if not targets: return [] added: list[str] = [] with self._pool.connection() as conn: for email in targets: cur = conn.execute( "INSERT INTO task_mentions " "(task_id, comment_id, mentioned_email, actor_email, source) " "VALUES (%s,%s,%s,%s,%s) ON CONFLICT DO NOTHING", (task_id, comment_id, email, actor, source), ) if cur.rowcount: added.append(email) return added def list_mentioned_tasks( self, *, mentioned_email: str, limit: int = 100 ) -> list[dict[str, Any]]: """내가 태그된 업무 목록(업무 1건당 1행, 가장 최근 태그 기준 정렬).""" email = store.norm_str(mentioned_email, lower=True) with self._pool.connection() as conn: rows = conn.execute( """ SELECT t.*, p.name AS project_name, p.color AS project_color, s.name AS stage_name, m.last_at AS mentioned_at, m.unread AS unread_mentions, m.last_actor AS mention_actor FROM ( SELECT task_id, MAX(created_at) AS last_at, COUNT(*) FILTER (WHERE NOT is_read) AS unread, (ARRAY_AGG(actor_email ORDER BY created_at DESC))[1] AS last_actor FROM task_mentions WHERE mentioned_email = %s GROUP BY task_id ) m JOIN tasks t ON t.id = m.task_id JOIN projects p ON p.id = t.project_id LEFT JOIN project_stages s ON s.id = t.stage_id ORDER BY m.last_at DESC LIMIT %s """, (email, int(limit)), ).fetchall() return [self._serialize(r) for r in rows] def count_unread_mentions(self, *, mentioned_email: str) -> int: with self._pool.connection() as conn: row = conn.execute( "SELECT COUNT(*) AS n FROM task_mentions " "WHERE mentioned_email = %s AND is_read = FALSE", (store.norm_str(mentioned_email, lower=True),), ).fetchone() return int(row["n"] or 0) def mark_mentions_read( self, *, mentioned_email: str, task_id: int | None = None ) -> int: clause = "WHERE mentioned_email = %s AND is_read = FALSE" params: list[Any] = [store.norm_str(mentioned_email, lower=True)] if task_id is not None: clause += " AND task_id = %s" params.append(task_id) with self._pool.connection() as conn: cur = conn.execute( f"UPDATE task_mentions SET is_read = TRUE {clause}", params ) 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 # ════════════════════════════════════════════════════════════ # 실시간 새로고침 — 프로젝트/업무/댓글/멤버/단계 중 가장 최근 변경 시각 # ════════════════════════════════════════════════════════════ def latest_version(self) -> str: """열어둔 화면이 8초마다 묻는 "뭔가 바뀌었나" 값. 마이그레이션 007 이 있으면 트리거가 올려주는 카운터 한 줄(PK)만 읽는다 — 삭제·세션 이름변경·첨부 추가까지 감지된다. 없으면 예전 MAX() 방식. """ if time.monotonic() >= self._live_retry_at: try: with self._pool.connection() as conn: row = conn.execute( "SELECT version FROM project_live_version WHERE id = 1" ).fetchone() return f"v{row['version']}" if row else "" except psycopg_errors.UndefinedTable: # 5분 뒤 다시 시도 — 재기동 없이 마이그레이션을 적용해도 따라간다. logger.warning("project_live_version 없음 — project_db_007 마이그레이션 적용 필요(MAX 방식으로 폴백)") self._live_retry_at = time.monotonic() + 300 with self._pool.connection() as conn: row = conn.execute( "SELECT GREATEST(" " COALESCE((SELECT MAX(updated_at) FROM projects), 'epoch'::timestamptz)," " COALESCE((SELECT MAX(updated_at) FROM tasks), 'epoch'::timestamptz)," " COALESCE((SELECT MAX(created_at) FROM task_comments), 'epoch'::timestamptz)," " COALESCE((SELECT MAX(created_at) FROM project_members), 'epoch'::timestamptz)," " COALESCE((SELECT MAX(created_at) FROM project_stages), 'epoch'::timestamptz)," " COALESCE((SELECT MAX(created_at) FROM task_mentions), 'epoch'::timestamptz)" ") AS ts" ).fetchone() ts = row["ts"] if row else None return ts.isoformat() if ts else "" # ════════════════════════════════════════════════════════════ # 직렬화 # ════════════════════════════════════════════════════════════ @staticmethod def _serialize(row: dict[str, Any] | None) -> dict[str, Any] | None: if row is None: return None out = dict(row) for k, v in list(out.items()): if isinstance(v, datetime): out[k] = v.astimezone(KST).isoformat(timespec="seconds") elif isinstance(v, dtime): out[k] = v.strftime("%H:%M") elif isinstance(v, date): out[k] = v.isoformat() for k in ("id", "parent_id", "project_id", "stage_id", "task_id", "sort_order", "parent_task_id"): if k in out and out[k] is not None: try: out[k] = int(out[k]) except (TypeError, ValueError): pass for k in ("is_done_stage", "is_read"): if k in out and out[k] is not None: out[k] = bool(out[k]) return out