feat(project): 파일 끌어 놓기 → 구글 드라이브 링크, 필터 켠 보드 카드 순서 버그 수정
- 설명란·세부 업무 목록·보드 카드에 파일을 놓으면 드라이브 프로젝트/섹션/업무/세부 업무 폴더에 올리고 설명에 "파일 이름.확장자" 링크(PROJECT_DRIVE_FOLDER_ID) - 설명에서 링크를 지우면 우리가 올린 파일만 드라이브 휴지통, 되살리면 복구 - 브라우저별 필터(localStorage)가 켜져 있으면 섹션 안 카드가 제자리로 돌아가던 버그 — 필터 중에도 순서 변경 허용, 숨은 업무는 제자리. 카드 속 이미지 끌기 오인 방지 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,146 @@
|
||||
// 실제 브라우저 — 보드 카드 끌기(필터를 켠 브라우저에서도 섹션 안 순서 변경, 숨은 업무는 제자리)와
|
||||
// 파일 → 구글 드라이브(설명란 = 놓은 자리에 링크, 보드 카드 = 서버가 설명 끝에 링크 append) (2026-10-19).
|
||||
// 서버는 가짜(이 파일의 http 서버), 화면은 실제 템플릿 렌더 결과.
|
||||
// python tests/js/render_project.py
|
||||
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/board_drive.browser.test.js
|
||||
const fs = require("node:fs"), path = require("node:path"), http = require("node:http");
|
||||
const { chromium } = require("playwright");
|
||||
const ROOT = path.resolve(__dirname, "../.."), OUT = path.join(__dirname, ".out"), STATIC = path.join(ROOT, "app/static");
|
||||
const fails = [];
|
||||
function check(name, cond, extra) {
|
||||
if (cond) console.log("PASS " + name);
|
||||
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
|
||||
}
|
||||
|
||||
// 렌더된 보드(할 일 섹션 = 작업 A·B) 에 완료된 C(필터 "미완료"로 숨김)와 D 를 더한다
|
||||
function boardHtml() {
|
||||
let html = fs.readFileSync(path.join(OUT, "project_render.html"), "utf8");
|
||||
return html.replace(/(<script id="pj-data" type="application\/json">)([\s\S]*?)(<\/script>)/, function (_, a, json, c) {
|
||||
const data = JSON.parse(json);
|
||||
const base = data.tasks.find(function (t) { return t.id === 101; });
|
||||
base.description = "<p>앞 글</p>";
|
||||
data.tasks.push(Object.assign({}, base, { description: "", id: 104, title: "작업 C(완료)", completed_at: "2026-10-01T00:00:00+09:00", sort_order: 104 }));
|
||||
data.tasks.push(Object.assign({}, base, { description: "", id: 105, title: "작업 D", sort_order: 105 }));
|
||||
return a + JSON.stringify(data) + c;
|
||||
});
|
||||
}
|
||||
|
||||
const orders = [], drives = [], puts = [];
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url, "http://localhost");
|
||||
const json = (code, body) => { res.statusCode = code; res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify(body)); };
|
||||
if (url.pathname === "/project/p/1") { res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(boardHtml()); return; }
|
||||
if (url.pathname.startsWith("/project/api/")) {
|
||||
const chunks = []; for await (const c of req) chunks.push(c);
|
||||
const raw = Buffer.concat(chunks).toString("utf8");
|
||||
const order = /^\/project\/api\/projects\/1\/stages\/(\d+)\/tasks\/order$/.exec(url.pathname);
|
||||
if (order) { orders.push({ stage: +order[1], ids: JSON.parse(raw).ordered_ids }); return json(200, { ok: true }); }
|
||||
const drive = /^\/project\/api\/tasks\/(\d+)\/drive-files$/.exec(url.pathname);
|
||||
if (drive && req.method === "POST") {
|
||||
const name = (/filename="([^"]+)"/.exec(raw) || [])[1] || "file";
|
||||
const append = /name="append"\r\n\r\ntrue/.test(raw);
|
||||
drives.push({ id: +drive[1], name: name, append: append });
|
||||
const f = { id: "FILE" + drives.length + "abcdefgh", name: name, url: "https://drive.google.com/file/d/FILE" + drives.length + "abcdefgh/view" };
|
||||
const out = { file: f, link_html: "" };
|
||||
if (append) out.task = { id: +drive[1], project_id: 1, context_project_id: 1, stage_id: 11, title: "작업", description: '<p><a href="' + f.url + '">' + name + "</a></p>" };
|
||||
return json(201, out);
|
||||
}
|
||||
const task = /^\/project\/api\/tasks\/(\d+)$/.exec(url.pathname);
|
||||
if (task && req.method === "GET") return json(200, { task: { id: +task[1], title: "작업 " + task[1], project_id: 1, context_project_id: 1, stage_id: 11,
|
||||
description: "<p>앞 글</p>", priority: "normal", assignee_email: "", subtasks: [], links: [], followers: [], access: "full", completed_at: null } });
|
||||
if (task && req.method === "PUT") {
|
||||
const body = JSON.parse(raw); puts.push({ id: +task[1], body: body });
|
||||
return json(200, { task: Object.assign({ id: +task[1], title: "작업", project_id: 1, context_project_id: 1, stage_id: 11 }, body) });
|
||||
}
|
||||
if (url.pathname.endsWith("/comments")) return json(200, { comments: [], events: [], features: {} });
|
||||
if (url.pathname.endsWith("/attachments")) return json(200, { attachments: [] });
|
||||
if (url.pathname.endsWith("/members")) return json(200, { members: [{ user_email: "me@test.local" }] });
|
||||
if (url.pathname.endsWith("/live-version")) return json(200, { ts: "v1" });
|
||||
if (url.pathname.endsWith("/alerts")) return json(200, { me: "me@test.local", latest_id: 0, alerts: [] });
|
||||
return json(200, {});
|
||||
}
|
||||
if (url.pathname.startsWith("/static/")) {
|
||||
const file = path.join(STATIC, decodeURIComponent(url.pathname.slice("/static/".length)));
|
||||
if (file.startsWith(STATIC) && fs.existsSync(file)) {
|
||||
res.setHeader("Content-Type", file.endsWith(".js") ? "text/javascript" : file.endsWith(".css") ? "text/css" : "application/octet-stream");
|
||||
res.end(fs.readFileSync(file)); return;
|
||||
}
|
||||
}
|
||||
res.statusCode = 404; res.end("");
|
||||
});
|
||||
|
||||
// 파일 끌어 놓기 흉내 — 진짜 File 을 담은 DataTransfer 로 dragenter·dragover·drop
|
||||
async function dropFile(page, selector, name) {
|
||||
await page.evaluate(function (a) {
|
||||
const target = document.querySelector(a.sel);
|
||||
const r = target.getBoundingClientRect();
|
||||
const dt = new DataTransfer();
|
||||
dt.items.add(new File(["hello"], a.name, { type: "text/plain" }));
|
||||
const opts = { bubbles: true, cancelable: true, dataTransfer: dt, clientX: r.left + 10, clientY: r.top + Math.min(10, r.height / 2) };
|
||||
["dragenter", "dragover", "drop"].forEach(function (k) { target.dispatchEvent(new DragEvent(k, opts)); });
|
||||
}, { sel: selector, name: name });
|
||||
}
|
||||
|
||||
(async function () {
|
||||
await new Promise(r => server.listen(0, "127.0.0.1", r));
|
||||
const base = "http://127.0.0.1:" + server.address().port;
|
||||
const browser = await chromium.launch(process.env.PJ_TEST_BROWSER ? { executablePath: process.env.PJ_TEST_BROWSER } : {});
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
|
||||
page.on("pageerror", e => console.log("PAGEERR", e.message));
|
||||
// 이 브라우저에는 "미완료만" 필터가 저장돼 있다(다른 컴퓨터는 없음) — 예전엔 이 상태에서 섹션 안 이동이 늘 제자리로
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem("pj_filter_1", JSON.stringify({ status: "open" }));
|
||||
localStorage.setItem("pj_view", "board");
|
||||
});
|
||||
await page.goto(base + "/project/p/1");
|
||||
await page.waitForSelector('.pj-card[data-task-id="105"]');
|
||||
check("필터(미완료) — 완료된 C 는 보드에 안 보임", !(await page.$('.pj-card[data-task-id="104"]')));
|
||||
|
||||
// ── 1) 섹션 안 카드 끌기: D 를 A 위로
|
||||
const a = await page.locator('.pj-card[data-task-id="101"]').boundingBox();
|
||||
const d = await page.locator('.pj-card[data-task-id="105"]').boundingBox();
|
||||
await page.mouse.move(d.x + d.width / 2, d.y + d.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(d.x + d.width / 2, d.y + d.height / 2 - 8, { steps: 3 });
|
||||
for (let i = 1; i <= 12; i++) await page.mouse.move(a.x + a.width / 2, d.y + (a.y + 4 - d.y) * i / 12, { steps: 2 });
|
||||
await page.waitForTimeout(150);
|
||||
await page.mouse.up();
|
||||
await page.waitForTimeout(400);
|
||||
check("필터를 켠 채 섹션 안 이동 — 순서 저장 요청", orders.length === 1, orders);
|
||||
check("숨은 C 는 제자리, D 는 A 앞", orders[0] && JSON.stringify(orders[0].ids) === JSON.stringify([105, 101, 102, 104]), orders[0]);
|
||||
const ids = await page.$$eval('.pj-col-body .pj-card[data-task-id]', els => els.map(e => +e.dataset.taskId));
|
||||
check("보드도 D·A·B 순서로 다시 그림", JSON.stringify(ids.slice(0, 3)) === JSON.stringify([105, 101, 102]), ids);
|
||||
|
||||
// ── 2) 보드 카드에 파일 놓기 → 서버가 설명 끝에 링크(append)
|
||||
await dropFile(page, '.pj-card[data-task-id="102"] .pj-card-title', "견적서.pdf");
|
||||
await page.waitForTimeout(400);
|
||||
check("보드 카드 파일 → drive-files(append) 한 번", drives.length === 1 && drives[0].id === 102 && drives[0].append && drives[0].name === "견적서.pdf", drives);
|
||||
|
||||
// ── 3) 업무 창 설명란에 파일 놓기 → 놓은 자리에 "파일 이름.확장자" 링크 + 설명 저장
|
||||
await page.click('.pj-card[data-task-id="101"] .pj-card-title');
|
||||
await page.waitForSelector("#pj-t-desc", { state: "visible" });
|
||||
await page.waitForFunction(() => document.getElementById("pj-t-desc").textContent.includes("앞 글"));
|
||||
await dropFile(page, "#pj-t-desc", "도면 v2.dwg");
|
||||
await page.waitForFunction(() => !!document.querySelector('#pj-t-desc a[href*="drive.google.com"]'), null, { timeout: 5000 }).catch(() => {});
|
||||
const link = await page.evaluate(() => {
|
||||
const x = document.querySelector('#pj-t-desc a[href*="drive.google.com"]');
|
||||
return x ? { text: x.textContent, href: x.getAttribute("href"), target: x.getAttribute("target"),
|
||||
busy: !!document.querySelector("#pj-t-desc .pj-drive-uploading") } : null;
|
||||
});
|
||||
check("설명란 파일 → drive-files(append 아님)", drives.length === 2 && drives[1].id === 101 && !drives[1].append, drives);
|
||||
check("설명란에 '파일 이름.확장자' 링크(새 탭)", link && link.text === "도면 v2.dwg" && /\/file\/d\/FILE2abcdefgh\/view$/.test(link.href) && link.target === "_blank" && !link.busy, link);
|
||||
await page.waitForTimeout(1600); // 설명 자동 저장(1.2초)
|
||||
const descPut = puts.filter(p => p.id === 101 && p.body.description != null).pop();
|
||||
check("링크가 들어간 설명 저장", !!descPut && descPut.body.description.includes("FILE2abcdefgh") &&
|
||||
/앞.*도면 v2\.dwg<\/a>.*글/.test(descPut.body.description), descPut); // 놓은 자리(앞|글 사이)에 링크
|
||||
|
||||
// ── 4) 업무 창이 열린 업무의 카드에 놓으면 서버 append 대신 편집기 끝에(옛 설명 저장이 링크를 지우지 않게)
|
||||
await dropFile(page, '.pj-card[data-task-id="101"] .pj-card-title', "사진.jpg");
|
||||
await page.waitForTimeout(500);
|
||||
const n = await page.$$eval('#pj-t-desc a[href*="drive.google.com"]', els => els.map(e => e.textContent));
|
||||
check("열린 업무 카드 → 편집기에 링크(append 아님)", drives.length === 3 && !drives[2].append && n.indexOf("사진.jpg") >= 0, { drives: drives, n: n });
|
||||
} finally { await browser.close(); server.close(); }
|
||||
console.log(fails.length ? "\n" + fails.length + " FAILED" : "\nALL PASS");
|
||||
process.exit(fails.length ? 1 : 0);
|
||||
})();
|
||||
@@ -0,0 +1,165 @@
|
||||
"""업무 파일 → 구글 드라이브(2026-10-19) — 폴더 경로·업로드 API·설명 링크 append·링크 지우면 휴지통. DB·Google 없이 가짜로."""
|
||||
import importlib
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.integrations import google_drive
|
||||
|
||||
api = importlib.import_module("app.modules.project.router")
|
||||
ME = {"email": "me@test.local", "role": "user"}
|
||||
|
||||
|
||||
class FakeDrive:
|
||||
enabled = True
|
||||
reason = ""
|
||||
|
||||
def __init__(self):
|
||||
self.paths, self.uploads, self.trash = [], [], []
|
||||
self.meta = {}
|
||||
|
||||
def ensure_folder_path(self, names, root=None):
|
||||
self.paths.append(list(names))
|
||||
return "FOLDER"
|
||||
|
||||
def upload(self, *, folder_id, name, stream, mimetype, task_id):
|
||||
self.uploads.append({"folder": folder_id, "name": name, "data": stream.read(), "task_id": task_id})
|
||||
fid = "F%dabcdefghij" % len(self.uploads)
|
||||
return {"id": fid, "name": name, "url": google_drive.file_url(fid)}
|
||||
|
||||
def ours(self, file_id):
|
||||
return self.meta.get(file_id)
|
||||
|
||||
def set_trashed(self, file_id, trashed):
|
||||
self.trash.append((file_id, trashed))
|
||||
|
||||
|
||||
class Store(MagicMock):
|
||||
TASKS = {
|
||||
1: {"id": 1, "project_id": 7, "project_name": "신제품", "stage_name": "기획", "title": "패키지 디자인",
|
||||
"parent_task_id": None, "description": "<p>기존</p>"},
|
||||
2: {"id": 2, "project_id": 7, "project_name": "신제품", "stage_name": None, "title": "시안 A",
|
||||
"parent_task_id": 1, "description": ""},
|
||||
}
|
||||
|
||||
def get_task(self, task_id):
|
||||
t = self.TASKS.get(int(task_id))
|
||||
return dict(t) if t else None
|
||||
|
||||
|
||||
class Base(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.st = Store()
|
||||
self.st.update_task.side_effect = lambda task_id, fields, actor, assignee_allowed=None: {
|
||||
**self.st.get_task(task_id), **fields}
|
||||
self.drive = FakeDrive()
|
||||
app = FastAPI()
|
||||
app.include_router(api.router)
|
||||
app.state.project_store = self.st
|
||||
app.state.data_dir = tempfile.mkdtemp(prefix="pj-drive-")
|
||||
self.client = TestClient(app, raise_server_exceptions=False)
|
||||
for p in (patch.object(api, "_require_user", return_value=ME), patch.object(api, "_db_or_503", return_value=self.st),
|
||||
patch.object(api, "_require_task", return_value="full"),
|
||||
patch.object(google_drive, "get_client", return_value=self.drive)):
|
||||
p.start()
|
||||
self.addCleanup(p.stop)
|
||||
|
||||
|
||||
class HelperTests(unittest.TestCase):
|
||||
def test_file_ids_in_description(self):
|
||||
html = ('<p><a href="https://drive.google.com/file/d/AbC_12-xyz9/view" target="_blank">a.pdf</a> '
|
||||
'<a href="https://example.com/file/d/zzzzzzzzzzzz/view">x</a></p>')
|
||||
self.assertEqual(google_drive.file_ids_in(html), {"AbC_12-xyz9"})
|
||||
self.assertEqual(google_drive.file_ids_in(""), set())
|
||||
|
||||
def test_folder_name_and_query_escape(self):
|
||||
self.assertEqual(google_drive.folder_name(" 기획\n 2차 "), "기획 2차")
|
||||
self.assertEqual(google_drive.folder_name(""), "(이름 없음)")
|
||||
self.assertEqual(google_drive._q("A's \\ b"), "A\\'s \\\\ b")
|
||||
|
||||
def test_folder_path_project_section_task_subtask(self):
|
||||
st = Store()
|
||||
self.assertEqual(api._drive_folder_names(st, st.get_task(1)), ["신제품", "기획", "패키지 디자인"])
|
||||
# 세부 업무 = 맨 위 업무의 섹션 + 업무 + 세부 업무
|
||||
self.assertEqual(api._drive_folder_names(st, st.get_task(2)), ["신제품", "기획", "패키지 디자인", "시안 A"])
|
||||
|
||||
def test_link_html_escapes_name(self):
|
||||
html = api.drive_link_html("https://drive.google.com/file/d/X1234567890/view", "<견적>.pdf")
|
||||
self.assertIn("<견적>.pdf</a>", html)
|
||||
self.assertIn('target="_blank"', html)
|
||||
|
||||
|
||||
class UploadApiTests(Base):
|
||||
def test_upload_returns_link_without_touching_description(self):
|
||||
r = self.client.post("/project/api/tasks/1/drive-files", files={"file": ("도면 v2.dwg", b"abc", "application/acad")})
|
||||
self.assertEqual(r.status_code, 201, r.text)
|
||||
body = r.json()
|
||||
self.assertEqual(body["file"]["name"], "도면 v2.dwg")
|
||||
self.assertTrue(body["file"]["url"].startswith("https://drive.google.com/file/d/"))
|
||||
self.assertEqual(self.drive.paths, [["신제품", "기획", "패키지 디자인"]])
|
||||
self.assertEqual(self.drive.uploads[0]["data"], b"abc")
|
||||
self.assertEqual(self.drive.uploads[0]["task_id"], 1)
|
||||
self.st.update_task.assert_not_called()
|
||||
|
||||
def test_upload_append_adds_link_to_subtask_description(self):
|
||||
r = self.client.post("/project/api/tasks/2/drive-files", files={"file": ("시안.png", b"png", "image/png")},
|
||||
data={"append": "true"})
|
||||
self.assertEqual(r.status_code, 201, r.text)
|
||||
self.assertEqual(self.drive.paths, [["신제품", "기획", "패키지 디자인", "시안 A"]])
|
||||
fields = self.st.update_task.call_args.kwargs["fields"]
|
||||
self.assertIn('href="https://drive.google.com/file/d/F1abcdefghij/view"', fields["description"])
|
||||
self.assertIn(">시안.png</a>", fields["description"])
|
||||
self.assertEqual(r.json()["task"]["description"], fields["description"])
|
||||
|
||||
def test_empty_file_and_disabled_drive(self):
|
||||
r = self.client.post("/project/api/tasks/1/drive-files", files={"file": ("a.txt", b"", "text/plain")})
|
||||
self.assertEqual(r.status_code, 400)
|
||||
self.drive.enabled = False
|
||||
self.drive.reason = "Google 인증 미설정"
|
||||
r = self.client.post("/project/api/tasks/1/drive-files", files={"file": ("a.txt", b"x", "text/plain")})
|
||||
self.assertEqual(r.status_code, 503)
|
||||
self.assertIn("Google 인증 미설정", r.json()["detail"])
|
||||
|
||||
def test_drive_error_is_502_with_message(self):
|
||||
self.drive.ensure_folder_path = MagicMock(side_effect=google_drive.GoogleDriveError("업무 파일 폴더를 찾을 수 없습니다"))
|
||||
r = self.client.post("/project/api/tasks/1/drive-files", files={"file": ("a.txt", b"x", "text/plain")})
|
||||
self.assertEqual(r.status_code, 502)
|
||||
self.assertIn("폴더", r.json()["detail"])
|
||||
|
||||
|
||||
class LinkSyncTests(Base):
|
||||
def test_removed_link_trashes_our_file_added_link_restores(self):
|
||||
self.drive.meta = {"GONE1234567": {"trashed": False, "task_id": "1"},
|
||||
"BACK1234567": {"trashed": True, "task_id": "1"},
|
||||
"KEEP1234567": {"trashed": False, "task_id": "1"},
|
||||
"OTHER123456": None}
|
||||
self.st.description_mentions.side_effect = lambda text, exclude_task_id: text == "KEEP1234567"
|
||||
api._sync_drive_links(self.st, 1, {"GONE1234567", "KEEP1234567", "OTHER123456"}, {"BACK1234567"})
|
||||
self.assertIn(("GONE1234567", True), self.drive.trash)
|
||||
self.assertIn(("BACK1234567", False), self.drive.trash)
|
||||
# 다른 업무 설명에 남은 링크·우리가 올리지 않은 파일은 그대로
|
||||
self.assertNotIn(("KEEP1234567", True), self.drive.trash)
|
||||
self.assertNotIn(("OTHER123456", True), self.drive.trash)
|
||||
|
||||
def test_description_save_schedules_sync(self):
|
||||
old = '<p><a href="https://drive.google.com/file/d/GONE1234567/view">a.pdf</a></p>'
|
||||
self.st.TASKS = {1: {**Store.TASKS[1], "description": old}}
|
||||
with patch.object(api, "_sync_drive_links") as sync, patch.object(api, "_record_mentions", return_value=[]):
|
||||
r = self.client.put("/project/api/tasks/1", json={"description": "<p>링크 지움</p>"})
|
||||
self.assertEqual(r.status_code, 200, r.text)
|
||||
sync.assert_called_once()
|
||||
_, task_id, removed, added = sync.call_args.args
|
||||
self.assertEqual((task_id, removed, added), (1, {"GONE1234567"}, set()))
|
||||
|
||||
def test_description_save_without_link_change_does_not_sync(self):
|
||||
with patch.object(api, "_sync_drive_links") as sync, patch.object(api, "_record_mentions", return_value=[]):
|
||||
r = self.client.put("/project/api/tasks/1", json={"description": "<p>글만 바뀜</p>"})
|
||||
self.assertEqual(r.status_code, 200, r.text)
|
||||
sync.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user