From bdf01fef6478caff38d86c1f8926a421e3b38929 Mon Sep 17 00:00:00 2001 From: s26011-cloud Date: Sat, 5 Dec 2026 00:07:45 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EB=8B=A4=EB=A5=B8=20=EC=9A=B4=EC=98=81?= =?UTF-8?q?=EC=9E=90=EA=B0=80=20=EB=A8=BC=EC=A0=80=20=EC=A0=80=EC=9E=A5?= =?UTF-8?q?=ED=95=9C=20=EA=B0=80=EC=9D=B4=EB=93=9C=EB=8A=94=20=EB=8D=AE?= =?UTF-8?q?=EC=96=B4=EC=93=B0=EA=B8=B0=20=EC=A0=84=EC=97=90=20=ED=99=95?= =?UTF-8?q?=EC=9D=B8=ED=95=A8=20(#57)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 저장할 때 고치기 시작한 가이드의 저장 시각(baseSavedAt)을 보내고, 409면 최신 가이드를 불러와 확인창을 띄운다. 가이드는 관리자용 조회 API에서 불러온다. --- src/features/guides/api.test.ts | 24 ++++-- src/features/guides/api.ts | 23 ++++-- .../guides/components/GuidesManager.tsx | 78 +++++++++++++++--- .../guides/components/SaveConflictDialog.tsx | 35 ++++++++ src/features/guides/conflict.test.ts | 82 +++++++++++++++++++ src/features/guides/data.ts | 15 ++++ src/features/guides/queries.ts | 26 ++++-- 7 files changed, 249 insertions(+), 34 deletions(-) create mode 100644 src/features/guides/components/SaveConflictDialog.tsx create mode 100644 src/features/guides/conflict.test.ts diff --git a/src/features/guides/api.test.ts b/src/features/guides/api.test.ts index 53f5200..edbe027 100644 --- a/src/features/guides/api.test.ts +++ b/src/features/guides/api.test.ts @@ -1,10 +1,12 @@ import { expect, test } from "vitest"; import { sent, setServer } from "@/test/fakeServer"; import { fetchGuides, saveGuide } from "./api"; +import { formatSavedAt } from "./data"; const leopard = { speciesId: 1, name: "레오파드 게코", + savedAt: "2026-10-21T05:02:00Z", sections: [ { key: "HABIT", title: "습성", body: "야행성", updatedAt: "2026-10-18" }, { key: "FEED", title: "먹이", body: "귀뚜라미", updatedAt: "2026-10-21" }, @@ -15,8 +17,8 @@ test("종마다 가이드를 불러와 칸을 채우고 가장 최근 수정 날 setServer(({ url }) => { if (url === "/admin/species") return [200, { data: { species: [{ id: 1 }, { id: 2 }] } }]; - if (url === "/species/1/guide") return [200, { data: leopard }]; - if (url === "/species/2/guide") + if (url === "/admin/species/1/guide") return [200, { data: leopard }]; + if (url === "/admin/species/2/guide") return [200, { data: { speciesId: 2, name: "볼 파이톤", sections: [] } }]; return [404, {}]; }); @@ -27,6 +29,7 @@ test("종마다 가이드를 불러와 칸을 채우고 가장 최근 수정 날 name: "레오파드 게코", content: { 습성: "야행성", 먹이: "귀뚜라미", 환경: "", 건강: "" }, updatedAt: "2026.10.21", + savedAt: "2026-10-21T05:02:00Z", }, { id: 2, @@ -40,16 +43,16 @@ test("종마다 가이드를 불러와 칸을 채우고 가장 최근 수정 날 test("저장할 때 빈 칸은 빼고 서버 섹션 키로 보낸다", async () => { setServer(() => [200, { data: leopard }]); - const saved = await saveGuide(1, { - 습성: "야행성", - 먹이: "귀뚜라미", - 환경: " ", - 건강: "", - }); + const saved = await saveGuide( + 1, + { 습성: "야행성", 먹이: "귀뚜라미", 환경: " ", 건강: "" }, + "2026-10-20T00:00:00Z", + ); const [request] = sent("/admin/species/1/guide"); expect(request.method).toBe("put"); expect(JSON.parse(request.data)).toEqual({ + baseSavedAt: "2026-10-20T00:00:00Z", sections: [ { key: "HABIT", body: "야행성" }, { key: "FEED", body: "귀뚜라미" }, @@ -57,3 +60,8 @@ test("저장할 때 빈 칸은 빼고 서버 섹션 키로 보낸다", async () }); expect(saved.updatedAt).toBe("2026.10.21"); }); + +test("저장 시각은 한국 시각으로 보여 준다", () => { + expect(formatSavedAt("2026-10-21T05:02:00Z")).toBe("10월 21일 14:02"); + expect(formatSavedAt("2026-10-20T15:00:00Z")).toBe("10월 21일 00:00"); +}); diff --git a/src/features/guides/api.ts b/src/features/guides/api.ts index edf8763..ffe74da 100644 --- a/src/features/guides/api.ts +++ b/src/features/guides/api.ts @@ -5,6 +5,7 @@ type GuideResponse = { speciesId: number; name: string; sections: { key: string; body: string; updatedAt: string }[]; + savedAt?: string | null; }; // 서버 섹션 키. 읽을 때와 저장할 때 모두 이 표로 칸을 찾는다 @@ -24,6 +25,7 @@ function toGuide({ speciesId, name, sections: guideSections, + savedAt, }: GuideResponse): Guide { const content = Object.fromEntries(sections.map((s) => [s, ""])) as Content; for (const { key, body } of guideSections) { @@ -40,24 +42,33 @@ function toGuide({ name, content, updatedAt: latest?.replaceAll("-", "."), + savedAt, }; } +// 편집용 조회라 저장 시각(savedAt)이 함께 온다 +export async function fetchGuide(id: number) { + return toGuide(await getData(`/admin/species/${id}/guide`)); +} + // shortcut: 목록에 수정 날짜가 없어 종마다 가이드를 따로 불러온다, 종이 많아지면 서버에 목록용 API 요청 // 숨긴 종도 이미 등록된 개체가 있으면 가이드가 보이므로 관리자 목록으로 숨긴 종까지 불러온다 export async function fetchGuides() { const { species } = await getData<{ species: { id: number }[] }>( "/admin/species", ); - const guides = await Promise.all( - species.map(({ id }) => getData(`/species/${id}/guide`)), - ); - return guides.map(toGuide); + return Promise.all(species.map(({ id }) => fetchGuide(id))); } -// 보낸 섹션으로 가이드 전체가 바뀐다. 빈 칸은 보내지 않아 서버에서 지워진다 -export async function saveGuide(id: number, content: Content) { +// 보낸 섹션으로 가이드 전체가 바뀐다. 빈 칸은 보내지 않아 서버에서 지워진다. +// baseSavedAt(고치기 시작한 가이드의 저장 시각) 뒤에 다른 저장이 있었으면 서버가 409를 준다 +export async function saveGuide( + id: number, + content: Content, + baseSavedAt?: string | null, +) { const body = { + baseSavedAt, sections: sections .filter((s) => content[s].trim()) .map((s) => ({ key: sectionKeys[s], body: content[s] })), diff --git a/src/features/guides/components/GuidesManager.tsx b/src/features/guides/components/GuidesManager.tsx index 16a48a6..9047d48 100644 --- a/src/features/guides/components/GuidesManager.tsx +++ b/src/features/guides/components/GuidesManager.tsx @@ -1,14 +1,17 @@ "use client"; +import { isAxiosError } from "axios"; import { useEffect, useState } from "react"; import Button from "@/components/Button"; import Dialog from "@/components/Dialog"; import Toast from "@/components/Toast"; +import { fetchGuide } from "../api"; import { sections, type Content, type Guide, type Section } from "../data"; -import { useGuides, useSaveGuide } from "../queries"; +import { useGuides, useSaveGuide, useSetGuide } from "../queries"; import AppCardPreview from "./AppCardPreview"; import GuideEditor from "./GuideEditor"; import SpeciesList from "./SpeciesList"; +import SaveConflictDialog from "./SaveConflictDialog"; export default function GuidesManager() { const { data } = useGuides(); @@ -16,11 +19,19 @@ export default function GuidesManager() { return data?.length ? : null; } -// 목록은 쿼리 캐시 값을 그대로 쓰고, 고치는 중인 내용만 draft로 따로 둔다 +// 목록은 쿼리 캐시 값을 그대로 쓰고, 고치는 중인 내용만 edit로 따로 둔다. +// savedAt은 고치기 시작한 때의 값이라, 그 뒤에 목록을 다시 불러와도 바뀌지 않는다 function Editor({ guides }: { guides: Guide[] }) { const { mutateAsync, isPending } = useSaveGuide(); const [selectedId, setSelectedId] = useState(guides[0].id); - const [draft, setDraft] = useState(guides[0].content); + const [edit, setEdit] = useState<{ + id: number; + content: Content; + savedAt?: string | null; + }>(); + // 저장이 409로 막혔을 때 서버에 있는 가이드 + const [conflict, setConflict] = useState(); + const setGuide = useSetGuide(); const [pendingId, setPendingId] = useState(); const [toast, setToast] = useState<{ tone: "success" | "error"; @@ -34,23 +45,53 @@ function Editor({ guides }: { guides: Guide[] }) { }, [toast]); const guide = guides.find((g) => g.id === selectedId)!; + const draft = edit?.content ?? guide.content; const dirty = sections.some((s) => draft[s] !== guide.content[s]); function select(id: number) { setSelectedId(id); - setDraft(guides.find((g) => g.id === id)!.content); + setEdit(undefined); + setConflict(undefined); setPendingId(undefined); } - async function save() { + function change(section: Section, value: string) { + setEdit((e) => ({ + id: selectedId, + savedAt: e ? e.savedAt : guide.savedAt, + content: { ...(e?.content ?? guide.content), [section]: value }, + })); + } + + async function save(baseSavedAt = edit?.savedAt) { // 저장 중에 다시 누르면 요청이 두 번 가지 않게 막는다 if (isPending) return; + setConflict(undefined); // 수정 날짜와 내용은 서버가 저장한 값으로 맞춘다 (useSaveGuide가 캐시를 바꾼다) try { - await mutateAsync({ id: selectedId, content: draft }); + const saved = await mutateAsync({ + id: selectedId, + content: draft, + baseSavedAt, + }); + // 저장하는 동안 더 고친 내용은 남기고, 방금 저장한 가이드를 기준으로 삼는다 + setEdit((e) => { + if (e?.id !== saved.id) return e; + return sections.some((s) => e.content[s] !== draft[s]) + ? { ...e, savedAt: saved.savedAt } + : undefined; + }); setToast({ tone: "success", text: `${guide.name} 가이드를 저장했어요` }); - } catch { - // draft는 건드리지 않아 고친 내용이 그대로 남는다 + } catch (error) { + if (isAxiosError(error) && error.response?.status === 409) { + try { + setConflict(await fetchGuide(selectedId)); + return; + } catch { + // 최신 가이드를 못 불러오면 아래 저장 실패 안내를 보여 준다 + } + } + // edit는 건드리지 않아 고친 내용이 그대로 남는다 setToast({ tone: "error", text: "저장하지 못했어요 · 고친 내용은 그대로예요", @@ -58,6 +99,12 @@ function Editor({ guides }: { guides: Guide[] }) { } } + function loadLatest(latest: Guide) { + setGuide(latest); + setEdit(undefined); + setConflict(undefined); + } + const pending = guides.find((g) => g.id === pendingId); return ( @@ -74,11 +121,9 @@ function Editor({ guides }: { guides: Guide[] }) { content={draft} status={dirty ? "dirty" : guide.updatedAt ? "saved" : "empty"} updatedAt={guide.updatedAt} - onChange={(section: Section, value) => - setDraft((d) => ({ ...d, [section]: value })) - } - onRevert={() => setDraft(guide.content)} - onSave={save} + onChange={change} + onRevert={() => setEdit(undefined)} + onSave={() => save()} /> {pending && ( @@ -100,6 +145,13 @@ function Editor({ guides }: { guides: Guide[] }) { )} + {conflict?.id === selectedId && ( + loadLatest(conflict)} + onOverwrite={() => save(conflict.savedAt)} + /> + )} {toast && ( {toast.text} diff --git a/src/features/guides/components/SaveConflictDialog.tsx b/src/features/guides/components/SaveConflictDialog.tsx new file mode 100644 index 0000000..d57ca8e --- /dev/null +++ b/src/features/guides/components/SaveConflictDialog.tsx @@ -0,0 +1,35 @@ +import Button from "@/components/Button"; +import Dialog from "@/components/Dialog"; +import { formatSavedAt, type Guide } from "../data"; + +// Figma W-4h 다른 운영자가 먼저 저장 +export default function SaveConflictDialog({ + latest, + onLoad, + onOverwrite, +}: { + latest: Guide; + onLoad: () => void; + onOverwrite: () => void; +}) { + return ( + + {latest.savedAt && `${formatSavedAt(latest.savedAt)}에 `}다른 운영자가{" "} + {latest.name} 가이드를 저장했어요. +
+ 지금 저장하면 그 내용을 덮어써요. + + } + > + + +
+ ); +} diff --git a/src/features/guides/conflict.test.ts b/src/features/guides/conflict.test.ts new file mode 100644 index 0000000..997d5ab --- /dev/null +++ b/src/features/guides/conflict.test.ts @@ -0,0 +1,82 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { act, createElement } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, test, vi } from "vitest"; +import { sent, setServer } from "@/test/fakeServer"; +import GuidesManager from "./components/GuidesManager"; + +const guide = (savedAt: string, body: string) => ({ + speciesId: 1, + name: "레오파드 게코", + savedAt, + sections: [{ key: "HABIT", body, updatedAt: "2026-10-21" }], +}); +const before = "2026-10-20T01:00:00Z"; +const after = "2026-10-21T05:02:00Z"; + +test("다른 운영자가 먼저 저장했으면 확인창에서 불러오거나 덮어쓴다", async () => { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + let server = guide(before, "처음"); + setServer(({ url, method, data }) => { + if (url === "/admin/species") + return [200, { data: { species: [{ id: 1 }] } }]; + if (method !== "put") return [200, { data: server }]; + const request = JSON.parse(data); + if (request.baseSavedAt !== server.savedAt) return [409, {}]; + server = guide("2026-10-22T00:00:00Z", request.sections[0].body); + return [200, { data: server }]; + }); + + const root = document.body.appendChild(document.createElement("div")); + await act(async () => + createRoot(root).render( + createElement( + QueryClientProvider, + { client: new QueryClient() }, + createElement(GuidesManager), + ), + ), + ); + const habit = () => root.querySelector("textarea")!; + const click = (label: string) => + act(async () => + [...root.querySelectorAll("button")] + .find((b) => b.textContent === label)! + .click(), + ); + // React가 입력을 알아채도록 원래 value setter로 넣는다 + const type = (value: string) => + act(async () => { + Object.getOwnPropertyDescriptor( + HTMLTextAreaElement.prototype, + "value", + )!.set!.call(habit(), value); + habit().dispatchEvent(new Event("input", { bubbles: true })); + }); + const dialog = () => root.querySelector('[role="dialog"]'); + await vi.waitFor(() => expect(habit()).not.toBeNull()); + + await type("내 내용"); + server = guide(after, "남의 내용"); + await click("저장"); + await vi.waitFor(() => expect(dialog()).not.toBeNull()); + expect(dialog()!.textContent).toContain( + "10월 21일 14:02에 다른 운영자가 레오파드 게코 가이드를 저장했어요.", + ); + + await click("최신 내용 불러오기"); + expect(dialog()).toBeNull(); + expect(habit().value).toBe("남의 내용"); + + await type("다시 고침"); + server = guide("2026-10-21T06:00:00Z", "또 남의 내용"); + await click("저장"); + await vi.waitFor(() => expect(dialog()).not.toBeNull()); + await click("내 내용으로 덮어쓰기"); + await vi.waitFor(() => expect(server.sections[0].body).toBe("다시 고침")); + expect(dialog()).toBeNull(); + expect(habit().value).toBe("다시 고침"); + expect( + sent("/admin/species/1/guide").filter((r) => r.method === "put"), + ).toHaveLength(3); +}); diff --git a/src/features/guides/data.ts b/src/features/guides/data.ts index c64d752..7f6c08c 100644 --- a/src/features/guides/data.ts +++ b/src/features/guides/data.ts @@ -9,4 +9,19 @@ export type Guide = { content: Content; // 작성 전이면 없다. "2026.10.20" 형식 updatedAt?: string; + // 서버가 마지막으로 저장한 시각(ISO). 저장할 때 보내 그 사이 다른 저장이 있었는지 확인한다 + savedAt?: string | null; }; + +const savedAtFormat = new Intl.DateTimeFormat("ko-KR", { + timeZone: "Asia/Seoul", + month: "long", + day: "numeric", + hour: "2-digit", + minute: "2-digit", + hourCycle: "h23", +}); + +// "2026-10-21T05:02:00Z" → "10월 21일 14:02" (한국 시각) +export const formatSavedAt = (savedAt: string) => + savedAtFormat.format(new Date(savedAt)); diff --git a/src/features/guides/queries.ts b/src/features/guides/queries.ts index edfba78..1fcf60e 100644 --- a/src/features/guides/queries.ts +++ b/src/features/guides/queries.ts @@ -13,15 +13,27 @@ export const useGuides = () => staleTime: 5 * 60 * 1000, }); +// 서버에서 받은 가이드 하나를 목록 캐시에 넣는다 +export function useSetGuide() { + const queryClient = useQueryClient(); + return (guide: Guide) => + queryClient.setQueryData(["guides"], (list) => + list?.map((g) => (g.id === guide.id ? guide : g)), + ); +} + // 저장한 가이드를 목록 캐시에도 넣어, 다른 화면에 갔다 와도 저장한 내용이 보이게 한다 export function useSaveGuide() { - const queryClient = useQueryClient(); return useMutation({ - mutationFn: ({ id, content }: { id: number; content: Content }) => - saveGuide(id, content), - onSuccess: (saved) => - queryClient.setQueryData(["guides"], (list) => - list?.map((g) => (g.id === saved.id ? saved : g)), - ), + mutationFn: ({ + id, + content, + baseSavedAt, + }: { + id: number; + content: Content; + baseSavedAt?: string | null; + }) => saveGuide(id, content, baseSavedAt), + onSuccess: useSetGuide(), }); }