feat(project): add cell moves and width menus

This commit is contained in:
2026-10-03 08:55:15 +09:00
parent 2c8542339d
commit 7647e4b20f
18 changed files with 695 additions and 26 deletions
+79 -3
View File
@@ -2275,8 +2275,13 @@ class ProjectStore:
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():
with self._pool.connection() as conn, conn.transaction():
# 빈 대상 칸을 포함해 일반 저장·이동·병합이 같은 영역 잠금으로 직렬화된다.
area = conn.execute(
"SELECT a.id AS area_id FROM goal_rows r JOIN goal_areas a ON a.id = r.area_id "
"WHERE r.id = %s FOR UPDATE OF a", (row_id,),
).fetchone()
if not area:
raise KeyError(row_id)
halves = self._table_exists(conn, "goal_cell_merges")
if m > 12 and not halves:
@@ -2285,7 +2290,7 @@ class ProjectStore:
raise store.GoalMigration017Needed()
if halves:
# 병합에 가려진 칸(글은 왼쪽 위 칸에만 둔다) — 다른 창에서 병합된 뒤의 늦은 저장
area_id = conn.execute("SELECT area_id FROM goal_rows WHERE id = %s", (row_id,)).fetchone()["area_id"]
area_id = area["area_id"]
ids, merges, _ = self._area_geometry(conn, int(area_id))
if self._covered_by(merges, ids.index(row_id), store.GOAL_COL_ORDER.index(m)):
raise ValueError("병합된 칸입니다. 새로고침해 주세요.")
@@ -2299,6 +2304,77 @@ class ProjectStore:
(row_id, m, text, store.norm_str(updated_by, lower=True)),
)
def move_goal_cell(
self, *, source_row: Any, source_month: Any, target_row: Any, target_month: Any,
source_body: str, target_body: str, body: str, updated_by: str = "",
) -> str:
"""같은 연도 안에서 셀의 내용·서식을 이동한다. 두 값의 비교와 이동은 한 트랜잭션.
병합 시작 칸끼리도 내용만 이동하며 병합 배치·영역 색·열 너비는 유지한다.
응답만 유실된 요청을 다시 보내면 이미 같은 이동이 완료된 상태는 성공으로 돌려준다.
"""
try:
sr, tr = int(source_row), int(target_row)
except (TypeError, ValueError):
raise ValueError("이동할 셀이 올바르지 않습니다.")
sm = store.validate_goal_month(source_month, allow_year=True)
tm = store.validate_goal_month(target_month, allow_year=True)
if sr <= 0 or tr <= 0 or (sr, sm) == (tr, tm):
raise ValueError("서로 다른 두 셀을 골라 주세요.")
expected_source, expected_target = store.validate_goal_text(source_body), store.validate_goal_text(target_body)
moved = store.validate_goal_text(body)
if not expected_source or not moved or store.goal_text_plain(moved).strip() != store.goal_text_plain(expected_source).strip():
raise ValueError("원본 내용과 이동할 내용이 일치하지 않습니다.")
with self._pool.connection() as conn:
with conn.transaction():
rows = conn.execute(
"SELECT r.id, r.area_id, a.year FROM goal_rows r JOIN goal_areas a ON a.id = r.area_id "
"WHERE r.id = ANY(%s)", ([sr, tr],),
).fetchall()
by_id = {int(r["id"]): r for r in rows}
if sr not in by_id or tr not in by_id:
raise KeyError(sr if sr not in by_id else tr)
if by_id[sr]["year"] != by_id[tr]["year"]:
raise ValueError("같은 연도의 셀로만 이동할 수 있습니다.")
areas = sorted({int(r["area_id"]) for r in rows})
# 교차 영역 이동도 같은 순서로 잠가 교착을 피하고, 행 삭제도 함께 차단한다.
conn.execute("SELECT id FROM goal_areas WHERE id = ANY(%s) ORDER BY id FOR UPDATE", (areas,)).fetchall()
locked = conn.execute(
"SELECT id, area_id FROM goal_rows WHERE id = ANY(%s) ORDER BY id FOR UPDATE", ([sr, tr],),
).fetchall()
if len(locked) != len(by_id):
raise KeyError("이동할 줄이 삭제되었습니다.")
halves = self._table_exists(conn, "goal_cell_merges")
if (sm > 12 or tm > 12) and not halves:
raise store.GoalMigration014Needed()
if (sm in store.GOAL_Q_NEW or tm in store.GOAL_Q_NEW) and not self._goal_quarters(conn):
raise store.GoalMigration017Needed()
geometry = {a: self._area_geometry(conn, a) for a in areas} if halves else {}
for rid, month in ((sr, sm), (tr, tm)):
if halves:
ids, merges, _ = geometry[int(by_id[rid]["area_id"])]
if rid not in ids or self._covered_by(merges, ids.index(rid), store.GOAL_COL_ORDER.index(month)):
raise store.GoalCellConflict("병합 배치가 바뀌었습니다. 새로고침한 뒤 다시 이동해 주세요.")
cells = conn.execute(
"SELECT row_id, month, body FROM goal_cells "
"WHERE (row_id = %s AND month = %s) OR (row_id = %s AND month = %s) FOR UPDATE",
(sr, sm, tr, tm),
).fetchall()
values = {(int(c["row_id"]), int(c["month"])): store.validate_goal_text(c["body"]) for c in cells}
source, target = values.get((sr, sm), ""), values.get((tr, tm), "")
if not source and target == moved:
return moved
if source != expected_source or target != expected_target:
raise store.GoalCellConflict("원본 또는 대상 내용이 바뀌었습니다. 새로고침한 뒤 다시 이동해 주세요.")
conn.execute(
"INSERT INTO goal_cells (row_id, month, body, updated_by) VALUES (%s,%s,%s,%s) "
"ON CONFLICT (row_id, month) DO UPDATE "
"SET body = EXCLUDED.body, updated_by = EXCLUDED.updated_by, updated_at = now()",
(tr, tm, moved, store.norm_str(updated_by, lower=True)),
)
conn.execute("DELETE FROM goal_cells WHERE row_id = %s AND month = %s", (sr, sm))
return moved
# ── 엑셀식 사각형 병합 ─────────────────────────────────────────
@staticmethod
def _column_exists(conn: Any, table: str, column: str) -> bool:
+18
View File
@@ -2598,6 +2598,8 @@ def _goal_call(fn: Any, *args: Any, **kwargs: Any) -> Any:
raise HTTPException(status_code=503, detail=_GOALS_016_MSG)
except store.GoalMigration017Needed:
raise HTTPException(status_code=503, detail=_GOALS_017_MSG)
except store.GoalCellConflict as exc:
raise HTTPException(status_code=409, detail=str(exc))
except UndefinedTable:
raise HTTPException(status_code=503, detail=_GOALS_MIGRATION_MSG)
except KeyError:
@@ -2807,6 +2809,22 @@ def api_set_goal_cell(
return JSONResponse({"ok": True})
@router.post("/api/goals/cells/move")
def api_move_goal_cell(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""내용·글자 서식만 원자적으로 이동. 원본·대상의 예상값이 바뀌면 409, 병합 배치는 유지."""
user = _require_admin(request)
st = _db_or_503(request)
if any(not isinstance(payload.get(k), str) for k in ("source_body", "target_body", "body")):
raise HTTPException(status_code=400, detail="이동할 내용과 두 칸의 현재 내용을 보내 주세요.")
body = _goal_call(
st.move_goal_cell, source_row=payload.get("source_row"), source_month=payload.get("source_month"),
target_row=payload.get("target_row"), target_month=payload.get("target_month"),
source_body=payload["source_body"], target_body=payload["target_body"], body=payload["body"],
updated_by=user["email"],
)
return JSONResponse({"ok": True, "body": body})
@router.post("/api/goals/areas/{area_id}/merge")
def api_merge_goal_rect(request: Request, area_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""엑셀식 병합 {row_from, row_to(줄 id), col_from, col_to(칸 번호 0·1~12·13~16)} — 같은 영역 안 사각형,
+4
View File
@@ -397,6 +397,10 @@ class GoalMigration017Needed(RuntimeError):
"""2·4분기 글 칸(15·16)은 마이그레이션 017(분기) 뒤에만 된다."""
class GoalCellConflict(RuntimeError):
"""셀 이동 전에 다른 창에서 원본 또는 대상 내용이 바뀜."""
GOAL_YEAR = 0 # 업무 영역 글 칸 — 연간
# 분기 글 칸(2026-10-01 상·하반기 → 1~4분기). 칸 번호는 예전 반기 칸을 그대로 이어 쓴다 — 데이터 옮기기 없이
# 예전 상반기 글(13)은 1분기, 하반기 글(14)은 3분기에 보인다. 2분기(15)·4분기(16)는 마이그레이션 017 뒤에 저장.
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261003e" />
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -296,5 +296,5 @@
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20261003g" defer></script>
<script src="/static/project.js?v=20261003h" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261003e" />
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -208,6 +208,7 @@
<div class="pj-goal-foot">
<button type="button" class="pj-btn" id="pj-goal-area-add">+ 업무 영역 추가</button>
<span class="pj-goal-note">칸을 고치면 바로 저장됩니다. 글자를 드래그해 선택하면 선택한 셀 상단에서 12색 견본·크기 2px 증감·굵게·기울임·밑줄·서식 초기화를 사용할 수 있습니다. 모든 행의 셀 오른쪽 경계를 끌어 열 너비를 조절하고, 더블클릭하면 그 열의 가장 긴 문단에 맞춥니다. 숫자 칸을 비우면 지워집니다. 구역·항목 칸을 우클릭하거나 칸의 ⋮ 버튼(키보드 Tab·Enter, 터치)을 누르면 색·순서·줄 추가·삭제 메뉴가 나옵니다.
셀 우클릭 → 현재 열·전체 열 너비 자동 맞춤(접힌 열 포함). 글 칸 하나를 클릭한 뒤 위·아래·왼쪽 테두리를 끌면 내용과 서식이 함께 이동합니다(대상에 글이 있으면 덮어쓰기 확인, Esc로 취소).
{%- if board.halves %} 칸을 마우스로 끌어 여러 칸을 고른 뒤 우클릭 → 셀 병합, 병합된 칸은 우클릭 → 병합 해제(글은 왼쪽 위 칸에 남음).{% endif %}
월 이름을 누르면 그 달 주간 회의록이 열립니다.</span>
</div>
@@ -223,5 +224,5 @@
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project-goal-text.js?v=20261003c" defer></script>
<script src="/static/project.js?v=20261003g" defer></script>
<script src="/static/project.js?v=20261003h" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261003e" />
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
<link rel="stylesheet" href="/static/project-help.css?v=20261002d" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -100,6 +100,8 @@
<span class="pjh-ui">서식 초기화</span>는 선택한 글자를 기본 서식으로 되돌리며 내용은 유지합니다. 서식도 자동으로 저장됩니다. 색상은 12색의 네모 견본에서 고릅니다.
<b>모든 행의 셀 오른쪽 경계</b>를 끌어 열 너비를 조절하고, 더블클릭하면 <b>그 열의 가장 긴 문단에 맞춰</b> 자동으로 조절합니다.
직접 넣은 줄바꿈은 유지하며 글자 크기·굵기·여백도 반영합니다. 병합 칸에서는 다른 열 너비를 유지하고 오른쪽 끝 열만 맞춥니다. 너비는 내 브라우저에 기억됩니다.
셀을 <b>우클릭</b>하면 <span class="pjh-ui">현재 열 너비 자동 맞춤</span>·<span class="pjh-ui">전체 열 너비 자동 맞춤</span>을 사용할 수 있습니다. 전체 맞춤에는 접힌 월 열도 포함됩니다.
관리자는 글 칸 하나를 클릭한 뒤 <b>위·아래·왼쪽 테두리</b>를 잡아 다른 글 칸으로 끌면 <b>내용과 글자 서식을 함께 이동</b>할 수 있습니다. 대상에 글이 있으면 덮어쓰기를 확인하며, <kbd>Esc</kbd>로 끌기를 취소합니다.
<b>행 높이는 가장 높은 글 칸에 맞춰</b> 자동으로 늘어나거나 줄어들며, 위·아래 여백은 각각 6px입니다. 짧은 글도 같은 위치에서 상단 정렬됩니다.
영역·줄 이름은 <b>눌러서 그 자리에서 고치고</b>(Enter 저장, Esc 취소),
구역·항목 칸을 <b>우클릭</b>하거나 칸 오른쪽 위의 작은 <span class="pjh-ui">⋮</span> 버튼(마우스를 올리면 보임)을 눌러 색·순서·줄 추가·삭제를 합니다.
@@ -108,7 +110,7 @@
끌어 여러 칸을 고른 뒤 우클릭 → "셀 병합", 병합된 칸은 우클릭 → "병합 해제"(글은 왼쪽 위 칸에 남음).
가로 병합은 같은 분기의 월 칸끼리만(연간·분기 칸은 세로로만) 되고, 칸들의 글은 순서대로 첫 칸에 모입니다.
<br><b>저장이 안 되면</b>(네트워크 끊김 등) 칸 테두리가 빨갛게 되고 <b>쓴 글은 그대로 남습니다</b> — 다시 입력하거나 칸을 떠나면 다시 저장합니다.
저장 안 된 칸이 있으면 줄·영역 추가·병합은 하지 않고 알려 주며, 그 상태로 페이지를 떠나려 하면 브라우저가 한 번 묻습니다.
저장 안 된 칸이 있으면 줄·영역 추가·병합·셀 이동은 하지 않고 알려 주며, 그 상태로 페이지를 떠나려 하면 브라우저가 한 번 묻습니다.
글은 내 브라우저에도 잠시 보관되어, 저장되지 못한 채 창이 닫혀도 다음에 열면 되살아납니다(그 사이 다른 사람이 같은 칸을 고쳤으면 되살리지 않음).</li>
<li><b>주간 회의록</b>(목표 표의 월 이름) — <b>지난주 리뷰</b>는 언제나 바로 앞 주(7일 전 월~일) 회의록만 보여 줍니다. 그 주 회의록이 없으면
"회의록 없음"으로 비워 두고, 몇 주 전 결과를 지난주처럼 보이지 않습니다. 회의록을 만드는 순서(다음 주를 먼저 만들어도)와 줄 이름 변경·순서 이동과
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261003e" />
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -104,5 +104,5 @@
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20261003g" defer></script>
<script src="/static/project.js?v=20261003h" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261003e" />
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -100,5 +100,5 @@
"today": {{ today | tojson }}
}
</script>
<script src="/static/project.js?v=20261003g" defer></script>
<script src="/static/project.js?v=20261003h" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261003e" />
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<!-- 타임라인 vis-timeline — self-host -->
@@ -496,5 +496,5 @@
</script>
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
<script src="/static/project.js?v=20261003g" defer></script>
<script src="/static/project.js?v=20261003h" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261003e" />
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -70,5 +70,5 @@
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20261003g" defer></script>
<script src="/static/project.js?v=20261003h" defer></script>
{% endblock %}
+11
View File
@@ -2349,6 +2349,17 @@ html.pj-goal-selecting .pj-goal-menu-btn { pointer-events: none; }
box-shadow: inset 0 0 0 2px var(--pj-accent);
background-image: linear-gradient(rgba(123, 104, 238, .12), rgba(123, 104, 238, .12));
}
.pj-goal-table td.pj-goal-texttd.is-goal-active { box-shadow: inset 0 0 0 2px var(--pj-accent); }
.pj-goal-move-edge { display: none; position: absolute; z-index: 4; cursor: grab; }
.is-goal-active > .pj-goal-move-edge { display: block; }
.pj-goal-move-edge[data-edge="top"] { top: 0; left: 0; right: 0; height: 4px; }
.pj-goal-move-edge[data-edge="bottom"] { bottom: 0; left: 0; right: 0; height: 4px; }
.pj-goal-move-edge[data-edge="left"] { top: 4px; bottom: 4px; left: 0; width: 4px; }
.pj-goal-move-edge[data-edge="right"] { top: 4px; bottom: 4px; right: 0; width: 4px; }
.pj-goal-table td.is-goal-moving { opacity: .55; }
.pj-goal-table td.is-goal-move-target { box-shadow: inset 0 0 0 3px var(--pj-accent); background-image: linear-gradient(var(--pj-accent-tint), var(--pj-accent-tint)); }
.pj-goal-table td.is-goal-move-saving { pointer-events: none; opacity: .65; }
html.pj-goal-moving, html.pj-goal-moving * { cursor: grabbing !important; user-select: none !important; }
.pj-goal-foot { display: flex; align-items: center; gap: 12px; margin: 12px 0 4px; }
+163 -7
View File
@@ -352,6 +352,13 @@
prune: prune, onBeforeUnload: onBeforeUnload,
savedOf: function (f) { const s = states.get(f); return s ? s.saved : undefined; },
failedOf: function (f) { const s = states.get(f); return !!(s && s.failed); },
acceptSaved: function (f, value) {
const s = states.get(f);
if (!s) return;
clearTimeout(s.timer); s.timer = null; s.saved = value; s.failed = false;
writeDraft(f, s);
if (cfg.onClear) cfg.onClear(f);
},
};
}
// 저장 실패 표시 — 칸 빨간 테두리 + 안내(입력한 내용은 지우지 않는다)
@@ -8667,13 +8674,16 @@
}
addColHandles();
function naturalCellWidth(td) {
// 원본은 건드리지 않는다. 같은 셀 안의 숨은 복사본으로 폰트·부분 서식·여백을
// 원본은 건드리지 않는다. 같은 표 구조의 숨은 복사본으로 폰트·부분 서식·여백을
// 그대로 재되, 화면 폭에 따른 줄바꿈만 해제한다(직접 넣은 줄바꿈은 유지).
const probe = document.createElement("div"), copy = td.cloneNode(true);
const measureTable = table.cloneNode(false), section = td.parentElement.parentElement.cloneNode(false), row = td.parentElement.cloneNode(false);
probe.style.cssText = "position:fixed;left:0;top:0;visibility:hidden;pointer-events:none;width:max-content;";
probe.setAttribute("aria-hidden", "true");
[measureTable, section, row].forEach(function (n) { n.removeAttribute("id"); });
measureTable.style.cssText += ";width:max-content;table-layout:auto;";
copy.classList.add("pj-goal-autofit-measure");
copy.querySelectorAll(".pj-goal-colresize, .pj-goal-menu-btn").forEach(function (n) { n.remove(); });
copy.querySelectorAll(".pj-goal-colresize, .pj-goal-menu-btn, .pj-goal-move-edge").forEach(function (n) { n.remove(); });
// input의 현재 초안은 HTML 속성과 다를 수 있고, 기본 입력칸의 내재 너비도 제외한다.
copy.querySelectorAll("input, textarea").forEach(function (n) {
const text = document.createElement("span");
@@ -8691,7 +8701,9 @@
}
});
copy.style.setProperty("display", "block", "important");
probe.appendChild(copy); td.appendChild(probe);
row.appendChild(copy); section.appendChild(row); measureTable.appendChild(section); probe.appendChild(measureTable);
// 접힌 분기의 display:none 셀도 전체 자동 맞춤 때 측정할 수 있다.
pane.appendChild(probe);
try { return Math.ceil(copy.getBoundingClientRect().width / uiZoom()) + 2; }
finally { probe.remove(); }
}
@@ -8707,6 +8719,36 @@
colW[key] = width;
applyColW(); saveColW(); fitAll(); stickKpi();
}
function autoFitAllCols() {
const cells = Array.from(table.querySelectorAll("[data-goal-cols]")).map(function (td) {
return { keys: td.dataset.goalCols.split(","), width: naturalCellWidth(td) };
});
Object.keys(colDefault).forEach(function (key) { colW[key] = colLimit(key)[0]; });
cells.filter(function (cell) { return cell.keys.length === 1; }).forEach(function (cell) {
colW[cell.keys[0]] = Math.max(colW[cell.keys[0]], cell.width);
});
cells.filter(function (cell) { return cell.keys.length > 1; }).forEach(function (cell) {
const sum = cell.keys.reduce(function (w, key) { return w + colW[key]; }, 0);
if (cell.width > sum) colW[cell.keys[cell.keys.length - 1]] += cell.width - sum;
});
applyColW(); saveColW(); fitAll(); stickKpi();
}
function widthMenuItems(td) {
const key = (td.dataset.goalCols || "").split(",").pop();
if (!colDefault[key]) return [];
return [
{ label: "현재 열 너비 자동 맞춤", icon: menuIcon("fit_screen"), onClick: function () { autoFitCol(key); } },
{ label: "전체 열 너비 자동 맞춤", icon: menuIcon("view_week"), onClick: autoFitAllCols },
];
}
table.addEventListener("contextmenu", function (e) {
const td = e.target.closest("th, td");
if (!td || !table.contains(td)) return;
// 관리자 업무 셀·이름 칸은 아래의 기존 편집 메뉴에 합쳐 표시한다.
if (isAdmin && td.closest("tbody.pj-goal-area") &&
(td.tagName === "TH" || table.dataset.halves === "true" || td.dataset.month === "0")) return;
e.preventDefault(); showContextMenu(e.clientX, e.clientY, widthMenuItems(td));
});
table.addEventListener("mousedown", function (e) {
const h = e.target.closest(".pj-goal-colresize");
if (!h) return;
@@ -8987,6 +9029,12 @@
if (ta.dataset.bound) return;
ta.dataset.bound = "1";
if (ta.tagName !== "TEXTAREA") window.PJGoalText.attach(ta);
["top", "right", "bottom", "left"].forEach(function (edge) {
const handle = document.createElement("span");
handle.className = "pj-goal-move-edge"; handle.dataset.edge = edge;
handle.title = "끌어서 내용과 서식 이동"; handle.setAttribute("aria-hidden", "true");
ta.closest("td").appendChild(handle);
});
const r = textSaver.track(ta, ta.value);
if (r === "restored") restored++;
else if (r === "conflict") conflict++;
@@ -8999,6 +9047,110 @@
}
bindTexts(table);
window.PJGoalText.init(table, el("pj-goal-format"));
let moveBusy = false, moveClickUntil = 0;
function goalCellTd(node) {
const td = node && node.closest && node.closest("tbody.pj-goal-area td.pj-goal-texttd");
return td && table.contains(td) && td.querySelector(".pj-goal-text") ? td : null;
}
function setMoveActive(td) {
table.querySelectorAll(".is-goal-active").forEach(function (cell) { cell.classList.remove("is-goal-active"); });
if (td) td.classList.add("is-goal-active");
}
function moveBody(editor) {
// 열의 기본 서식도 현재 표시값으로 명시해 연간·분기의 굵기가 이동 뒤 달라지지 않게 한다.
const cs = getComputedStyle(editor), rgb = cs.color.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
const defaults = { bold: Number(cs.fontWeight) >= 600 || cs.fontWeight === "bold", italic: cs.fontStyle === "italic",
underline: (cs.textDecorationLine || "").includes("underline") };
const size = Math.round(parseFloat(cs.fontSize)); if (size >= 10 && size <= 32) defaults.size = size;
if (rgb) defaults.color = "#" + rgb.slice(1).map(function (v) { return Number(v).toString(16).padStart(2, "0"); }).join("");
return window.PJGoalText.encode(window.PJGoalText.readRuns(editor).map(function (run) { return Object.assign({}, defaults, run); }));
}
function moveCell(sourceTd, targetTd) {
if (moveBusy || sourceTd === targetTd) return;
moveBusy = true;
return withStruct(async function () {
const source = sourceTd.querySelector(".pj-goal-text"), target = targetTd.querySelector(".pj-goal-text");
const fields = [source, target], attrs = fields.map(function (n) { return n.getAttribute("contenteditable"); });
try {
if (!document.contains(sourceTd) || !document.contains(targetTd) || !source.value) return;
fields.forEach(function (n) { n.setAttribute("contenteditable", "false"); n.closest("td").classList.add("is-goal-move-saving"); });
await flushTexts();
const sourceBody = source.value, targetBody = target.value;
if (targetBody && !await confirm("대상 셀의 내용을 덮어쓸까요? 원본의 내용과 서식으로 바뀝니다.", { okText: "덮어쓰기", cancelText: "취소" })) return;
const res = await api("POST", "/project/api/goals/cells/move", {
source_row: source.dataset.row, source_month: source.dataset.month,
target_row: target.dataset.row, target_month: target.dataset.month,
source_body: sourceBody, target_body: targetBody, body: moveBody(source),
});
source.value = ""; target.value = res.body;
textSaver.acceptSaved(source, ""); textSaver.acceptSaved(target, target.value);
fit(source); fit(target); clearMergeSel(); setMoveActive(targetTd); flashSaved(targetTd);
showToast("내용과 서식을 이동했습니다.");
} catch (err) {
showToast("셀 이동 실패: " + err.message + " — 두 칸의 화면 내용은 유지됩니다. 다시 시도하거나 새로고침해 저장 상태를 확인해 주세요.", "error");
} finally {
fields.forEach(function (n, i) {
if (attrs[i] == null) n.removeAttribute("contenteditable"); else n.setAttribute("contenteditable", attrs[i]);
n.closest("td").classList.remove("is-goal-move-saving");
});
moveBusy = false;
}
});
}
// 선택한 셀의 테두리는 이동, 일반 본문 드래그는 기존 글/병합 범위 선택을 유지한다.
table.addEventListener("mousedown", function (e) {
if (e.button !== 0 || e.shiftKey) return;
const source = goalCellTd(e.target), handle = e.target.closest(".pj-goal-move-edge");
if (!source) return;
if (!handle) { if (!moveBusy) setMoveActive(source); return; }
e.preventDefault(); e.stopImmediatePropagation();
if (moveBusy || !source.querySelector(".pj-goal-text").value) return;
const startX = e.clientX, startY = e.clientY;
let moving = false, target = null, frame = null, x = startX, y = startY;
function updateTarget() {
table.querySelectorAll(".is-goal-move-target").forEach(function (n) { n.classList.remove("is-goal-move-target"); });
target = goalCellTd(document.elementFromPoint(x, y));
if (target === source) target = null;
if (target) target.classList.add("is-goal-move-target");
}
function scroll() {
const r = pane.getBoundingClientRect();
if (x >= r.left && x <= r.right && y >= r.top && y <= r.bottom) {
if (x < r.left + 24) pane.scrollLeft -= 16; else if (x > r.right - 24) pane.scrollLeft += 16;
if (y < r.top + 24) pane.scrollTop -= 16; else if (y > r.bottom - 24) pane.scrollTop += 16;
}
updateTarget(); frame = requestAnimationFrame(scroll);
}
function move(ev) {
x = ev.clientX; y = ev.clientY;
if (!moving && Math.hypot(x - startX, y - startY) < 4) return;
if (!moving) {
moving = true; source.classList.add("is-goal-moving");
document.documentElement.classList.add("pj-goal-moving");
const selection = window.getSelection(); if (selection) selection.removeAllRanges();
frame = requestAnimationFrame(scroll);
}
updateTarget();
}
function end(ev) {
if (frame !== null) cancelAnimationFrame(frame);
document.removeEventListener("mousemove", move); document.removeEventListener("mouseup", end);
document.removeEventListener("keydown", key, true); window.removeEventListener("blur", cancel);
source.classList.remove("is-goal-moving"); document.documentElement.classList.remove("pj-goal-moving");
table.querySelectorAll(".is-goal-move-target").forEach(function (n) { n.classList.remove("is-goal-move-target"); });
if (moving) moveClickUntil = Date.now() + 300;
if (ev && moving && target) moveCell(source, target);
}
function cancel() { end(null); }
function key(ev) { if (ev.key === "Escape") { ev.preventDefault(); ev.stopImmediatePropagation(); cancel(); } }
document.addEventListener("mousemove", move); document.addEventListener("mouseup", end);
document.addEventListener("keydown", key, true); window.addEventListener("blur", cancel);
}, true);
table.addEventListener("click", function (e) {
if ((Date.now() < moveClickUntil && e.detail !== 0 && goalCellTd(e.target)) || e.target.closest(".pj-goal-move-edge")) {
e.preventDefault(); e.stopImmediatePropagation();
}
}, true);
// 칸이 세로로 길어도(옆 칸 글이 길거나 세로 병합) 칸 아무 곳이나 누르면 그 칸 입력 — 커서는 글 끝(엑셀처럼).
// 입력칸(textarea)은 글 높이만큼이라 그 아래를 누르면 아무것도 안 되던 것. Shift+클릭(범위 고르기)·끌기는 그대로.
table.addEventListener("click", function (e) {
@@ -9238,7 +9390,7 @@
return items;
}
function openAreaMenu(th, x, y, opts) {
showContextMenu(x, y, areaMenuItems(th.closest("tbody"), { x: x, y: y }),
showContextMenu(x, y, areaMenuItems(th.closest("tbody"), { x: x, y: y }).concat([null], widthMenuItems(th)),
Object.assign({ label: textOf(th, ".pj-goal-area-text") + " 구역 메뉴" }, opts || {}));
}
table.addEventListener("contextmenu", function (e) {
@@ -9326,7 +9478,7 @@
// 2열 = 항목 칸 밖에 따로 추가(묶음의 맨 위·맨 아래 기준), 묶인 칸이면 "항목 칸 나누기"도
const grouped = (th.rowSpan || 1) > 1;
showContextMenu(x, y, rowMenuItems(tr, labelGroupBottom(tr), true,
{ splitRow: grouped ? tr : null, move: grouped ? null : tr }),
{ splitRow: grouped ? tr : null, move: grouped ? null : tr }).concat([null], widthMenuItems(th)),
Object.assign({ label: (textOf(th, ".pj-goal-row-text") || "이름 없는") + " 줄 메뉴" }, opts || {}));
}
table.addEventListener("contextmenu", function (e) {
@@ -9371,7 +9523,7 @@
if (!td || !table.contains(td)) return;
e.preventDefault();
const r = yearCellRows(td);
showContextMenu(e.clientX, e.clientY, rowMenuItems(r.top, r.bottom, r.single, { sameLabel: true }));
showContextMenu(e.clientX, e.clientY, rowMenuItems(r.top, r.bottom, r.single, { sameLabel: true }).concat([null], widthMenuItems(td)));
});
}
@@ -9487,12 +9639,14 @@
let drag = null;
clearMergeSel = function () {
sel = null;
setMoveActive(null);
table.querySelectorAll("td.is-merge-sel").forEach(function (td) { td.classList.remove("is-merge-sel"); });
};
const paint = function () {
table.querySelectorAll("td.is-merge-sel").forEach(function (td) { td.classList.remove("is-merge-sel"); });
if (!sel) return;
sel.cells.forEach(function (c) { if (hits(c, sel)) c.td.classList.add("is-merge-sel"); });
setMoveActive(sel.n === 1 ? sel.cells.find(function (c) { return hits(c, sel); }).td : null);
};
const select = function (tbody, a, b) {
const cells = gridOf(tbody);
@@ -9578,6 +9732,7 @@
clearMergeSel();
anchorCell = { tbody: tbody, td: td };
drag = { tbody: tbody, td: td, moved: false };
select(tbody, td, td);
});
table.addEventListener("mouseover", function (e) {
if (!drag) return;
@@ -9633,7 +9788,8 @@
if (items.length) items.push(null);
rowMenuItems(r.top, r.bottom, r.single, { sameLabel: true }).forEach(function (it) { items.push(it); });
}
if (!items.length) { clearMergeSel(); return; }
if (items.length) items.push(null);
widthMenuItems(td).forEach(function (item) { items.push(item); });
e.preventDefault();
showContextMenu(e.clientX, e.clientY, items);
});
+11 -1
View File
@@ -646,7 +646,7 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
또는 **Shift+클릭**(마지막으로 누른 칸부터). 범위가 병합된 칸에 걸치면 **엑셀처럼 그 칸 전체로 넓힌다**(`expand`). 칸 한 번 클릭은
그대로 입력. 다른 곳 누름·Esc = 해제.
- **우클릭**: "셀 병합 (N줄 × M칸)"(2칸 이상) · "병합 해제"(범위 안 병합된 칸, 여러 곳이면 개수). 범위 밖을 우클릭하면 그 칸만
고른 것으로(엑셀과 같음). 해당 메뉴가 없으면 브라우저 기본 메뉴. 묶음이 다른 가로 범위는 서버를 부르지 않고 안내.
고른 것으로(엑셀과 같음). 너비 자동 맞춤 메뉴도 함께 표시한다. 묶음이 다른 가로 범위는 서버를 부르지 않고 안내.
- `POST /api/goals/areas/{area_id}/merge {row_from, row_to(줄 id), col_from, col_to(칸 번호)}` → `db.merge_goal_rect`: 영역 FOR UPDATE,
걸친 병합 흡수(넓힌 뒤 묶음 다시 검사), 범위 안 글을 **왼쪽 위부터 줄·칸 순서대로 줄바꿈으로 이어 왼쪽 위 칸에**(글을 잃지 않게 —
엑셀은 왼쪽 위 값만 남기지만 여기선 잇는다), 나머지 칸 글·안쪽 병합은 지운다. 응답 `{row_id, start, span, row_span}`.
@@ -691,6 +691,16 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
- **고른 칸 내용 지우기(엑셀 Del)** — 끌기·Shift+클릭으로 고른 범위에서 Del → 범위 안 글 칸을 비우고 칸마다 바로 저장, 안내 토스트.
바로 직전 지우기는 **Ctrl+Z** 로 되돌림(되돌린 값도 저장). 입력 중(글 칸에 커서)일 때의 Del·Ctrl+Z 는 평소 글자 편집.
우클릭 메뉴에도 "내용 지우기 (Del)"(`ink_eraser`, 고른 범위에 글이 있을 때).
- **우클릭 너비 자동 맞춤**(2026-10-03) — 목표 표의 이름·글·숫자·머리 칸 모두 "현재 열 너비 자동 맞춤" / "전체 열 너비 자동 맞춤"을 표시한다.
보기 전용 사용자도 사용 가능하며 너비는 브라우저에 저장한다. 현재 열은 경계 더블클릭과 같고, 병합 칸은 오른쪽 끝 열을 맞춘다.
전체 맞춤은 접힌 월 열도 포함해 각 열의 가장 긴 문단에 맞추고, 병합 글에 부족한 폭은 그 병합의 마지막 열에 더한다.
- **셀 테두리로 내용 이동**(관리자, 2026-10-03) — 업무 영역의 연간·월·분기 글 칸 하나를 클릭한 뒤 위·아래·왼쪽 테두리를 잡아
다른 글 칸에 놓으면 내용과 색·크기·굵게·기울임·밑줄을 옮긴다. 오른쪽 경계는 열 너비 조절용이다. 끄는 동안 대상 칸을 표시하고
표 가장자리에서는 자동 스크롤한다. Esc·창 포커스 해제·원본에 놓기는 취소한다. 대상에 글이 있으면 덮어쓰기를 확인한다.
병합 시작 칸의 글도 이동 가능하며 병합 배치·영역 색·열 너비는 유지한다. 연간·분기의 기본 글자 서식도 명시해 원본의 표시를 보존한다.
미저장 글을 먼저 저장한 후 `POST /api/goals/cells/move`로 두 칸을 한 트랜잭션에서 이동한다(추가 마이그레이션 없음).
일반 글 저장·병합과 영역 잠금을 공유하고 원본·대상 예상값을 비교한다. 다른 창의 수정·병합에 가려진 칸은 409로 중단한다.
성공 응답 뒤 원본을 비우며, 실패하면 두 칸의 화면 내용을 유지한다. 응답이 유실된 동일 요청 재시도는 완료 상태를 확인해 성공으로 반환한다.
- **우클릭 메뉴 아이콘** — `menuIcon(name)`(Material Symbols)을 `showContextMenu` 항목 `icon` 에: 위에 줄 추가 `add_row_above` ·
아래에 줄 추가 `add_row_below` · 줄 삭제 `delete`(빨강) · 셀 병합 `cell_merge` · 병합 해제 `call_split` · 항목 칸 나누기
`horizontal_split` · (회의록) 위로/아래로 `arrow_upward`/`arrow_downward` · 쇼핑몰 연결 `link` · 연결 안 함 `link_off` · 쇼핑몰 `storefront`.
+11
View File
@@ -29,6 +29,8 @@ node tests/js/goals_meeting_ui.test.js # jsdom 필요(npm install jsdom
목표 열 자동 맞춤은 실제 Chromium에서도 검증한다. 로컬 테스트 HTML·프로젝트 CSS/폰트를 사용하며 운영 서버·DB에 연결하지 않는다.
부분 서식과 셀 여백, 명시적 줄바꿈, 75% 배율, 600px를 넘는 긴 문단, 저장된 너비 복원을 확인한다.
행 높이는 3줄/2줄 셀의 상단 정렬·같은 위아래 여백, 한 줄로 줄였을 때 높이 축소, 큰 글씨, 보기 전용 화면까지 확인한다.
실제 마우스로 셀 테두리를 끌어 내용·부분 서식을 이동하고, 지연 응답 동안 원본을 유지하는지 확인한다.
우클릭 현재/전체 열 자동 맞춤은 접힌 월 열의 측정·너비 저장도 검증한다. jsdom에서는 저장 실패·409 충돌·덮어쓰기 취소·Esc 취소를 추가로 확인한다.
```powershell
python tests/js/render_goals.py
@@ -38,3 +40,12 @@ node tests/js/goals_autofit.browser.test.js
```
`PJ_TEST_BROWSER`를 생략하면 Playwright에 설치된 기본 Chromium을 사용한다.
셀 이동 API의 권한·예상값 충돌·트랜잭션 롤백·응답 유실 재시도는 DB 없이 실행할 수 있다.
```bash
python -m unittest discover -s tests -p test_project_goal_move.py
```
실제 PostgreSQL 이동·동시 요청 검증은 `python tests/test_project_module.py`에 포함된다.
`PROJECT_TEST_DB_URL`에 기존 로컬 테스트 DB를 지정해야 하며, 미설정 또는 로컬 주소가 아니면 건너뛴다.
+64
View File
@@ -201,6 +201,70 @@ const server = http.createServer(function (req, res) {
console.log("PASS content row height, symmetric padding, top alignment" + (readonly ? " (read-only)" : ", shrink and large font"));
await heightPage.close();
}
const interactive = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
let releaseMove, startedMove;
const moveGate = new Promise(function (resolve) { releaseMove = resolve; });
const moveStarted = new Promise(function (resolve) { startedMove = resolve; });
const moveRequests = [];
await interactive.route("**/project/api/**", async function (route) {
const request = route.request();
if (request.url().endsWith("/goals/cells/move")) {
const payload = request.postDataJSON(); moveRequests.push(payload); startedMove();
await moveGate;
await route.fulfill({ json: { ok: true, body: payload.body } });
} else await route.fulfill({ json: { ok: true } });
});
await interactive.addInitScript(function () {
localStorage.setItem("pj_goal_col_w", JSON.stringify({ y: 240, m1: 240, m2: 240 }));
});
await interactive.goto("http://127.0.0.1:" + server.address().port + "/project/goals/2026");
const sourceCell = interactive.locator('tr[data-row-id="10"] td[data-month="1"]');
const targetCell = interactive.locator('tr[data-row-id="11"] td[data-month="2"]');
await sourceCell.locator(".pj-goal-text").evaluate(function (editor) {
editor.value = "pj-rich:v1:" + JSON.stringify([{ text: "드래그 이동", bold: true, italic: true, underline: true, size: 24, color: "#ff0000" }]);
});
await sourceCell.locator(".pj-goal-text").click();
const edge = await sourceCell.locator('.pj-goal-move-edge[data-edge="bottom"]').boundingBox();
const dest = await targetCell.boundingBox();
await interactive.mouse.move(edge.x + edge.width / 2, edge.y + edge.height / 2);
await interactive.mouse.down();
await interactive.mouse.move(dest.x + dest.width / 2, dest.y + dest.height / 2, { steps: 6 });
assert(await targetCell.evaluate(function (td) { return td.classList.contains("is-goal-move-target"); }));
await interactive.mouse.up(); await moveStarted;
assert.equal(moveRequests.length, 1);
assert.equal(await sourceCell.locator(".pj-goal-text").textContent(), "드래그 이동");
assert.equal(await targetCell.locator(".pj-goal-text").textContent(), "");
releaseMove();
await interactive.waitForFunction(function () {
return document.querySelector('tr[data-row-id="10"] .pj-goal-text[data-month="1"]').textContent === "";
});
const moved = await targetCell.locator(".pj-goal-text").evaluate(function (editor) { return JSON.parse(editor.value.slice(11))[0]; });
assert.equal(moved.text, "드래그 이동"); assert.equal(moved.color, "#ff0000"); assert.equal(moved.size, 24);
assert(moved.bold && moved.italic && moved.underline);
assert.deepEqual(await targetCell.evaluate(function (td) { return [td.colSpan, td.rowSpan]; }), [1, 1]);
console.log("PASS actual mouse border drag, delayed atomic response, all text formats, unchanged cell geometry");
await targetCell.click({ button: "right" });
await interactive.getByRole("menuitem", { name: "현재 열 너비 자동 맞춤" }).click();
const oneWidth = await interactive.locator('thead th[data-col="m2"]').evaluate(function (th) { return parseFloat(th.style.getPropertyValue("--cw")); });
assert(oneWidth < 240 && oneWidth > 100);
await interactive.evaluate(function () {
// 접힌 열도 전체 너비 계산에 포함한다.
const editor = document.querySelector('.pj-goal-text[data-row="20"][data-month="4"]');
editor.value = "접힌 열도 길이가 아주 긴 문단을 반영합니다";
document.querySelector('thead th[data-col="q2"]').click();
});
await interactive.waitForTimeout(400);
await targetCell.click({ button: "right" });
await interactive.getByRole("menuitem", { name: "전체 열 너비 자동 맞춤" }).click();
const all = await interactive.evaluate(function () {
const head = document.querySelector('thead th[data-col="m4"]');
return { width: parseFloat(head.style.getPropertyValue("--cw")), folded: head.classList.contains("is-gone"),
saved: JSON.parse(localStorage.getItem("pj_goal_col_w")).m4 };
});
assert(all.folded && all.width > 200 && all.saved === all.width, JSON.stringify(all));
console.log("PASS context menu single/all column fitting including collapsed columns");
await interactive.close();
console.log("ALL PASS");
} finally {
if (browser) await browser.close();
+89 -1
View File
@@ -145,6 +145,17 @@ function mockAutoFitLayout(env) {
return measured;
}
function beginGoalMove(env, source, target) {
const td = source.closest("td");
td.dispatchEvent(new env.w.MouseEvent("mousedown", { bubbles: true, button: 0, clientX: 10, clientY: 10 }));
env.d.dispatchEvent(new env.w.MouseEvent("mouseup", { bubbles: true }));
const edge = td.querySelector('.pj-goal-move-edge[data-edge="bottom"]');
edge.dispatchEvent(new env.w.MouseEvent("mousedown", { bubbles: true, button: 0, clientX: 20, clientY: 20 }));
env.d.elementFromPoint = function () { return target; };
env.d.dispatchEvent(new env.w.MouseEvent("mousemove", { bubbles: true, clientX: 300, clientY: 200 }));
return function () { env.d.dispatchEvent(new env.w.MouseEvent("mouseup", { bubbles: true, clientX: 300, clientY: 200 })); };
}
// ── 가짜 서버 — 목표 표(글 칸 상태를 기억해 화면 GET 에 반영) ───────────────
function goalsServer(env, st) {
st = Object.assign({ cells: {}, areaAdded: false, cellHook: null, metricHook: null, getHook: null }, st || {});
@@ -182,6 +193,13 @@ function goalsServer(env, st) {
}
return { text: html };
});
env.route("POST", new RegExp("/project/api/goals/cells/move$"), async function (u, body, call) {
st.moves = (st.moves || 0) + 1;
if (st.moveHook) { const result = await st.moveHook(body, call); if (result) return result; }
st.cells[body.source_row + ":" + body.source_month] = "";
st.cells[body.target_row + ":" + body.target_month] = body.body;
return { body: { ok: true, body: body.body } };
});
return st;
}
@@ -581,7 +599,7 @@ function meetServer(env, st) {
check("[8] 보기 전용: 메뉴 버튼·이름 편집 없음", !env.d.querySelector(".pj-goal-menu-btn") && !env.d.querySelector("[data-goal-edit]"));
const th = env.d.querySelector("th.pj-goal-area-name");
th.dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true }));
check("[8] 보기 전용: 우클릭 편집 메뉴 없음", !env.d.querySelector(".pj-ctxmenu"));
check("[8] 보기 전용: 우클릭은 너비 맞춤만 제공", Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).map(itemLabel).join("|") === "현재 열 너비 자동 맞춤|전체 열 너비 자동 맞춤");
// 분기 접기는 보기 전용도
const qth = env.d.querySelector('th.pj-goal-fold-th[data-h="1"]');
qth.dispatchEvent(new env.w.MouseEvent("click", { bubbles: true }));
@@ -669,6 +687,76 @@ function meetServer(env, st) {
check("[자동 너비] 보기 전용도 내용 맞춤 가능·쓰기 요청 없음", restored.d.querySelector('thead th[data-col="m1"]').style.getPropertyValue("--cw") === "95px" && !restored.calls.some(function (c) { return c.method !== "GET"; }));
});
await section(async function () {
const env = makeEnv(PAGE.goals_admin, GOALS_URL); goalsServer(env); await boot(env); mockAutoFitLayout(env);
const table = env.d.getElementById("pj-goal-table"), editor = table.querySelector('.pj-goal-text[data-row="10"][data-month="1"]');
editor.value = "길게".repeat(25);
function menu(cell) { cell.dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true })); }
function action(label) { return Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).find(function (b) { return itemLabel(b) === label; }); }
menu(editor);
check("[너비 메뉴] 기존 내용 지우기·현재 열·전체 열 맞춤 함께 표시", !!action("내용 지우기 (Del)") && !!action("현재 열 너비 자동 맞춤") && !!action("전체 열 너비 자동 맞춤"));
action("현재 열 너비 자동 맞춤").click();
check("[너비 메뉴] 현재 열만 맞춤", table.querySelector('thead th[data-col="m1"]').style.getPropertyValue("--cw") === "515px" && table.querySelector('thead th[data-col="m2"]').style.getPropertyValue("--cw") === "85px");
table.querySelector('thead th[data-col="q1"]').click();
menu(table.querySelector('thead th[data-col="y"]')); action("전체 열 너비 자동 맞춤").click();
check("[너비 메뉴] 머리에서도 전체 맞춤·접힌 열 포함·저장", table.querySelector('thead th[data-col="m1"]').style.getPropertyValue("--cw") === "515px" && table.querySelector('thead th[data-col="q1"]').classList.contains("is-folded") && JSON.parse(env.w.localStorage.getItem("pj_goal_col_w")).m1 === 515);
menu(table.querySelector("th.pj-goal-area-name"));
check("[너비 메뉴] 구역 이름 편집 메뉴에도 맞춤 제공", !!action("색 바꾸기") && !!action("현재 열 너비 자동 맞춤"));
});
await section(async function () {
const gate = deferred(), env = makeEnv(PAGE.goals_admin, GOALS_URL);
const st = goalsServer(env, { moveHook: async function (body) { await gate.promise; return { body: { ok: true, body: body.body } }; } });
await boot(env);
const source = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]'), target = env.d.querySelector('.pj-goal-text[data-row="11"][data-month="2"]');
type(env, source, "pj-rich:v1:" + JSON.stringify([{ text: "이동할 글", color: "#ff0000", size: 24, bold: true, italic: true, underline: true }]));
const original = source.value;
const drop = beginGoalMove(env, source, target);
check("[셀 이동] 대상 미리보기·일반 범위 선택과 분리", target.closest("td").classList.contains("is-goal-move-target") && env.d.documentElement.classList.contains("pj-goal-moving"));
drop(); await settle();
check("[셀 이동] 먼저 초안 저장·이동은 한 번·응답 전 원본 유지", st.moves === 1 && source.value === original && target.value === "" && source.getAttribute("contenteditable") === "false" && target.getAttribute("contenteditable") === "false");
const moveIndex = env.calls.findIndex(function (c) { return /cells\/move$/.test(c.url); });
check("[셀 이동] 글 PUT 뒤 원자적 이동 API", moveIndex > env.calls.findIndex(function (c) { return c.method === "PUT" && /rows\/10\/cells\/1$/.test(c.url); }));
gate.resolve(); await settle();
const run = JSON.parse(target.value.slice(11))[0];
check("[셀 이동] 성공 뒤 원본 비우기·대상 글과 모든 서식 보존", source.value === "" && run.text === "이동할 글" && run.color === "#ff0000" && run.size === 24 && run.bold && run.italic && run.underline);
const count = env.calls.length; fire(env, source, "blur"); fire(env, target, "blur"); await settle();
check("[셀 이동] 저장 기준값·초안 정리·후속 blur 중복 저장 없음", env.calls.length === count && !env.w.localStorage.getItem("pj_draft:goal:10:1") && source.getAttribute("contenteditable") === "true" && target.closest("td").classList.contains("is-goal-active"));
});
for (const failure of ["network", "conflict", "save"]) await section(async function () {
const env = makeEnv(PAGE.goals_admin, GOALS_URL);
const st = goalsServer(env, { moveHook: function () { return failure === "network" ? "NETWORK" : { status: 409, body: { detail: "다른 창에서 수정" } }; },
cellHook: failure === "save" ? function () { return { status: 503, body: { detail: "저장 장애" } }; } : null });
await boot(env);
const source = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]'), target = env.d.querySelector('.pj-goal-text[data-row="11"][data-month="2"]');
if (failure === "save") type(env, source, "미저장 초안");
const before = source.value; beginGoalMove(env, source, target)(); await settle();
check("[셀 이동 " + failure + "] 실패해도 양쪽 내용·편집 가능 상태 유지", source.value === before && target.value === "" && source.getAttribute("contenteditable") === "true" && !env.d.documentElement.classList.contains("pj-goal-moving"));
check("[셀 이동 " + failure + "] 저장 실패면 이동 API 생략", failure !== "save" || !st.moves);
});
await section(async function () {
const env = makeEnv(PAGE.goals_admin, GOALS_URL), st = goalsServer(env); await boot(env);
const source = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]'), target = env.d.querySelector('.pj-goal-text[data-row="11"][data-month="2"]');
target.value = "대상 기존 글"; let confirmations = 0;
env.w.erpConfirm = function () { confirmations++; return Promise.resolve(false); };
beginGoalMove(env, source, target)(); await settle();
check("[셀 이동] 덮어쓰기 취소는 두 내용 유지·이동 없음", confirmations === 1 && !st.moves && source.value === "original" && target.value === "대상 기존 글");
env.w.erpConfirm = function () { return Promise.resolve(true); };
beginGoalMove(env, source, target)(); await settle();
check("[셀 이동] 확인 뒤 덮어쓰기·원본 비우기", st.moves === 1 && source.value === "" && target.textContent === "original");
});
await section(async function () {
const env = makeEnv(PAGE.goals_admin, GOALS_URL), st = goalsServer(env); await boot(env);
const source = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]'), target = env.d.querySelector('.pj-goal-text[data-row="11"][data-month="2"]');
beginGoalMove(env, source, target); key(env, env.d, "Escape"); await settle();
check("[셀 이동] Esc 취소는 원본 유지·이동 요청 없음", !st.moves && source.value === "original" && !env.d.documentElement.classList.contains("pj-goal-moving"));
beginGoalMove(env, source, target); env.w.dispatchEvent(new env.w.Event("blur")); await settle();
check("[셀 이동] 창 포커스 이탈도 이동 취소·드래그 정리", !st.moves && !env.d.querySelector(".is-goal-move-target"));
beginGoalMove(env, source, source)(); await settle();
check("[셀 이동] 자기 셀에 놓기 = 변경 없음", !st.moves && source.value === "original");
const ro = makeEnv(PAGE.goals_ro, GOALS_URL); goalsServer(ro); await boot(ro);
check("[셀 이동] 보기 전용에는 이동 테두리 없음", !ro.d.querySelector(".pj-goal-move-edge"));
});
// ════════════════════ [9] 매출 자동 갱신 — 정상 조용히 · 실패/일부 실패 안내 + 재시도 · 권한 없음 ════════════════════
await section(async function () {
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
+179
View File
@@ -0,0 +1,179 @@
"""셀 이동의 실제 저장소/라우터 로직을 트랜잭션 대역으로 검증(실제 PostgreSQL 테스트는 test_project_module.py)."""
import copy
import importlib
import json
import unittest
from contextlib import contextmanager
from types import SimpleNamespace
from unittest.mock import patch
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.project import store
from app.modules.project.db import ProjectStore
api_module = importlib.import_module("app.modules.project.router")
class Rows:
def __init__(self, rows=()):
self.rows = list(rows)
def fetchall(self):
return self.rows
def fetchone(self):
return self.rows[0] if self.rows else None
class Connection:
def __init__(self):
self.rows = {10: {"id": 10, "area_id": 2, "year": 2026}, 20: {"id": 20, "area_id": 1, "year": 2026}}
self.cells = {(10, 1): "original", (20, 2): "existing"}
self.calls, self.commits, self.rollbacks = [], 0, 0
self.fail_delete = False
self.transaction_depth = 0
@contextmanager
def transaction(self):
before = copy.deepcopy(self.cells)
self.transaction_depth += 1
try:
yield self
except Exception:
self.cells = before
self.rollbacks += 1
raise
else:
self.commits += 1
finally:
self.transaction_depth -= 1
def execute(self, sql, params):
self.calls.append((sql, params))
if sql.startswith("SELECT r.id, r.area_id, a.year"):
return Rows(self.rows[r] for r in set(params[0]) if r in self.rows)
if sql.startswith("SELECT id FROM goal_areas"):
return Rows({"id": a} for a in params[0])
if sql.startswith("SELECT id, area_id FROM goal_rows"):
return Rows(self.rows[r] for r in sorted(set(params[0])) if r in self.rows)
if sql.startswith("SELECT row_id, month, body"):
keys = [(params[0], params[1]), (params[2], params[3])]
return Rows({"row_id": r, "month": m, "body": self.cells[r, m]} for r, m in keys if (r, m) in self.cells)
if sql.startswith("INSERT INTO goal_cells"):
assert self.transaction_depth > 0, "Cell writes must hold the area lock until commit"
self.cells[params[0], params[1]] = params[2]
return Rows()
if sql.startswith("DELETE FROM goal_cells"):
assert self.transaction_depth > 0, "Cell writes must hold the area lock until commit"
if self.fail_delete:
raise RuntimeError("simulated delete failure")
self.cells.pop((params[0], params[1]), None)
return Rows()
if sql.startswith("SELECT a.id AS area_id"):
assert self.transaction_depth > 0, "Autocommit releases the area lock before the write"
row = self.rows.get(params[0])
return Rows([{"area_id": row["area_id"]}] if row else [])
raise AssertionError("Unexpected SQL: " + sql)
class GoalMoveTests(unittest.TestCase):
def setUp(self):
self.conn = Connection()
@contextmanager
def connection():
yield self.conn
self.st = ProjectStore.__new__(ProjectStore)
self.st._pool = SimpleNamespace(connection=connection)
self.st._table_exists = lambda conn, name: True
self.st._goal_quarters = lambda conn: True
self.merges = {}
self.st._area_geometry = lambda conn, area: (
[r for r in self.conn.rows if self.conn.rows[r]["area_id"] == area], self.merges.get(area, []), True)
self.payload = dict(source_row=10, source_month=1, target_row=20, target_month=2,
source_body="original", target_body="existing", body="original", updated_by="ADMIN@TEST.LOCAL")
def move(self, **changes):
return self.st.move_goal_cell(**(self.payload | changes))
def test_move_preserves_all_explicit_formats_and_locks_in_order(self):
rich = store.validate_goal_text(store.GOAL_RICH_PREFIX + json.dumps([
{"text": "formatted", "bold": True, "italic": True, "underline": True, "size": 24, "color": "#ff0000"}]))
self.conn.cells[10, 1] = rich
self.assertEqual(self.move(source_body=rich, body=rich), rich)
self.assertNotIn((10, 1), self.conn.cells)
self.assertEqual(self.conn.cells[20, 2], rich)
self.assertEqual(self.conn.commits, 1)
self.assertTrue(any("goal_areas" in sql and "FOR UPDATE" in sql and p == ([1, 2],) for sql, p in self.conn.calls))
def test_failure_after_target_write_rolls_back_both_cells(self):
before = dict(self.conn.cells)
self.conn.fail_delete = True
with self.assertRaises(RuntimeError):
self.move()
self.assertEqual(self.conn.cells, before)
self.assertEqual(self.conn.rollbacks, 1)
def test_concurrent_change_in_either_cell_aborts_without_writes(self):
for key in ((10, 1), (20, 2)):
with self.subTest(key=key):
self.setUp()
self.conn.cells[key] = "another user's edit"
before = dict(self.conn.cells)
with self.assertRaises(store.GoalCellConflict):
self.move()
self.assertEqual(self.conn.cells, before)
def test_lost_response_retry_succeeds_without_writing_again(self):
self.move()
count = len([sql for sql, _ in self.conn.calls if sql.startswith(("INSERT", "DELETE"))])
self.assertEqual(self.move(), "original")
self.assertEqual(len([sql for sql, _ in self.conn.calls if sql.startswith(("INSERT", "DELETE"))]), count)
def test_empty_target_and_defaults_become_explicit_styles(self):
self.conn.cells.pop((20, 2))
rich = store.GOAL_RICH_PREFIX + json.dumps([{"text": "original", "bold": False, "size": 14, "color": "#050505"}])
result = self.move(target_body="", body=rich)
self.assertEqual(store.goal_text_plain(result), "original")
self.assertIn('"bold":false', result)
def test_bad_content_missing_rows_wrong_year_and_hidden_merge_cell(self):
for changes, error in [({"body": "different"}, ValueError), ({"target_row": 999}, KeyError),
({"target_month": 17}, ValueError), ({"target_row": 10, "target_month": 1}, ValueError)]:
with self.subTest(changes=changes), self.assertRaises(error):
self.move(**changes)
self.conn.rows[20]["year"] = 2027
with self.assertRaises(ValueError):
self.move()
self.conn.rows[20]["year"] = 2026
self.merges[1] = [{"r0": 0, "r1": 0, "c0": 1, "c1": 2}]
with self.assertRaises(store.GoalCellConflict):
self.move()
def test_normal_save_uses_the_same_area_lock(self):
self.st.set_goal_cell(row_id=10, month=1, body="new")
self.assertIn("FOR UPDATE OF a", self.conn.calls[0][0])
self.assertEqual(self.conn.cells[10, 1], "new")
self.assertEqual(self.conn.commits, 1)
def test_http_admin_permissions_validation_and_conflict_status(self):
app = FastAPI()
app.include_router(api_module.router)
app.state.project_store = self.st
client = TestClient(app)
payload = {k: v for k, v in self.payload.items() if k != "updated_by"}
with patch.object(api_module, "_require_user", return_value={"email": "a@test.local", "role": "user"}):
self.assertEqual(client.post("/project/api/goals/cells/move", json=payload).status_code, 403)
with patch.object(api_module, "_require_user", return_value={"email": "a@test.local", "role": "admin"}):
self.assertEqual(client.post("/project/api/goals/cells/move", json=payload | {"source_body": None}).status_code, 400)
self.conn.cells[20, 2] = "changed"
self.assertEqual(client.post("/project/api/goals/cells/move", json=payload).status_code, 409)
self.conn.cells[20, 2] = "existing"
result = client.post("/project/api/goals/cells/move", json=payload)
self.assertEqual(result.status_code, 200)
self.assertEqual(result.json(), {"ok": True, "body": "original"})
if __name__ == "__main__":
unittest.main()
+49
View File
@@ -499,6 +499,55 @@ def test_store_goal_quarters_unit():
# ════════════════════════════════════════════════════════════
# 연간 목표 — 상·하반기 글 칸 · 월 칸 병합(마이그레이션 014) · 로아스 % 표기
# ════════════════════════════════════════════════════════════
def test_goal_cell_content_move():
"""실제 PostgreSQL: 서식 포함 이동·동시 이동 충돌·권한·병합 가림·응답 유실 재시도."""
from app.modules.project import store
year = 2060 + int(RUN, 16) % 40
assert req("POST", "/project/api/goals/years", ADMIN, json={"year": year}).status_code == 201
try:
board = ST.get_goal_board(year=year)
rid = board["areas"][0]["rows"][0]["id"]
rich = store.validate_goal_text(store.GOAL_RICH_PREFIX + '[{"text":"move","color":"#ff0000","size":24,"bold":true,"italic":true,"underline":true}]')
ST.set_goal_cell(row_id=rid, month=1, body=rich)
payload = {"source_row": rid, "source_month": 1, "target_row": rid, "target_month": 2,
"source_body": rich, "target_body": "", "body": rich}
endpoint = "/project/api/goals/cells/move"
assert req("POST", endpoint, BOB, json=payload).status_code == 403
assert req("POST", endpoint, ADMIN, json=payload | {"target_month": 17}).status_code == 400
ST.set_goal_cell(row_id=rid, month=2, body="another edit")
assert req("POST", endpoint, ADMIN, json=payload).status_code == 409
ST.set_goal_cell(row_id=rid, month=2, body="")
assert req("POST", endpoint, ADMIN, json=payload).json() == {"ok": True, "body": rich}
assert req("POST", endpoint, ADMIN, json=payload).status_code == 200
cells = ST.get_goal_board(year=year)["areas"][0]["rows"][0]["cells"]
assert 1 not in cells and cells[2] == rich
# 같은 원본을 서로 다른 대상으로 동시에 이동하면 한 요청만 성공한다.
ST.set_goal_cell(row_id=rid, month=1, body=rich)
ST.set_goal_cell(row_id=rid, month=2, body="")
barrier = threading.Barrier(2)
results = []
def move_to(month):
barrier.wait()
try:
ST.move_goal_cell(source_row=rid, source_month=1, target_row=rid, target_month=month,
source_body=rich, target_body="", body=rich, updated_by=ADMIN)
results.append("ok")
except store.GoalCellConflict:
results.append("conflict")
workers = [threading.Thread(target=move_to, args=(m,)) for m in (2, 3)]
for t in workers: t.start()
for t in workers: t.join(timeout=10)
assert sorted(results) == ["conflict", "ok"], results
aid = board["areas"][0]["id"]
ST.merge_goal_rect(area_id=aid, row_from=rid, row_to=rid, col_from=4, col_to=5)
hidden = payload | {"source_month": 2 if 2 in ST.get_goal_board(year=year)["areas"][0]["rows"][0]["cells"] else 3,
"target_month": 5}
assert req("POST", endpoint, ADMIN, json=hidden).status_code == 409
finally:
ST.delete_goal_year(year=year)
def test_goal_halves_and_merges():
year = 2060 + int(RUN, 16) % 40
ST.delete_goal_year(year=year) if year in ST.list_goal_years() else None