feat(project): 세션 기본 담당자

세션 편집 창에서 기본 담당자(프로젝트 멤버·owner)를 지정하면, 그 세션에
업무를 만들거나 다른 세션에서 옮겨올 때 담당자가 빈 업무만 자동 배정.
이미 담당자가 있으면 그대로. 보드 세션 머리에 담당자 아바타 표시,
새 업무 팝업은 기본 담당자를 미리 채움. 자동 배정도 일반 배정처럼
알림·팔로워·메일 처리.

DB: project_db_009 (project_stages.default_assignee_email). 미적용이어도
to_jsonb 로 읽어 동작, 지정 시도만 503 안내.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-23 23:51:38 +09:00
parent 11fa0f6519
commit 3dbb613092
10 changed files with 193 additions and 19 deletions
+71 -9
View File
@@ -275,22 +275,31 @@ class ProjectStore:
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(
"INSERT INTO project_stages (project_id, name, sort_order, is_done_stage, color, created_by) "
"VALUES (%s,%s,%s,%s,%s,%s) RETURNING *",
(project_id, nm, int(nxt["n"]), bool(is_done_stage), col,
store.norm_str(created_by, lower=True)),
f"INSERT INTO project_stages ({cols}) "
f"VALUES ({','.join(['%s'] * len(vals))}) RETURNING *",
vals,
).fetchone()
return self._serialize(row)
@@ -301,6 +310,35 @@ class ProjectStore:
).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 은 그대로).
@@ -587,6 +625,10 @@ class ProjectStore:
(project_id,),
).fetchone()
stage_id = st["id"] if st else None
# 담당자 없이 만들면 그 세션의 기본 담당자를 배정(하위 업무는
# 세션이 없어 해당 없음).
if not assignee and stage_id is not None:
assignee, assignee_name = self._stage_default_assignee(conn, stage_id, project_id)
nxt = conn.execute(
"SELECT COALESCE(MAX(sort_order), -1) + 1 AS n FROM tasks "
"WHERE project_id = %s",
@@ -631,6 +673,24 @@ class ProjectStore:
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"]))
@@ -670,9 +730,6 @@ class ProjectStore:
# 를 그대로 다시 보내는데, 여기서 무조건 판정하면 방금 "완료로 표시"로
# 켠 completed_at 을(단계는 그대로인데) 다시 꺼버리는 버그가 있었다.
if "stage_id" in fields:
new_stage = self.stage_in_project(
stage_id=fields["stage_id"], project_id=prev["project_id"]
)
sets.append("stage_id = %s")
params.append(new_stage)
if new_stage != prev.get("stage_id"):
@@ -940,9 +997,11 @@ class ProjectStore:
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 는 지정 안 함(기본 `...`)과 명시적으로 지우기(`None`)를
구분해야 해서 다른 필드처럼 `is None` 이 아니라 `is not ...` 로 검사한다."""
"""color·default_assignee_email 은 지정 안 함(기본 `...`)과 명시적으로
지우기(`None`/'')를 구분해야 해서 `is None` 이 아니라 `is not ...` 로
검사한다. 기본 담당자가 프로젝트 멤버인지는 라우터가 검사한다."""
sets: list[str] = []
params: list[Any] = []
if name is not None:
@@ -957,6 +1016,9 @@ class ProjectStore:
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)
+30
View File
@@ -42,6 +42,7 @@ from fastapi.responses import (
JSONResponse,
RedirectResponse,
)
from psycopg.errors import UndefinedColumn
from app.timezone import today_kst
@@ -992,6 +993,7 @@ def api_add_stage(
user = _require_user(request)
st = _db_or_503(request)
_require_manage(request, st, user, project_id)
dae = _stage_default_assignee_arg(st, project_id, payload)
try:
stage = st.add_stage(
project_id=project_id,
@@ -999,12 +1001,36 @@ def api_add_stage(
is_done_stage=bool(payload.get("is_done_stage", False)),
color=payload.get("color"),
created_by=user["email"],
default_assignee_email="" if dae is ... else dae,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except UndefinedColumn:
raise HTTPException(status_code=503, detail=_STAGE_ASSIGNEE_MIGRATION_MSG)
return JSONResponse({"stage": stage}, status_code=201)
_STAGE_ASSIGNEE_MIGRATION_MSG = (
"세션 기본 담당자 기능이 아직 준비되지 않았습니다(DB 마이그레이션 009 필요)."
)
def _stage_default_assignee_arg(st: Any, project_id: int, payload: dict[str, Any]) -> Any:
"""payload 의 세션 기본 담당자 — 키가 없으면 `...`(변경 안 함), 빈 값이면 ''
(해제). 값이 있으면 그 프로젝트 멤버 또는 owner 여야 한다(업무 담당자
후보와 같은 기준)."""
if "default_assignee_email" not in payload:
return ...
email = store.norm_str(payload.get("default_assignee_email") or "", lower=True)
if email:
allowed = {m["user_email"] for m in st.list_members(project_id=project_id)}
project = st.get_project(project_id=project_id) or {}
allowed.add(store.norm_str(project.get("owner_email") or "", lower=True))
if email not in allowed:
raise HTTPException(status_code=400, detail="기본 담당자는 이 프로젝트 멤버여야 합니다.")
return email
def _stage_of_project(st: Any, stage_id: int, project_id: int) -> dict[str, Any]:
"""URL 의 세션이 URL 의 프로젝트 것인지 확인. 권한 검사는 project_id 로
하므로, 이걸 안 보면 아무 프로젝트 멤버나 남의 세션을 고칠 수 있다."""
@@ -1706,15 +1732,19 @@ def api_update_stage(
st = _db_or_503(request)
_require_manage(request, st, user, project_id)
_stage_of_project(st, stage_id, project_id)
dae = _stage_default_assignee_arg(st, project_id, payload)
try:
stage = st.update_stage(
stage_id=stage_id,
name=payload.get("name"),
is_done_stage=payload.get("is_done_stage"),
color=payload.get("color", ...),
default_assignee_email=dae,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except UndefinedColumn:
raise HTTPException(status_code=503, detail=_STAGE_ASSIGNEE_MIGRATION_MSG)
except KeyError:
raise HTTPException(status_code=404, detail="단계를 찾을 수 없습니다.")
return JSONResponse({"stage": stage})
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260923j" />
<link rel="stylesheet" href="/static/project.css?v=20260923k" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -98,5 +98,5 @@
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20260923j" defer></script>
<script src="/static/project.js?v=20260923k" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260923j" />
<link rel="stylesheet" href="/static/project.css?v=20260923k" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -119,5 +119,5 @@
"today": {{ today | tojson }}
}
</script>
<script src="/static/project.js?v=20260923j" defer></script>
<script src="/static/project.js?v=20260923k" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260923j" />
<link rel="stylesheet" href="/static/project.css?v=20260923k" />
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<!-- 타임라인 vis-timeline — self-host -->
@@ -250,6 +250,10 @@
<label>색상
<span class="pj-color-palette" id="pj-stg-colors"></span>
</label>
<label>기본 담당자
<select id="pj-stg-assignee"><option value="">없음</option></select>
<span class="pj-modal-hint pj-stg-assignee-hint">이 세션에 업무를 새로 만들거나 카드를 옮겨오면, 담당자가 비어 있는 업무만 이 사람에게 자동 배정됩니다.</span>
</label>
<div class="pj-modal-actions">
<span style="flex:1"></span>
<button type="button" class="pj-btn" data-close>취소</button>
@@ -501,5 +505,5 @@
</script>
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
<script src="/static/project.js?v=20260923j" defer></script>
<script src="/static/project.js?v=20260923k" defer></script>
{% endblock %}