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
+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