Files
dbx-main/app/modules/project/db.py
T
king c9bce7c976 feat(project): 연간 목표 엑셀식 칸 병합(끌어 고르기·우클릭 병합/해제) + 월별 주간 회의록
엑셀식 칸 병합 (예전 Shift+클릭·병합 버튼·오른쪽/왼쪽 칸 병합 메뉴 대체)
- 글 칸을 마우스로 끌어(또는 Shift+클릭) 사각형 선택 → 우클릭 "셀 병합 (N줄 × M칸)" / "병합 해제"
- 같은 업무 영역 안 세로(row_span) + 같은 반기 월 칸 가로, 연간·상·하반기 칸은 세로로만
- 걸친 병합은 엑셀처럼 범위를 넓혀 흡수, 글은 왼쪽 위부터 이어 왼쪽 위 칸에, 해제하면 왼쪽 위 칸에 남음
- POST /api/goals/areas/{id}/merge {row_from,row_to,col_from,col_to} (db.merge_goal_rect), router._goal_area_layout(colspan·rowspan)
- 가려진 칸 저장 거절(세로 포함), 병합 안쪽 줄 끼우기 +1 / 가려진 줄 지우기 -1, 세로 병합에 걸린 줄 이동 거절

주간 회의록 (/project/goals/{연도}/meetings/{월}, 목표 표 월 머리 클릭)
- 주(월~일) 탭, 주마다 회의록: 이번주 할 일·목표 금액 | 지난주 할 일·목표·결과·달성률·평가
- 앞선 회의록 줄 이어받기(carry_from), 처음이면 목표 표 업무 영역 + 기본 양식 줄(유통 줄 쇼핑몰 연결 추측)
- 머리: 월 목표·지난주까지 누적·주당 필요 매출(페이싱)·전주 목표/결과/달성률·금주 목표/현재 실적
- 쇼핑몰 연결 줄의 결과·누적·주간 매출은 실적 모듈 performance_store 읽기 전용(없으면 직접 입력)
- 금액 입력 120만·1.5억·3천만·1억2천만, 참석자·결정 사항 메모, 줄 메뉴(추가·순서·쇼핑몰 연결·삭제), 인쇄

마이그레이션 015(project_db): goal_cell_merges.row_span + CHECK 교체, goal_meetings, goal_meeting_items
캐시 버전 20261001c, 테스트(DB 회귀 test_goal_rect_merges·test_goal_meetings)·문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 11:46:25 +09:00

2651 lines
138 KiB
Python

"""project_db PostgreSQL 저장소.
- 드라이버: psycopg 3 (`psycopg[binary,pool]`) — 다른 모듈과 동일 패턴.
- 연결 정보: 환경변수 `PROJECT_DB_URL`
(예: postgresql://project_app:<pwd>@postgres-db:5432/project_db)
- 스키마는 앱이 만들지 않는다. `scripts/sql/project_db_init.sql` 을 superuser 가
사전 적용한다. 앱 계정(project_app)은 CRUD 권한만 받는다.
- 연결 풀은 lazy open.
순수 검증/상수는 store.py 에 있고, 여기서는 DB I/O 와 직렬화만 담당한다.
"""
from __future__ import annotations
import logging
import re
import time
from datetime import date, datetime
from datetime import time as dtime
from typing import Any
from psycopg import errors as psycopg_errors
from psycopg.rows import dict_row
from psycopg.types.json import Jsonb
from psycopg_pool import ConnectionPool
from app.timezone import KST, now_kst
from . import store
logger = logging.getLogger("project.db")
class ProjectStore:
def __init__(self, dsn: str, *, min_size: int = 1, max_size: int = 5):
self._pool = ConnectionPool(
conninfo=dsn,
min_size=min_size,
max_size=max_size,
kwargs={"row_factory": dict_row, "autocommit": True},
open=False,
)
self._pool.open(wait=False)
self._live_retry_at = 0.0 # latest_version: 007 카운터 테이블 재시도 시각
def close(self) -> None:
self._pool.close()
# ════════════════════════════════════════════════════════════
# 프로젝트 / 서브프로젝트
# ════════════════════════════════════════════════════════════
def list_projects(
self, *, include_archived: bool = False, member_email: str | None = None
) -> list[dict[str, Any]]:
"""전체 프로젝트(서브 포함) 평면 목록. member_email 지정 시 그 사용자가
멤버이거나 owner 인 프로젝트만(관리자는 라우터에서 None 으로 전체 조회).
"""
clauses: list[str] = []
params: list[Any] = []
if not include_archived:
clauses.append("p.status <> 'archived'")
if member_email:
clauses.append(
"(p.owner_email = %s OR EXISTS ("
" SELECT 1 FROM project_members m "
" WHERE m.project_id = p.id AND m.user_email = %s))"
)
params.extend([member_email, member_email])
where = ("WHERE " + " AND ".join(clauses)) if clauses else ""
with self._pool.connection() as conn:
rows = conn.execute(
f"SELECT p.* FROM projects p {where} "
"ORDER BY p.parent_id NULLS FIRST, p.sort_order ASC, p.id ASC",
params,
).fetchall()
return [self._serialize(r) for r in rows]
def get_project(self, *, project_id: int) -> dict[str, Any] | None:
with self._pool.connection() as conn:
row = conn.execute(
"SELECT * FROM projects WHERE id = %s", (project_id,)
).fetchone()
return self._serialize(row) if row else None
def create_project(
self,
*,
name: str,
parent_id: int | None = None,
description: str = "",
color: str = "",
owner_email: str = "",
start_date: str | None = None,
due_date: str | None = None,
created_by: str = "",
seed_stages: bool = False,
icon: str | None = None,
) -> dict[str, Any]:
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"]
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
if "start_date" in clean or "due_date" in clean:
# 한쪽만 바꿔도 기존 값과 합친 최종 상태로 검사한다.
existing = self.get_project(project_id=project_id)
if existing is None:
raise KeyError(project_id)
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"),
)
params.append(project_id)
with self._pool.connection() as conn:
row = conn.execute(
f"UPDATE projects SET {', '.join(sets)} WHERE id = %s RETURNING *",
params,
).fetchone()
if not row:
raise KeyError(project_id)
return self._serialize(row)
def delete_project(self, *, project_id: int) -> list[int]:
"""프로젝트(서브프로젝트·단계·업무 CASCADE) 삭제.
같이 지워진 업무 id 목록을 돌려준다 — DB 행은 CASCADE 로 사라지지만
디스크의 첨부 폴더(DATA_DIR/project/<task_id>)는 라우터가 치워야 한다.
"""
with self._pool.connection() as conn:
with conn.transaction():
rows = conn.execute(
"WITH RECURSIVE tree AS ("
" SELECT id FROM projects WHERE id = %s "
" UNION ALL "
" SELECT p.id FROM projects p JOIN tree ON p.parent_id = tree.id"
") SELECT t.id FROM tasks t WHERE t.project_id IN (SELECT id FROM tree)",
(project_id,),
).fetchall()
cur = conn.execute("DELETE FROM projects WHERE id = %s", (project_id,))
if cur.rowcount == 0:
raise KeyError(project_id)
return [int(r["id"]) for r in rows]
# ════════════════════════════════════════════════════════════
# 멤버
# ════════════════════════════════════════════════════════════
def list_members(self, *, project_id: int) -> list[dict[str, Any]]:
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT * FROM project_members WHERE project_id = %s "
"ORDER BY role DESC, user_email ASC",
(project_id,),
).fetchall()
return [self._serialize(r) for r in rows]
def is_member(self, *, project_id: int, user_email: str) -> bool:
email = store.norm_str(user_email, lower=True)
with self._pool.connection() as conn:
row = conn.execute(
"SELECT 1 FROM projects p "
"LEFT JOIN project_members m "
" ON m.project_id = p.id AND m.user_email = %s "
"WHERE p.id = %s AND (p.owner_email = %s OR m.id IS NOT NULL) LIMIT 1",
(email, project_id, email),
).fetchone()
return bool(row)
def add_member(
self, *, project_id: int, user_email: str, user_name: str = "", role: str = "member"
) -> dict[str, Any]:
email = store.norm_str(user_email, lower=True)
if not email or "@" not in email:
raise ValueError("올바른 이메일이 아닙니다.")
rl = store.validate_role(role)
with self._pool.connection() as conn:
row = conn.execute(
"""
INSERT INTO project_members (project_id, user_email, user_name, role)
VALUES (%s,%s,%s,%s)
ON CONFLICT (project_id, user_email) DO UPDATE
SET role = EXCLUDED.role, user_name = EXCLUDED.user_name
RETURNING *
""",
(project_id, email, store.norm_str(user_name), rl),
).fetchone()
return self._serialize(row)
def remove_member(self, *, project_id: int, user_email: str) -> None:
email = store.norm_str(user_email, lower=True)
with self._pool.connection() as conn:
conn.execute(
"DELETE FROM project_members WHERE project_id = %s AND user_email = %s",
(project_id, email),
)
# ════════════════════════════════════════════════════════════
# 단계 (stages)
# ════════════════════════════════════════════════════════════
def list_stages(self, *, project_id: int) -> list[dict[str, Any]]:
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT * FROM project_stages WHERE project_id = %s "
"ORDER BY sort_order ASC, id ASC",
(project_id,),
).fetchall()
return [self._serialize(r) for r in rows]
def list_stages_for_projects(self, *, project_ids: list[int]) -> dict[int, list[dict[str, Any]]]:
"""여러 프로젝트의 세션을 한 번에 — {project_id: [stage, ...]} (세션 없는 프로젝트도 빈 목록)."""
ids = [int(i) for i in project_ids]
out: dict[int, list[dict[str, Any]]] = {i: [] for i in ids}
if not ids:
return out
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT * FROM project_stages WHERE project_id = ANY(%s) "
"ORDER BY project_id, sort_order ASC, id ASC",
(ids,),
).fetchall()
for r in rows:
s = self._serialize(r)
out.setdefault(s["project_id"], []).append(s)
return out
def add_stage(
self, *, project_id: int, name: str, is_done_stage: bool = False,
color: str | None = None, created_by: str = "",
default_assignee_email: str = "",
) -> dict[str, Any]:
nm = store.norm_str(name)
if not nm:
raise ValueError("섹션 이름은 필수입니다.")
col = store.validate_stage_color(color)
dae = store.norm_str(default_assignee_email or "", lower=True)
with self._pool.connection() as conn:
nxt = conn.execute(
"SELECT COALESCE(MAX(sort_order), -1) + 1 AS n "
"FROM project_stages WHERE project_id = %s",
(project_id,),
).fetchone()
# 기본 담당자 컬럼(009)은 값이 있을 때만 넣는다 — 009 미적용
# 환경에서도 담당자 없는 세션 추가는 그대로 되게.
cols = "project_id, name, sort_order, is_done_stage, color, created_by"
vals: list[Any] = [project_id, nm, int(nxt["n"]), bool(is_done_stage), col,
store.norm_str(created_by, lower=True)]
if dae:
cols += ", default_assignee_email"
vals.append(dae)
row = conn.execute(
f"INSERT INTO project_stages ({cols}) "
f"VALUES ({','.join(['%s'] * len(vals))}) RETURNING *",
vals,
).fetchone()
return self._serialize(row)
def get_stage(self, *, stage_id: int) -> dict[str, Any] | None:
with self._pool.connection() as conn:
row = conn.execute(
"SELECT * FROM project_stages WHERE id = %s", (stage_id,)
).fetchone()
return self._serialize(row) if row else None
@staticmethod
def _stage_default_assignee(conn: Any, stage_id: Any, project_id: int) -> tuple[str, str]:
"""세션 기본 담당자(마이그레이션 009) → (email, name). 미지정·009 미적용·
그 사람이 이제 프로젝트 멤버가 아니면 ('', '').
컬럼이 없어도 에러가 나지 않게 to_jsonb(행) 에서 키로 읽는다."""
if stage_id in (None, ""):
return "", ""
row = conn.execute(
"SELECT to_jsonb(s) ->> 'default_assignee_email' AS e "
"FROM project_stages s WHERE id = %s",
(stage_id,),
).fetchone()
email = store.norm_str((row or {}).get("e") or "", lower=True)
if not email:
return "", ""
# 멤버 또는 프로젝트 owner(멤버 행이 없을 수 있다)만 — 업무 담당자
# 후보와 같은 기준.
m = conn.execute(
"SELECT user_name FROM project_members WHERE project_id = %s AND user_email = %s "
"UNION ALL "
"SELECT '' FROM projects WHERE id = %s AND owner_email = %s "
"LIMIT 1",
(project_id, email, project_id, email),
).fetchone()
if not m:
return "", ""
return email, m["user_name"] or ""
@staticmethod
def _check_stage_in_project(conn: Any, stage_id: Any, project_id: int) -> int | None:
"""세션이 그 프로젝트 것인지 확인하고 int 로 돌려준다(None 은 그대로).
확인 안 하면 다른 프로젝트의 세션 id 를 넣어 업무를 엉뚱한 세션에
묶거나(보드에서 사라짐) 남의 세션 완료 여부로 완료 처리가 될 수 있다.
"""
if stage_id in (None, ""):
return None
try:
sid = int(stage_id)
except (TypeError, ValueError):
raise ValueError("섹션 값이 올바르지 않습니다.")
row = conn.execute(
"SELECT 1 FROM project_stages WHERE id = %s AND project_id = %s",
(sid, project_id),
).fetchone()
if not row:
raise ValueError("이 프로젝트의 섹션이 아닙니다.")
return sid
def stage_in_project(self, *, stage_id: Any, project_id: int) -> int | None:
with self._pool.connection() as conn:
return self._check_stage_in_project(conn, stage_id, project_id)
def delete_stage(self, *, stage_id: int) -> None:
with self._pool.connection() as conn:
cur = conn.execute("DELETE FROM project_stages WHERE id = %s", (stage_id,))
if cur.rowcount == 0:
raise KeyError(stage_id)
# ════════════════════════════════════════════════════════════
# 업무 (tasks)
# ════════════════════════════════════════════════════════════
# 업무 목록에 함께 붙이는 하위업무 집계(댓글수와 같은 방식). 여러 쿼리에서
# 재사용하므로 상수로 뽑아둔다.
_SUBTASK_COUNTS_SQL = (
"(SELECT COUNT(*) FROM tasks st WHERE st.parent_task_id = t.id) AS subtask_total, "
"(SELECT COUNT(*) FROM tasks st WHERE st.parent_task_id = t.id "
" AND st.completed_at IS NOT NULL) AS subtask_done"
)
def list_tasks(
self,
*,
project_id: int | None = None,
assignee_email: str | None = None,
include_subprojects: bool = False,
parent_task_id: int | None = None,
top_level_only: bool = True,
include_links: bool = True,
limit: int = 1000,
) -> list[dict[str, Any]]:
"""업무 목록.
기본은 최상위 업무만(`parent_task_id IS NULL`) — 하위 업무는 부모 안에서만
보인다(아사나와 동일, 보드/캘린더/리스트 카드로 따로 뜨지 않는다).
`parent_task_id` 를 주면 그 부모의 하위 업무만 받는다.
`project_id` 하나만 지정하고(`include_subprojects=False`, 최상위 조회일
때) `include_links=True`(기본값)이면, 그 프로젝트에 멀티호밍
(`task_project_links`)으로 연결된 다른 프로젝트의 업무도 함께 반환한다.
프로젝트 상세 화면이 '이 프로젝트만' 보여줄 때 쓰는 경로가 이 조합이다.
다른 조합(홈 전체보기·내 업무 등, `project_id=None`)은 연결 업무를 섞지
않는다 — 같은 업무가 여러 곳에서 중복으로 집계되는 것을 막기 위함이다.
"""
link_mode = (
include_links and project_id is not None
and not include_subprojects and parent_task_id is None
)
if link_mode:
return self._list_tasks_for_project_with_links(
project_id=project_id, assignee_email=assignee_email, limit=limit,
)
clauses: list[str] = []
params: list[Any] = []
if project_id is not None:
if include_subprojects:
clauses.append(
"t.project_id IN ("
" WITH RECURSIVE tree AS ("
" SELECT id FROM projects WHERE id = %s "
" UNION ALL "
" SELECT p.id FROM projects p JOIN tree ON p.parent_id = tree.id"
" ) SELECT id FROM tree)"
)
params.append(project_id)
else:
clauses.append("t.project_id = %s")
params.append(project_id)
if assignee_email:
clauses.append("t.assignee_email = %s")
params.append(store.norm_str(assignee_email, lower=True))
if parent_task_id is not None:
clauses.append("t.parent_task_id = %s")
params.append(parent_task_id)
elif top_level_only:
clauses.append("t.parent_task_id IS NULL")
where = ("WHERE " + " AND ".join(clauses)) if clauses else ""
params.append(int(limit))
with self._pool.connection() as conn:
rows = conn.execute(
f"SELECT t.*, p.name AS project_name, p.color AS project_color, "
f" s.name AS stage_name, s.is_done_stage, "
f" (SELECT COUNT(*) FROM task_comments c WHERE c.task_id = t.id) AS comment_count, "
f" {self._SUBTASK_COUNTS_SQL} "
f"FROM tasks t "
f"JOIN projects p ON p.id = t.project_id "
f"LEFT JOIN project_stages s ON s.id = t.stage_id "
f"{where} "
"ORDER BY t.sort_order ASC, t.id ASC LIMIT %s",
params,
).fetchall()
return [self._serialize(r) for r in rows]
def _list_tasks_for_project_with_links(
self, *, project_id: int, assignee_email: str | None, limit: int,
) -> list[dict[str, Any]]:
"""`list_tasks` 의 "이 프로젝트 + 여기 연결된 업무" 경로."""
return self.list_tasks_for_projects(
project_ids=[project_id], assignee_email=assignee_email, limit=limit,
)
def list_tasks_for_projects(
self, *, project_ids: list[int], assignee_email: str | None = None,
limit: int = 20000,
) -> list[dict[str, Any]]:
"""여러 프로젝트의 최상위 업무(+ 각 프로젝트에 연결된 업무)를 쿼리 한 번에.
프로젝트 화면은 접근 가능한 모든 프로젝트의 업무를 그리는데, 예전엔
프로젝트마다 쿼리를 따로 날렸다(N+1). 행마다 붙는 값:
context_project_id : 어느 프로젝트 맥락의 행인지(연결 업무는 연결된 쪽)
is_linked : 다른 프로젝트에서 연결돼 온 행인지
stage_id : 그 맥락에서의 세션(연결이면 link.stage_id — 없으면 NULL)
home_stage_id : 원래 소속 세션(tasks.stage_id). 업무 편집 팝업의
"세션" 선택은 항상 이 값을 쓴다.
`t.*` 뒤에 같은 이름(`stage_id`)을 다시 셀렉트해 덮어쓴다 — dict_row 는
중복 컬럼명이면 마지막 값을 쓴다. 원래 소속 배지(`project_name`/`color`)는
`t.project_id` 기준 그대로 둬 "다른 프로젝트에서 온 업무"임을 보인다.
"""
ids = [int(i) for i in project_ids]
if not ids:
return []
params: dict[str, Any] = {"ids": ids, "limit": int(limit)}
extra = ""
if assignee_email:
extra = "AND t.assignee_email = %(assignee)s"
params["assignee"] = store.norm_str(assignee_email, lower=True)
with self._pool.connection() as conn:
rows = conn.execute(
f"""
SELECT t.*, p.name AS project_name, p.color AS project_color,
(SELECT COUNT(*) FROM task_comments c WHERE c.task_id = t.id) AS comment_count,
{self._SUBTASK_COUNTS_SQL},
x.context_project_id,
x.is_linked,
t.stage_id AS home_stage_id,
CASE WHEN x.is_linked THEN es.name ELSE s.name END AS stage_name,
CASE WHEN x.is_linked THEN es.is_done_stage ELSE s.is_done_stage END AS is_done_stage,
CASE WHEN x.is_linked THEN x.link_stage_id ELSE t.stage_id END AS stage_id
FROM (
SELECT id AS task_id, project_id AS context_project_id,
FALSE AS is_linked, NULL::bigint AS link_stage_id
FROM tasks
WHERE parent_task_id IS NULL AND project_id = ANY(%(ids)s)
UNION ALL
SELECT l.task_id, l.project_id, TRUE, l.stage_id
FROM task_project_links l
JOIN tasks lt ON lt.id = l.task_id
WHERE l.project_id = ANY(%(ids)s)
AND lt.parent_task_id IS NULL
AND lt.project_id <> l.project_id
) x
JOIN tasks t ON t.id = x.task_id
JOIN projects p ON p.id = t.project_id
LEFT JOIN project_stages s ON s.id = t.stage_id
LEFT JOIN project_stages es ON es.id = x.link_stage_id
WHERE TRUE {extra}
ORDER BY x.context_project_id, t.sort_order ASC, t.id ASC
LIMIT %(limit)s
""",
params,
).fetchall()
return [self._serialize(r) for r in rows]
def count_my_open(self, *, assignee_email: str) -> int:
"""사이드바 "내 업무" 배지 — 내가 담당인 미완료 업무 수(하위 업무 포함,
내 업무 화면 목록과 같은 기준)."""
with self._pool.connection() as conn:
row = conn.execute(
"SELECT COUNT(*) AS n FROM tasks "
"WHERE assignee_email = %s AND completed_at IS NULL",
(store.norm_str(assignee_email, lower=True),),
).fetchone()
return int(row["n"] or 0)
def list_my_tasks(self, *, assignee_email: str, limit: int = 1000) -> list[dict[str, Any]]:
""""내 업무" 화면 전용 — 내가 담당자인 업무를 레벨(최상위/하위) 상관없이
전부 반환한다. 하위 업무 행에는 부모 업무 정보(`parent_title` 등)를 같이
붙여서, 부모가 내 업무가 아니어도(다른 사람 담당) 화면에서 트리로 묶어
보여줄 수 있게 한다.
"""
email = store.norm_str(assignee_email, lower=True)
with self._pool.connection() as conn:
rows = conn.execute(
f"SELECT t.*, p.name AS project_name, p.color AS project_color, "
f" s.name AS stage_name, s.is_done_stage, "
f" (SELECT COUNT(*) FROM task_comments c WHERE c.task_id = t.id) AS comment_count, "
f" {self._SUBTASK_COUNTS_SQL}, "
f" pt.title AS parent_title, pt.completed_at AS parent_completed_at, "
f" pt.assignee_email AS parent_assignee_email "
f"FROM tasks t "
f"JOIN projects p ON p.id = t.project_id "
f"LEFT JOIN project_stages s ON s.id = t.stage_id "
f"LEFT JOIN tasks pt ON pt.id = t.parent_task_id "
f"WHERE t.assignee_email = %s "
"ORDER BY t.sort_order ASC, t.id ASC LIMIT %s",
(email, int(limit)),
).fetchall()
return [self._serialize(r) for r in rows]
def get_task(self, *, task_id: int) -> dict[str, Any] | None:
with self._pool.connection() as conn:
row = conn.execute(
f"SELECT t.*, p.name AS project_name, p.color AS project_color, "
f" s.name AS stage_name, s.is_done_stage, "
f" (SELECT COUNT(*) FROM task_comments c WHERE c.task_id = t.id) AS comment_count, "
f" {self._SUBTASK_COUNTS_SQL} "
f"FROM tasks t JOIN projects p ON p.id = t.project_id "
f"LEFT JOIN project_stages s ON s.id = t.stage_id "
f"WHERE t.id = %s",
(task_id,),
).fetchone()
return self._serialize(row) if row else None
def create_task(
self,
*,
project_id: int,
title: str,
stage_id: int | None = None,
description: str = "",
assignee_email: str = "",
assignee_name: str = "",
priority: str = "normal",
start_date: str | None = None,
due_date: str | None = None,
start_time: str | None = None,
due_time: str | None = None,
created_by: str = "",
parent_task_id: int | None = None,
) -> dict[str, Any]:
ttl = store.validate_task_title(title)
pr = store.validate_priority(priority)
sd = store.validate_date(start_date)
dd = store.validate_date(due_date)
sti = store.validate_time(start_time)
dti = store.validate_time(due_time)
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)
# 완료 섹션에 바로 만든 작업은 완료 섹션으로 옮긴 것과 같이 완료 처리(완료 시각·이력).
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 = ""
) -> dict[str, Any]:
"""업무 수정. 반환에 알림 힌트를 담는다(라우터가 메일 발송 판단).
반환 dict 에 추가되는 키:
_newly_assigned: 새 담당자 이메일 or None
_newly_completed: 완료로 전환됐으면 True
"""
prev = self.get_task(task_id=task_id)
if prev is None:
raise KeyError(task_id)
sets: list[str] = []
params: list[Any] = []
newly_assigned: str | None = None
newly_completed = False
new_stage: Any = None
if "stage_id" in fields:
new_stage = self.stage_in_project(
stage_id=fields["stage_id"], project_id=prev["project_id"]
)
# 다른 세션으로 옮겨왔고 (옮긴 뒤에도) 담당자가 비어 있으면 그 세션의
# 기본 담당자를 배정한다. 이미 담당자가 있으면 그대로 둔다.
if new_stage is not None and new_stage != prev.get("stage_id"):
final_assignee = (
store.norm_str(fields["assignee_email"], lower=True)
if "assignee_email" in fields else (prev.get("assignee_email") or "")
)
if not final_assignee:
with self._pool.connection() as conn:
dae, dan = self._stage_default_assignee(conn, new_stage, prev["project_id"])
if dae:
fields = {**fields, "assignee_email": dae, "assignee_name": dan}
if "title" in fields:
sets.append("title = %s")
params.append(store.validate_task_title(fields["title"]))
if "description" in fields:
sets.append("description = %s")
params.append(store.norm_str(fields["description"]))
if "priority" in fields:
sets.append("priority = %s")
params.append(store.validate_priority(fields["priority"]))
if "start_date" in fields:
sets.append("start_date = %s")
params.append(store.validate_date(fields["start_date"]))
if "due_date" in fields:
sets.append("due_date = %s")
params.append(store.validate_date(fields["due_date"]))
if "start_time" in fields:
sets.append("start_time = %s")
params.append(store.validate_time(fields["start_time"]))
if "due_time" in fields:
sets.append("due_time = %s")
params.append(store.validate_time(fields["due_time"]))
if "assignee_email" in fields:
new_assignee = store.norm_str(fields["assignee_email"], lower=True)
sets.append("assignee_email = %s")
params.append(new_assignee)
if "assignee_name" in fields:
sets.append("assignee_name = %s")
params.append(store.norm_str(fields["assignee_name"]))
if new_assignee and new_assignee != (prev.get("assignee_email") or ""):
newly_assigned = new_assignee
elif "assignee_name" in fields:
sets.append("assignee_name = %s")
params.append(store.norm_str(fields["assignee_name"]))
# 단계 변경 → 완료단계 진입 시 completed_at 자동 세팅. 단, 실제로 단계가
# 바뀐 경우에만 판정한다 — 업무 편집 모달의 "저장"은 매번 현재 stage_id
# 를 그대로 다시 보내는데, 여기서 무조건 판정하면 방금 "완료로 표시"로
# 켠 completed_at 을(단계는 그대로인데) 다시 꺼버리는 버그가 있었다.
if "stage_id" in fields:
sets.append("stage_id = %s")
params.append(new_stage)
if new_stage != prev.get("stage_id"):
done = self._stage_is_done(new_stage)
if done and not prev.get("completed_at"):
sets.append("completed_at = %s")
params.append(now_kst())
newly_completed = True
elif not done and prev.get("completed_at"):
sets.append("completed_at = NULL")
# 직접 완료 토글 — 하위 업무는 세션(칸반 컬럼)이 없어 위 자동 세팅이
# 적용되지 않는다. "stage_id" 를 같이 보냈으면 그쪽 판정이 우선한다.
elif "completed" in fields:
if fields["completed"] and not prev.get("completed_at"):
sets.append("completed_at = %s")
params.append(now_kst())
newly_completed = True
elif not fields["completed"] and prev.get("completed_at"):
sets.append("completed_at = NULL")
if not sets:
return {**prev, "_newly_assigned": None, "_newly_completed": False}
# 날짜 범위 — 한쪽만 바꾸거나 지워도 기존 값과 합친 최종 상태로 검사.
if any(k in fields for k in ("start_date", "due_date", "start_time", "due_time")):
def final(key: str, fn: Any) -> Any:
return fn(fields[key]) if key in fields else prev.get(key)
store.validate_date_range(
final("start_date", store.validate_date), final("due_date", store.validate_date),
final("start_time", store.validate_time), final("due_time", store.validate_time),
)
params.append(task_id)
with self._pool.connection() as conn:
with conn.transaction():
conn.execute(
f"UPDATE tasks SET {', '.join(sets)} WHERE id = %s", params
)
if newly_assigned:
self._log(conn, project_id=prev["project_id"], task_id=task_id,
actor=actor, action=store.ACTION_ASSIGNED,
detail=f"{prev['title']} → {newly_assigned}")
if newly_completed:
self._log(conn, project_id=prev["project_id"], task_id=task_id,
actor=actor, action=store.ACTION_COMPLETED,
detail=prev["title"])
out = self.get_task(task_id=task_id)
out["_newly_assigned"] = newly_assigned
out["_newly_completed"] = newly_completed
return out
# ════════════════════════════════════════════════════════════
# 휴지통 (마이그레이션 010) — 지우기 직전 스냅샷, 관리자 복구, 3개월 보관
# ════════════════════════════════════════════════════════════
# 업무에 딸린 테이블(task_id 로 묶임). 복구 때 이 순서대로 다시 넣는다 —
# task_mentions·task_attachments 의 comment_id 가 댓글을 가리키므로 댓글 먼저.
# 알림(project_notifications)은 되살리면 수신함에 옛 알림이 다시 쌓여 제외.
TRASH_CHILD_TABLES = (
"task_comments", "task_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}
def _stage_is_done(self, stage_id: Any) -> bool:
if stage_id is None:
return False
with self._pool.connection() as conn:
row = conn.execute(
"SELECT is_done_stage FROM project_stages WHERE id = %s", (stage_id,)
).fetchone()
return bool(row and row["is_done_stage"])
# ════════════════════════════════════════════════════════════
# 멀티호밍 (task_project_links) — 업무 1개가 여러 프로젝트/세션에 동시 소속.
# 원래 소속(tasks.project_id/stage_id)은 여기서 건드리지 않는다("기본 홈"은
# 업무 삭제로만 없어진다). 같은 프로젝트에 중복 연결하면 세션만 갱신한다.
# ════════════════════════════════════════════════════════════
def add_task_link(
self, *, task_id: int, project_id: int, stage_id: int | None = None,
created_by: str = "",
) -> dict[str, Any]:
with self._pool.connection() as conn:
row = conn.execute(
"""
INSERT INTO task_project_links (task_id, project_id, stage_id, created_by)
VALUES (%s,%s,%s,%s)
ON CONFLICT (task_id, project_id) DO UPDATE
SET stage_id = EXCLUDED.stage_id
RETURNING *
""",
(task_id, project_id, stage_id, store.norm_str(created_by, lower=True)),
).fetchone()
return self._serialize(row)
def remove_task_link(self, *, task_id: int, project_id: int) -> None:
with self._pool.connection() as conn:
conn.execute(
"DELETE FROM task_project_links WHERE task_id = %s AND project_id = %s",
(task_id, project_id),
)
def list_task_links(self, *, task_id: int) -> list[dict[str, Any]]:
with self._pool.connection() as conn:
rows = conn.execute(
"""
SELECT l.*, p.name AS project_name, p.color AS project_color,
s.name AS stage_name
FROM task_project_links l
JOIN projects p ON p.id = l.project_id
LEFT JOIN project_stages s ON s.id = l.stage_id
WHERE l.task_id = %s
ORDER BY l.created_at ASC
""",
(task_id,),
).fetchall()
return [self._serialize(r) for r in rows]
# ════════════════════════════════════════════════════════════
# 활동 이력
# ════════════════════════════════════════════════════════════
def list_activity(self, *, project_id: int, limit: int = 100) -> list[dict[str, Any]]:
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT * FROM project_activity WHERE project_id = %s "
"ORDER BY created_at DESC, id DESC LIMIT %s",
(project_id, int(limit)),
).fetchall()
return [self._serialize(r) for r in rows]
@staticmethod
def _log(
conn: Any, *, project_id: int | None = None, task_id: int | None = None,
actor: str = "", action: str = "", detail: str = "",
) -> None:
conn.execute(
"INSERT INTO project_activity "
"(project_id, task_id, actor_email, action, detail) "
"VALUES (%s,%s,%s,%s,%s)",
(project_id, task_id, store.norm_str(actor, lower=True), action,
store.norm_str(detail)),
)
# ════════════════════════════════════════════════════════════
# 댓글 (task_comments)
# ════════════════════════════════════════════════════════════
def 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 count_unread(self, *, recipient_email: str) -> int:
with self._pool.connection() as conn:
row = conn.execute(
"SELECT COUNT(*) AS n FROM project_notifications "
"WHERE recipient_email = %s AND is_read = FALSE",
(store.norm_str(recipient_email, lower=True),),
).fetchone()
return int(row["n"] or 0)
def mark_read(self, *, notification_id: int, recipient_email: str) -> None:
with self._pool.connection() as conn:
conn.execute(
"UPDATE project_notifications SET is_read = TRUE "
"WHERE id = %s AND recipient_email = %s",
(notification_id, store.norm_str(recipient_email, lower=True)),
)
def mark_all_read(self, *, recipient_email: str) -> int:
with self._pool.connection() as conn:
cur = conn.execute(
"UPDATE project_notifications SET is_read = TRUE "
"WHERE recipient_email = %s AND is_read = FALSE",
(store.norm_str(recipient_email, lower=True),),
)
return cur.rowcount or 0
# ════════════════════════════════════════════════════════════
# 멘션(@태그) — task_mentions
#
# 설명란/댓글에서 @로 지정된 사람. 수신함의 "나를 태그한 업무" 목록이
# 이걸 읽는다. 같은 자리(설명란=comment_id NULL, 또는 같은 댓글)에서 같은
# 사람을 두 번 저장하지 않는다(마이그레이션 006 의 UNIQUE 인덱스).
# ════════════════════════════════════════════════════════════
def add_mentions(
self, *, task_id: int, emails: list[str], actor_email: str = "",
comment_id: int | None = None, source: str = "description",
) -> list[str]:
"""멘션을 기록하고 '이번에 새로 추가된' 이메일만 돌려준다(알림 대상)."""
actor = store.norm_str(actor_email, lower=True)
targets = [e for e in store.normalize_emails(emails) if e != actor]
if not targets:
return []
added: list[str] = []
with self._pool.connection() as conn:
for email in targets:
cur = conn.execute(
"INSERT INTO task_mentions "
"(task_id, comment_id, mentioned_email, actor_email, source) "
"VALUES (%s,%s,%s,%s,%s) ON CONFLICT DO NOTHING",
(task_id, comment_id, email, actor, source),
)
if cur.rowcount:
added.append(email)
return added
def list_mentioned_tasks(
self, *, mentioned_email: str, limit: int = 100
) -> list[dict[str, Any]]:
"""내가 태그된 업무 목록(업무 1건당 1행, 가장 최근 태그 기준 정렬)."""
email = store.norm_str(mentioned_email, lower=True)
with self._pool.connection() as conn:
rows = conn.execute(
"""
SELECT t.*, p.name AS project_name, p.color AS project_color,
s.name AS stage_name,
m.last_at AS mentioned_at,
m.unread AS unread_mentions,
m.last_actor AS mention_actor
FROM (
SELECT task_id,
MAX(created_at) AS last_at,
COUNT(*) FILTER (WHERE NOT is_read) AS unread,
(ARRAY_AGG(actor_email ORDER BY created_at DESC))[1] AS last_actor
FROM task_mentions
WHERE mentioned_email = %s
GROUP BY task_id
) m
JOIN tasks t ON t.id = m.task_id
JOIN projects p ON p.id = t.project_id
LEFT JOIN project_stages s ON s.id = t.stage_id
ORDER BY m.last_at DESC
LIMIT %s
""",
(email, int(limit)),
).fetchall()
return [self._serialize(r) for r in rows]
def count_unread_mentions(self, *, mentioned_email: str) -> int:
with self._pool.connection() as conn:
row = conn.execute(
"SELECT COUNT(*) AS n FROM task_mentions "
"WHERE mentioned_email = %s AND is_read = FALSE",
(store.norm_str(mentioned_email, lower=True),),
).fetchone()
return int(row["n"] or 0)
def mark_mentions_read(
self, *, mentioned_email: str, task_id: int | None = None
) -> int:
clause = "WHERE mentioned_email = %s AND is_read = FALSE"
params: list[Any] = [store.norm_str(mentioned_email, lower=True)]
if task_id is not None:
clause += " AND task_id = %s"
params.append(task_id)
with self._pool.connection() as conn:
cur = conn.execute(
f"UPDATE task_mentions SET is_read = TRUE {clause}", params
)
return cur.rowcount or 0
# ════════════════════════════════════════════════════════════
# 팔로워(task_followers, 마이그레이션 008) — 아사나의 "협업자".
# 업무 알림(완료·댓글)은 담당자 + 팔로워에게만 간다. 008 미적용이면
# psycopg_errors.UndefinedTable 이 나고, 라우터가 예전 동작으로 폴백한다.
# ════════════════════════════════════════════════════════════
def list_followers(self, *, task_id: int) -> list[str]:
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT user_email FROM task_followers WHERE task_id = %s "
"ORDER BY created_at ASC, user_email ASC",
(task_id,),
).fetchall()
return [r["user_email"] for r in rows]
def add_followers(self, *, task_id: int, emails: list[str]) -> list[str]:
"""팔로워 추가(이미 있으면 무시). 새로 추가된 이메일만 돌려준다."""
targets = store.normalize_emails(emails)
if not targets:
return []
with self._pool.connection() as conn:
rows = conn.execute(
"INSERT INTO task_followers (task_id, user_email) "
"SELECT %s, e FROM unnest(%s::text[]) AS e "
"ON CONFLICT DO NOTHING RETURNING user_email",
(task_id, targets),
).fetchall()
return [r["user_email"] for r in rows]
def remove_follower(self, *, task_id: int, user_email: str) -> None:
with self._pool.connection() as conn:
conn.execute(
"DELETE FROM task_followers WHERE task_id = %s AND user_email = %s",
(task_id, store.norm_str(user_email, lower=True)),
)
# ════════════════════════════════════════════════════════════
# 전체 검색 — 제목·설명·댓글 (008 의 pg_trgm 인덱스가 있으면 그걸 탄다)
# ════════════════════════════════════════════════════════════
def search_tasks(
self, *, query: str, project_ids: set[int] | None, limit: int = 30,
) -> list[dict[str, Any]]:
"""제목/설명/댓글에 검색어가 들어간 업무(하위 업무 포함).
project_ids 가 None 이면 전체(관리자), 아니면 그 프로젝트들만.
설명은 HTML 이라 태그 이름·속성에만 걸린 경우(예: "img")를 걸러내려고
넉넉히 가져온 뒤 라우터가 본문 텍스트로 다시 확인한다.
"""
q = store.norm_str(query)
if not q:
return []
if project_ids is not None and not project_ids:
return []
pat = "%" + q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
params: dict[str, Any] = {"pat": pat, "limit": int(limit)}
scope = ""
if project_ids is not None:
scope = "AND t.project_id = ANY(%(ids)s)"
params["ids"] = sorted(project_ids)
with self._pool.connection() as conn:
rows = conn.execute(
f"""
SELECT t.id, t.title, t.description, t.project_id, t.parent_task_id,
t.completed_at, t.due_date, t.assignee_email,
p.name AS project_name, p.color AS project_color,
pt.title AS parent_title,
(t.title ILIKE %(pat)s) AS hit_title,
(SELECT c.body FROM task_comments c
WHERE c.task_id = t.id AND c.body ILIKE %(pat)s
ORDER BY c.created_at DESC LIMIT 1) AS comment_hit
FROM tasks t
JOIN projects p ON p.id = t.project_id
LEFT JOIN tasks pt ON pt.id = t.parent_task_id
WHERE (t.title ILIKE %(pat)s
OR t.description ILIKE %(pat)s
OR t.id IN (SELECT c.task_id FROM task_comments c WHERE c.body ILIKE %(pat)s))
{scope}
ORDER BY (t.title ILIKE %(pat)s) DESC, (t.completed_at IS NULL) DESC,
t.updated_at DESC, t.id DESC
LIMIT %(limit)s
""",
params,
).fetchall()
return [self._serialize(r) for r in rows]
# ════════════════════════════════════════════════════════════
# 마감 알림 (task_reminders, 마이그레이션 008) — reminders.py 가 부른다
# ════════════════════════════════════════════════════════════
def list_open_tasks_due_between(self, *, start: date, end: date) -> list[dict[str, Any]]:
"""미완료 + 마감일이 [start, end] 인 업무(하위 업무 포함) + 팔로워 목록.
보관(archived) 프로젝트는 뺀다."""
with self._pool.connection() as conn:
rows = conn.execute(
"""
SELECT t.id, t.title, t.due_date, t.assignee_email, t.project_id,
t.parent_task_id, p.name AS project_name,
COALESCE((SELECT array_agg(f.user_email ORDER BY f.user_email)
FROM task_followers f WHERE f.task_id = t.id),
'{}'::text[]) AS followers
FROM tasks t
JOIN projects p ON p.id = t.project_id
WHERE t.completed_at IS NULL
AND t.due_date BETWEEN %s AND %s
AND p.status <> 'archived'
ORDER BY t.due_date ASC, t.id ASC
""",
(start, end),
).fetchall()
return [self._serialize(r) for r in rows]
def 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")
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 = []
for a in areas:
labels = conn.execute(
"SELECT label FROM goal_rows WHERE area_id = %s ORDER BY sort_order, id",
(a["id"],),
).fetchall()
plan.append((a["name"], a["color"], tuple(r["label"] for r in labels) or ("",)))
else:
plan = list(store.DEFAULT_GOAL_AREAS)
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 in enumerate(labels):
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 적용 여부(상·하반기 글 칸·병합)
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()
row_rows = conn.execute(
"SELECT r.id, r.area_id, r.label 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")
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, {})}
)
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}
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("세로로 병합된 칸에 걸린 줄은 옮길 수 없습니다. 병합을 해제한 뒤 옮기세요.")
self._move_goal_item("goal_rows", "area_id", row_id, direction)
def add_goal_row(
self, *, area_id: int, label: str = "", ref_row_id: int | None = None, place: str = "below"
) -> int:
"""줄 추가 — 기준 줄(ref_row_id)이 있으면 그 줄 위(place="above")/아래("below")에, 없으면 영역 맨 끝에."""
lb = store.validate_goal_row_label(label)
if place not in ("above", "below"):
raise ValueError("place 는 above 또는 below 입니다.")
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)
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)
# 세로 병합 안쪽(시작 줄 아래 ~ 마지막 줄)에 끼우면 엑셀처럼 그 병합이 한 줄 늘어난다
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"]),
)
conn.execute("DELETE FROM goal_rows WHERE id = %s", (row_id,))
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:
if not conn.execute("SELECT 1 FROM goal_rows WHERE id = %s", (row_id,)).fetchone():
raise KeyError(row_id)
halves = self._table_exists(conn, "goal_cell_merges")
if m > 12 and not halves:
raise store.GoalMigration014Needed()
if halves:
# 병합에 가려진 칸(글은 왼쪽 위 칸에만 둔다) — 다른 창에서 병합된 뒤의 늦은 저장
area_id = conn.execute("SELECT area_id FROM goal_rows WHERE id = %s", (row_id,)).fetchone()["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)),
)
# ── 엑셀식 사각형 병합 ─────────────────────────────────────────
@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~6월·상반기·7~12월·하반기) — 가로는 같은 반기 월 칸끼리만.
걸친 기존 병합은 통째로 흡수(엑셀이 선택을 넓히듯). 글은 범위 안 칸들의 글을 왼쪽 위부터 줄·칸 순서대로
줄바꿈으로 이어 왼쪽 위 칸에 두고, 나머지 칸 글은 지운다(글을 잃지 않게)."""
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 in (store.GOAL_YEAR, store.GOAL_H1, store.GOAL_H2)) and not rect:
raise store.GoalMigration015Needed()
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.validate_goal_text("\n".join(
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()
@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
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.
prev_meeting = 이 회의록보다 앞선 가장 가까운 회의록의 머리(전주 목표)."""
with self._pool.connection() as conn:
self._require_meetings(conn)
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
items = conn.execute(
f"SELECT {self._MEETING_ITEM_COLS} FROM goal_meeting_items WHERE week_start = %s "
"ORDER BY sort_order, id", (week_start,),
).fetchall()
prev_ids = [int(r["carry_from"]) for r in items if r["carry_from"] is not None]
prevs = {int(r["id"]): self._meeting_item(r) for r in conn.execute(
f"SELECT {self._MEETING_ITEM_COLS} FROM goal_meeting_items WHERE id = ANY(%s)", (prev_ids,),
).fetchall()} if prev_ids else {}
prev_head = conn.execute(
"SELECT week_start, week_target FROM goal_meetings WHERE week_start < %s "
"ORDER BY week_start DESC LIMIT 1", (week_start,),
).fetchone()
out_items = []
for r in items:
it = self._meeting_item(r)
it["prev"] = prevs.get(it["carry_from"]) if it["carry_from"] 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,
}
def create_meeting(self, *, week_start: date, sections: list[tuple[str, str]], created_by: str = "") -> bool:
"""회의록 만들기 — 이미 있으면 False. 앞선 가장 가까운 회의록이 있으면 그 줄(구역·이름·쇼핑몰 연결·순서)을
글 없이 이어받고(carry_from = 그 줄 → 이번 회의에서 지난주 할 일·목표·결과를 나란히 리뷰), 없으면 sections
(목표 표 업무 영역 이름·색)마다 기본 양식 줄(store.MEETING_TEMPLATE)로 시작한다."""
ws = store.validate_week_start(week_start)
who = store.norm_str(created_by, lower=True)
with self._pool.connection() as conn:
with conn.transaction():
self._require_meetings(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
prev = conn.execute(
"SELECT week_start FROM goal_meetings WHERE week_start < %s ORDER BY week_start DESC LIMIT 1",
(ws,),
).fetchone()
prev_items = conn.execute(
"SELECT id, section, section_color, label, marketplace_code, sort_order FROM goal_meeting_items "
"WHERE week_start = %s ORDER BY sort_order, id", (prev["week_start"],),
).fetchall() if prev else []
if prev_items:
for n, r in enumerate(prev_items):
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"], r["id"], 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, ("",)):
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=500, 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:
self._require_meetings(conn)
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))
rows = conn.execute(
"SELECT id, section, section_color 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)
new_id = int(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,0,%s) RETURNING id",
(week_start, sec, color, lb, store.guess_meeting_market(sec, lb),
store.norm_str(updated_by, lower=True)),
).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(그 주 결과, 원) · 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_text(fields["content"]))
for k in ("target_amount", "result_amount"):
if k in fields:
v = store.validate_meeting_amount(fields[k])
if k == "target_amount" and v is not None and v < 0:
raise ValueError("목표 금액은 0 이상이어야 합니다.")
sets.append(f"{k} = %s")
params.append(v)
if "status" in fields:
sets.append("status = %s")
params.append(store.validate_meeting_status(fields["status"]))
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:
self._require_meetings(conn)
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_ITEM_COLS}",
(*params, store.norm_str(updated_by, lower=True), item_id),
).fetchone()
else:
row = conn.execute(
f"SELECT {self._MEETING_ITEM_COLS} FROM goal_meeting_items WHERE id = %s", (item_id,),
).fetchone()
if row is None:
raise KeyError(item_id)
return self._meeting_item(row)
def delete_meeting_item(self, *, item_id: int) -> None:
with self._pool.connection() as conn:
self._require_meetings(conn)
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)
me = conn.execute(
"SELECT week_start, section FROM goal_meeting_items WHERE id = %s", (item_id,)
).fetchone()
if me is None:
raise KeyError(item_id)
rows = conn.execute(
"SELECT id, section FROM goal_meeting_items WHERE week_start = %s ORDER BY sort_order, id "
"FOR UPDATE", (me["week_start"],),
).fetchall()
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"] != me["section"]:
return
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 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"))}
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