feat(project): 보드에서 하위 업무 한 줄을 다른 업무 카드로 드래그해 옮기기

카드에 펼친 하위 업무 줄을 끌어 다른 카드에 놓으면 그 업무의 하위 업무로
옮긴다. 카드 자체 드래그(세션 이동)와 섞이지 않게 별도 드래그 타입을 쓰고,
놓을 수 있는 카드는 보라 테두리로 표시한다.

- API: POST /project/api/tasks/{id}/move-parent {parent_task_id}
- db.move_subtask: 받는 쪽은 같은 프로젝트의 최상위 업무만(순환 방지),
  활동 로그 subtask_moved, 목록 끝으로 정렬
- 정적 파일 버전 20260925d

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-25 18:28:56 +09:00
parent db1ffdd636
commit d5e02b04a4
10 changed files with 169 additions and 8 deletions
+46
View File
@@ -656,6 +656,52 @@ class ProjectStore:
detail=f"{ttl} → {assignee}")
return self.get_task(task_id=row["id"])
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]:
+29
View File
@@ -1356,6 +1356,35 @@ def api_get_task(request: Request, task_id: int) -> JSONResponse:
return JSONResponse({"task": task})
@router.post("/api/tasks/{task_id}/move-parent")
def api_move_subtask(
request: Request,
task_id: int,
payload: dict[str, Any] = Body(...),
) -> JSONResponse:
"""하위 업무를 다른 상위 업무로 옮긴다 — 보드에서 하위 업무 줄을 다른 카드로 드래그.
body: {"parent_task_id": 받는 업무 id}. 받는 업무는 같은 프로젝트의 최상위 업무만.
"""
user = _require_user(request)
st = _db_or_503(request)
existing = st.get_task(task_id=task_id)
if existing is None:
raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.")
_require_manage(request, st, user, existing["project_id"])
try:
parent_id = int(payload.get("parent_task_id"))
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail="parent_task_id 가 필요합니다.")
try:
task = st.move_subtask(task_id=task_id, parent_task_id=parent_id, actor=user["email"])
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except KeyError as exc:
raise HTTPException(status_code=404, detail=str(exc))
return JSONResponse({"task": task})
# ────────────────────────────────────────────────────────────
# JSON API — 팔로워 (아사나의 협업자)
# ────────────────────────────────────────────────────────────
+1
View File
@@ -37,6 +37,7 @@ ACTION_ASSIGNED = "assigned"
ACTION_COMPLETED = "completed"
ACTION_STAGE_CHANGED = "stage_changed"
ACTION_REOPENED = "reopened"
ACTION_SUBTASK_MOVED = "subtask_moved" # 하위 업무를 다른 상위 업무로 옮김(보드 드래그)
# 프로젝트 색상 팔레트(아사나 느낌) — UI 선택지
COLOR_PALETTE: tuple[str, ...] = (
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260925c" />
<link rel="stylesheet" href="/static/project.css?v=20260925d" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -99,5 +99,5 @@
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20260925c" defer></script>
<script src="/static/project.js?v=20260925d" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260925c" />
<link rel="stylesheet" href="/static/project.css?v=20260925d" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -98,5 +98,5 @@
"today": {{ today | tojson }}
}
</script>
<script src="/static/project.js?v=20260925c" defer></script>
<script src="/static/project.js?v=20260925d" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260925c" />
<link rel="stylesheet" href="/static/project.css?v=20260925d" />
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<!-- 타임라인 vis-timeline — self-host -->
@@ -460,5 +460,5 @@
</script>
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
<script src="/static/project.js?v=20260925c" defer></script>
<script src="/static/project.js?v=20260925d" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260925c" />
<link rel="stylesheet" href="/static/project.css?v=20260925d" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -68,5 +68,5 @@
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20260925c" defer></script>
<script src="/static/project.js?v=20260925d" defer></script>
{% endblock %}
+4
View File
@@ -297,6 +297,10 @@
}
.pj-card:hover { box-shadow: var(--pj-card-shadow-hover); transform: translateY(-1px); }
.pj-card.is-dragging { opacity: .5; }
/* 하위 업무 한 줄 드래그 — 끄는 줄은 흐리게, 놓을 수 있는 카드는 보라 테두리 */
.pj-card-sub[draggable="true"] .pj-card-sub-title { cursor: grab; }
.pj-card-sub.is-dragging { opacity: .4; }
.pj-card.is-sub-drop { outline: 2px solid var(--pj-accent); outline-offset: -2px; background: var(--pj-accent-tint); }
.pj-card.is-done .pj-card-title { text-decoration: line-through; color: #9aa1a9; }
.pj-card-title { font-size: 13.5px; font-weight: 600; color: var(--pj-ink); line-height: 1.4; }
.pj-card-meta { display: flex; align-items: center; gap: 6px; margin-top: 10px; }
+78
View File
@@ -3171,6 +3171,10 @@
// 닫히면(거기서 하위 업무를 고쳤을 수 있으니) 캐시를 비운다(아래 observer).
const expandedSubs = new Set();
const subsCache = {};
// 지금 끌고 있는 하위 업무 줄 { sub, from(상위 업무) } — dragover 중엔
// dataTransfer 값을 읽을 수 없어서(보안상 type 만 보임) 여기 들고 있는다.
let dragSub = null;
const SUB_DRAG_TYPE = "application/x-pj-subtask";
// 아사나의 하위 업무 아이콘(위 노드 하나에서 두 갈래로 뻗은 노드).
const SUBTASK_ICON_SVG =
'<svg class="pj-card-subtoggle-ic" viewBox="0 0 16 16" width="15" height="15" fill="none" ' +
@@ -3265,6 +3269,24 @@
box.querySelectorAll(".pj-card-sub").forEach(function (row) {
const sub = subs.find(function (x) { return String(x.id) === row.dataset.subId; });
if (!sub) return;
// 드래그 — 이 하위 업무 한 줄만 다른 카드(상위 업무)로 옮긴다. 카드 자체도
// draggable 이라 이벤트가 카드로 올라가면 카드 이동이 시작되므로 막는다.
if (canManage) {
row.draggable = true;
row.addEventListener("dragstart", function (e) {
e.stopPropagation();
dragSub = { sub: sub, from: t };
e.dataTransfer.setData(SUB_DRAG_TYPE, String(sub.id));
e.dataTransfer.effectAllowed = "move";
row.classList.add("is-dragging");
});
row.addEventListener("dragend", function (e) {
e.stopPropagation();
row.classList.remove("is-dragging");
dragSub = null;
document.querySelectorAll(".pj-card.is-sub-drop").forEach(function (c) { c.classList.remove("is-sub-drop"); });
});
}
// 우클릭 — 하위 업무 메뉴(아사나처럼): 열기 / 완료 / 삭제.
if (canManage) row.addEventListener("contextmenu", function (e) {
e.preventDefault();
@@ -3326,6 +3348,40 @@
});
}
// 하위 업무 한 줄을 다른 상위 업무(카드)로 옮긴다 — 보드에서 드래그해 놓았을 때.
// 같은 업무가 여러 프로젝트 맥락 행으로 tasks 에 들어 있을 수 있어(멀티호밍)
// 개수는 같은 id 의 행 모두에서 맞춘다.
function adjustSubCounts(taskId, dTotal, dDone) {
tasks.forEach(function (x) {
if (x.id !== taskId) return;
x.subtask_total = Math.max(0, (x.subtask_total || 0) + dTotal);
x.subtask_done = Math.max(0, (x.subtask_done || 0) + dDone);
});
}
async function moveSubtaskTo(sub, from, to) {
if (sub.project_id && to.project_id && sub.project_id !== to.project_id) {
showToast("다른 프로젝트의 업무로는 옮길 수 없습니다.", "error");
return;
}
try {
const res = await api("POST", "/project/api/tasks/" + sub.id + "/move-parent",
{ parent_task_id: to.id });
const moved = (res && res.task) || Object.assign({}, sub, { parent_task_id: to.id });
const done = sub.completed_at ? 1 : 0;
const fromSubs = subsCache[from.id];
if (fromSubs) {
const i = fromSubs.indexOf(sub);
if (i >= 0) fromSubs.splice(i, 1);
}
if (subsCache[to.id]) subsCache[to.id].push(moved);
adjustSubCounts(from.id, -1, -done);
adjustSubCounts(to.id, 1, done);
if (!from.subtask_total) expandedSubs.delete(from.id);
renderBoard();
showToast("'" + (sub.title || "") + "' → '" + (to.title || "") + "' 로 옮겼습니다.");
} catch (err) { showToast("이동 실패: " + err.message, "error"); }
}
// 카드 하위 업무 펼치기/접기 — 보드를 다시 그리지 않고 그 카드 안에서만
// 높이를 애니메이션한다(아사나처럼 카드가 아래로 스르륵 늘어남).
// 펼칠 땐 목록을 먼저 받아 채운 뒤 펼친다 — "불러오는 중…"에서 목록으로
@@ -3445,6 +3501,28 @@
card.classList.add("is-dragging");
});
card.addEventListener("dragend", function () { card.classList.remove("is-dragging"); });
// 하위 업무 줄을 이 카드에 놓으면 이 업무의 하위 업무로 옮긴다.
// 원래 상위 업무 카드 위에서는 받지 않는다(제자리).
card.addEventListener("dragover", function (e) {
if (!dragSub || !e.dataTransfer.types.includes(SUB_DRAG_TYPE)) return;
if (dragSub.from.id === t.id) return;
e.preventDefault();
e.stopPropagation();
e.dataTransfer.dropEffect = "move";
card.classList.add("is-sub-drop");
});
card.addEventListener("dragleave", function (e) {
if (!card.contains(e.relatedTarget)) card.classList.remove("is-sub-drop");
});
card.addEventListener("drop", function (e) {
if (!dragSub || !e.dataTransfer.types.includes(SUB_DRAG_TYPE)) return;
e.preventDefault();
e.stopPropagation();
card.classList.remove("is-sub-drop");
const moving = dragSub;
dragSub = null;
if (moving.from.id !== t.id) moveSubtaskTo(moving.sub, moving.from, t);
});
card.addEventListener("contextmenu", function (e) {
e.preventDefault();
showContextMenu(e.clientX, e.clientY, taskContextItems(t));
+3
View File
@@ -39,6 +39,9 @@
업무만 카드로 뜬다(하위 업무는 부모 카드의 "N ⤷ ▾" 토글로 — 누르면 아사나처럼 카드 아래로
하위 업무 목록(완료 체크·제목·마감·담당자)이 펼쳐진다. 펼친 상태는 페이지에 머무는 동안 유지).
세션을 갖지 않는다(칸반에 안 보이므로).
펼친 하위 업무 한 줄을 다른 카드로 드래그하면 그 업무의 하위 업무로 옮겨진다
(`POST /api/tasks/{id}/move-parent` `{parent_task_id}` → `db.move_subtask`, 활동 `subtask_moved`).
받는 쪽은 **같은 프로젝트의 최상위 업무만**(순환 방지), 하위 업무의 하위 업무는 함께 따라간다.
- **멀티호밍(다른 프로젝트에 연결)** — `task_project_links` 테이블. 업무 하나가
원래 소속(기본 홈, `tasks.project_id`/`stage_id`)과 무관하게 다른 프로젝트의
한 세션에도 동시에 나타날 수 있다(아사나의 "Add to project"). 업무 편집