"""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 hashlib import logging import re import secrets import time import uuid from datetime import date, datetime, timedelta 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() @property def pool(self) -> Any: """같은 project_db 를 쓰는 다른 저장소(긴급 공지 — app/modules/notice)가 연결 풀을 같이 쓴다.""" return self._pool # ════════════════════════════════════════════════════════════ # 프로젝트 / 서브프로젝트 # ════════════════════════════════════════════════════════════ 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, icon: str | None = None, member_emails: list[str] | None = None, ) -> dict[str, Any]: """member_emails — 만들면서 같이 넣을 멤버(같은 트랜잭션). 남을 소유자로 지정해 만든 사람이 만든 직후 자기 프로젝트를 못 여는 일이 없게 라우터가 만든 사람을 넣는다(일반 멤버 — 나중에 뺄 수 있다).""" nm = store.validate_project_name(name) col = store.validate_color(color) ic = store.validate_project_icon(icon) sd = store.validate_date(start_date) dd = store.validate_date(due_date) store.validate_date_range(sd, dd) 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}") # 아이콘을 고른 경우에만 icon 컬럼을 쓴다 — 마이그레이션 011 전에도 # 아이콘 없이 만드는 건 예전처럼 된다. cols = ["parent_id", "name", "description", "color", "owner_email", "start_date", "due_date", "created_by"] vals: list[Any] = [ parent_id, nm, store.norm_str(description), col, store.norm_str(owner_email, lower=True), sd, dd, store.norm_str(created_by, lower=True), ] if ic: cols.append("icon") vals.append(ic) row = conn.execute( f"INSERT INTO projects ({', '.join(cols)}) " f"VALUES ({', '.join(['%s'] * len(cols))}) RETURNING *", vals, ).fetchone() pid = row["id"] for em in store.normalize_emails(member_emails or []): conn.execute( "INSERT INTO project_members (project_id, user_email, user_name, role) " "VALUES (%s,%s,'','member') ON CONFLICT (project_id, user_email) DO NOTHING", (pid, em), ) 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), "icon": lambda v: store.validate_project_icon(v), # 마이그레이션 011 "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] = [] clean: dict[str, Any] = {} for key, fn in allowed.items(): if key in fields: clean[key] = fn(fields[key]) sets.append(f"{key} = %s") params.append(clean[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: with conn.transaction(): if "start_date" in clean or "due_date" in clean: # 한쪽만 바꿔도 기존 값과 합친 최종 상태로 검사한다 — 그 행을 잠근 뒤 읽어서(FOR UPDATE) # 두 사람이 시작일·마감일을 동시에 바꿔도 각자 옛 값으로 검사해 역전되지 않게. existing = conn.execute( "SELECT start_date, due_date FROM projects WHERE id = %s FOR UPDATE", (project_id,) ).fetchone() if existing is None: raise KeyError(project_id) existing = self._serialize(existing) store.validate_date_range( clean["start_date"] if "start_date" in clean else existing.get("start_date"), clean["due_date"] if "due_date" in clean else existing.get("due_date"), ) 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, allowed: Any = None) -> tuple[str, str]: """세션 기본 담당자(마이그레이션 009) → (email, name). 미지정·009 미적용· 그 사람이 이제 프로젝트 멤버가 아니면 ('', ''). allowed(email) 가 있으면 그것도 통과해야 한다 — 삭제된 사용자·project 모듈 권한을 잃은 사람에게 자동 배정(과 배정 알림)이 가지 않게(라우터가 넘김). 컬럼이 없어도 에러가 나지 않게 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 "", "" if allowed is not None and not allowed(email): return "", "" return email, m["user_name"] or "" @staticmethod def _stage_is_done_conn(conn: Any, stage_id: Any) -> bool: if stage_id is None: return False row = conn.execute("SELECT is_done_stage FROM project_stages WHERE id = %s", (stage_id,)).fetchone() return bool(row and row["is_done_stage"]) @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_subtasks_of(self, *, parent_ids: list[int]) -> list[dict[str, Any]]: """세부 업무 요약(대시보드 담당자별 집계·업무 목록 패널용) — id·부모·제목·마감일·완료·담당자. 세부 업무의 세부 업무까지 모든 단계(2026-10-08) — root_task_id = 맨 위 메인 업무(parent_ids 중 하나), parent_title = 바로 위 업무 제목(목록 패널 "상위:" 표시). 깊이 20 단계에서 멈춘다(잘못된 순환 방어).""" ids = sorted({int(i) for i in parent_ids}) if not ids: return [] with self._pool.connection() as conn: rows = conn.execute( "WITH RECURSIVE sub AS (" " SELECT t.id, t.parent_task_id, t.parent_task_id AS root_task_id, 1 AS depth" " FROM tasks t WHERE t.parent_task_id = ANY(%s)" " UNION ALL" " SELECT c.id, c.parent_task_id, s.root_task_id, s.depth + 1" " FROM tasks c JOIN sub s ON c.parent_task_id = s.id WHERE s.depth < 20" ") " "SELECT DISTINCT ON (t.id) t.id, t.parent_task_id, s.root_task_id, s.depth, t.title, t.due_date, t.completed_at," " t.assignee_email, t.assignee_name, p.title AS parent_title " "FROM sub s JOIN tasks t ON t.id = s.id LEFT JOIN tasks p ON p.id = t.parent_task_id " "ORDER BY t.id, s.depth", (ids,), ).fetchall() return [{"id": int(r["id"]), "parent_task_id": int(r["parent_task_id"]), "root_task_id": int(r["root_task_id"]), "depth": int(r["depth"]), "parent_title": r["parent_title"] or "", "title": r["title"] or "", "due_date": r["due_date"].isoformat() if r["due_date"] else None, "completed_at": r["completed_at"].isoformat() if r["completed_at"] else None, "assignee_email": r["assignee_email"] or "", "assignee_name": r["assignee_name"] or "", "done": r["completed_at"] is not None} for r in rows] 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, completed_limit: int = 1000) -> list[dict[str, Any]]: """"내 업무" 화면 전용 — 내가 담당자인 업무를 레벨(최상위/하위) 상관없이 반환한다. 세부 업무 행에는 부모 업무 정보(`parent_title` 등)를 같이 붙여서, 부모가 내 업무가 아니어도 (다른 사람 담당) 화면에서 트리로 묶어 보여줄 수 있게 한다. 미완료는 **전부**, 완료는 최근에 완료한 completed_limit 건까지 — 예전엔 전체를 1000건에서 잘라 오래된 완료 업무가 새 미완료 업무를 목록 밖으로 밀어낼 수 있었다. """ 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 " " AND (t.completed_at IS NULL OR t.id IN (" " SELECT d.id FROM tasks d WHERE d.assignee_email = %s AND d.completed_at IS NOT NULL " " ORDER BY d.completed_at DESC, d.id DESC LIMIT %s)) " "ORDER BY t.sort_order ASC, t.id ASC", (email, email, int(completed_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, assignee_allowed: Any = None, ) -> dict[str, Any]: """assignee_allowed — update_task 와 같이 섹션 기본 담당자 자동 배정 전 지금 권한 확인(라우터가 넘김).""" 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) store.validate_date_range(sd, dd, sti, dti) assignee = store.norm_str(assignee_email, lower=True) done_at = None 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, allowed=assignee_allowed) # 완료 섹션에 바로 만든 작업은 완료 섹션으로 옮긴 것과 같이 완료 처리(완료 시각·이력). if stage_id is not None: done_row = conn.execute( "SELECT is_done_stage FROM project_stages WHERE id = %s", (stage_id,) ).fetchone() if done_row and done_row["is_done_stage"]: done_at = now_kst() 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, completed_at) VALUES (%s,%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), done_at, ), ).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}") if done_at is not None: self._log(conn, project_id=project_id, task_id=row["id"], actor=created_by, action=store.ACTION_COMPLETED, detail=ttl) out = self.get_task(task_id=row["id"]) out["_newly_completed"] = done_at is not None return out def move_subtask( self, *, task_id: int, parent_task_id: int, actor: str = "" ) -> dict[str, Any]: """세부 업무를 다른 상위 업무 밑으로 옮긴다(보드 카드로 드래그). 받는 쪽은 보드 카드 = 최상위 업무만 허용한다 — 그래서 자기 자신이나 자기 하위로 옮기는 순환이 생기지 않는다. 같은 프로젝트 안에서만 (세부 업무는 부모와 같은 프로젝트에 속한다 — create_task 와 같은 규칙). 세부 업무의 세부 업무는 그대로 따라간다. 목록 끝(sort_order 최대+1)으로. """ with self._pool.connection() as conn: with conn.transaction(): sub = conn.execute( "SELECT id, project_id, parent_task_id, title FROM tasks " "WHERE id = %s FOR UPDATE", (task_id,), ).fetchone() if not sub: raise KeyError(f"작업을 찾을 수 없습니다: {task_id}") if sub["parent_task_id"] is None: raise ValueError("세부 작업만 다른 작업으로 옮길 수 있습니다.") parent = conn.execute( "SELECT id, project_id, parent_task_id, title FROM tasks WHERE id = %s", (parent_task_id,), ).fetchone() if not parent: raise KeyError(f"상위 작업을 찾을 수 없습니다: {parent_task_id}") if parent["parent_task_id"] is not None: raise ValueError("세부 작업 안으로는 옮길 수 없습니다.") if int(parent["project_id"]) != int(sub["project_id"]): raise ValueError("다른 프로젝트의 작업으로는 옮길 수 없습니다.") if int(parent["id"]) != int(sub["parent_task_id"]): nxt = conn.execute( "SELECT COALESCE(MAX(sort_order), -1) + 1 AS n FROM tasks " "WHERE project_id = %s", (sub["project_id"],), ).fetchone() conn.execute( "UPDATE tasks SET parent_task_id = %s, sort_order = %s WHERE id = %s", (parent["id"], int(nxt["n"]), task_id), ) self._log(conn, project_id=sub["project_id"], task_id=task_id, actor=actor, action=store.ACTION_SUBTASK_MOVED, detail=f"{sub['title']} → {parent['title']}") return self.get_task(task_id=task_id) def update_task( self, *, task_id: int, fields: dict[str, Any], actor: str = "", assignee_allowed: Any = None, ) -> dict[str, Any]: """업무 수정. 반환에 알림 힌트를 담는다(라우터가 메일 발송 판단). 반환 dict 에 추가되는 키: _newly_assigned: 새 담당자 이메일 or None _newly_completed: 완료로 전환됐으면 True 동시성 — 기존 값 읽기·최종 날짜 검사·변경·이력을 **한 트랜잭션에서 그 작업 행을 잠그고** (SELECT … FOR UPDATE) 한다. 두 사람이 시작일·마감일을 동시에 바꿔도 각자 옛 값으로 검사해 날짜가 역전되지 않고, 동시에 완료해도 완료 이력·알림 힌트는 실제로 완료로 바뀐 한 요청에서만 생긴다. 섹션 확인·기본 담당자·완료 섹션 여부도 같은 연결로 읽는다(다른 연결을 다시 빌리지 않는다). assignee_allowed(email) — 섹션 기본 담당자를 자동 배정하기 전에 그 사람이 지금 등록된 project 권한 사용자인지(사용자 목록은 DB 밖이라 라우터가 넘긴다). 없으면 멤버·owner 여부만 본다. """ # 형식 검사는 잠그기 전에(잠금을 짧게) — 값이 틀리면 DB 에 가지 않는다. clean: dict[str, Any] = {} if "title" in fields: clean["title"] = store.validate_task_title(fields["title"]) if "description" in fields: clean["description"] = store.norm_str(fields["description"]) if "priority" in fields: clean["priority"] = store.validate_priority(fields["priority"]) for k in ("start_date", "due_date"): if k in fields: clean[k] = store.validate_date(fields[k]) for k in ("start_time", "due_time"): if k in fields: clean[k] = store.validate_time(fields[k]) newly_assigned: str | None = None newly_completed = False with self._pool.connection() as conn: with conn.transaction(): row = conn.execute("SELECT * FROM tasks WHERE id = %s FOR UPDATE", (task_id,)).fetchone() if row is None: raise KeyError(task_id) prev = self._serialize(row) sets: list[str] = [] params: list[Any] = [] for k in ("title", "description", "priority", "start_date", "due_date", "start_time", "due_time"): if k in clean: sets.append(f"{k} = %s") params.append(clean[k]) assignee_fields = {k: fields[k] for k in ("assignee_email", "assignee_name") if k in fields} new_stage: Any = None if "stage_id" in fields: new_stage = self._check_stage_in_project(conn, fields["stage_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: dae, dan = self._stage_default_assignee(conn, new_stage, prev["project_id"], allowed=assignee_allowed) if dae: assignee_fields = {"assignee_email": dae, "assignee_name": dan} if "assignee_email" in assignee_fields: new_assignee = store.norm_str(assignee_fields["assignee_email"], lower=True) sets.append("assignee_email = %s") params.append(new_assignee) if "assignee_name" in assignee_fields: sets.append("assignee_name = %s") params.append(store.norm_str(assignee_fields["assignee_name"])) if new_assignee and new_assignee != (prev.get("assignee_email") or ""): newly_assigned = new_assignee elif "assignee_name" in assignee_fields: sets.append("assignee_name = %s") params.append(store.norm_str(assignee_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_conn(conn, 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: changed = False else: changed = True # 날짜 범위 — 한쪽만 바꾸거나 지워도 (잠근) 기존 값과 합친 최종 상태로 검사. if any(k in clean for k in ("start_date", "due_date", "start_time", "due_time")): def final(key: str) -> Any: return clean[key] if key in clean else prev.get(key) store.validate_date_range(final("start_date"), final("due_date"), final("start_time"), final("due_time")) conn.execute(f"UPDATE tasks SET {', '.join(sets)} WHERE id = %s", (*params, task_id)) 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) if out is None: raise KeyError(task_id) out["_newly_assigned"] = newly_assigned if changed else None out["_newly_completed"] = newly_completed if changed else False return out # ════════════════════════════════════════════════════════════ # 휴지통 (마이그레이션 010) — 지우기 직전 스냅샷, 관리자 복구, 3개월 보관 # ════════════════════════════════════════════════════════════ # 업무에 딸린 테이블(task_id 로 묶임). 복구 때 이 순서대로 다시 넣는다 — # task_mentions·task_attachments 의 comment_id 가 댓글을 가리키므로 댓글 먼저. # 알림(project_notifications)은 되살리면 수신함에 옛 알림이 다시 쌓여 제외. TRASH_CHILD_TABLES = ( "task_comments", "task_comment_reactions", "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} # ════════════════════════════════════════════════════════════ # 멀티호밍 (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 comment_features(self) -> dict[str, bool]: """답글(parent_id)·반응 테이블이 있는지(마이그레이션 012). 한 번 켜지면 기억.""" cached = getattr(self, "_comment_features", None) if cached and cached["replies"] and cached["reactions"]: return cached with self._pool.connection() as conn: col = conn.execute( "SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' " "AND table_name = 'task_comments' AND column_name = 'parent_id'" ).fetchone() feats = { "replies": bool(col), "reactions": self._table_exists(conn, "task_comment_reactions"), } self._comment_features = feats return feats def list_comments(self, *, task_id: int) -> list[dict[str, Any]]: """댓글(작성순). 012 가 있으면 각 댓글에 reactions=[{emoji, users}] 를 붙인다.""" feats = self.comment_features() 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() reacts: list[dict[str, Any]] = [] if feats["reactions"]: reacts = conn.execute( "SELECT comment_id, emoji, array_agg(user_email ORDER BY created_at) AS users " "FROM task_comment_reactions WHERE task_id = %s " "GROUP BY comment_id, emoji ORDER BY MIN(created_at)", (task_id,), ).fetchall() by_comment: dict[int, list[dict[str, Any]]] = {} for r in reacts: by_comment.setdefault(int(r["comment_id"]), []).append( {"emoji": r["emoji"], "users": list(r["users"] or [])} ) out = [] for r in rows: c = self._serialize(r) c.setdefault("parent_id", None) c["reactions"] = by_comment.get(int(c["id"]), []) out.append(c) return out def list_completion_events(self, *, task_id: int) -> list[dict[str, Any]]: """이 작업의 '완료' 이력 — 댓글 목록에 "OO 님이 이 작업을 완료했습니다"로 끼워 보인다.""" with self._pool.connection() as conn: rows = conn.execute( "SELECT actor_email, created_at FROM project_activity " "WHERE task_id = %s AND action = %s ORDER BY created_at ASC, id ASC", (task_id, store.ACTION_COMPLETED), ).fetchall() return [self._serialize(r) for r in rows] def toggle_reaction( self, *, comment_id: int, user_email: str, emoji: str ) -> list[dict[str, Any]]: """반응 켜기/끄기 → 그 댓글의 반응 목록. 댓글이 없으면 KeyError.""" email = store.norm_str(user_email, lower=True) with self._pool.connection() as conn: with conn.transaction(): c = conn.execute( "SELECT task_id FROM task_comments WHERE id = %s", (comment_id,) ).fetchone() if not c: raise KeyError(comment_id) gone = conn.execute( "DELETE FROM task_comment_reactions " "WHERE comment_id = %s AND user_email = %s AND emoji = %s RETURNING 1", (comment_id, email, emoji), ).fetchone() if not gone: conn.execute( "INSERT INTO task_comment_reactions (comment_id, task_id, user_email, emoji) " "VALUES (%s,%s,%s,%s) ON CONFLICT DO NOTHING", (comment_id, c["task_id"], email, emoji), ) rows = conn.execute( "SELECT emoji, array_agg(user_email ORDER BY created_at) AS users " "FROM task_comment_reactions WHERE comment_id = %s " "GROUP BY emoji ORDER BY MIN(created_at)", (comment_id,), ).fetchall() return [{"emoji": r["emoji"], "users": list(r["users"] or [])} 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, parent_id: int | None = None, ) -> dict[str, Any]: """allow_empty — 채팅 팝업에서 파일/이미지만 보내는 메시지(본문 없음)를 허용할 때 True. 일반 댓글 입력은 여전히 빈 값을 막는다. parent_id — 답글(012). 같은 작업의 댓글이어야 하고, 답글에 단 답글은 원 댓글에 붙인다(한 단계). 없는 댓글이면 ValueError.""" text = store.norm_str(body) if not text and not allow_empty: raise ValueError("댓글 내용이 비었습니다.") with self._pool.connection() as conn: if parent_id: p = conn.execute( "SELECT id, task_id, parent_id FROM task_comments WHERE id = %s", (parent_id,) ).fetchone() if not p or int(p["task_id"]) != int(task_id): raise ValueError("답글을 달 댓글을 찾을 수 없습니다.") root = int(p["parent_id"] or p["id"]) row = conn.execute( "INSERT INTO task_comments (task_id, author_email, author_name, body, parent_id) " "VALUES (%s,%s,%s,%s,%s) RETURNING *", (task_id, store.norm_str(author_email, lower=True), store.norm_str(author_name), text, root), ).fetchone() else: 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 add_comment_with_attachments( self, *, task_id: int, author_email: str, author_name: str, body: str, files: list[dict[str, Any]], parent_id: int | None = None, ) -> tuple[dict[str, Any], list[dict[str, Any]]]: """댓글과 첨부를 한 트랜잭션에 — 둘 중 하나라도 실패하면 아무것도 남지 않는다 (첨부 없이 빈 댓글만 남던 문제). files = [{filename, stored_name, content_type, size_bytes}]. 본문이 비어도 되지만 첨부가 한 개 이상 있어야 한다.""" text = store.norm_str(body) if not files and not text: raise ValueError("댓글 내용이 비었습니다.") author = store.norm_str(author_email, lower=True) with self._pool.connection() as conn: with conn.transaction(): root = None if parent_id: p = conn.execute( "SELECT id, task_id, parent_id FROM task_comments WHERE id = %s", (parent_id,) ).fetchone() if not p or int(p["task_id"]) != int(task_id): raise ValueError("답글을 달 댓글을 찾을 수 없습니다.") root = int(p["parent_id"] or p["id"]) if root is not None: row = conn.execute( "INSERT INTO task_comments (task_id, author_email, author_name, body, parent_id) " "VALUES (%s,%s,%s,%s,%s) RETURNING *", (task_id, author, store.norm_str(author_name), text, root), ).fetchone() else: row = conn.execute( "INSERT INTO task_comments (task_id, author_email, author_name, body) " "VALUES (%s,%s,%s,%s) RETURNING *", (task_id, author, store.norm_str(author_name), text), ).fetchone() atts = [] for f in files: atts.append(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(f["filename"]), f["stored_name"], store.norm_str(f.get("content_type") or "application/octet-stream"), int(f["size_bytes"]), author, row["id"]), ).fetchone()) return self._serialize(row), [self._serialize(a) for a in atts] 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("본인 댓글만 삭제할 수 있습니다.") # 답글(012)도 CASCADE 로 같이 지워지므로 답글의 첨부 파일도 모은다. reply_clause = ( " OR comment_id IN (SELECT id FROM task_comments WHERE parent_id = %s)" if self.comment_features()["replies"] else "" ) files = conn.execute( "SELECT task_id, stored_name FROM task_attachments WHERE comment_id = %s" + reply_clause, (comment_id, comment_id) if reply_clause else (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), ) def reorder_subtasks(self, *, parent_task_id: int, ordered_ids: list[int]) -> None: """작업 팝업의 세부 작업 목록 드래그 재정렬 — 이 상위 작업의 세부 작업만 0부터 다시 매긴다(목록은 parent_task_id 로 먼저 거른 뒤 sort_order 순).""" 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.parent_task_id = %s", ([int(i) for i in ordered_ids], parent_task_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 list_unread_after( self, *, recipient_email: str, after_id: int, types: tuple[str, ...], limit: int = 200, ) -> list[dict[str, Any]]: """큰 팝업 알림 후보 — 이 사람·읽지 않음·종류·id > after_id 를 DB 에서 먼저 걸러 **오래된 것(id)부터**. 라우터가 지금 볼 수 있는 것만 남기며 마지막 id 를 다음 after_id 로 넘겨 끝까지 읽는다.""" with self._pool.connection() as conn: rows = conn.execute( "SELECT * FROM project_notifications " "WHERE recipient_email = %s AND is_read = FALSE AND id > %s AND type = ANY(%s) " "ORDER BY id ASC LIMIT %s", (store.norm_str(recipient_email, lower=True), int(after_id), list(types), int(limit)), ).fetchall() return [self._serialize(r) for r in rows] def list_unread_refs(self, *, recipient_email: str) -> list[dict[str, Any]]: """읽지 않은 알림 전부의 (id, project_id, task_id) — 수신함 배지를 개수 제한 없이 정확히 세려고 가벼운 열만 읽는다(지금 권한 거르기는 라우터).""" with self._pool.connection() as conn: rows = conn.execute( "SELECT id, project_id, task_id FROM project_notifications " "WHERE recipient_email = %s AND is_read = FALSE", (store.norm_str(recipient_email, lower=True),), ).fetchall() return [dict(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 # ════════════════════════════════════════════════════════════ # PC 알림 프로그램 연결(023) — notifier_links → notifier_tokens. 원문은 저장하지 않고 SHA-256 만. # ════════════════════════════════════════════════════════════ NOTIFIER_LINK_TTL_MIN = 10 NOTIFIER_MAX_PENDING = 200 # 로그인 없이 부르는 연결 요청이 쌓이지 않게(만료 전 대기 건 상한) _CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" # 헷갈리는 0·O·1·I 제외 @staticmethod def _sha(value: str) -> str: return hashlib.sha256(value.encode("utf-8")).hexdigest() def notifier_enabled(self) -> bool: with self._pool.connection() as conn: return self._table_exists(conn, "notifier_tokens") def notifier_start_link(self, *, device_name: str) -> dict[str, Any]: """연결 요청 — 화면 코드와 poll 비밀값(원문은 여기서만 돌려준다).""" poll = secrets.token_urlsafe(32) with self._pool.connection() as conn: with conn.transaction(): conn.execute("DELETE FROM notifier_links WHERE expires_at < now() - interval '1 day'") row = conn.execute("SELECT count(*) AS n FROM notifier_links WHERE expires_at > now() AND approved_at IS NULL").fetchone() if int(row["n"]) >= self.NOTIFIER_MAX_PENDING: raise OverflowError("연결 요청이 너무 많습니다. 잠시 뒤 다시 시도하세요.") for _ in range(5): raw = "".join(secrets.choice(self._CODE_ALPHABET) for _ in range(8)) code = raw[:4] + "-" + raw[4:] hit = conn.execute( "INSERT INTO notifier_links (code, poll_hash, device_name, expires_at) " "VALUES (%s, %s, %s, now() + make_interval(mins => %s)) ON CONFLICT (code) DO NOTHING RETURNING id", (code, self._sha(poll), device_name[:80], self.NOTIFIER_LINK_TTL_MIN), ).fetchone() if hit: return {"code": code, "poll": poll, "expires_in": self.NOTIFIER_LINK_TTL_MIN * 60} raise RuntimeError("연결 코드를 만들지 못했습니다.") def notifier_get_link(self, *, code: str) -> dict[str, Any] | None: """승인 화면용 — 아직 유효한(만료 전·토큰 미발급) 요청만.""" with self._pool.connection() as conn: row = conn.execute( "SELECT code, device_name, email, approved_at, expires_at FROM notifier_links " "WHERE code = %s AND expires_at > now() AND consumed_at IS NULL", (store.norm_str(code).upper(),), ).fetchone() return self._serialize(row) if row else None def notifier_approve_link(self, *, code: str, email: str) -> bool: """[연결] — 아직 아무도 승인하지 않은 유효한 요청만 이 사용자로 승인.""" with self._pool.connection() as conn: cur = conn.execute( "UPDATE notifier_links SET email = %s, approved_at = now() " "WHERE code = %s AND expires_at > now() AND approved_at IS NULL AND consumed_at IS NULL", (store.norm_str(email, lower=True), store.norm_str(code).upper()), ) return bool(cur.rowcount) def notifier_poll_link(self, *, poll: str) -> dict[str, Any]: """프로그램의 확인 — 승인됐으면 토큰을 한 번만 발급. {"status": pending|expired|ok, ...}""" with self._pool.connection() as conn: with conn.transaction(): row = conn.execute( "SELECT id, email, device_name, approved_at, consumed_at, expires_at > now() AS alive " "FROM notifier_links WHERE poll_hash = %s FOR UPDATE", (self._sha(poll),), ).fetchone() if not row or row["consumed_at"] or not row["alive"]: return {"status": "expired"} if not row["approved_at"]: return {"status": "pending"} token = secrets.token_urlsafe(32) conn.execute("UPDATE notifier_links SET consumed_at = now() WHERE id = %s", (row["id"],)) conn.execute( "INSERT INTO notifier_tokens (email, token_hash, device_name) VALUES (%s, %s, %s)", (row["email"], self._sha(token), row["device_name"]), ) return {"status": "ok", "token": token, "email": row["email"]} def notifier_token_email(self, *, token: str) -> str | None: """토큰 → 사용자 이메일(해제된 토큰은 None). 마지막 접속 시각은 1분에 한 번만 갱신.""" if not token: return None with self._pool.connection() as conn: row = conn.execute( "UPDATE notifier_tokens SET last_seen_at = now() " "WHERE token_hash = %s AND revoked_at IS NULL " "AND (last_seen_at IS NULL OR last_seen_at < now() - interval '1 minute') RETURNING email", (self._sha(token),), ).fetchone() if row is None: row = conn.execute( "SELECT email FROM notifier_tokens WHERE token_hash = %s AND revoked_at IS NULL", (self._sha(token),), ).fetchone() return row["email"] if row else None def notifier_active(self, *, email: str, within_sec: int = 180) -> bool: """이 사용자의 PC 알림 프로그램이 지금 돌고 있나 — 해제 안 된 토큰 중 최근(기본 3분) 확인한 것이 있으면 True. 프로그램은 20초마다 확인하고 last_seen_at 은 1분에 한 번 갱신되므로 3분이면 꺼진 PC 는 곧 빠진다. 023 미적용이면 False.""" try: with self._pool.connection() as conn: row = conn.execute( "SELECT 1 FROM notifier_tokens WHERE email = %s AND revoked_at IS NULL " "AND last_seen_at > now() - make_interval(secs => %s) LIMIT 1", (store.norm_str(email, lower=True), within_sec), ).fetchone() except psycopg_errors.UndefinedTable: return False return row is not None def notifier_revoke_token(self, *, token: str) -> None: with self._pool.connection() as conn: conn.execute("UPDATE notifier_tokens SET revoked_at = now() WHERE token_hash = %s AND revoked_at IS NULL", (self._sha(token),)) def notifier_list_devices(self, *, email: str) -> list[dict[str, Any]]: with self._pool.connection() as conn: rows = conn.execute( "SELECT id, device_name, created_at, last_seen_at FROM notifier_tokens " "WHERE email = %s AND revoked_at IS NULL ORDER BY created_at DESC", (store.norm_str(email, lower=True),), ).fetchall() return [self._serialize(r) for r in rows] def notifier_revoke_device(self, *, device_id: int, email: str) -> bool: with self._pool.connection() as conn: cur = conn.execute( "UPDATE notifier_tokens SET revoked_at = now() WHERE id = %s AND email = %s AND revoked_at IS NULL", (device_id, store.norm_str(email, lower=True)), ) return bool(cur.rowcount) # ════════════════════════════════════════════════════════════ # 멘션(@태그) — 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 list_unread_mention_refs(self, *, mentioned_email: str) -> list[dict[str, Any]]: """미확인 태그가 있는 작업마다 (id, project_id, unread_mentions) — 배지를 제한 없이 세는 가벼운 조회.""" with self._pool.connection() as conn: rows = conn.execute( "SELECT t.id, t.project_id, m.unread AS unread_mentions " "FROM (SELECT task_id, COUNT(*) AS unread FROM task_mentions " " WHERE mentioned_email = %s AND is_read = FALSE GROUP BY task_id) m " "JOIN tasks t ON t.id = m.task_id", (store.norm_str(mentioned_email, lower=True),), ).fetchall() return [dict(r) for r in rows] def list_my_open_refs(self, *, assignee_email: str) -> list[dict[str, Any]]: """내가 담당인 미완료 작업 전부의 (id, project_id) — "내 작업" 배지를 제한 없이 정확히 센다.""" with self._pool.connection() as conn: rows = conn.execute( "SELECT id, project_id FROM tasks WHERE assignee_email = %s AND completed_at IS NULL", (store.norm_str(assignee_email, lower=True),), ).fetchall() return [dict(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 add_reminder_notification( self, *, task_id: int, kind: str, due_date: str, recipient_email: str, project_id: int | None, title: str, body: str, ) -> bool: """마감 알림 발송 기록 + 수신함 알림을 한 트랜잭션에. 처음이면 둘 다 넣고 True, 이미 보냈으면(UNIQUE) False. 알림 생성이 실패하면 발송 기록도 되돌려져 다음 실행에서 다시 시도된다(예전엔 기록만 남아 영영 안 갔다). 동시에 두 번 돌아도 UNIQUE 로 한 번만.""" rcpt = store.norm_str(recipient_email, lower=True) with self._pool.connection() as conn: with conn.transaction(): 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, rcpt), ).fetchone() if row is None: return False conn.execute( "INSERT INTO project_notifications " "(recipient_email, actor_email, project_id, task_id, type, title, body) " "VALUES (%s,'',%s,%s,%s,%s,%s)", (rcpt, project_id, task_id, kind, store.norm_str(title), store.norm_str(body)), ) return True def task_link_scope(self, *, task_ids: list[int]) -> dict[int, set[int]]: """작업 id → 이 작업 또는 그 상위 작업들이 연결(멀티호밍)된 프로젝트 id 집합. 연결된 프로젝트 멤버가 그 작업(과 세부 작업)을 읽기 전용으로 볼 수 있는지 판단한다.""" ids = sorted({int(i) for i in task_ids}) if not ids: return {} with self._pool.connection() as conn: rows = conn.execute( """ WITH RECURSIVE chain AS ( SELECT id AS task_id, id AS anc_id, parent_task_id, 0 AS depth FROM tasks WHERE id = ANY(%s) UNION ALL SELECT c.task_id, t.id, t.parent_task_id, c.depth + 1 FROM chain c JOIN tasks t ON t.id = c.parent_task_id WHERE c.depth < 20 ) SELECT c.task_id, l.project_id FROM chain c JOIN task_project_links l ON l.task_id = c.anc_id """, (ids,), ).fetchall() out: dict[int, set[int]] = {} for r in rows: out.setdefault(int(r["task_id"]), set()).add(int(r["project_id"])) return out 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 "" # ════════════════════════════════════════════════════════════ # 연간 목표 (마이그레이션 013) — 사이드바 "목표" → 연도 → 목표 표 # ════════════════════════════════════════════════════════════ def goals_enabled(self) -> bool: with self._pool.connection() as conn: return self._table_exists(conn, "goal_years") @staticmethod def _goal_quarters(conn: Any) -> bool: """마이그레이션 017(분기) 적용 여부 — goal_cells 월 칸 CHECK 가 16(4분기)까지 받는가.""" row = conn.execute( "SELECT pg_get_constraintdef(c.oid) AS d FROM pg_constraint c " "WHERE c.conname = 'goal_cells_month_check' AND c.conrelid = 'goal_cells'::regclass" ).fetchone() return bool(row) and "16" in str(row["d"]) def goals_halves_enabled(self) -> bool: """상·하반기 글 칸·월 칸 병합(마이그레이션 014) 적용 여부.""" with self._pool.connection() as conn: return self._table_exists(conn, "goal_cell_merges") def list_goal_years(self) -> list[int]: """목표를 만든 연도(최근 연도 먼저). 013 미적용이면 UndefinedTable.""" with self._pool.connection() as conn: rows = conn.execute("SELECT year FROM goal_years ORDER BY year DESC").fetchall() return [int(r["year"]) for r in rows] def create_goal_year(self, *, year: int, created_by: str = "") -> None: """연도 추가 — 가장 가까운 이전 연도(없으면 가장 가까운 다음 연도)의 업무 영역·줄 구조를 글 없이 복사한다. 목표를 둔 연도가 하나도 없으면 기본 영역(DEFAULT_GOAL_AREAS).""" y = store.validate_goal_year(year) with self._pool.connection() as conn: with conn.transaction(): row = conn.execute( "INSERT INTO goal_years (year, created_by) VALUES (%s, %s) " "ON CONFLICT (year) DO NOTHING RETURNING year", (y, store.norm_str(created_by, lower=True)), ).fetchone() if row is None: raise ValueError(f"{y}년 목표는 이미 있습니다.") src = conn.execute( "SELECT year FROM goal_years WHERE year <> %s " "ORDER BY (year > %s), abs(year - %s) LIMIT 1", (y, y, y), ).fetchone() if src: areas = conn.execute( "SELECT id, name, color, sort_order FROM goal_areas " "WHERE year = %s ORDER BY sort_order, id", (src["year"],), ).fetchall() plan = [] groups = self._column_exists(conn, "goal_rows", "label_cont") for a in areas: labels = conn.execute( "SELECT label" + (", label_cont" if groups else "") + " FROM goal_rows " "WHERE area_id = %s ORDER BY sort_order, id", (a["id"],), ).fetchall() plan.append((a["name"], a["color"], tuple((r["label"], bool(r.get("label_cont"))) for r in labels) or (("", False),))) else: plan = [(n, c, tuple((lb, False) for lb in labels)) for n, c, labels in store.DEFAULT_GOAL_AREAS] groups = self._column_exists(conn, "goal_rows", "label_cont") for i, (name, color, labels) in enumerate(plan): aid = conn.execute( "INSERT INTO goal_areas (year, name, color, sort_order) " "VALUES (%s, %s, %s, %s) RETURNING id", (y, name, color, i), ).fetchone()["id"] for j, (label, cont) in enumerate(labels): if groups: conn.execute( "INSERT INTO goal_rows (area_id, label, label_cont, sort_order) VALUES (%s, %s, %s, %s)", (aid, label, cont and j > 0, j), ) else: conn.execute( "INSERT INTO goal_rows (area_id, label, sort_order) VALUES (%s, %s, %s)", (aid, label, j), ) def delete_goal_year(self, *, year: int) -> None: with self._pool.connection() as conn: row = conn.execute( "DELETE FROM goal_years WHERE year = %s RETURNING year", (year,) ).fetchone() if row is None: raise KeyError(year) def update_goal_year(self, *, year: int, sales_unit: str) -> None: unit = store.norm_str(sales_unit)[:20] with self._pool.connection() as conn: row = conn.execute( "UPDATE goal_years SET sales_unit = %s WHERE year = %s RETURNING year", (unit, year), ).fetchone() if row is None: raise KeyError(year) def get_goal_board(self, *, year: int) -> dict[str, Any] | None: """한 해 목표 표 전체. 연도가 없으면 None. metrics = {"sales": {"target": {1: 12.0, ...}, "actual": {...}}, "roas": {...}} areas = [{id, name, color, rows: [{id, label, cells: {0: "연간 글", 1: "1월 글", 13: "상반기 글", ...}, merges: {시작 칸: (가로 칸 수, 세로 줄 수)}}]}] halves = 마이그레이션 014 적용 여부(기간 글 칸·병합 — 이름은 예전 그대로, 지금은 분기 칸) quarters = 마이그레이션 017 적용 여부(2·4분기 칸 15·16 저장) rect = 마이그레이션 015 적용 여부(세로 병합·연간/반기 칸 병합·주간 회의록) """ with self._pool.connection() as conn: head = conn.execute( "SELECT year, sales_unit FROM goal_years WHERE year = %s", (year,) ).fetchone() if head is None: return None metric_rows = conn.execute( "SELECT metric, kind, month, value FROM goal_metrics WHERE year = %s", (year,) ).fetchall() area_rows = conn.execute( "SELECT id, name, color FROM goal_areas WHERE year = %s ORDER BY sort_order, id", (year,), ).fetchall() groups = self._column_exists(conn, "goal_rows", "label_cont") row_rows = conn.execute( "SELECT r.id, r.area_id, r.label" + (", r.label_cont" if groups else "") + " FROM goal_rows r " "JOIN goal_areas a ON a.id = r.area_id WHERE a.year = %s " "ORDER BY r.sort_order, r.id", (year,), ).fetchall() cell_rows = conn.execute( "SELECT c.row_id, c.month, c.body FROM goal_cells c " "JOIN goal_rows r ON r.id = c.row_id JOIN goal_areas a ON a.id = r.area_id " "WHERE a.year = %s", (year,), ).fetchall() halves = self._table_exists(conn, "goal_cell_merges") rect = halves and self._column_exists(conn, "goal_cell_merges", "row_span") quarters = halves and self._goal_quarters(conn) merge_rows = conn.execute( "SELECT m.row_id, m.start_month, m.span" + (", m.row_span" if rect else "") + " FROM goal_cell_merges m " "JOIN goal_rows r ON r.id = m.row_id JOIN goal_areas a ON a.id = r.area_id " "WHERE a.year = %s", (year,), ).fetchall() if halves else [] metrics: dict[str, dict[str, dict[int, float]]] = { m: {k: {} for k in store.GOAL_KINDS} for m in store.GOAL_METRICS } for r in metric_rows: metrics[r["metric"]][r["kind"]][int(r["month"])] = float(r["value"]) cells: dict[int, dict[int, str]] = {} for c in cell_rows: cells.setdefault(int(c["row_id"]), {})[int(c["month"])] = c["body"] merges: dict[int, dict[int, tuple[int, int]]] = {} for g in merge_rows: merges.setdefault(int(g["row_id"]), {})[int(g["start_month"])] = ( int(g["span"]), int(g.get("row_span") or 1)) rows_by_area: dict[int, list[dict[str, Any]]] = {} for r in row_rows: rid = int(r["id"]) rows_by_area.setdefault(int(r["area_id"]), []).append( {"id": rid, "label": r["label"], "cells": cells.get(rid, {}), "merges": merges.get(rid, {}), "label_cont": bool(r.get("label_cont"))} ) areas = [ {"id": int(a["id"]), "name": a["name"], "color": a["color"], "rows": rows_by_area.get(int(a["id"]), [])} for a in area_rows ] return {"year": int(head["year"]), "sales_unit": head["sales_unit"], "metrics": metrics, "areas": areas, "halves": halves, "rect": rect, "groups": groups, "quarters": quarters} def set_goal_metric( self, *, year: int, metric: str, kind: str, month: int, value: float | None, updated_by: str = "" ) -> None: if metric not in store.GOAL_METRICS or kind not in store.GOAL_KINDS: raise ValueError("지표 종류가 올바르지 않습니다.") m = store.validate_goal_month(month) with self._pool.connection() as conn: if not conn.execute("SELECT 1 FROM goal_years WHERE year = %s", (year,)).fetchone(): raise KeyError(year) if value is None: conn.execute( "DELETE FROM goal_metrics WHERE year=%s AND metric=%s AND kind=%s AND month=%s", (year, metric, kind, m), ) else: conn.execute( "INSERT INTO goal_metrics (year, metric, kind, month, value, updated_by) " "VALUES (%s,%s,%s,%s,%s,%s) " "ON CONFLICT (year, metric, kind, month) DO UPDATE " "SET value = EXCLUDED.value, updated_by = EXCLUDED.updated_by, updated_at = now()", (year, metric, kind, m, value, store.norm_str(updated_by, lower=True)), ) def add_goal_area(self, *, year: int, name: str, color: str = "") -> int: nm = store.validate_goal_area_name(name) col = store.validate_goal_color(color) with self._pool.connection() as conn: with conn.transaction(): if not conn.execute("SELECT 1 FROM goal_years WHERE year = %s", (year,)).fetchone(): raise KeyError(year) aid = conn.execute( "INSERT INTO goal_areas (year, name, color, sort_order) VALUES (%s, %s, %s, " "(SELECT COALESCE(MAX(sort_order), -1) + 1 FROM goal_areas WHERE year = %s)) " "RETURNING id", (year, nm, col, year), ).fetchone()["id"] conn.execute("INSERT INTO goal_rows (area_id, label) VALUES (%s, '')", (aid,)) return int(aid) def update_goal_area(self, *, area_id: int, fields: dict[str, Any]) -> None: sets: list[str] = [] params: list[Any] = [] if "name" in fields: sets.append("name = %s") params.append(store.validate_goal_area_name(fields["name"])) if "color" in fields: sets.append("color = %s") params.append(store.validate_goal_color(fields["color"])) if not sets: return with self._pool.connection() as conn: row = conn.execute( f"UPDATE goal_areas SET {', '.join(sets)} WHERE id = %s RETURNING id", (*params, area_id), ).fetchone() if row is None: raise KeyError(area_id) def delete_goal_area(self, *, area_id: int) -> None: with self._pool.connection() as conn: row = conn.execute("DELETE FROM goal_areas WHERE id = %s RETURNING id", (area_id,)).fetchone() if row is None: raise KeyError(area_id) def _move_goal_item(self, table: str, parent_col: str, item_id: int, direction: int) -> None: """영역(연도 안)·줄(영역 안) 순서를 한 칸 위/아래로 — 같은 부모 안에서 번호를 다시 매긴다.""" with self._pool.connection() as conn: with conn.transaction(): me = conn.execute( f"SELECT {parent_col} AS p FROM {table} WHERE id = %s", (item_id,) ).fetchone() if me is None: raise KeyError(item_id) ids = [int(r["id"]) for r in conn.execute( f"SELECT id FROM {table} WHERE {parent_col} = %s ORDER BY sort_order, id", (me["p"],), ).fetchall()] i = ids.index(item_id) j = i + (1 if direction > 0 else -1) if not 0 <= j < len(ids): return ids[i], ids[j] = ids[j], ids[i] for n, x in enumerate(ids): conn.execute(f"UPDATE {table} SET sort_order = %s WHERE id = %s", (n, x)) def move_goal_area(self, *, area_id: int, direction: int) -> None: self._move_goal_item("goal_areas", "year", area_id, direction) def move_goal_row(self, *, row_id: int, direction: int) -> None: """줄 순서 바꾸기 — 세로로 병합된 칸에 걸린 줄(자신 또는 바꿀 이웃)은 옮기지 않는다(엑셀처럼 병합을 먼저 해제).""" with self._pool.connection() as conn: me = conn.execute("SELECT area_id FROM goal_rows WHERE id = %s", (row_id,)).fetchone() if me is None: raise KeyError(row_id) ids, merges, _ = self._area_geometry(conn, int(me["area_id"])) i = ids.index(row_id) j = i + (1 if direction > 0 else -1) if 0 <= j < len(ids) and any(g["r1"] > g["r0"] and (g["r0"] <= i <= g["r1"] or g["r0"] <= j <= g["r1"]) for g in merges): raise ValueError("세로로 병합된 칸에 걸린 줄은 옮길 수 없습니다. 병합을 해제한 뒤 옮기세요.") if 0 <= j < len(ids): conts = self._label_conts(int(me["area_id"]), ids) in_group = lambda k: conts[k] or (k + 1 < len(ids) and conts[k + 1]) # noqa: E731 if in_group(i) or in_group(j): raise ValueError("같은 항목 칸으로 묶인 줄은 옮길 수 없습니다. 항목 칸을 나눈 뒤 옮기세요.") self._move_goal_item("goal_rows", "area_id", row_id, direction) def _label_conts(self, area_id: int, ids: list[int]) -> list[bool]: """영역 줄 순서(ids)대로 label_cont — 016 미적용이면 모두 False.""" with self._pool.connection() as conn: if not self._column_exists(conn, "goal_rows", "label_cont"): return [False] * len(ids) got = {int(r["id"]): bool(r["label_cont"]) for r in conn.execute( "SELECT id, label_cont FROM goal_rows WHERE area_id = %s", (area_id,)).fetchall()} return [got.get(i, False) for i in ids] def add_goal_row( self, *, area_id: int, label: str = "", ref_row_id: int | None = None, place: str = "below", same_label: bool = False, ) -> int: """줄 추가 — 기준 줄(ref_row_id)이 있으면 그 줄 위(place="above")/아래("below")에, 없으면 영역 맨 끝에. same_label(3열에서 추가, 016) = 새 줄을 기준 줄과 **같은 항목 칸(2열)** 안에 넣는다: 아래면 새 줄이 묶음에 이어 붙고 (label_cont), 위면 — 기준 줄이 묶음 첫 줄이면 새 줄이 첫 줄이 되어 이름을 넘겨받고 기준 줄이 이어 붙는다.""" lb = store.validate_goal_row_label(label) if place not in ("above", "below"): raise ValueError("place 는 above 또는 below 입니다.") if same_label and ref_row_id is None: raise ValueError("같은 항목 칸에 추가하려면 기준 줄이 필요합니다.") with self._pool.connection() as conn: with conn.transaction(): if not conn.execute( "SELECT 1 FROM goal_areas WHERE id = %s FOR UPDATE", (area_id,) ).fetchone(): raise KeyError(area_id) if ref_row_id is None: rid = conn.execute( "INSERT INTO goal_rows (area_id, label, sort_order) VALUES (%s, %s, " "(SELECT COALESCE(MAX(sort_order), -1) + 1 FROM goal_rows WHERE area_id = %s)) " "RETURNING id", (area_id, lb, area_id), ).fetchone()["id"] return int(rid) ids = [int(r["id"]) for r in conn.execute( "SELECT id FROM goal_rows WHERE area_id = %s ORDER BY sort_order, id", (area_id,) ).fetchall()] if ref_row_id not in ids: raise KeyError(ref_row_id) if same_label: if not self._column_exists(conn, "goal_rows", "label_cont"): raise store.GoalMigration016Needed() ref = conn.execute("SELECT label, label_cont FROM goal_rows WHERE id = %s", (ref_row_id,)).fetchone() if place == "above" and not ref["label_cont"]: # 묶음 첫 줄 위 — 새 줄이 첫 줄(이름을 넘겨받음), 기준 줄은 이어 붙는다 rid = int(conn.execute( "INSERT INTO goal_rows (area_id, label, label_cont, sort_order) VALUES (%s, %s, false, 0) " "RETURNING id", (area_id, ref["label"]), ).fetchone()["id"]) conn.execute("UPDATE goal_rows SET label = '', label_cont = true WHERE id = %s", (ref_row_id,)) else: rid = int(conn.execute( "INSERT INTO goal_rows (area_id, label, label_cont, sort_order) VALUES (%s, '', true, 0) " "RETURNING id", (area_id,), ).fetchone()["id"]) else: rid = int(conn.execute( "INSERT INTO goal_rows (area_id, label, sort_order) VALUES (%s, %s, 0) RETURNING id", (area_id, lb), ).fetchone()["id"]) i = ids.index(ref_row_id) + (1 if place == "below" else 0) # 따로 추가(2열 메뉴·+)는 화면이 묶음의 맨 위(위에)·맨 아래(아래) 줄을 기준으로 보내 묶음 밖에 들어간다 # 세로 병합 안쪽(시작 줄 아래 ~ 마지막 줄)에 끼우면 엑셀처럼 그 병합이 한 줄 늘어난다 if self._table_exists(conn, "goal_cell_merges") and self._column_exists( conn, "goal_cell_merges", "row_span"): _, merges, _ = self._area_geometry(conn, area_id) for g in merges: if g["r0"] < i <= g["r1"]: conn.execute( "UPDATE goal_cell_merges SET row_span = row_span + 1 " "WHERE row_id = %s AND start_month = %s", (g["row_id"], g["start"]), ) ids.insert(i, rid) for n, x in enumerate(ids): conn.execute("UPDATE goal_rows SET sort_order = %s WHERE id = %s", (n, x)) return rid def update_goal_row(self, *, row_id: int, label: str) -> None: lb = store.validate_goal_row_label(label) with self._pool.connection() as conn: row = conn.execute( "UPDATE goal_rows SET label = %s WHERE id = %s RETURNING id", (lb, row_id) ).fetchone() if row is None: raise KeyError(row_id) def delete_goal_row(self, *, row_id: int) -> None: """줄 삭제 — 영역의 마지막 한 줄은 지울 수 없다(영역을 지운다).""" with self._pool.connection() as conn: with conn.transaction(): me = conn.execute("SELECT area_id FROM goal_rows WHERE id = %s", (row_id,)).fetchone() if me is None: raise KeyError(row_id) n = conn.execute( "SELECT count(*) AS n FROM goal_rows WHERE area_id = %s", (me["area_id"],) ).fetchone()["n"] if n <= 1: raise ValueError("업무 영역의 마지막 줄은 지울 수 없습니다. 영역을 삭제하세요.") # 세로 병합에 가려진 줄이면 그 병합이 한 줄 준다(시작 줄을 지우면 병합도 같이 지워진다 — CASCADE) if self._table_exists(conn, "goal_cell_merges") and self._column_exists( conn, "goal_cell_merges", "row_span"): ids, merges, _ = self._area_geometry(conn, int(me["area_id"])) i = ids.index(row_id) for g in merges: if g["r0"] < i <= g["r1"]: if g["span"] * (g["row_span"] - 1) >= 2: conn.execute( "UPDATE goal_cell_merges SET row_span = row_span - 1 " "WHERE row_id = %s AND start_month = %s", (g["row_id"], g["start"]), ) else: conn.execute( "DELETE FROM goal_cell_merges WHERE row_id = %s AND start_month = %s", (g["row_id"], g["start"]), ) if self._column_exists(conn, "goal_rows", "label_cont"): # 묶음 첫 줄을 지우면 바로 아래 이어 붙은 줄이 첫 줄이 되고 이름을 넘겨받는다(비어 있으면) me2 = conn.execute("SELECT label, label_cont, sort_order FROM goal_rows WHERE id = %s", (row_id,)).fetchone() if not me2["label_cont"]: nxt = conn.execute( "SELECT id, label, label_cont FROM goal_rows WHERE area_id = %s AND id <> %s " "AND (sort_order, id) > (%s, %s) ORDER BY sort_order, id LIMIT 1", (me["area_id"], row_id, me2["sort_order"], row_id), ).fetchone() if nxt and nxt["label_cont"]: conn.execute( "UPDATE goal_rows SET label_cont = false, label = CASE WHEN label = '' THEN %s ELSE label END " "WHERE id = %s", (me2["label"], nxt["id"]), ) conn.execute("DELETE FROM goal_rows WHERE id = %s", (row_id,)) def split_goal_label(self, *, row_id: int) -> int: """항목 칸 나누기 — row_id(묶음 첫 줄) 아래 이어 붙은 줄들을 각자 항목 칸으로(이름은 빈 칸). 나눈 줄 수.""" with self._pool.connection() as conn: with conn.transaction(): if not self._column_exists(conn, "goal_rows", "label_cont"): raise store.GoalMigration016Needed() me = conn.execute("SELECT area_id FROM goal_rows WHERE id = %s FOR UPDATE", (row_id,)).fetchone() if me is None: raise KeyError(row_id) rows = conn.execute( "SELECT id, label_cont FROM goal_rows WHERE area_id = %s ORDER BY sort_order, id", (me["area_id"],) ).fetchall() ids = [int(r["id"]) for r in rows] n = 0 for r in rows[ids.index(row_id) + 1:]: if not r["label_cont"]: break conn.execute("UPDATE goal_rows SET label_cont = false WHERE id = %s", (r["id"],)) n += 1 return n def set_goal_cell(self, *, row_id: int, month: int, body: str, updated_by: str = "") -> None: m = store.validate_goal_month(month, allow_year=True) text = store.validate_goal_text(body) with self._pool.connection() as conn, conn.transaction(): # 빈 대상 칸을 포함해 일반 저장·이동·병합이 같은 영역 잠금으로 직렬화된다. area = conn.execute( "SELECT a.id AS area_id FROM goal_rows r JOIN goal_areas a ON a.id = r.area_id " "WHERE r.id = %s FOR UPDATE OF a", (row_id,), ).fetchone() if not area: raise KeyError(row_id) halves = self._table_exists(conn, "goal_cell_merges") if m > 12 and not halves: raise store.GoalMigration014Needed() if m in store.GOAL_Q_NEW and not self._goal_quarters(conn): raise store.GoalMigration017Needed() if halves: # 병합에 가려진 칸(글은 왼쪽 위 칸에만 둔다) — 다른 창에서 병합된 뒤의 늦은 저장 area_id = area["area_id"] ids, merges, _ = self._area_geometry(conn, int(area_id)) if self._covered_by(merges, ids.index(row_id), store.GOAL_COL_ORDER.index(m)): raise ValueError("병합된 칸입니다. 새로고침해 주세요.") if not text: conn.execute("DELETE FROM goal_cells WHERE row_id = %s AND month = %s", (row_id, m)) else: conn.execute( "INSERT INTO goal_cells (row_id, month, body, updated_by) VALUES (%s,%s,%s,%s) " "ON CONFLICT (row_id, month) DO UPDATE " "SET body = EXCLUDED.body, updated_by = EXCLUDED.updated_by, updated_at = now()", (row_id, m, text, store.norm_str(updated_by, lower=True)), ) def move_goal_cell( self, *, source_row: Any, source_month: Any, target_row: Any, target_month: Any, source_body: str, target_body: str, body: str, updated_by: str = "", ) -> str: """같은 연도 안에서 셀의 내용·서식을 이동한다. 두 값의 비교와 이동은 한 트랜잭션. 병합 시작 칸끼리도 내용만 이동하며 병합 배치·영역 색·열 너비는 유지한다. 응답만 유실된 요청을 다시 보내면 이미 같은 이동이 완료된 상태는 성공으로 돌려준다. """ try: sr, tr = int(source_row), int(target_row) except (TypeError, ValueError): raise ValueError("이동할 셀이 올바르지 않습니다.") sm = store.validate_goal_month(source_month, allow_year=True) tm = store.validate_goal_month(target_month, allow_year=True) if sr <= 0 or tr <= 0 or (sr, sm) == (tr, tm): raise ValueError("서로 다른 두 셀을 골라 주세요.") expected_source, expected_target = store.validate_goal_text(source_body), store.validate_goal_text(target_body) moved = store.validate_goal_text(body) if not expected_source or not moved or store.goal_text_plain(moved).strip() != store.goal_text_plain(expected_source).strip(): raise ValueError("원본 내용과 이동할 내용이 일치하지 않습니다.") with self._pool.connection() as conn: with conn.transaction(): rows = conn.execute( "SELECT r.id, r.area_id, a.year FROM goal_rows r JOIN goal_areas a ON a.id = r.area_id " "WHERE r.id = ANY(%s)", ([sr, tr],), ).fetchall() by_id = {int(r["id"]): r for r in rows} if sr not in by_id or tr not in by_id: raise KeyError(sr if sr not in by_id else tr) if by_id[sr]["year"] != by_id[tr]["year"]: raise ValueError("같은 연도의 셀로만 이동할 수 있습니다.") areas = sorted({int(r["area_id"]) for r in rows}) # 교차 영역 이동도 같은 순서로 잠가 교착을 피하고, 행 삭제도 함께 차단한다. conn.execute("SELECT id FROM goal_areas WHERE id = ANY(%s) ORDER BY id FOR UPDATE", (areas,)).fetchall() locked = conn.execute( "SELECT id, area_id FROM goal_rows WHERE id = ANY(%s) ORDER BY id FOR UPDATE", ([sr, tr],), ).fetchall() if len(locked) != len(by_id): raise KeyError("이동할 줄이 삭제되었습니다.") halves = self._table_exists(conn, "goal_cell_merges") if (sm > 12 or tm > 12) and not halves: raise store.GoalMigration014Needed() if (sm in store.GOAL_Q_NEW or tm in store.GOAL_Q_NEW) and not self._goal_quarters(conn): raise store.GoalMigration017Needed() geometry = {a: self._area_geometry(conn, a) for a in areas} if halves else {} for rid, month in ((sr, sm), (tr, tm)): if halves: ids, merges, _ = geometry[int(by_id[rid]["area_id"])] if rid not in ids or self._covered_by(merges, ids.index(rid), store.GOAL_COL_ORDER.index(month)): raise store.GoalCellConflict("병합 배치가 바뀌었습니다. 새로고침한 뒤 다시 이동해 주세요.") cells = conn.execute( "SELECT row_id, month, body FROM goal_cells " "WHERE (row_id = %s AND month = %s) OR (row_id = %s AND month = %s) FOR UPDATE", (sr, sm, tr, tm), ).fetchall() values = {(int(c["row_id"]), int(c["month"])): store.validate_goal_text(c["body"]) for c in cells} source, target = values.get((sr, sm), ""), values.get((tr, tm), "") if not source and target == moved: return moved if source != expected_source or target != expected_target: raise store.GoalCellConflict("원본 또는 대상 내용이 바뀌었습니다. 새로고침한 뒤 다시 이동해 주세요.") conn.execute( "INSERT INTO goal_cells (row_id, month, body, updated_by) VALUES (%s,%s,%s,%s) " "ON CONFLICT (row_id, month) DO UPDATE " "SET body = EXCLUDED.body, updated_by = EXCLUDED.updated_by, updated_at = now()", (tr, tm, moved, store.norm_str(updated_by, lower=True)), ) conn.execute("DELETE FROM goal_cells WHERE row_id = %s AND month = %s", (sr, sm)) return moved # ── 엑셀식 사각형 병합 ───────────────────────────────────────── @staticmethod def _column_exists(conn: Any, table: str, column: str) -> bool: row = conn.execute( "SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' " "AND table_name = %s AND column_name = %s", (table, column), ).fetchone() return row is not None def _area_geometry(self, conn: Any, area_id: int) -> tuple[list[int], list[dict[str, Any]], bool]: """업무 영역 하나의 병합 배치 — (줄 id 순서, 병합 목록, 세로 병합(015) 가능 여부). 병합 = {row_id, start, span, row_span, r0, r1(줄 순번), c0, c1(화면 칸 순번)}. 줄 범위는 영역 끝에서 자른다.""" ids = [int(r["id"]) for r in conn.execute( "SELECT id FROM goal_rows WHERE area_id = %s ORDER BY sort_order, id", (area_id,) ).fetchall()] if not self._table_exists(conn, "goal_cell_merges"): return ids, [], False rect = self._column_exists(conn, "goal_cell_merges", "row_span") rows = conn.execute( "SELECT m.row_id, m.start_month, m.span" + (", m.row_span" if rect else "") + " FROM goal_cell_merges m JOIN goal_rows r ON r.id = m.row_id WHERE r.area_id = %s", (area_id,), ).fetchall() merges = [] for g in rows: rid, start = int(g["row_id"]), int(g["start_month"]) if rid not in ids or start not in store.GOAL_COL_ORDER: continue r0 = ids.index(rid) span, rs = int(g["span"]), int(g.get("row_span") or 1) if rect else 1 c0 = store.GOAL_COL_ORDER.index(start) merges.append({"row_id": rid, "start": start, "span": span, "row_span": rs, "r0": r0, "r1": min(len(ids) - 1, r0 + rs - 1), "c0": c0, "c1": min(len(store.GOAL_COL_ORDER) - 1, c0 + span - 1)}) return ids, merges, rect @staticmethod def _covered_by(merges: list[dict[str, Any]], ri: int, ci: int) -> dict[str, Any] | None: """(줄 순번, 칸 순번)을 가리는 병합(시작 칸 자신은 빼고).""" for g in merges: if g["r0"] <= ri <= g["r1"] and g["c0"] <= ci <= g["c1"] and (ri, ci) != (g["r0"], g["c0"]): return g return None def merge_goal_rect( self, *, area_id: int, row_from: Any, row_to: Any, col_from: Any, col_to: Any, updated_by: str = "" ) -> dict[str, int]: """업무 영역 칸을 엑셀처럼 사각형으로 합친다 → {row_id(왼쪽 위 줄), start, span, row_span}. 줄은 같은 영역 안 연속된 줄, 칸은 화면 순서(연간·1~3월·1분기·…·10~12월·4분기) — 가로는 같은 분기 월 칸끼리만. 걸친 기존 병합은 통째로 흡수(엑셀이 선택을 넓히듯). 글은 범위 안 칸들의 글을 왼쪽 위부터 줄·칸 순서대로 줄바꿈으로 이어 왼쪽 위 칸에 두고, 나머지 칸 글은 지운다(글을 잃지 않게).""" who = store.norm_str(updated_by, lower=True) try: rf, rt = int(row_from), int(row_to) except (TypeError, ValueError): raise ValueError("병합할 줄이 올바르지 않습니다.") store.validate_goal_rect_cols(col_from, col_to) # 칸 번호 검사(묶음 검사는 넓힌 뒤 다시) with self._pool.connection() as conn: with conn.transaction(): if not self._table_exists(conn, "goal_cell_merges"): raise store.GoalMigration014Needed() if not conn.execute("SELECT 1 FROM goal_areas WHERE id = %s FOR UPDATE", (area_id,)).fetchone(): raise KeyError(area_id) ids, merges, rect = self._area_geometry(conn, area_id) if rf not in ids or rt not in ids: raise KeyError(rf if rf not in ids else rt) r0, r1 = sorted((ids.index(rf), ids.index(rt))) c0, c1 = sorted((store.GOAL_COL_ORDER.index(int(col_from)), store.GOAL_COL_ORDER.index(int(col_to)))) grown = True while grown: # 걸친 병합을 통째로 품을 때까지 넓힌다 grown = False for g in merges: if g["r0"] <= r1 and g["r1"] >= r0 and g["c0"] <= c1 and g["c1"] >= c0: n = (min(r0, g["r0"]), max(r1, g["r1"]), min(c0, g["c0"]), max(c1, g["c1"])) if n != (r0, r1, c0, c1): r0, r1, c0, c1 = n grown = True start, span = store.validate_goal_rect_cols(store.GOAL_COL_ORDER[c0], store.GOAL_COL_ORDER[c1]) row_span = r1 - r0 + 1 if span * row_span < 2: raise ValueError("두 칸 이상 골라야 병합할 수 있습니다.") if (row_span > 1 or start == store.GOAL_YEAR or start in store.GOAL_COL_QUARTER) and not rect: raise store.GoalMigration015Needed() if start in store.GOAL_Q_NEW and not self._goal_quarters(conn): raise store.GoalMigration017Needed() rows_in = ids[r0:r1 + 1] cols_in = list(store.GOAL_COL_ORDER[c0:c1 + 1]) bodies = {(int(c["row_id"]), int(c["month"])): str(c["body"]).strip() for c in conn.execute( "SELECT row_id, month, body FROM goal_cells WHERE row_id = ANY(%s) AND month = ANY(%s)", (rows_in, cols_in), ).fetchall()} text = store.merge_goal_texts([ bodies[(r, m)] for r in rows_in for m in cols_in if bodies.get((r, m)) ]) conn.execute( "DELETE FROM goal_cell_merges WHERE row_id = ANY(%s) AND start_month = ANY(%s)", (rows_in, cols_in), ) conn.execute( "DELETE FROM goal_cells WHERE row_id = ANY(%s) AND month = ANY(%s)", (rows_in, cols_in), ) anchor = rows_in[0] if text: conn.execute( "INSERT INTO goal_cells (row_id, month, body, updated_by) VALUES (%s,%s,%s,%s)", (anchor, start, text, who), ) if rect: conn.execute( "INSERT INTO goal_cell_merges (row_id, start_month, span, row_span, updated_by) " "VALUES (%s, %s, %s, %s, %s)", (anchor, start, span, row_span, who), ) else: conn.execute( "INSERT INTO goal_cell_merges (row_id, start_month, span, updated_by) VALUES (%s, %s, %s, %s)", (anchor, start, span, who), ) return {"row_id": anchor, "start": start, "span": span, "row_span": row_span} def unmerge_goal_cells(self, *, row_id: int, start: int) -> None: """병합 해제 — 글은 시작 월 칸에 그대로 남는다.""" with self._pool.connection() as conn: if not self._table_exists(conn, "goal_cell_merges"): raise store.GoalMigration014Needed() row = conn.execute( "DELETE FROM goal_cell_merges WHERE row_id = %s AND start_month = %s RETURNING row_id", (row_id, start), ).fetchone() if row is None: raise KeyError(row_id) # ════════════════════════════════════════════════════════════ # 주간 회의록 (마이그레이션 015) — 목표 표 월 머리 → 그 달 주차별 회의록 # ════════════════════════════════════════════════════════════ _MEETING_ITEM_COLS = ("id, week_start, section, section_color, label, content, target_amount, result_amount, " "status, marketplace_code, carry_from, sort_order") def meetings_enabled(self) -> bool: with self._pool.connection() as conn: return self._table_exists(conn, "goal_meetings") def _require_meetings(self, conn: Any) -> None: if not self._table_exists(conn, "goal_meetings"): raise store.GoalMigration015Needed() def _meeting_keys(self, conn: Any) -> bool: """마이그레이션 018 — goal_meeting_items.line_key(주가 바뀌어도 같은 줄을 가리키는 연결키) 적용 여부. 적용되면 한 번만 확인한다(되돌리는 마이그레이션은 없다).""" if getattr(self, "_meeting_keys_ok", False): return True ok = self._column_exists(conn, "goal_meeting_items", "line_key") if ok: self._meeting_keys_ok = True return ok def _meeting_cols(self, conn: Any) -> str: return (self._MEETING_ITEM_COLS + (", line_key" if self._meeting_keys(conn) else "") + (", content_row_span" if self._meeting_cells(conn) else "") + (", result_note" if self._meeting_v20(conn) else "") + (", target_text, result_text" if self._meeting_v21(conn) else "")) def _meeting_v21(self, conn: Any) -> bool: """마이그레이션 021 — 정량 목표·결과 글(target_text·result_text, 예: "20개").""" if getattr(self, "_meeting_v21_ok", False): return True ok = self._column_exists(conn, "goal_meeting_items", "target_text") if ok: self._meeting_v21_ok = True return ok def _meeting_v20(self, conn: Any) -> bool: """마이그레이션 020 — 결과 글 칸(result_note)·월요일이 아닌 주차 시작일·주차별 목표(goal_week_targets).""" if getattr(self, "_meeting_v20_ok", False): return True ok = self._column_exists(conn, "goal_meeting_items", "result_note") if ok: self._meeting_v20_ok = True return ok def _meeting_v22(self, conn: Any) -> bool: """마이그레이션 022 — 회의 완료(goal_meetings.completed_at, 수정 잠금).""" if getattr(self, "_meeting_v22_ok", False): return True ok = self._column_exists(conn, "goal_meetings", "completed_at") if ok: self._meeting_v22_ok = True return ok def _check_meeting_open(self, conn: Any, week_start: Any) -> None: """그 주차 회의록이 완료(잠금)됐으면 MeetingLocked. 022 전이면 잠금 없음.""" if not self._meeting_v22(conn): return row = conn.execute("SELECT completed_at FROM goal_meetings WHERE week_start = %s", (week_start,)).fetchone() if row and row["completed_at"] is not None: raise store.MeetingLocked() def _check_result_open(self, conn: Any, own_week: Any) -> None: """결과 칸(result_*·status)만 고칠 때 — 그 주 결과는 다음 주 회의에서 리뷰하며 적는다(6-14 표). · 다음 주차 회의록이 있으면 그 회의록이 열려 있을 때만(완료되면 잠금 — 그 주 회의록 완료 여부와 무관) · 다음 주차 회의록이 아직 없으면 그 주 회의록이 열려 있을 때만(예전엔 그 주가 완료돼도 다음 회의록이 없으면 고칠 수 있었다) 다음 주차 = 바로 다음 주차 시작일(store.week_period 끝 + 1일 — 달이 바뀌어도, 월요일이 아닌 시작일도 get_meeting 이 "지난주"를 찾는 규칙과 같다). 다음 회의록 행도 잠근다(FOR SHARE) — 이미 그 주 회의록을 잠근 뒤라 잠금 순서는 늘 주차 오름차순(교착 없음), 확인 뒤 다음 회의록이 완료돼도 끼어들지 못한다. 022 전이면 잠금 없음.""" if not self._meeting_v22(conn): return nxt = store.week_period(own_week)[1] + timedelta(days=1) row = conn.execute("SELECT completed_at FROM goal_meetings WHERE week_start = %s FOR SHARE", (nxt,)).fetchone() if row is None: self._check_meeting_open(conn, own_week) elif row["completed_at"] is not None: raise store.MeetingLocked() def set_meeting_completed(self, *, week_start: date, done: bool, by: str = "") -> dict[str, Any]: """회의 완료(잠금)·완료 해제 — 관리자만(라우터). 바뀐 상태를 돌려준다.""" with self._pool.connection() as conn: self._require_meetings(conn) if not self._meeting_v22(conn): raise store.MeetingMigration022Needed() row = conn.execute( "UPDATE goal_meetings SET completed_at = CASE WHEN %s THEN COALESCE(completed_at, now()) ELSE NULL END, " "completed_by = CASE WHEN %s THEN %s ELSE '' END, updated_at = now() " "WHERE week_start = %s RETURNING completed_at, completed_by", (done, done, store.norm_str(by, lower=True), week_start), ).fetchone() if row is None: raise KeyError(str(week_start)) return {"completed": row["completed_at"] is not None, "completed_at": row["completed_at"].astimezone(KST).isoformat(timespec="minutes") if row["completed_at"] else "", "completed_by": row["completed_by"] or ""} def meetings_v20(self) -> bool: with self._pool.connection() as conn: return self._table_exists(conn, "goal_meetings") and self._meeting_v20(conn) def _meeting_cells(self, conn: Any) -> bool: if getattr(self, "_meeting_cells_ok", False): return True ok = self._column_exists(conn, "goal_meeting_items", "content_row_span") if ok: self._meeting_cells_ok = True return ok def _locked_meeting_items(self, conn: Any, item_id: int, *, check_open: bool = True) -> list[dict[str, Any]]: """글 저장·이동·병합·줄 변경이 같은 주 잠금을 공유한다. check_open — 회의 완료(022)된 주면 MeetingLocked.""" me = conn.execute("SELECT week_start FROM goal_meeting_items WHERE id = %s", (item_id,)).fetchone() if me is None: raise KeyError(item_id) if not conn.execute("SELECT week_start FROM goal_meetings WHERE week_start = %s FOR UPDATE", (me["week_start"],)).fetchone(): raise KeyError(item_id) if check_open: self._check_meeting_open(conn, me["week_start"]) rows = conn.execute(f"SELECT {self._meeting_cols(conn)} FROM goal_meeting_items " "WHERE week_start = %s ORDER BY sort_order, id FOR UPDATE", (me["week_start"],)).fetchall() if not any(int(r["id"]) == item_id for r in rows): raise KeyError(item_id) return rows @staticmethod def _meeting_merge_ranges(rows: list[dict[str, Any]]) -> list[tuple[int, int]]: ranges = [] for i, row in enumerate(rows): span = int(row.get("content_row_span") or 1) if span > 1: end = i + span - 1 if end >= len(rows) or any(r["section"] != row["section"] for r in rows[i:end + 1]): raise store.GoalCellConflict("병합 범위가 바뀌었습니다. 새로고침해 주세요.") ranges.append((i, end)) return ranges def _require_meeting_cell_visible(self, rows: list[dict[str, Any]], item_id: int) -> int: i = next((n for n, r in enumerate(rows) if int(r["id"]) == item_id), -1) if i < 0: raise KeyError(item_id) if any(a < i <= b for a, b in self._meeting_merge_ranges(rows)): raise store.GoalCellConflict("병합에 가려진 셀입니다. 새로고침해 주세요.") return i @staticmethod def _meeting_item(r: dict[str, Any]) -> dict[str, Any]: out = dict(r) out["id"] = int(out["id"]) out["week_start"] = out["week_start"].isoformat() for k in ("target_amount", "result_amount", "carry_from"): out[k] = int(out[k]) if out.get(k) is not None else None if out.get("line_key") is not None: out["line_key"] = str(out["line_key"]) return out def meeting_weeks(self, *, start: date, end: date) -> list[str]: """기간 안에 회의록이 있는 주차(시작일) 목록.""" with self._pool.connection() as conn: if not self._table_exists(conn, "goal_meetings"): return [] rows = conn.execute( "SELECT week_start FROM goal_meetings WHERE week_start BETWEEN %s AND %s ORDER BY week_start", (start, end), ).fetchall() return [r["week_start"].isoformat() for r in rows] def get_meeting(self, *, week_start: date) -> dict[str, Any] | None: """한 주 회의록 — 머리(금주 목표·참석자·메모) + 줄(지난주 줄 prev 포함). 없으면 None. "지난주"는 **바로 앞 주차(store.prev_week_period)** 만이다(몇 주 전 회의록을 지난주로 보이지 않게). · prev_meeting = 그 주 회의록 머리(전주 목표), 그 주 회의록이 없으면 None. · 줄의 prev = 그 주 회의록에서 **같은 연결키(line_key, 마이그레이션 018)** 의 줄 — 생성 순서·이름 변경· 순서 이동과 무관하다. 018 미적용이면 예전 carry_from 을 쓰되 가리키는 줄이 정확히 7일 전 주일 때만. """ with self._pool.connection() as conn: self._require_meetings(conn) cols = self._meeting_cols(conn) keyed = self._meeting_keys(conn) cell_merges = self._meeting_cells(conn) result_notes = self._meeting_v20(conn) v22 = self._meeting_v22(conn) done_row = conn.execute("SELECT completed_at, completed_by FROM goal_meetings WHERE week_start = %s", (week_start,)).fetchone() if v22 else None head = conn.execute( "SELECT week_start, week_target, attendees, notes, updated_by, updated_at " "FROM goal_meetings WHERE week_start = %s", (week_start,), ).fetchone() if head is None: return None prev_week = store.prev_week_period(week_start)[0] items = conn.execute( f"SELECT {cols} FROM goal_meeting_items WHERE week_start = %s " "ORDER BY sort_order, id", (week_start,), ).fetchall() prev_head = conn.execute( "SELECT week_start, week_target FROM goal_meetings WHERE week_start = %s", (prev_week,), ).fetchone() prev_rows = conn.execute( f"SELECT {cols} FROM goal_meeting_items WHERE week_start = %s", (prev_week,), ).fetchall() if prev_head else [] by_key = {str(r["line_key"]): r for r in prev_rows if r.get("line_key") is not None} if keyed else {} by_id = {int(r["id"]): r for r in prev_rows} out_items = [] for r in items: it = self._meeting_item(r) if keyed: p = by_key.get(it.get("line_key") or "") else: p = by_id.get(it["carry_from"]) if it["carry_from"] is not None else None it["prev"] = self._meeting_item(p) if p is not None else None out_items.append(it) return { "week_start": head["week_start"].isoformat(), "week_target": int(head["week_target"]) if head["week_target"] is not None else None, "attendees": head["attendees"], "notes": head["notes"], "updated_by": head["updated_by"], "updated_at": head["updated_at"].astimezone(KST).isoformat(timespec="minutes") if head["updated_at"] else "", "items": out_items, "prev_meeting": {"week_start": prev_head["week_start"].isoformat(), "week_target": int(prev_head["week_target"]) if prev_head["week_target"] is not None else None} if prev_head else None, "line_keys": keyed, "cell_merges": cell_merges, "result_notes": result_notes, "can_complete": v22, "completed": bool(done_row and done_row["completed_at"] is not None), "completed_at": done_row["completed_at"].astimezone(KST).strftime("%Y-%m-%d %H:%M") if done_row and done_row["completed_at"] else "", "completed_by": (done_row["completed_by"] or "") if done_row else "", } def create_meeting(self, *, week_start: date, sections: list[tuple[str, str]], created_by: str = "") -> bool: """회의록 만들기 — 이미 있으면 False. 줄(구역·이름·색·쇼핑몰 연결·순서)을 글 없이 이어받을 원본: ① 앞선 가장 가까운 회의록(평소 순서), ② 앞선 회의록이 없으면 뒤에 있는 가장 가까운 회의록 (다음 주를 먼저 만들고 앞 주를 나중에 만든 경우 — 다음 주 줄이 이 주 줄을 "지난주"로 찾게), ③ 둘 다 없으면 sections(목표 표 업무 영역 이름·색)마다 기본 양식 줄(store.MEETING_TEMPLATE). 이어받은 줄은 원본 줄의 연결키(line_key, 018)를 그대로 갖는다 → 생성 순서와 무관하게 7일 전 주의 같은 키 줄이 "지난주"가 된다. 새 줄(양식·줄 추가)은 새 키. carry_from 은 앞선 원본 줄일 때만 기록(이력, 화면 연결에는 안 씀).""" ws = store.validate_period_start(week_start) who = store.norm_str(created_by, lower=True) with self._pool.connection() as conn: with conn.transaction(): self._require_meetings(conn) if ws.weekday() != 0 and not self._meeting_v20(conn): raise store.MeetingMigration020Needed() # 월요일만 허용하던 CHECK 가 아직 있다 keyed = self._meeting_keys(conn) ins = conn.execute( "INSERT INTO goal_meetings (week_start, created_by, updated_by) VALUES (%s, %s, %s) " "ON CONFLICT (week_start) DO NOTHING RETURNING week_start", (ws, who, who), ).fetchone() if ins is None: return False src_cols = "id, section, section_color, label, marketplace_code, sort_order" + (", line_key" if keyed else "") src_items: list[dict[str, Any]] = [] src_is_prev = True for cmp_, order, is_prev in (("<", "DESC", True), (">", "ASC", False)): # 줄이 하나라도 있는 가장 가까운 회의록(빈 회의록은 건너뜀) src = conn.execute( f"SELECT m.week_start FROM goal_meetings m WHERE m.week_start {cmp_} %s " "AND EXISTS (SELECT 1 FROM goal_meeting_items i WHERE i.week_start = m.week_start) " f"ORDER BY m.week_start {order} LIMIT 1", (ws,), ).fetchone() if src: src_items = conn.execute( f"SELECT {src_cols} FROM goal_meeting_items WHERE week_start = %s ORDER BY sort_order, id", (src["week_start"],), ).fetchall() src_is_prev = is_prev break if src_items: for n, r in enumerate(src_items): key = str(r["line_key"]) if keyed and r.get("line_key") is not None else str(uuid.uuid4()) carry = r["id"] if src_is_prev else None if keyed: conn.execute( "INSERT INTO goal_meeting_items (week_start, section, section_color, label, " "marketplace_code, carry_from, sort_order, updated_by, line_key) " "VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)", (ws, r["section"], r["section_color"], r["label"], r["marketplace_code"], carry, n, who, key), ) else: conn.execute( "INSERT INTO goal_meeting_items (week_start, section, section_color, label, " "marketplace_code, carry_from, sort_order, updated_by) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)", (ws, r["section"], r["section_color"], r["label"], r["marketplace_code"], carry, n, who), ) else: n = 0 for name, color in sections or [(k, "") for k in store.MEETING_TEMPLATE]: for label in store.MEETING_TEMPLATE.get(name, ("",)): if keyed: conn.execute( "INSERT INTO goal_meeting_items (week_start, section, section_color, label, " "marketplace_code, sort_order, updated_by, line_key) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)", (ws, name, color, label, store.guess_meeting_market(name, label), n, who, str(uuid.uuid4())), ) else: conn.execute( "INSERT INTO goal_meeting_items (week_start, section, section_color, label, " "marketplace_code, sort_order, updated_by) VALUES (%s,%s,%s,%s,%s,%s,%s)", (ws, name, color, label, store.guess_meeting_market(name, label), n, who), ) n += 1 return True def delete_meeting(self, *, week_start: date) -> None: with self._pool.connection() as conn: self._require_meetings(conn) row = conn.execute( "DELETE FROM goal_meetings WHERE week_start = %s RETURNING week_start", (week_start,) ).fetchone() if row is None: raise KeyError(str(week_start)) def update_meeting(self, *, week_start: date, fields: dict[str, Any], updated_by: str = "") -> None: """머리 칸 — week_target(금주 목표 매출, 원) · attendees(참석자) · notes(결정 사항·메모).""" sets: list[str] = [] params: list[Any] = [] if "week_target" in fields: v = store.validate_meeting_amount(fields["week_target"]) if v is not None and v < 0: raise ValueError("금주 목표는 0 이상이어야 합니다.") sets.append("week_target = %s") params.append(v) if "attendees" in fields: sets.append("attendees = %s") params.append(store.validate_meeting_text(fields["attendees"], limit=3000, what="참석자")) if "notes" in fields: sets.append("notes = %s") params.append(store.validate_meeting_text(fields["notes"], what="메모")) if not sets: return with self._pool.connection() as conn: with conn.transaction(): self._require_meetings(conn) # 완료 확인과 머리 변경을 한 트랜잭션에서 그 회의록 행을 잠그고 — [회의 완료](set_meeting_completed # 의 UPDATE 도 같은 행을 잠근다)와 동시에 와도 완료된 회의록이 바뀌지 않는다. if not conn.execute("SELECT week_start FROM goal_meetings WHERE week_start = %s FOR UPDATE", (week_start,)).fetchone(): raise KeyError(str(week_start)) self._check_meeting_open(conn, week_start) row = conn.execute( f"UPDATE goal_meetings SET {', '.join(sets)}, updated_by = %s, updated_at = now() " "WHERE week_start = %s RETURNING week_start", (*params, store.norm_str(updated_by, lower=True), week_start), ).fetchone() if row is None: raise KeyError(str(week_start)) def add_meeting_item( self, *, week_start: date, section: str, section_color: str = "", label: str = "", ref_item_id: int | None = None, place: str = "below", updated_by: str = "", ) -> int: """줄 추가 — 기준 줄 위/아래(같은 구역), 없으면 그 구역 끝(구역이 없으면 맨 끝 = 새 구역).""" sec = store.norm_str(section) if not sec or len(sec) > store.MEETING_LABEL_MAX: raise ValueError("구역 이름을 입력하세요(50자 이하).") lb = store.validate_meeting_text(label, limit=store.MEETING_LABEL_MAX, what="줄 이름") if place not in ("above", "below"): raise ValueError("place 는 above 또는 below 입니다.") with self._pool.connection() as conn: with conn.transaction(): self._require_meetings(conn) if not conn.execute( "SELECT 1 FROM goal_meetings WHERE week_start = %s FOR UPDATE", (week_start,) ).fetchone(): raise KeyError(str(week_start)) self._check_meeting_open(conn, week_start) rows = conn.execute( f"SELECT {self._meeting_cols(conn)} FROM goal_meeting_items WHERE week_start = %s " "ORDER BY sort_order, id", (week_start,), ).fetchall() ids = [int(r["id"]) for r in rows] color = store.norm_str(section_color) or next( (r["section_color"] for r in rows if r["section"] == sec), "") if ref_item_id is not None: if ref_item_id not in ids: raise KeyError(ref_item_id) i = ids.index(ref_item_id) + (1 if place == "below" else 0) else: same = [n for n, r in enumerate(rows) if r["section"] == sec] i = same[-1] + 1 if same else len(ids) if any(a < i <= b for a, b in self._meeting_merge_ranges(rows)): raise ValueError("병합된 셀 안에 줄을 추가하려면 먼저 병합을 해제해 주세요.") # 새 줄 = 새 연결키(018) — 이름이 같은 다른 줄과 섞이지 않는다 keyed = self._meeting_keys(conn) new_id = int(conn.execute( "INSERT INTO goal_meeting_items (week_start, section, section_color, label, marketplace_code, " "sort_order, updated_by" + (", line_key" if keyed else "") + ") VALUES (%s,%s,%s,%s,%s,0,%s" + (",%s" if keyed else "") + ") RETURNING id", (week_start, sec, color, lb, store.guess_meeting_market(sec, lb), store.norm_str(updated_by, lower=True), *((str(uuid.uuid4()),) if keyed else ())), ).fetchone()["id"]) ids.insert(i, new_id) for n, x in enumerate(ids): conn.execute("UPDATE goal_meeting_items SET sort_order = %s WHERE id = %s", (n, x)) return new_id def update_meeting_item(self, *, item_id: int, fields: dict[str, Any], updated_by: str = "") -> dict[str, Any]: """줄 칸 — label · content(주요 업무) · target_amount · result_amount(그 주 결과, 원) · result_note(그 주 결과 글, 020) · status(평가, 화면에선 폐지) · marketplace_code(화면에선 폐지). 저장된 줄을 돌려준다.""" sets: list[str] = [] params: list[Any] = [] if "label" in fields: sets.append("label = %s") params.append(store.validate_meeting_text(fields["label"], limit=store.MEETING_LABEL_MAX, what="줄 이름")) if "content" in fields: sets.append("content = %s") params.append(store.validate_meeting_content(fields["content"])) # 정량 목표·결과 — 숫자로 읽히면(1,200,000 · 120만) 원 정수 칸, 아니면(예: "20개") 글 칸(021). 둘 중 하나만 채운다. texts: list[tuple[str, str, str]] = [] # (글 칸, 글, 021 이 없을 때 낼 오류) for k in ("target_amount", "result_amount"): if k in fields: try: v, text, err = store.validate_meeting_amount(fields[k]), "", "" except ValueError as exc: v, err = None, str(exc) text = store.validate_meeting_text(fields[k], limit=store.MEETING_AMOUNT_TEXT_MAX, what="정량 목표·결과") if k == "target_amount" and v is not None and v < 0: raise ValueError("목표 금액은 0 이상이어야 합니다.") sets.append(f"{k} = %s") params.append(v) texts.append((k.replace("_amount", "_text"), text, err)) if "status" in fields: sets.append("status = %s") params.append(store.validate_meeting_status(fields["status"])) if "result_note" in fields: sets.append("result_note = %s") params.append(store.validate_meeting_text(fields["result_note"], what="결과")) if "marketplace_code" in fields: code = store.norm_str(fields["marketplace_code"], lower=True) if len(code) > 30 or not re.fullmatch(r"[a-z0-9_]*", code): raise ValueError("쇼핑몰 코드가 올바르지 않습니다.") sets.append("marketplace_code = %s") params.append(code) with self._pool.connection() as conn: with conn.transaction(): self._require_meetings(conn) if "result_note" in fields and not self._meeting_v20(conn): raise store.MeetingMigration020Needed() result_only = bool(fields) and set(fields) <= {"result_note", "result_amount", "status"} if self._meeting_v21(conn): for col, text, _err in texts: sets.append(f"{col} = %s") params.append(text) elif any(text for _c, text, _e in texts): raise ValueError(next(e for _c, t, e in texts if t)) # 021 전 — 예전처럼 숫자만 rows = self._locked_meeting_items(conn, item_id, check_open=not result_only) if result_only: own = next(r for r in rows if int(r["id"]) == item_id)["week_start"] self._check_result_open(conn, own) if "content" in fields: self._require_meeting_cell_visible(rows, item_id) if sets: row = conn.execute( f"UPDATE goal_meeting_items SET {', '.join(sets)}, updated_by = %s, updated_at = now() " f"WHERE id = %s RETURNING {self._meeting_cols(conn)}", (*params, store.norm_str(updated_by, lower=True), item_id), ).fetchone() else: row = next((r for r in rows if int(r["id"]) == item_id), None) if row is None: raise KeyError(item_id) return self._meeting_item(row) def move_meeting_cell(self, *, source_item: Any, target_item: Any, source_body: Any, target_body: Any, updated_by: str = "") -> str: if not isinstance(source_body, str) or not isinstance(target_body, str): raise ValueError("원본·대상 셀의 예상 내용을 문자열로 보내 주세요.") try: source, target = int(source_item), int(target_item) except (TypeError, ValueError): raise ValueError("옮길 셀이 올바르지 않습니다.") if source <= 0 or target <= 0: raise ValueError("옮길 셀이 올바르지 않습니다.") expected_source = store.validate_meeting_content(source_body) expected_target = store.validate_meeting_content(target_body) if not expected_source: raise ValueError("비어 있는 셀은 옮길 수 없습니다.") with self._pool.connection() as conn: with conn.transaction(): self._require_meetings(conn) rows = self._locked_meeting_items(conn, source) a = self._require_meeting_cell_visible(rows, source) b = self._require_meeting_cell_visible(rows, target) body = store.validate_meeting_content(rows[a]["content"]) old_target = store.validate_meeting_content(rows[b]["content"]) if source == target: return body # 응답 유실 후 같은 요청 재전송은 이미 저장된 이동으로 처리한다. if body == "" and old_target == expected_source: return old_target if body != expected_source or old_target != expected_target: raise store.GoalCellConflict("다른 곳에서 셀 내용이 바뀌었습니다. 새로고침 후 다시 옮겨 주세요.") for item, text in ((target, body), (source, "")): conn.execute("UPDATE goal_meeting_items SET content = %s, updated_by = %s, updated_at = now() " "WHERE id = %s", (text, store.norm_str(updated_by, lower=True), item)) return body def merge_meeting_cells(self, *, item_from: Any, item_to: Any, updated_by: str = "") -> dict[str, Any]: try: first, last = int(item_from), int(item_to) except (TypeError, ValueError): raise ValueError("병합할 셀이 올바르지 않습니다.") with self._pool.connection() as conn: with conn.transaction(): self._require_meetings(conn) if not self._meeting_cells(conn): raise store.MeetingCellMigrationNeeded() rows = self._locked_meeting_items(conn, first) indices = {int(r["id"]): n for n, r in enumerate(rows)} if last not in indices: raise KeyError(last) a, b = sorted((indices[first], indices[last])) # 마지막 셀이 이미 병합된 경우 그 아래까지 선택 범위를 넓힌다. b += int(rows[b].get("content_row_span") or 1) - 1 if a == b or b - a + 1 > 500 or any(r["section"] != rows[a]["section"] for r in rows[a:b + 1]): raise ValueError("같은 구역의 이번주 할 일 셀을 2줄 이상 선택해 주세요.") if any(x < a <= y or x <= b < y for x, y in self._meeting_merge_ranges(rows)): raise store.GoalCellConflict("병합된 셀 전체를 선택해 주세요.") body = store.validate_meeting_content(store.merge_goal_texts([r["content"] for r in rows[a:b + 1]])) who = store.norm_str(updated_by, lower=True) for n in range(a, b + 1): conn.execute("UPDATE goal_meeting_items SET content = %s, content_row_span = %s, " "updated_by = %s, updated_at = now() WHERE id = %s", (body if n == a else "", b - a + 1 if n == a else 1, who, rows[n]["id"])) return {"item_id": int(rows[a]["id"]), "row_span": b - a + 1, "body": body} def unmerge_meeting_cell(self, *, item_id: int, updated_by: str = "") -> None: with self._pool.connection() as conn: with conn.transaction(): self._require_meetings(conn) if not self._meeting_cells(conn): raise store.MeetingCellMigrationNeeded() rows = self._locked_meeting_items(conn, item_id) self._require_meeting_cell_visible(rows, item_id) conn.execute("UPDATE goal_meeting_items SET content_row_span = 1, updated_by = %s, " "updated_at = now() WHERE id = %s", (store.norm_str(updated_by, lower=True), item_id)) def delete_meeting_item(self, *, item_id: int) -> None: with self._pool.connection() as conn: with conn.transaction(): self._require_meetings(conn) rows = self._locked_meeting_items(conn, item_id) i = next(n for n, r in enumerate(rows) if int(r["id"]) == item_id) if any(a <= i <= b for a, b in self._meeting_merge_ranges(rows)): raise ValueError("병합된 셀의 줄을 삭제하려면 먼저 병합을 해제해 주세요.") row = conn.execute("DELETE FROM goal_meeting_items WHERE id = %s RETURNING id", (item_id,)).fetchone() if row is None: raise KeyError(item_id) def move_meeting_item(self, *, item_id: int, direction: int) -> None: """같은 구역 안에서 한 칸 위/아래.""" with self._pool.connection() as conn: with conn.transaction(): self._require_meetings(conn) rows = self._locked_meeting_items(conn, item_id) ids = [int(r["id"]) for r in rows] i = ids.index(item_id) j = i + (1 if direction > 0 else -1) if not 0 <= j < len(ids) or rows[j]["section"] != rows[i]["section"]: return if any(a <= i <= b or a <= j <= b for a, b in self._meeting_merge_ranges(rows)): raise ValueError("병합된 셀의 줄을 이동하려면 먼저 병합을 해제해 주세요.") ids[i], ids[j] = ids[j], ids[i] for n, x in enumerate(ids): conn.execute("UPDATE goal_meeting_items SET sort_order = %s WHERE id = %s", (n, x)) def move_meeting_section(self, *, item_id: int, direction: int) -> None: """구역(표 첫 열 "구분") 통째로 한 칸 위/아래 — item_id 가 든 구역 묶음(이어진 같은 구역 줄)과 옆 구역 묶음의 자리를 바꾼다. 묶음 안 줄 순서·세로 병합(content_row_span)은 그대로 따라간다. 맨 위/맨 아래면 그대로.""" with self._pool.connection() as conn: with conn.transaction(): self._require_meetings(conn) rows = self._locked_meeting_items(conn, item_id) ids = [int(r["id"]) for r in rows] blocks: list[list[int]] = [] # 이어진 같은 구역 줄 묶음(화면의 tbody 하나) for i, r in enumerate(rows): if i and r["section"] == rows[i - 1]["section"]: blocks[-1].append(ids[i]) else: blocks.append([ids[i]]) b = next(n for n, blk in enumerate(blocks) if item_id in blk) j = b + (1 if direction > 0 else -1) if not 0 <= j < len(blocks): return blocks[b], blocks[j] = blocks[j], blocks[b] order = [x for blk in blocks for x in blk] for n, x in enumerate(order): conn.execute("UPDATE goal_meeting_items SET sort_order = %s WHERE id = %s", (n, x)) # ── 회의록 작업 등록 표(025) — 주차별 한 표, 모두가 같이 본다. [적용] 전 줄은 고치고, [적용]은 한 번만 ── # 026 — 작업 칸(parent_task_id): 고르면 [적용] 때 그 작업의 세부 작업으로(비우면 그 섹션에 새 작업). # 025 의 parent_id(표 안 줄끼리 세부 작업)는 화면에서 쓰지 않는다(열·값은 그대로, 읽기·쓰기 안 함). _MT_BASE = ("id, week_start, sort_order, title, assignee_email, project_id, stage_id, task_id, " "created_by, updated_by, created_at, updated_at") def _mt_v26(self, conn: Any) -> bool: """026(작업 칸 parent_task_id) 적용 여부 — 적용되면 한 번만 확인.""" if getattr(self, "_mt_v26_ok", False): return True ok = self._column_exists(conn, "goal_meeting_tasks", "parent_task_id") if ok: self._mt_v26_ok = True return ok def _mt_cols(self, conn: Any, prefix: str = "") -> str: cols = [prefix + c.strip() for c in self._MT_BASE.split(",")] if self._mt_v26(conn): cols.append(prefix + "parent_task_id") return ", ".join(cols) def _mt_conn(self) -> Any: return self._pool.connection() @staticmethod def _mt_call(fn: Any) -> Any: try: return fn() except psycopg_errors.UndefinedTable: raise store.MeetingTaskMigrationNeeded() @staticmethod def _mt_row(r: dict[str, Any]) -> dict[str, Any]: out = {k: r.get(k) for k in ("id", "sort_order", "title", "assignee_email", "project_id", "stage_id", "task_id", "parent_task_id", "created_by", "updated_by")} for k in ("id", "project_id", "stage_id", "task_id", "parent_task_id"): out[k] = int(out[k]) if out[k] is not None else None out["week_start"] = r["week_start"].isoformat() out["updated_at"] = r["updated_at"].astimezone(KST).isoformat(timespec="seconds") if r.get("updated_at") else "" for k in ("project_name", "project_status", "stage_name", "task_title", "task_project_id", "parent_task_title"): if k in r: out[k] = r[k] if "task_exists" in r: out["task_exists"] = bool(r["task_exists"]) return out def _mt_clean(self, conn: Any, fields: dict[str, Any], *, project_id: Any = None) -> dict[str, Any]: """고칠 칸 정리 — title(200자)·assignee_email·project_id·stage_id(그 프로젝트 섹션)·parent_task_id(그 프로젝트 작업, 026). 프로젝트가 바뀌면 섹션·작업을 비운다.""" clean: dict[str, Any] = {} v26 = self._mt_v26(conn) if "title" in fields: t = store.norm_str(fields.get("title")) if len(t) > 200: raise ValueError("작업 제목은 200자 이하로 입력하세요.") clean["title"] = t if "assignee_email" in fields: clean["assignee_email"] = store.norm_str(fields.get("assignee_email") or "", lower=True) pid = project_id if "project_id" in fields: raw = fields.get("project_id") try: pid = int(raw) if raw not in (None, "") else None except (TypeError, ValueError): raise ValueError("프로젝트 값이 올바르지 않습니다.") clean["project_id"] = pid if "stage_id" not in fields: clean["stage_id"] = None if v26 and "parent_task_id" not in fields: clean["parent_task_id"] = None if "stage_id" in fields: sid = fields.get("stage_id") if sid in (None, ""): clean["stage_id"] = None else: if pid is None: raise ValueError("프로젝트를 먼저 고르세요.") clean["stage_id"] = self._check_stage_in_project(conn, sid, int(pid)) if "parent_task_id" in fields: if not v26: raise store.MeetingParentTaskMigrationNeeded() raw = fields.get("parent_task_id") if raw in (None, ""): clean["parent_task_id"] = None else: try: tid = int(raw) except (TypeError, ValueError): raise ValueError("작업 값이 올바르지 않습니다.") if pid is None: raise ValueError("프로젝트를 먼저 고르세요.") t = conn.execute("SELECT project_id FROM tasks WHERE id = %s", (tid,)).fetchone() if t is None or int(t["project_id"]) != int(pid): raise ValueError("이 프로젝트의 작업이 아닙니다.") clean["parent_task_id"] = tid return clean def _mt_select(self, conn: Any, where: str, params: tuple[Any, ...]) -> list[dict[str, Any]]: """줄 + 프로젝트·섹션·고른 작업 이름 + 만든 작업 존재 여부(목록·한 줄 응답 공용).""" v26 = self._mt_v26(conn) return conn.execute( f"SELECT {self._mt_cols(conn, 'm.')}, " " p.name AS project_name, p.status AS project_status, s.name AS stage_name, " " t.title AS task_title, t.project_id AS task_project_id, (t.id IS NOT NULL) AS task_exists" + (", pt.title AS parent_task_title " if v26 else " ") + "FROM goal_meeting_tasks m " "LEFT JOIN projects p ON p.id = m.project_id " "LEFT JOIN project_stages s ON s.id = m.stage_id " "LEFT JOIN tasks t ON t.id = m.task_id " + ("LEFT JOIN tasks pt ON pt.id = m.parent_task_id " if v26 else "") + f"WHERE {where} ORDER BY m.sort_order, m.id", params, ).fetchall() def list_meeting_tasks(self, *, week_start: date) -> list[dict[str, Any]]: """그 주차 표 — 순서대로. 프로젝트·섹션·고른 작업 이름, 만든 작업 존재 여부를 붙인다.""" def run() -> list[dict[str, Any]]: with self._mt_conn() as conn: return [self._mt_row(r) for r in self._mt_select(conn, "m.week_start = %s", (week_start,))] return self._mt_call(run) def get_meeting_task(self, *, item_id: int) -> dict[str, Any] | None: def run() -> dict[str, Any] | None: with self._mt_conn() as conn: rows = self._mt_select(conn, "m.id = %s", (item_id,)) return self._mt_row(rows[0]) if rows else None return self._mt_call(run) def add_meeting_task(self, *, week_start: date, fields: dict[str, Any], by: str = "", task_id: int | None = None) -> dict[str, Any]: """줄 추가(빈 줄도). task_id = 예전 브라우저 표에서 옮겨 온 이미 등록된 줄.""" who = store.norm_str(by, lower=True) def run() -> int: with self._mt_conn() as conn: with conn.transaction(): self._check_meeting_open(conn, week_start) clean = self._mt_clean(conn, fields) nxt = conn.execute("SELECT COALESCE(MAX(sort_order), -1) + 1 AS n FROM goal_meeting_tasks " "WHERE week_start = %s", (week_start,)).fetchone()["n"] cols = ["week_start", "sort_order", "title", "assignee_email", "project_id", "stage_id", "task_id", "created_by", "updated_by"] vals = [week_start, int(nxt), clean.get("title", ""), clean.get("assignee_email", ""), clean.get("project_id"), clean.get("stage_id"), task_id, who, who] if clean.get("parent_task_id") is not None: cols.append("parent_task_id") vals.append(clean["parent_task_id"]) return int(conn.execute( f"INSERT INTO goal_meeting_tasks ({', '.join(cols)}) VALUES ({', '.join(['%s'] * len(cols))}) " "RETURNING id", vals, ).fetchone()["id"]) return self.get_meeting_task(item_id=self._mt_call(run)) # type: ignore[return-value] def update_meeting_task(self, *, item_id: int, fields: dict[str, Any], by: str = "") -> dict[str, Any]: """[적용] 전 줄만 고친다(줄을 잠그고 — 다른 사람이 막 [적용]한 줄은 409). 회의 완료된 주차면 잠금.""" def run() -> None: with self._mt_conn() as conn: with conn.transaction(): row = conn.execute("SELECT week_start, project_id, task_id FROM goal_meeting_tasks WHERE id = %s FOR UPDATE", (item_id,)).fetchone() if row is None: raise KeyError(item_id) self._check_meeting_open(conn, row["week_start"]) if row["task_id"] is not None: raise store.GoalCellConflict("이미 [적용]해 작업으로 만든 줄입니다. 새로고침해 주세요.") clean = self._mt_clean(conn, fields, project_id=row["project_id"]) if not clean: return sets = ", ".join(f"{k} = %s" for k in clean) conn.execute(f"UPDATE goal_meeting_tasks SET {sets}, updated_by = %s, updated_at = now() WHERE id = %s", (*clean.values(), store.norm_str(by, lower=True), item_id)) self._mt_call(run) return self.get_meeting_task(item_id=item_id) # type: ignore[return-value] def delete_meeting_task(self, *, item_id: int) -> dict[str, Any]: """줄 지우기. 만든 작업은 라우터·화면이 따로 지운다(휴지통).""" def run() -> dict[str, Any]: with self._mt_conn() as conn: with conn.transaction(): row = conn.execute(f"SELECT {self._mt_cols(conn)} FROM goal_meeting_tasks WHERE id = %s FOR UPDATE", (item_id,)).fetchone() if row is None: raise KeyError(item_id) self._check_meeting_open(conn, row["week_start"]) conn.execute("DELETE FROM goal_meeting_tasks WHERE id = %s", (item_id,)) return self._mt_row(row) return self._mt_call(run) def apply_meeting_task(self, *, item_id: int, create: Any) -> tuple[dict[str, Any], bool]: """[적용] — 줄을 잠그고 아직 작업이 없을 때만 create(줄, 상위 작업 id) 로 작업을 만들어 task_id 를 남긴다. 작업 칸(parent_task_id)을 골랐으면 그 작업의 세부 작업으로(섹션 없이). (줄, 이번에 만들었는가). 두 사람이 동시에 눌러도 작업은 하나. create 가 실패하면 줄은 그대로.""" def run() -> tuple[int, bool]: with self._mt_conn() as conn: with conn.transaction(): row = conn.execute(f"SELECT {self._mt_cols(conn)} FROM goal_meeting_tasks WHERE id = %s FOR UPDATE", (item_id,)).fetchone() if row is None: raise KeyError(item_id) self._check_meeting_open(conn, row["week_start"]) if row["task_id"] is not None: return item_id, False use = self._mt_row(row) parent_task = use.get("parent_task_id") if parent_task is not None: t = conn.execute("SELECT project_id FROM tasks WHERE id = %s", (parent_task,)).fetchone() if t is None or use["project_id"] is None or int(t["project_id"]) != int(use["project_id"]): raise ValueError("고른 작업이 없어졌거나 다른 프로젝트로 옮겨졌습니다. 작업 칸을 다시 고르세요.") use = {**use, "stage_id": None} task = create(use, parent_task) conn.execute("UPDATE goal_meeting_tasks SET task_id = %s, updated_at = now() WHERE id = %s", (int(task["id"]), item_id)) return item_id, True iid, made = self._mt_call(run) return self.get_meeting_task(item_id=iid), made # type: ignore[return-value] def goal_month_targets(self, *, year: int, month: int) -> dict[str, Any]: """회의록 머리 — 그 달 매출 목표·실적, 로아스 목표(목표 표 숫자), 매출 단위. 목표 표가 없으면 빈 값.""" with self._pool.connection() as conn: if not self._table_exists(conn, "goal_years"): return {"sales_unit": "", "sales_target": None, "sales_actual": None, "roas_target": None} head = conn.execute("SELECT sales_unit FROM goal_years WHERE year = %s", (year,)).fetchone() vals = {(r["metric"], r["kind"]): float(r["value"]) for r in conn.execute( "SELECT metric, kind, value FROM goal_metrics WHERE year = %s AND month = %s", (year, month), ).fetchall()} return {"sales_unit": head["sales_unit"] if head else "", "sales_target": vals.get(("sales", "target")), "sales_actual": vals.get(("sales", "actual")), "roas_target": vals.get(("roas", "target"))} # ── 주차별 매출 목표(020) — 목표 표 매출 단위 그대로, 월 목표는 따로 직접 입력(주차 합계와 다를 수 있음) ── def week_targets_enabled(self) -> bool: with self._pool.connection() as conn: return self._table_exists(conn, "goal_week_targets") def goal_week_targets(self, *, start: date, end: date) -> dict[str, float]: """기간 안 주차 시작일 → 목표(매출 단위). 020 미적용이면 빈 값.""" with self._pool.connection() as conn: if not self._table_exists(conn, "goal_week_targets"): return {} rows = conn.execute( "SELECT week_start, value FROM goal_week_targets WHERE week_start BETWEEN %s AND %s ORDER BY week_start", (start, end), ).fetchall() return {r["week_start"].isoformat(): float(r["value"]) for r in rows} def set_goal_week_targets( self, *, year: int, month: int, values: dict[date, float | None], month_value: float | None, updated_by: str = "" ) -> float | None: """그 달 주차별 목표 저장(None = 지움) + 월 매출 목표(goal_metrics sales/target)는 month_value 그대로 (None = 지움). 월 목표는 주차 합계와 따로 — 차이는 화면이 계산한다. 그 달 주차 합계를 돌려준다(없으면 None).""" if month_value is not None and month_value < 0: raise ValueError("월 목표는 0 이상이어야 합니다.") m = store.validate_goal_month(month) periods = {a for a, _ in store.month_weeks(year, m)} if any(d not in periods for d in values): raise ValueError("주차가 바뀌었습니다. 새로고침해 주세요.") who = store.norm_str(updated_by, lower=True) with self._pool.connection() as conn: with conn.transaction(): if not self._table_exists(conn, "goal_week_targets"): raise store.MeetingMigration020Needed() if not conn.execute("SELECT 1 FROM goal_years WHERE year = %s FOR UPDATE", (year,)).fetchone(): raise KeyError(year) for d, v in values.items(): if v is None: conn.execute("DELETE FROM goal_week_targets WHERE week_start = %s", (d,)) else: if v < 0: raise ValueError("주차 목표는 0 이상이어야 합니다.") conn.execute( "INSERT INTO goal_week_targets (week_start, year, month, value, updated_by) " "VALUES (%s,%s,%s,%s,%s) ON CONFLICT (week_start) DO UPDATE " "SET value = EXCLUDED.value, updated_by = EXCLUDED.updated_by, updated_at = now()", (d, year, m, v, who), ) row = conn.execute( "SELECT count(*) AS n, sum(value) AS total FROM goal_week_targets WHERE year = %s AND month = %s", (year, m), ).fetchone() total = float(row["total"]) if row["n"] else None if month_value is None: conn.execute("DELETE FROM goal_metrics WHERE year=%s AND metric='sales' AND kind='target' AND month=%s", (year, m)) else: conn.execute( "INSERT INTO goal_metrics (year, metric, kind, month, value, updated_by) " "VALUES (%s,'sales','target',%s,%s,%s) ON CONFLICT (year, metric, kind, month) DO UPDATE " "SET value = EXCLUDED.value, updated_by = EXCLUDED.updated_by, updated_at = now()", (year, m, month_value, who), ) return total def goal_area_sections(self, *, year: int) -> list[tuple[str, str]]: """그 해 목표 표의 업무 영역(이름, 색) — 첫 회의록 구역. 없으면 빈 목록(기본 양식 구역).""" with self._pool.connection() as conn: if not self._table_exists(conn, "goal_areas"): return [] rows = conn.execute( "SELECT name, color FROM goal_areas WHERE year = %s ORDER BY sort_order, id", (year,) ).fetchall() return [(r["name"], r["color"]) for r in rows] # ════════════════════════════════════════════════════════════ # 직렬화 # ════════════════════════════════════════════════════════════ @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