diff --git a/src/_storybook/features/grammar-example-generation/GrammarExampleManager.stories.tsx b/src/_storybook/features/grammar-example-generation/GrammarExampleManager.stories.tsx index c23634cb..d9524f6d 100644 --- a/src/_storybook/features/grammar-example-generation/GrammarExampleManager.stories.tsx +++ b/src/_storybook/features/grammar-example-generation/GrammarExampleManager.stories.tsx @@ -6,7 +6,9 @@ import { } from "@/features/grammar-example-generation"; import { createEditorNote } from "@/_tests/features/grammar-note-editor/fixtures"; import { createExampleCandidates } from "@/_tests/features/grammar-example-generation/fixtures"; + const note = createEditorNote(); + const meta = { title: "features/grammar-example-generation/GrammarExampleManager", component: GrammarExampleManager, @@ -31,12 +33,17 @@ const meta = { ), ], } satisfies Meta; + export default meta; + type Story = StoryObj; + export const Empty: Story = {}; + export const SelectAndSave: Story = { play: async ({ canvasElement, args }) => { const canvas = within(canvasElement); + await userEvent.click(canvas.getByRole("button", { name: "예문 3개 생성" })); await expect(await canvas.findAllByRole("checkbox")).toHaveLength(3); await userEvent.click(canvas.getAllByRole("checkbox")[0]); @@ -45,6 +52,7 @@ export const SelectAndSave: Story = { await expect(canvas.getAllByRole("checkbox")).toHaveLength(2); }, }; + export const Retry: Story = { args: { generate: fn(async () => ({ @@ -52,23 +60,28 @@ export const Retry: Story = { data: createExampleCandidates(), })), }, + play: async ({ canvasElement, args }) => { args.generate.mockResolvedValueOnce({ ok: false, - message: "생성에 실패했습니다. 다시 생성해 주세요.", + code: "FAILED", }); const canvas = within(canvasElement); + await userEvent.click(canvas.getByRole("button", { name: "예문 3개 생성" })); await expect(await canvas.findByRole("alert")).toBeVisible(); await userEvent.click(canvas.getByRole("button", { name: "예문 다시 생성" })); await expect(await canvas.findAllByRole("checkbox")).toHaveLength(3); }, }; + export const EditCandidate: Story = { play: async ({ canvasElement }) => { const canvas = within(canvasElement); + await userEvent.click(canvas.getByRole("button", { name: "예문 3개 생성" })); const input = (await canvas.findAllByLabelText("한국어 뜻"))[0]; + await userEvent.clear(input); await userEvent.type(input, "그는 운전사가 아니라 교사입니다."); await expect(input).toHaveValue("그는 운전사가 아니라 교사입니다."); diff --git a/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx b/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx index 6122136c..3359c02b 100644 --- a/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx +++ b/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx @@ -4,7 +4,9 @@ import type { GrammarNoteEditorProps } from "@/features/grammar-note-editor"; import { GrammarNoteEditor } from "@/features/grammar-note-editor"; import { GrammarAnalysisEditor } from "@/features/grammar-analysis-edit"; import { createEditorNote } from "@/_tests/features/grammar-note-editor/fixtures"; + const note = createEditorNote(); + const meta = { title: "features/grammar-note-editor/GrammarNoteEditor", component: GrammarNoteEditor, @@ -29,36 +31,46 @@ const meta = { ), ], } satisfies Meta; + export default meta; + type Story = StoryObj; + export const EmptyInput: Story = { play: async ({ canvasElement }) => { const canvas = within(canvasElement); + await userEvent.click(canvas.getByRole("button", { name: "문장 분석하기" })); await expect(canvas.getAllByRole("alert")).toHaveLength(2); await expect(canvas.queryByLabelText("제목")).not.toBeInTheDocument(); }, }; + export const ReviewAndSave: Story = { args: { initialNote: note }, + play: async ({ canvasElement, args }) => { const canvas = within(canvasElement); + await expect(canvas.getByRole("button", { name: "검토 완료 · 노트 저장" })).toBeDisabled(); await userEvent.click(canvas.getByRole("checkbox")); await userEvent.click(canvas.getByRole("button", { name: "검토 완료 · 노트 저장" })); await expect(args.onSaved).toHaveBeenCalled(); }, }; + export const SaveFailure: Story = { args: { initialNote: note, save: fn(async () => ({ ok: false as const, - message: "노트를 저장하지 못했습니다. 다시 저장해 주세요.", + code: "PERSISTENCE_FAILED", })), }, + play: async ({ canvasElement }) => { const canvas = within(canvasElement); + await userEvent.click(canvas.getByRole("checkbox")); await userEvent.click(canvas.getByRole("button", { name: "검토 완료 · 노트 저장" })); await expect(await canvas.findByRole("alert")).toBeVisible(); @@ -70,6 +82,7 @@ export const SaveFailure: Story = { export const AnalyzeThenReview: Story = { play: async ({ canvasElement }) => { const canvas = within(canvasElement); + await userEvent.type(canvas.getByLabelText(/영어 문장/), note.source.sentence); await userEvent.type(canvas.getByLabelText(/핵심 어법 설명/), note.source.learningNote); await userEvent.click(canvas.getByRole("button", { name: "문장 분석하기" })); @@ -78,10 +91,13 @@ export const AnalyzeThenReview: Story = { await expect(canvas.getByLabelText(/영어 문장/)).toHaveValue(note.source.sentence); }, }; + export const UnappliedAnalysisBlocksSave: Story = { args: { initialNote: note }, + play: async ({ canvasElement }) => { const canvas = within(canvasElement); + await userEvent.click(canvas.getByRole("button", { name: "She" })); await userEvent.click(canvas.getByRole("button", { name: "분석 수정" })); await userEvent.type(canvas.getByLabelText("직독직해"), " 수정"); diff --git a/src/_storybook/views/grammar-library/GrammarNoteList.stories.tsx b/src/_storybook/views/grammar-library/GrammarNoteList.stories.tsx new file mode 100644 index 00000000..c013cd94 --- /dev/null +++ b/src/_storybook/views/grammar-library/GrammarNoteList.stories.tsx @@ -0,0 +1,57 @@ +import type { Meta, StoryObj } from "@storybook/nextjs-vite"; +import { expect, within } from "storybook/test"; +import { GrammarNoteList } from "@/views/grammar-library"; + +const meta = { + title: "Views/Grammar/Note list", + component: GrammarNoteList, + args: { query: "", data: { items: [], total: 0, page: 1, pageSize: 20 } }, +} satisfies Meta; + +export default meta; + +type Story = StoryObj; + +export const Empty: Story = { + play: async ({ canvasElement }) => { + await expect(within(canvasElement).getByText("첫 어법 노트를 만들어보세요")).toBeVisible(); + }, +}; + +export const SearchEmpty: Story = { args: { query: "unknown" } }; + +export const Notes: Story = { + args: { + query: "not", + data: { + page: 2, + pageSize: 20, + total: 42, + items: [ + { + id: "00000000-0000-4000-8000-000000000001", + ownerId: "00000000-0000-4000-8000-000000000002", + title: "not A but B", + sentence: "She is not a teacher but a doctor.", + tags: ["대조", "보어"], + version: 1, + createdAt: "2026-10-01T00:00:00Z", + updatedAt: "2026-10-01T00:00:00Z", + }, + ], + }, + }, + + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + + await expect(canvas.getByRole("link", { name: /not A but B/ })).toHaveAttribute( + "href", + expect.stringContaining("returnTo=%2Fgrammar%3Fq%3Dnot%26page%3D2"), + ); + await expect(canvas.getByRole("link", { name: "2페이지" })).toHaveAttribute( + "aria-current", + "page", + ); + }, +}; diff --git a/src/_tests/features/grammar-analysis-edit/GrammarAnalysisEditor.test.tsx b/src/_tests/features/grammar-analysis-edit/GrammarAnalysisEditor.test.tsx index 721257e8..d67fbb3a 100644 --- a/src/_tests/features/grammar-analysis-edit/GrammarAnalysisEditor.test.tsx +++ b/src/_tests/features/grammar-analysis-edit/GrammarAnalysisEditor.test.tsx @@ -8,6 +8,7 @@ describe("grammar analysis review below the sentence", () => { it("selects a chunk and edits its explanation without losing the source", async () => { const user = userEvent.setup(); const onChange = jest.fn(); + render(); await user.click(screen.getByRole("button", { name: "She" })); await user.click(screen.getByRole("button", { name: "분석 수정" })); @@ -22,9 +23,11 @@ describe("grammar analysis review below the sentence", () => { }), ); }); + it("keeps an invalid hierarchy draft visible with a recoverable error", async () => { const user = userEvent.setup(); const onChange = jest.fn(); + render(); await user.click(screen.getByRole("button", { name: "분석 수정" })); await user.click(screen.getByRole("button", { name: "절" })); @@ -41,6 +44,7 @@ describe("grammar analysis review below the sentence", () => { it("asks before leaving an unapplied edit and preserves input when continuing", async () => { const user = userEvent.setup(); + render(); await user.click(screen.getByRole("button", { name: "She" })); await user.click(screen.getByRole("button", { name: "분석 수정" })); @@ -57,6 +61,7 @@ it("asks before leaving an unapplied edit and preserves input when continuing", it("shows AI chunks for reading and keeps correction controls behind edit mode", async () => { const user = userEvent.setup(); const onChange = jest.fn(); + render(); expect(screen.queryByRole("button", { name: "절" })).not.toBeInTheDocument(); await user.click(screen.getByRole("button", { name: "She" })); @@ -72,6 +77,7 @@ it("shows AI chunks for reading and keeps correction controls behind edit mode", it("guards returning to reading and restores the selected chunk after discarding edits", async () => { const user = userEvent.setup(); const onChange = jest.fn(); + render(); await user.click(screen.getByRole("button", { name: "She" })); await user.click(screen.getByRole("button", { name: "분석 수정" })); @@ -92,6 +98,7 @@ it("isolates selection and edits between mounted editors", async () => { const user = userEvent.setup(); const firstChange = jest.fn(); const secondChange = jest.fn(); + render( <>
@@ -104,6 +111,7 @@ it("isolates selection and edits between mounted editors", async () => { ); const first = within(screen.getByRole("region", { name: "첫 번째 노트" })); const second = within(screen.getByRole("region", { name: "두 번째 노트" })); + await user.click(first.getByRole("button", { name: "She" })); expect(second.getByRole("button", { name: "She" })).toHaveAttribute("aria-pressed", "false"); await user.click(first.getByRole("button", { name: "분석 수정" })); @@ -118,16 +126,32 @@ it("preserves drafts on parent rerender and notifies the current callback", asyn const user = userEvent.setup(); const original = jest.fn(); const current = jest.fn(); + const originalDirty = jest.fn(); + const currentDirty = jest.fn(); const { rerender } = render( - , + , ); + await user.click(screen.getByRole("button", { name: "분석 수정" })); await user.type(screen.getByLabelText("직독직해"), " 수정"); - rerender(); + expect(originalDirty.mock.calls).toEqual([[true]]); + rerender( + , + ); expect(screen.getByLabelText("직독직해")).toHaveValue("그녀는 수정"); await user.click(screen.getByRole("button", { name: "풀이 적용" })); expect(original).not.toHaveBeenCalled(); expect(current).toHaveBeenCalledTimes(1); + expect(originalDirty.mock.calls).toEqual([[true]]); + expect(currentDirty.mock.calls).toEqual([[false]]); }); it("starts a fresh editor when the document key changes", async () => { @@ -140,9 +164,11 @@ it("starts a fresh editor when the document key changes", async () => { onChange={onChange} />, ); + await user.click(screen.getByRole("button", { name: "분석 수정" })); await user.type(screen.getByLabelText("직독직해"), " 수정"); const next = createGrammarAnalysis(); + rerender( { it("keeps the editor draft when Escape dismisses the confirmation dialog", async () => { const user = userEvent.setup(); + render(); await user.click(screen.getByRole("button", { name: "분석 수정" })); await user.type(screen.getByLabelText("직독직해"), " 수정"); @@ -174,9 +201,11 @@ it("keeps the editor draft when Escape dismisses the confirmation dialog", async it("applies current text with a boundary edit and keeps input after validation failure", async () => { const user = userEvent.setup(); const onChange = jest.fn(); + render(); await user.click(screen.getByRole("button", { name: "분석 수정" })); const input = screen.getByLabelText("직독직해"); + // 도메인 길이 제한을 넘는 입력에도 다른 편집 후보를 반영하지 않는다. fireEvent.change(input, { target: { value: "x".repeat(4001) } }); await user.selectOptions(screen.getByLabelText("다음 구간과의 경계"), "3"); diff --git a/src/_tests/features/grammar-analysis-edit/editAnalysis.test.ts b/src/_tests/features/grammar-analysis-edit/editAnalysis.test.ts index 658ee212..4feb8015 100644 --- a/src/_tests/features/grammar-analysis-edit/editAnalysis.test.ts +++ b/src/_tests/features/grammar-analysis-edit/editAnalysis.test.ts @@ -8,44 +8,62 @@ describe("analysis edits", () => { it("moves adjacent boundaries together without changing source and requires review", () => { const source = createGrammarAnalysis(); const result = new EditAnalysisService(source).moveBoundary("c1", 3); + expect(result.ok).toBe(true); + if (!result.ok) throw new Error(result.message); + expect(result.analysis.chunks[0].range.end).toBe(3); expect(result.analysis.chunks[1].range.start).toBe(3); expect(result.analysis.sourceText).toBe(source.sourceText); expect(result.analysis.reviewStatus).toBe("needs-review"); expect(source.chunks[0].range.end).toBe(4); }); + it.each([-1, 0, 7, 100, NaN])("rejects an invalid boundary %s atomically", (end) => { const source = createGrammarAnalysis(); const before = JSON.stringify(source); + expect(new EditAnalysisService(source).moveBoundary("c1", end).ok).toBe(false); expect(JSON.stringify(source)).toBe(before); }); + it("splits and merges meaning chunks while preserving exact text coverage", () => { const source = createGrammarAnalysis(); const split = new EditAnalysisService(source).splitChunk("c3", 21, "c4"); + if (!split.ok) throw new Error(split.message); + expect(split.analysis.chunks).toHaveLength(4); const merged = new EditAnalysisService(split.analysis).mergeNext("c3"); + if (!merged.ok) throw new Error(merged.message); + expect(merged.analysis.chunks.map((c) => c.range)).toEqual(source.chunks.map((c) => c.range)); }); + it("rejects unknown targets and duplicate IDs", () => { const a = createGrammarAnalysis(); + expect(new EditAnalysisService(a).mergeNext("missing").ok).toBe(false); expect(new EditAnalysisService(a).splitChunk("c3", 21, "s").ok).toBe(false); }); + it("allows reparenting a child to root and rejects deleting its parent while attached", () => { const a = createGrammarAnalysis(); + expect(new EditAnalysisService(a).deleteSyntax("clause").ok).toBe(false); const result = new EditAnalysisService(a).saveSyntax({ ...a.syntax[1], parentId: null }); + expect(result.ok).toBe(true); }); + it("rejects reparenting into a descendant", () => { const a = createGrammarAnalysis(); + expect(new EditAnalysisService(a).saveSyntax({ ...a.syntax[0], parentId: "s" }).ok).toBe(false); }); + it("supports discontinuous construction boundary edits", () => { const a = createGrammarAnalysis(); const result = new EditAnalysisService(a).saveConstruction({ @@ -55,12 +73,15 @@ describe("analysis edits", () => { { start: 21, end: 33 }, ], }); + expect(result.ok).toBe(true); }); + it("does not notify document consumers when only selection changes or an edit fails", () => { const onChange = jest.fn(); const store = createAnalysisEditorStore({ initialAnalysis: createGrammarAnalysis(), onChange }); const original = store.getState().analysis; + store.getState().select("c1"); store.getState().edit((service) => service.moveBoundary("c1", -1)); expect(store.getState().analysis).toBe(original); @@ -78,6 +99,7 @@ it("applies text and structural edits together or preserves both on failure", () (service) => service.editChunk("c1", { literalMeaning: "수정한 뜻", explanation: "" }), (service) => service.moveBoundary("c1", -1), ]); + expect(result.ok).toBe(false); expect(store.getState().analysis).toBe(before); expect(onChange).not.toHaveBeenCalled(); @@ -86,6 +108,7 @@ it("applies text and structural edits together or preserves both on failure", () it("commits a successful batch once, preserving the first edit in the next candidate", () => { const onChange = jest.fn(); const store = createAnalysisEditorStore({ initialAnalysis: createGrammarAnalysis(), onChange }); + store.getState().select("c1"); store.getState().startEditing(); store.getState().markDirty(); @@ -95,6 +118,7 @@ it("commits a successful batch once, preserving the first edit in the next candi (service) => service.editChunk("c1", { literalMeaning: "수정한 뜻", explanation: "설명" }), (service) => service.moveBoundary("c1", 3), ]); + expect(result.ok).toBe(true); expect(store.getState().analysis.chunks[0]).toMatchObject({ literalMeaning: "수정한 뜻", @@ -109,6 +133,7 @@ it("commits a successful batch once, preserving the first edit in the next candi it("keeps dirty input and selection and skips later operations when a batch fails", () => { const onChange = jest.fn(); const store = createAnalysisEditorStore({ initialAnalysis: createGrammarAnalysis(), onChange }); + store.getState().select("c1"); store.getState().startEditing(); store.getState().markDirty(); @@ -121,6 +146,7 @@ it("keeps dirty input and selection and skips later operations when a batch fail (service) => service.moveBoundary("c1", -1), later, ]); + expect(result.ok).toBe(false); expect(store.getState()).toMatchObject({ selectedId: "c1", dirty: true, editing: true }); expect(store.getState().analysis).toBe(before); @@ -133,25 +159,35 @@ it("adds, updates and deletes annotations without changing the input snapshot", const before = JSON.stringify(source); const service = new EditAnalysisService(source); const added = service.saveSyntax({ ...source.syntax[1], id: "new-subject" }); + if (!added.ok) throw new Error(added.message); + expect(added.analysis.syntax).toHaveLength(source.syntax.length + 1); const deleted = new EditAnalysisService(added.analysis).deleteSyntax("new-subject"); + if (!deleted.ok) throw new Error(deleted.message); + expect(deleted.analysis.syntax).toEqual(source.syntax); const construction = service.saveConstruction({ ...source.constructions[0], id: "new-contrast" }); + if (!construction.ok) throw new Error(construction.message); + const updated = new EditAnalysisService(construction.analysis).saveConstruction({ ...source.constructions[0], id: "new-contrast", meaning: "수정된 뜻", }); + if (!updated.ok) throw new Error(updated.message); + expect(updated.analysis.constructions).toHaveLength(source.constructions.length + 1); expect(updated.analysis.constructions.find((item) => item.id === "new-contrast")?.meaning).toBe( "수정된 뜻", ); const removed = new EditAnalysisService(updated.analysis).deleteConstruction("new-contrast"); + if (!removed.ok) throw new Error(removed.message); + expect(removed.analysis.constructions).toEqual(source.constructions); expect(JSON.stringify(source)).toBe(before); }); @@ -172,7 +208,9 @@ it("validates every edit method and rejects unknown targets without changing the (s) => s.deleteConstruction("missing"), (s) => s.saveConstruction({ ...source.constructions[0], id: source.chunks[0].id }), ]; + for (const operation of invalid) expect(operation(service).ok).toBe(false); + expect(JSON.stringify(source)).toBe(before); }); @@ -182,7 +220,9 @@ it("updates only explanation fields even when the supplied object contains chunk ...source.chunks[1], literalMeaning: "수정한 뜻", }); + if (!result.ok) throw new Error(result.message); + expect(result.analysis.chunks[0]).toMatchObject({ id: "c1", range: source.chunks[0].range, @@ -190,3 +230,40 @@ it("updates only explanation fields even when the supplied object contains chunk }); expect(result.analysis.sourceText).toBe(source.sourceText); }); + +it("notifies dirty changes within editing events and keeps failed/discard-cancelled drafts dirty", () => { + const onDirtyChange = jest.fn(); + const store = createAnalysisEditorStore({ + initialAnalysis: createGrammarAnalysis(), + onChange: jest.fn(), + onDirtyChange, + }); + + store.getState().markDirty(); + expect(onDirtyChange).not.toHaveBeenCalled(); + store.getState().startEditing(); + store.getState().markDirty(); + store.getState().markDirty(); + expect(onDirtyChange.mock.calls).toEqual([[true]]); + const failed = store.getState().edit((service) => + service.saveSyntax({ + id: "s", + ranges: [{ start: 0, end: 1 }], + parentId: "s", + role: "other", + label: "invalid", + explanation: "", + }), + ); + + expect(failed.ok).toBe(false); + expect(store.getState().dirty).toBe(true); + store.getState().finishEditing(); + store.getState().resolveSelection(false); + expect(store.getState().dirty).toBe(true); + expect(onDirtyChange.mock.calls).toEqual([[true]]); + store.getState().finishEditing(); + store.getState().resolveSelection(true); + expect(store.getState().dirty).toBe(false); + expect(onDirtyChange.mock.calls).toEqual([[true], [false]]); +}); diff --git a/src/_tests/features/grammar-example-generation/GrammarExampleManager.test.tsx b/src/_tests/features/grammar-example-generation/GrammarExampleManager.test.tsx new file mode 100644 index 00000000..af759e9f --- /dev/null +++ b/src/_tests/features/grammar-example-generation/GrammarExampleManager.test.tsx @@ -0,0 +1,40 @@ +import { describe, expect, it, jest } from "@jest/globals"; +import { fireEvent, render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { + GrammarExampleManager, + type GrammarExampleManagerProps, +} from "@/features/grammar-example-generation"; +import { createEditorNote } from "../grammar-note-editor/fixtures"; +import { createExampleCandidates } from "./fixtures"; + +describe("예문 편집 세션", () => { + it("같은 노트의 버전 갱신에는 초안을 유지하고 최신 콜백을 쓰며 다른 노트에는 초기화한다", async () => { + const note = createEditorNote(); + const generate = jest + .fn() + .mockResolvedValue({ ok: true, data: createExampleCandidates() }); + const save = jest.fn(); + const latestSave = jest + .fn() + .mockResolvedValue({ ok: false, code: "VERSION_CONFLICT" }); + const props = { note, generate, save, onUpdated: jest.fn() }; + const { rerender } = render(); + const user = userEvent.setup(); + + await user.click(screen.getByRole("button", { name: "예문 3개 생성" })); + fireEvent.change((await screen.findAllByLabelText("영어 예문"))[0], { + target: { value: "Edited sentence." }, + }); + await user.click(screen.getAllByRole("checkbox")[0]); + rerender(); + expect(screen.getAllByLabelText("영어 예문")[0]).toHaveValue("Edited sentence."); + await user.click(screen.getByRole("button", { name: "선택한 예문 1개 저장" })); + expect(save).not.toHaveBeenCalled(); + expect(latestSave).toHaveBeenCalledWith(expect.objectContaining({ expectedVersion: 1 })); + expect(await screen.findByRole("alert")).toHaveTextContent("노트가 변경되었습니다"); + expect(screen.getAllByRole("checkbox")[0]).toBeChecked(); + rerender(); + expect(screen.queryByLabelText("영어 예문")).not.toBeInTheDocument(); + }); +}); diff --git a/src/_tests/features/grammar-example-generation/createExampleStore.test.ts b/src/_tests/features/grammar-example-generation/createExampleStore.test.ts index 0be40034..239a2354 100644 --- a/src/_tests/features/grammar-example-generation/createExampleStore.test.ts +++ b/src/_tests/features/grammar-example-generation/createExampleStore.test.ts @@ -3,6 +3,7 @@ import { createExampleStore } from "@/features/grammar-example-generation/servic import type { GrammarExampleManagerProps } from "@/features/grammar-example-generation"; import { createEditorNote } from "../grammar-note-editor/fixtures"; import { createExampleCandidates } from "./fixtures"; + function setup() { const note = createEditorNote(); const dependencies = { @@ -16,24 +17,30 @@ function setup() { onUpdated: jest.fn(), }; const store = createExampleStore(dependencies); + return { store, ...dependencies }; } + describe("예문 초안 이벤트", () => { it("재생성 실패시 기존 예문 수정과 선택을 보존한다", async () => { const { store, generate } = setup(); + await store.getState().generate(); store.getState().change("candidate-0", "sentence", "Edited sentence"); store.getState().select("candidate-0", true); - generate.mockResolvedValue({ ok: false, message: "실패" }); + generate.mockResolvedValue({ ok: false, code: "FAILED" }); await store.getState().generate("candidate-1"); expect(store.getState().candidates[0].sentence).toBe("Edited sentence"); expect(store.getState().selected).toEqual(["candidate-0"]); - expect(store.getState().error).toBe("실패"); + expect(store.getState().error).toBe("FAILED"); }); + it("부분 재생성은 다른 수정본을 건드리지 않는다", async () => { const { store, generate } = setup(); + await store.getState().generate(); const preserved = store.getState().candidates[0]; + generate.mockResolvedValue({ ok: true, data: [{ ...createExampleCandidates()[1], id: "replacement" }], @@ -42,10 +49,13 @@ describe("예문 초안 이벤트", () => { expect(store.getState().candidates[0]).toBe(preserved); expect(store.getState().candidates[1].id).toBe("replacement"); }); + it("진행중 후보 수정 이후 늦게 도착한 생성 결과를 무시한다", async () => { const { store, generate } = setup(); + await store.getState().generate(); let resolve!: (value: Awaited>) => void; + generate.mockImplementation( () => new Promise((r) => { @@ -53,14 +63,17 @@ describe("예문 초안 이벤트", () => { }), ); const pending = store.getState().generate("candidate-0"); + store.getState().change("candidate-0", "translation", "수정한 뜻"); resolve({ ok: true, data: [{ ...createExampleCandidates()[0], id: "old-response" }] }); await pending; expect(store.getState().candidates[0].translation).toBe("수정한 뜻"); }); + it("돌아간 뒤 늦게 도착한 생성 결과를 표시하지 않는다", async () => { const { store, generate } = setup(); let resolve!: (value: Awaited>) => void; + generate.mockImplementation( () => new Promise((r) => { @@ -68,13 +81,16 @@ describe("예문 초안 이벤트", () => { }), ); const pending = store.getState().generate(); + store.getState().discard(); resolve({ ok: true, data: createExampleCandidates() }); await pending; expect(store.getState().candidates).toEqual([]); }); + it("검토한 선택 예문만 저장하고 선택하지 않은 후보는 유지한다", async () => { const { store, save } = setup(); + await store.getState().generate(); store.getState().select("candidate-1", true); await store.getState().save(); @@ -82,8 +98,10 @@ describe("예문 초안 이벤트", () => { expect(store.getState().candidates.map((c) => c.id)).toEqual(["candidate-0", "candidate-2"]); expect(store.getState().note.version).toBe(2); }); + it("저장 네트워크 실패시 선택된 수정 후보를 유지한다", async () => { const { store, save } = setup(); + await store.getState().generate(); store.getState().select("candidate-0", true); save.mockRejectedValue(new Error("network")); @@ -92,8 +110,10 @@ describe("예문 초안 이벤트", () => { expect(store.getState().candidates).toHaveLength(3); expect(store.getState().pending).toBeNull(); }); + it("필수 후보 내용이 공백이면 저장하지 않는다", async () => { const { store, save } = setup(); + await store.getState().generate(); store.getState().change("candidate-0", "sentence", " "); store.getState().select("candidate-0", true); diff --git a/src/_tests/features/grammar-example-generation/exampleActions.test.ts b/src/_tests/features/grammar-example-generation/exampleActions.test.ts index a1ae9573..be02bf76 100644 --- a/src/_tests/features/grammar-example-generation/exampleActions.test.ts +++ b/src/_tests/features/grammar-example-generation/exampleActions.test.ts @@ -7,28 +7,42 @@ import type { SaveExamplesCommand, } from "@/features/grammar-example-generation"; import type { requestExampleOutput as RequestOutput } from "@/features/grammar-example-generation/services/server/requestExampleOutput"; + let createSupabaseServerClient: typeof CreateClient; + let requestExampleOutput: typeof RequestOutput; + async function requestGrammarExamples(command: GenerateExamplesCommand) { const action = await import("@/features/grammar-example-generation/services/actions/exampleActions"); + return action.requestGrammarExamples(command); } + async function saveGrammarExamples(command: SaveExamplesCommand) { const action = await import("@/features/grammar-example-generation/services/actions/exampleActions"); + return action.saveGrammarExamples(command); } + import { createEditorNote } from "../grammar-note-editor/fixtures"; import { createExampleCandidates } from "./fixtures"; + jest.mock("server-only", () => ({})); + jest.mock("@/shared/lib/supabase/server", () => ({ createSupabaseServerClient: jest.fn() })); + jest.mock("@/shared/lib/logging/pino", () => ({ recordOperationEvent: jest.fn() })); + jest.mock("@/features/grammar-example-generation/services/server/requestExampleOutput", () => ({ requestExampleOutput: jest.fn(), })); + Object.defineProperty(globalThis.crypto, "randomUUID", { value: randomUUID, configurable: true }); + const rpc = jest.fn<() => Promise<{ data: string | null; error: Error | null }>>(); + beforeEach(async () => { ({ createSupabaseServerClient } = await import("@/shared/lib/supabase/server")); ({ requestExampleOutput } = @@ -41,6 +55,7 @@ beforeEach(async () => { rpc, } as never); }); + describe("예문 서버 액션 권한", () => { it("비로그인 생성과 저장은 조회나 유료 호출 전에 차단한다", async () => { jest.mocked(createSupabaseServerClient).mockResolvedValue({ @@ -58,16 +73,18 @@ describe("예문 서버 액션 권한", () => { expectedVersion: 1, candidates: createExampleCandidates(), }); + expect(generation.ok).toBe(false); expect(saving.ok).toBe(false); expect(find).not.toHaveBeenCalled(); expect(requestExampleOutput).not.toHaveBeenCalled(); }); + it.each([ - ["not_invited", "AI 기능을 사용할 권한이 없습니다."], - ["rate_limited", "AI 요청 한도에 도달했습니다. 잠시 후 다시 시도해 주세요."], - ["unexpected", "예문 작업을 완료하지 못했습니다. 기존 내용은 유지됩니다. 다시 시도해 주세요."], - ])("권한 %s이면 AI를 실행하지 않는다", async (permission, message) => { + ["not_invited", "NOT_INVITED"], + ["rate_limited", "RATE_LIMITED"], + ["unexpected", "FAILED"], + ])("권한 %s이면 AI를 실행하지 않는다", async (permission, code) => { jest.spyOn(GrammarNoteRepository.prototype, "findById").mockResolvedValue(createEditorNote()); rpc.mockResolvedValue({ data: permission, error: null }); const result = await requestGrammarExamples({ @@ -75,9 +92,11 @@ describe("예문 서버 액션 권한", () => { expectedVersion: 1, count: 3, }); - expect(result).toEqual({ ok: false, message }); + + expect(result).toEqual({ ok: false, code }); expect(requestExampleOutput).not.toHaveBeenCalled(); }); + it("한도 조회 실패를 허용으로 처리하지 않는다", async () => { jest.spyOn(GrammarNoteRepository.prototype, "findById").mockResolvedValue(createEditorNote()); rpc.mockResolvedValue({ data: null, error: new Error("network") }); @@ -92,8 +111,10 @@ describe("예문 서버 액션 권한", () => { ).toBe(false); expect(requestExampleOutput).not.toHaveBeenCalled(); }); + it("선택 저장에는 AI 비용을 소비하지 않는다", async () => { const note = createEditorNote(); + jest.spyOn(GrammarNoteRepository.prototype, "findById").mockResolvedValue(note); jest .spyOn(GrammarNoteRepository.prototype, "update") diff --git a/src/_tests/features/grammar-example-generation/exampleServices.test.ts b/src/_tests/features/grammar-example-generation/exampleServices.test.ts index 4efb3987..e9778f5c 100644 --- a/src/_tests/features/grammar-example-generation/exampleServices.test.ts +++ b/src/_tests/features/grammar-example-generation/exampleServices.test.ts @@ -6,7 +6,9 @@ import { generateExamples } from "@/features/grammar-example-generation/services import { saveExamples } from "@/features/grammar-example-generation/services/saveExamples"; import { createEditorNote } from "../grammar-note-editor/fixtures"; import { createExampleCandidates } from "./fixtures"; + Object.defineProperty(globalThis.crypto, "randomUUID", { value: randomUUID, configurable: true }); + function setup() { const note = createEditorNote(); const repository = { @@ -27,6 +29,7 @@ function setup() { const consumeRequest = jest .fn() .mockResolvedValue("allowed"); + return { note, repository, @@ -35,49 +38,63 @@ function setup() { command: { noteId: note.id, expectedVersion: 1, count: 3 as const }, }; } + describe("저장 노트 기반 예문 생성 및 채택", () => { it("서버가 읽은 어법을 전달하고 검증된 후보를 미검토 상태로 반환한다", async () => { const deps = setup(); const result = await generateExamples(deps.command, deps); + expect(deps.generate).toHaveBeenCalledWith(deps.note, 3); expect(result).toHaveLength(3); expect(result.every((example) => example.reviewStatus === "needs-review")).toBe(true); expect(new Set(result.map((example) => example.id)).size).toBe(3); }); + it("클라이언트가 목표 어법을 끼워 넣으면 외부 호출 전에 거절한다", async () => { const deps = setup(); + await expect(generateExamples({ ...deps.command, target: "override" }, deps)).rejects.toThrow(); expect(deps.generate).not.toHaveBeenCalled(); }); + it("소유하지 않은 노트를 읽을 수 없으면 비용을 소비하지 않는다", async () => { const deps = setup(); + deps.repository.findById.mockResolvedValue(null); await expect(generateExamples(deps.command, deps)).rejects.toMatchObject({ code: "NOT_FOUND" }); expect(deps.consumeRequest).not.toHaveBeenCalled(); }); + it("버전이 달라지면 이전 어법으로 생성하지 않는다", async () => { const deps = setup(); + await expect( generateExamples({ ...deps.command, expectedVersion: 2 }, deps), ).rejects.toMatchObject({ code: "VERSION_CONFLICT" }); expect(deps.generate).not.toHaveBeenCalled(); }); + it("한도를 초과하면 외부 요청을 보내지 않는다", async () => { const deps = setup(); + deps.consumeRequest.mockResolvedValue("rate_limited"); await expect(generateExamples(deps.command, deps)).rejects.toThrow("rate_limited"); expect(deps.generate).not.toHaveBeenCalled(); }); + it("예문 개수가 다르거나 공백인 결과를 반환하지 않는다", async () => { const deps = setup(); + deps.generate.mockResolvedValue({ examples: [{ sentence: " ", translation: "뜻", targetExplanation: "설명" }], }); await expect(generateExamples({ ...deps.command, count: 1 }, deps)).rejects.toThrow(); }); + it("선택한 예문만 검토 완료로 저장하고 기존 노트와 예문을 보존한다", async () => { const deps = setup(); const candidates = createExampleCandidates(); + deps.repository.findById.mockResolvedValue({ ...deps.note, examples: [candidates[0]] }); await saveExamples( { noteId: deps.note.id, expectedVersion: 1, candidates: [candidates[1]] }, @@ -94,8 +111,10 @@ describe("저장 노트 기반 예문 생성 및 채택", () => { }, }); }); + it("저장 충돌은 다른 노트 변경을 덮어쓰지 않는다", async () => { const deps = setup(); + await expect( saveExamples( { noteId: deps.note.id, expectedVersion: 2, candidates: createExampleCandidates() }, @@ -104,9 +123,11 @@ describe("저장 노트 기반 예문 생성 및 채택", () => { ).rejects.toMatchObject({ code: "VERSION_CONFLICT" }); expect(deps.repository.update).not.toHaveBeenCalled(); }); + it("중복 후보 식별자는 저장하지 않는다", async () => { const deps = setup(); const candidate = createExampleCandidates()[0]; + await expect( saveExamples( { noteId: deps.note.id, expectedVersion: 1, candidates: [candidate, candidate] }, @@ -115,6 +136,7 @@ describe("저장 노트 기반 예문 생성 및 채택", () => { ).rejects.toThrow(); expect(deps.repository.update).not.toHaveBeenCalled(); }); + it("saved candidate retry does not increment the version", async () => { const deps = setup(); const candidates = createExampleCandidates().map((candidate) => ({ @@ -122,12 +144,100 @@ describe("저장 노트 기반 예문 생성 및 채택", () => { reviewStatus: "reviewed" as const, })); const stored = { ...deps.note, version: 2, examples: candidates }; + deps.repository.findById.mockResolvedValue(stored); const result = await saveExamples( { noteId: deps.note.id, expectedVersion: 1, candidates: createExampleCandidates() }, deps.repository, ); + expect(result).toBe(stored); expect(deps.repository.update).not.toHaveBeenCalled(); }); }); + +describe("생성·채택 정책 회귀", () => { + it("요청 개수와 다른 생성 응답을 후보로 전달하지 않는다", async () => { + const deps = setup(); + deps.generate.mockResolvedValue({ + examples: createExampleCandidates() + .slice(0, 2) + .map(({ sentence, translation, targetExplanation }) => ({ + sentence, + translation, + targetExplanation, + })), + }); + await expect(generateExamples(deps.command, deps)).rejects.toThrow("INVALID_EXAMPLE_COUNT"); + }); + + it("공백·대소문자만 다른 생성 문장을 중복으로 검사한다", async () => { + const deps = setup(); + const examples = createExampleCandidates().map( + ({ sentence, translation, targetExplanation }) => ({ + sentence, + translation, + targetExplanation, + }), + ); + examples[1].sentence = ` ${examples[0].sentence.toUpperCase()} `; + deps.generate.mockResolvedValue({ examples }); + await expect(generateExamples(deps.command, deps)).rejects.toThrow("DUPLICATE_EXAMPLES"); + }); + + it.each(["source", "saved"])("%s 문장을 재사용한 생성 결과는 반환하지 않는다", async (kind) => { + const deps = setup(); + const examples = createExampleCandidates().map( + ({ sentence, translation, targetExplanation }) => ({ + sentence, + translation, + targetExplanation, + }), + ); + if (kind === "source") examples[0].sentence = ` ${deps.note.source.sentence.toUpperCase()} `; + else + deps.repository.findById.mockResolvedValue({ + ...deps.note, + examples: [createExampleCandidates()[0]], + }); + deps.generate.mockResolvedValue({ examples }); + await expect(generateExamples(deps.command, deps)).rejects.toThrow("REPEATED_EXAMPLES"); + }); + + it.each(["sentence", "translation", "targetExplanation"] as const)( + "저장된 후보의 %s가 달라지면 동일 재시도로 인정하지 않는다", + async (field) => { + const deps = setup(); + const candidate = createExampleCandidates()[0]; + deps.repository.findById.mockResolvedValue({ + ...deps.note, + version: 2, + examples: [{ ...candidate, reviewStatus: "reviewed" }], + }); + await expect( + saveExamples( + { + noteId: deps.note.id, + expectedVersion: 1, + candidates: [{ ...candidate, [field]: "Changed content" }], + }, + deps.repository, + ), + ).rejects.toMatchObject({ code: "VERSION_CONFLICT" }); + expect(deps.repository.update).not.toHaveBeenCalled(); + }, + ); + + it("일부 ID만 이미 저장되었다면 새 후보를 중복 채택하지 않는다", async () => { + const deps = setup(); + const candidates = createExampleCandidates(); + deps.repository.findById.mockResolvedValue({ + ...deps.note, + examples: [{ ...candidates[0], reviewStatus: "reviewed" }], + }); + await expect( + saveExamples({ noteId: deps.note.id, expectedVersion: 1, candidates }, deps.repository), + ).rejects.toThrow("DUPLICATE_CANDIDATE"); + expect(deps.repository.update).not.toHaveBeenCalled(); + }); +}); diff --git a/src/_tests/features/grammar-example-generation/fixtures.ts b/src/_tests/features/grammar-example-generation/fixtures.ts index 629f2c7b..35ae1837 100644 --- a/src/_tests/features/grammar-example-generation/fixtures.ts +++ b/src/_tests/features/grammar-example-generation/fixtures.ts @@ -1,4 +1,5 @@ import type { GrammarExample } from "@/entities/grammar-note"; + export function createExampleCandidates(): GrammarExample[] { return [ "He is not a driver but a teacher.", diff --git a/src/_tests/features/grammar-note-editor/GrammarNoteEditor.test.tsx b/src/_tests/features/grammar-note-editor/GrammarNoteEditor.test.tsx index 0fc45d68..d2727c81 100644 --- a/src/_tests/features/grammar-note-editor/GrammarNoteEditor.test.tsx +++ b/src/_tests/features/grammar-note-editor/GrammarNoteEditor.test.tsx @@ -3,12 +3,16 @@ import { describe, expect, it, jest } from "@jest/globals"; import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { GrammarNoteEditor, type GrammarNoteEditorProps } from "@/features/grammar-note-editor"; +import type { GrammarNotePersistenceErrorCode } from "@/entities/grammar-note"; import { GrammarAnalysisEditor } from "@/features/grammar-analysis-edit"; import { createEditorNote } from "./fixtures"; + Object.defineProperty(globalThis.crypto, "randomUUID", { value: randomUUID, configurable: true }); + function setup() { const note = createEditorNote(); const save = jest.fn().mockResolvedValue({ ok: true, note }); + render( {}} />, ); + return { user: userEvent.setup(), save, note }; } + describe("분석 초안과 노트 저장 연결", () => { it("미적용 풀이가 있으면 저장을 막고 적용 이후 검토를 다시 받는다", async () => { const { user, save } = setup(); + await user.click(screen.getByRole("button", { name: "She" })); await user.click(screen.getByRole("button", { name: "분석 수정" })); await user.clear(screen.getByLabelText("직독직해")); @@ -50,8 +57,10 @@ describe("분석 초안과 노트 저장 연결", () => { }), ); }); + it("미적용 풀이에서 입력으로 돌아가기 전 확인하고 원문은 보존한다", async () => { const { user, note } = setup(); + await user.click(screen.getByRole("button", { name: "She" })); await user.click(screen.getByRole("button", { name: "분석 수정" })); await user.type(screen.getByLabelText("직독직해"), " 수정"); @@ -64,3 +73,51 @@ describe("분석 초안과 노트 저장 연결", () => { expect(screen.getByLabelText(/영어 문장/)).toHaveValue(note.source.sentence); }); }); + +it.each<[GrammarNotePersistenceErrorCode, string]>([ + ["UNAUTHORIZED", "로그인 후 다시 저장해 주세요."], + ["VERSION_CONFLICT", "다른 화면에서 노트가 변경되었습니다. 새로고침 후 다시 확인해 주세요."], + ["PERSISTENCE_FAILED", "저장하지 못했습니다. 입력을 유지했으니 다시 저장해 주세요."], +])("%s 저장 오류의 안내는 UI에서 선택하고 재시도할 내용을 유지한다", async (code, message) => { + const { user, save } = setup(); + + save.mockResolvedValue({ ok: false, code }); + await user.click(screen.getByRole("button", { name: "분석 수정" })); + await user.type(screen.getByLabelText("직독직해"), " 수정"); + await user.click(screen.getByRole("button", { name: "풀이 적용" })); + await user.click(screen.getByRole("checkbox")); + await user.click(screen.getByRole("button", { name: "검토 완료 · 노트 저장" })); + expect(await screen.findByRole("alert")).toHaveTextContent(message); + expect(screen.getByLabelText("직독직해")).toHaveValue("그녀는 수정"); + expect(screen.getByRole("button", { name: "검토 완료 · 노트 저장" })).toBeEnabled(); +}); + +it("부모가 다시 렌더링되어도 입력을 유지하고 새 분석 콜백을 호출한다", async () => { + const note = createEditorNote(); + const original = jest.fn(); + const current = jest + .fn() + .mockResolvedValue({ status: "error", message: "분석 서비스 오류" }); + const props = { + save: jest.fn(), + AnalysisEditor: GrammarAnalysisEditor, + onSaved: jest.fn(), + onExit: jest.fn(), + }; + const { rerender } = render(); + const user = userEvent.setup(); + + await user.type(screen.getByLabelText(/영어 문장/), note.source.sentence); + await user.type(screen.getByLabelText(/핵심 어법 설명/), note.source.learningNote); + rerender(); + expect(screen.getByLabelText(/영어 문장/)).toHaveValue(note.source.sentence); + await user.click(screen.getByRole("button", { name: "문장 분석하기" })); + expect(original).not.toHaveBeenCalled(); + expect(current).toHaveBeenCalledWith( + expect.objectContaining({ + sentence: note.source.sentence, + learningNote: note.source.learningNote, + }), + ); + expect(await screen.findByRole("alert")).toHaveTextContent("분석 서비스 오류"); +}); diff --git a/src/_tests/features/grammar-note-editor/createEditorStore.test.ts b/src/_tests/features/grammar-note-editor/createEditorStore.test.ts index 4a284aa3..9902cd1d 100644 --- a/src/_tests/features/grammar-note-editor/createEditorStore.test.ts +++ b/src/_tests/features/grammar-note-editor/createEditorStore.test.ts @@ -1,5 +1,7 @@ import { randomUUID } from "node:crypto"; + Object.defineProperty(globalThis.crypto, "randomUUID", { value: randomUUID, configurable: true }); + import { describe, expect, it, jest } from "@jest/globals"; import { createEditorStore } from "@/features/grammar-note-editor/services/createEditorStore"; import type { @@ -7,8 +9,10 @@ import type { GrammarNoteEditorProps, } from "@/features/grammar-note-editor/models/interface"; import { createEditorNote } from "./fixtures"; + function dependencies() { const note = createEditorNote(); + return { initialNote: note, analyze: jest.fn().mockResolvedValue({ @@ -19,18 +23,22 @@ function dependencies() { onSaved: jest.fn(), }; } + describe("어법 등록 이벤트", () => { it("두 필수 입력이 없으면 분석 요청을 보내지 않는다", async () => { const deps = dependencies(); const store = createEditorStore({ ...deps, initialNote: undefined }); + await store.getState().analyze(); expect(deps.analyze).not.toHaveBeenCalled(); expect(store.getState().fieldErrors).toHaveProperty("sentence"); expect(store.getState().fieldErrors).toHaveProperty("learningNote"); }); + it("입력을 수정하면 진행 중인 이전 분석을 무시한다", async () => { let resolve!: (result: EditorAnalysisResult) => void; const deps = dependencies(); + deps.analyze.mockImplementation( () => new Promise((r) => { @@ -39,6 +47,7 @@ describe("어법 등록 이벤트", () => { ); const store = createEditorStore(deps); const pending = store.getState().analyze(); + store.getState().changeSource("learningNote", "새로운 설명"); resolve({ status: "analyzed", @@ -48,9 +57,11 @@ describe("어법 등록 이벤트", () => { expect(store.getState().result).toBeNull(); expect(store.getState().source.learningNote).toBe("새로운 설명"); }); + it("분석 취소 후 늦게 도착한 결과로 검토 화면으로 이동하지 않는다", async () => { let resolve!: (result: EditorAnalysisResult) => void; const deps = dependencies(); + deps.analyze.mockImplementation( () => new Promise((r) => { @@ -59,6 +70,7 @@ describe("어법 등록 이벤트", () => { ); const store = createEditorStore(deps); const pending = store.getState().analyze(); + store.getState().back(); resolve({ status: "analyzed", @@ -67,10 +79,13 @@ describe("어법 등록 이벤트", () => { await pending; expect(store.getState().stage).toBe("input"); }); + it("네트워크 저장 실패 후 재시도에 동일 요청 식별자를 사용한다", async () => { const deps = dependencies(); + deps.save.mockRejectedValueOnce(new Error("network")); const store = createEditorStore({ ...deps, initialNote: undefined }); + store.setState({ source: deps.initialNote.source, result: { @@ -80,22 +95,26 @@ describe("어법 등록 이벤트", () => { reviewed: true, }); await store.getState().save(); - expect(store.getState().error).toContain("다시 저장"); + expect(store.getState().error).toEqual({ code: "PERSISTENCE_FAILED" }); await store.getState().save(); expect(deps.save.mock.calls[0][0].requestId).toBe(deps.save.mock.calls[1][0].requestId); expect(deps.onSaved).toHaveBeenCalledTimes(1); }); + it("검토를 확인하기 전에는 저장하지 않고 분석 수정 후 확인을 해제한다", async () => { const deps = dependencies(); const store = createEditorStore(deps); + await store.getState().save(); expect(deps.save).not.toHaveBeenCalled(); store.getState().setReviewed(true); store.getState().changeAnalysis(deps.initialNote.analysis); expect(store.getState().reviewed).toBe(false); }); + it("사전 체크 수정 필요는 입력을 유지하고 분석 검토로 넘어가지 않는다", async () => { const deps = dependencies(); + deps.analyze.mockResolvedValue({ status: "needs-input", precheck: { @@ -105,12 +124,15 @@ describe("어법 등록 이벤트", () => { }, }); const store = createEditorStore(deps); + await store.getState().analyze(); expect(store.getState().stage).toBe("input"); expect(store.getState().source).toEqual(deps.initialNote.source); }); + it("원문과 불일치하는 분석은 저장 가능한 결과로 적용하지 않는다", async () => { const deps = dependencies(); + deps.analyze.mockResolvedValue({ status: "analyzed", data: { @@ -119,13 +141,17 @@ describe("어법 등록 이벤트", () => { }, }); const store = createEditorStore(deps); + await store.getState().analyze(); - expect(store.getState().error).toContain("분석"); + expect(store.getState().error).toEqual({ code: "ANALYSIS_FAILED" }); }); + it("편집 저장은 읽은 버전을 전달하고 충돌시 초안을 유지한다", async () => { const deps = dependencies(); - deps.save.mockResolvedValue({ ok: false, message: "버전 충돌" }); + + deps.save.mockResolvedValue({ ok: false, code: "VERSION_CONFLICT" }); const store = createEditorStore(deps); + store.getState().setReviewed(true); await store.getState().save(); expect(deps.save.mock.calls[0][0].existing).toEqual({ @@ -133,6 +159,6 @@ describe("어법 등록 이벤트", () => { expectedVersion: 1, }); expect(store.getState().result).not.toBeNull(); - expect(store.getState().error).toBe("버전 충돌"); + expect(store.getState().error).toEqual({ code: "VERSION_CONFLICT" }); }); }); diff --git a/src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts b/src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts index f694d168..9831c451 100644 --- a/src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts +++ b/src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts @@ -4,19 +4,30 @@ import { GrammarNotePersistenceError, GrammarNoteRepository } from "@/entities/g import type { createSupabaseServerClient as CreateClient } from "@/shared/lib/supabase/server"; import type { recordOperationEvent as RecordEvent } from "@/shared/lib/logging/pino"; import type { SaveNoteCommand } from "@/features/grammar-note-editor"; + async function saveGrammarNote(command: SaveNoteCommand) { const action = await import("@/features/grammar-note-editor/services/actions/saveGrammarNote"); + return action.saveGrammarNote(command); } + let createSupabaseServerClient: typeof CreateClient; + let recordOperationEvent: typeof RecordEvent; + import { createEditorNote } from "./fixtures"; + jest.mock("server-only", () => ({})); + jest.mock("@/shared/lib/supabase/server", () => ({ createSupabaseServerClient: jest.fn() })); + jest.mock("@/shared/lib/logging/pino", () => ({ recordOperationEvent: jest.fn() })); + Object.defineProperty(globalThis.crypto, "randomUUID", { value: randomUUID, configurable: true }); + function command() { const note = createEditorNote(); + return { requestId: randomUUID(), content: { @@ -27,6 +38,7 @@ function command() { }, }; } + beforeEach(async () => { ({ createSupabaseServerClient } = await import("@/shared/lib/supabase/server")); ({ recordOperationEvent } = await import("@/shared/lib/logging/pino")); @@ -36,38 +48,46 @@ beforeEach(async () => { auth: { getUser: async () => ({ data: { user: { id: "owner" } }, error: null }) }, } as never); }); + describe("어법 저장 서버 경계", () => { it("인증 실패시 저장소 쓰기를 호출하지 않는다", async () => { jest.mocked(createSupabaseServerClient).mockResolvedValue({ auth: { getUser: async () => ({ data: { user: null }, error: null }) }, } as never); const create = jest.spyOn(GrammarNoteRepository.prototype, "create"); + expect(await saveGrammarNote(command())).toEqual({ ok: false, - message: "로그인 후 다시 저장해 주세요.", + code: "UNAUTHORIZED", }); expect(create).not.toHaveBeenCalled(); }); + it("클라이언트가 미검토 분석을 보내면 저장하지 않는다", async () => { const create = jest.spyOn(GrammarNoteRepository.prototype, "create"); const input = command(); + input.content.analysis = { ...input.content.analysis, reviewStatus: "needs-review" }; expect((await saveGrammarNote(input)).ok).toBe(false); expect(create).not.toHaveBeenCalled(); }); + it("정상 저장은 동일 요청 ID와 검토 내용을 저장소에 전달한다", async () => { const input = command(); const create = jest .spyOn(GrammarNoteRepository.prototype, "create") .mockResolvedValue(createEditorNote()); + expect((await saveGrammarNote(input)).ok).toBe(true); expect(create).toHaveBeenCalledWith(input); }); + it("수정 저장 응답을 잃은 재시도는 이미 저장한 동일 버전을 성공으로 돌려준다", async () => { const note = createEditorNote(); const update = jest .spyOn(GrammarNoteRepository.prototype, "update") .mockRejectedValue(new GrammarNotePersistenceError("VERSION_CONFLICT")); + jest .spyOn(GrammarNoteRepository.prototype, "findById") .mockResolvedValue({ ...note, version: 2 }); @@ -75,11 +95,14 @@ describe("어법 저장 서버 경계", () => { ...command(), existing: { id: note.id, expectedVersion: 1 }, }); + expect(result.ok).toBe(true); expect(update).toHaveBeenCalledTimes(1); }); + it("내용이 다른 버전 충돌을 성공으로 오인하지 않고 초안 재검토를 요청한다", async () => { const note = createEditorNote(); + jest .spyOn(GrammarNoteRepository.prototype, "update") .mockRejectedValue(new GrammarNotePersistenceError("VERSION_CONFLICT")); @@ -92,16 +115,19 @@ describe("어법 저장 서버 경계", () => { ...command(), existing: { id: note.id, expectedVersion: 1 }, }); + expect(result).toEqual({ ok: false, - message: "다른 화면에서 노트가 변경되었습니다. 새로고침 후 다시 확인해 주세요.", + code: "VERSION_CONFLICT", }); }); + it("실패는 내부 이벤트로 기록하고 원문과 내부 오류를 UI에 노출하지 않는다", async () => { jest .spyOn(GrammarNoteRepository.prototype, "create") .mockRejectedValue(new Error("secret database url")); const result = await saveGrammarNote(command()); + expect(JSON.stringify(result)).not.toContain("secret"); expect(recordOperationEvent).toHaveBeenCalledWith(expect.objectContaining({ phase: "failed" })); expect(JSON.stringify(jest.mocked(recordOperationEvent).mock.calls)).not.toContain( diff --git a/src/_tests/shared/lib/supabase/getAuthenticatedUser.test.ts b/src/_tests/shared/lib/supabase/getAuthenticatedUser.test.ts new file mode 100644 index 00000000..202c4827 --- /dev/null +++ b/src/_tests/shared/lib/supabase/getAuthenticatedUser.test.ts @@ -0,0 +1,31 @@ +/** @jest-environment node */ +import { describe, expect, it, jest } from "@jest/globals"; + +jest.mock("server-only", () => ({})); +jest.mock("next/navigation", () => ({ + notFound: () => { + throw new Error("NEXT_NOT_FOUND"); + }, +})); + +describe("공용 사용자 인증 확인", () => { + it.each([ + { user: { id: "owner" }, error: null, expected: { id: "owner" } }, + { user: null, error: null, expected: null }, + { user: { id: "owner" }, error: { message: "invalid token" }, expected: null }, + ])("사용자와 인증 오류를 함께 확인한다: $error", async ({ user, error, expected }) => { + const { getAuthenticatedUser } = await import("@/shared/lib/supabase/getAuthenticatedUser"); + const getUser = jest.fn(async () => ({ data: { user }, error })); + expect(await getAuthenticatedUser({ auth: { getUser } } as never)).toEqual(expected); + expect(getUser).toHaveBeenCalledTimes(1); + }); + + it("기존 requireUser의 미인증 404 응답을 유지한다", async () => { + const { requireUser } = await import("@/features/login/services/requireUser"); + await expect( + requireUser({ + auth: { getUser: async () => ({ data: { user: null }, error: null }) }, + } as never), + ).rejects.toThrow("NEXT_NOT_FOUND"); + }); +}); diff --git a/src/_tests/views/grammar-library/GrammarLibraryPage.test.tsx b/src/_tests/views/grammar-library/GrammarLibraryPage.test.tsx new file mode 100644 index 00000000..877ddb4c --- /dev/null +++ b/src/_tests/views/grammar-library/GrammarLibraryPage.test.tsx @@ -0,0 +1,48 @@ +/** @jest-environment node */ +import { describe, it, expect, jest, beforeEach } from "@jest/globals"; + +import type { GrammarNoteRepository } from "@/entities/grammar-note"; + +jest.mock("@/shared/lib/supabase/server", () => ({ createSupabaseServerClient: jest.fn() })); + +jest.mock("@/shared/lib/logging/pino", () => ({ recordOperationEvent: jest.fn() })); + +jest.mock("next/navigation", () => ({ + redirect: (url: string) => { + throw new Error(`redirect:${url}`); + }, +})); + +describe("grammar list route", () => { + const findMany = jest.fn["findMany"]>(); + + beforeEach(async () => { + const { GrammarNoteRepository } = await import("@/entities/grammar-note"); + const { createSupabaseServerClient } = await import("@/shared/lib/supabase/server"); + + jest.spyOn(GrammarNoteRepository.prototype, "findMany").mockImplementation(findMany); + jest.mocked(createSupabaseServerClient).mockResolvedValue({ + auth: { getUser: async () => ({ data: { user: { id: "owner" } }, error: null }) }, + } as unknown as Awaited>); + findMany.mockResolvedValue({ items: [], total: 41, page: 999, pageSize: 20 }); + }); + + it("redirects an out-of-range page to last valid page with search preserved", async () => { + const { GrammarLibraryContent } = + await import("@/views/grammar-library/ui/GrammarLibraryContent"); + + await expect(GrammarLibraryContent({ query: { page: 999, query: "verb" } })).rejects.toThrow( + "redirect:/grammar?q=verb&page=3", + ); + expect(findMany).toHaveBeenCalledWith({ page: 999, pageSize: 20, query: "verb" }); + }); + + it("normalizes an invalid URL before rendering valid links", async () => { + findMany.mockResolvedValue({ items: [], total: 0, page: 1, pageSize: 20 }); + const { default: GrammarLibraryPage } = await import("@/app/(protected)/grammar/(list)/page"); + + await expect( + GrammarLibraryPage({ searchParams: Promise.resolve({ page: "bad" }) }), + ).rejects.toThrow("redirect:/grammar"); + }); +}); diff --git a/src/_tests/views/grammar-library/libraryQuery.test.ts b/src/_tests/views/grammar-library/libraryQuery.test.ts new file mode 100644 index 00000000..8d7e46db --- /dev/null +++ b/src/_tests/views/grammar-library/libraryQuery.test.ts @@ -0,0 +1,23 @@ +import { describe, it, expect } from "@jest/globals"; +import { + parseGrammarLibraryQuery, + grammarLibraryHref, +} from "@/views/grammar-library/services/libraryQuery"; + +describe("grammar library URL", () => { + it.each(["0", "-1", "1.5", "Infinity", "2147483648", "bad"])( + "normalizes invalid page %s", + (page) => expect(parseGrammarLibraryQuery({ page }).page).toBe(1), + ); + + it("preserves search and page in a safely encoded return URL", () => + expect(grammarLibraryHref({ page: 3, query: "not A & B" })).toBe( + "/grammar?q=not+A+%26+B&page=3", + )); + + it("bounds search and accepts a single value from repeated query", () => + expect(parseGrammarLibraryQuery({ page: ["2", "3"], q: [" verb ", "other"] })).toEqual({ + page: 2, + query: "verb", + })); +}); diff --git a/src/app/(protected)/grammar/(list)/error.tsx b/src/app/(protected)/grammar/(list)/error.tsx new file mode 100644 index 00000000..06b11217 --- /dev/null +++ b/src/app/(protected)/grammar/(list)/error.tsx @@ -0,0 +1,22 @@ +"use client"; + +import { BackNavigation } from "@/shared/components/ui/back-navigation/BackNavigation"; + +export default function GrammarLibraryError({ reset }: { reset: () => void }) { + return ( +
+ +

어법 노트를 불러오지 못했습니다.

+

+ 잠시 후 다시 시도해주세요. +

+ +
+ ); +} diff --git a/src/app/(protected)/grammar/(list)/loading.tsx b/src/app/(protected)/grammar/(list)/loading.tsx new file mode 100644 index 00000000..bb04cf63 --- /dev/null +++ b/src/app/(protected)/grammar/(list)/loading.tsx @@ -0,0 +1 @@ +export { GrammarLibrarySkeleton as default } from "@/views/grammar-library"; diff --git a/src/app/(protected)/grammar/(list)/page.tsx b/src/app/(protected)/grammar/(list)/page.tsx new file mode 100644 index 00000000..8a50782b --- /dev/null +++ b/src/app/(protected)/grammar/(list)/page.tsx @@ -0,0 +1,30 @@ +import { Suspense } from "react"; +import { redirect } from "next/navigation"; +import { + GrammarLibrarySkeleton, + parseGrammarLibraryQuery, + grammarLibraryHref, +} from "@/views/grammar-library"; +import { GrammarLibraryContent } from "@/views/grammar-library/ui/GrammarLibraryContent"; + +interface Props { + searchParams: Promise<{ page?: string | string[]; q?: string | string[] }>; +} + +export default async function GrammarLibraryPage({ searchParams }: Props) { + const raw = await searchParams; + const query = parseGrammarLibraryQuery(raw); + + if ( + (raw.page !== undefined && raw.page !== String(query.page)) || + (raw.q !== undefined && raw.q !== query.query) + ) + redirect(grammarLibraryHref(query)); + + // 검색어/페이지 변경도 새 데이터가 준비될 때까지 해당 목록의 스켈레톤을 보여준다. + return ( + }> + + + ); +} diff --git a/src/features/grammar-analysis-edit/models/store.ts b/src/features/grammar-analysis-edit/models/store.ts index 61d6126a..cc9534a1 100644 --- a/src/features/grammar-analysis-edit/models/store.ts +++ b/src/features/grammar-analysis-edit/models/store.ts @@ -4,7 +4,11 @@ import type { AnalysisEditorProps, AnalysisEditorState } from "./interface"; import { applyAnalysisEdits } from "../services/applyAnalysisEdits"; /** 에디터 수명에 맞춰 상태를 생성한다. onChange는 성공한 편집을 상위 문서에 전달한다. */ -export function createAnalysisEditorStore({ initialAnalysis, onChange }: AnalysisEditorProps) { +export function createAnalysisEditorStore({ + initialAnalysis, + onChange, + onDirtyChange, +}: AnalysisEditorProps) { return createStore((set, get) => ({ analysis: sentenceAnalysisSchema.parse(initialAnalysis), selectedId: null, @@ -12,18 +16,23 @@ export function createAnalysisEditorStore({ initialAnalysis, onChange }: Analysi editing: false, dirty: false, pendingSelection: null, + startEditing: () => set({ editing: true, selectedId: get().selectedId ?? get().analysis.chunks[0].id }), + finishEditing: () => { const state = get(); const id = state.analysis.chunks.some((chunk) => chunk.id === state.readingId) ? state.readingId : null; + if (state.dirty) set({ pendingSelection: { id, editing: false } }); else set({ selectedId: id, editing: false }); }, + addSyntax: () => { if (get().dirty) return { ok: false, message: "현재 수정을 먼저 적용해 주세요." }; + const id = crypto.randomUUID(); const result = get().edit((service) => service.saveSyntax({ @@ -35,25 +44,36 @@ export function createAnalysisEditorStore({ initialAnalysis, onChange }: Analysi explanation: "", }), ); + if (result.ok) set({ selectedId: id, editing: true }); + return result; }, + markDirty: () => { - if (get().editing) set({ dirty: true }); + if (!get().editing || get().dirty) return; + + set({ dirty: true }); + onDirtyChange?.(true); }, + resolveSelection: (discard) => { const pending = get().pendingSelection; - if (discard && pending) + + if (discard && pending) { set({ selectedId: pending.id, editing: pending.editing, dirty: false, + pendingSelection: null, readingId: get().analysis.chunks.some((chunk) => chunk.id === pending.id) ? pending.id : get().readingId, }); - set({ pendingSelection: null }); + onDirtyChange?.(false); + } else set({ pendingSelection: null }); }, + select: (selectedId) => { if (get().dirty) set({ pendingSelection: { id: selectedId, editing: get().editing } }); else @@ -64,22 +84,28 @@ export function createAnalysisEditorStore({ initialAnalysis, onChange }: Analysi : get().readingId, }); }, + edit: (command) => { const result = applyAnalysisEdits(get().analysis, command); + if (result.ok) { const ids = [ ...result.analysis.chunks, ...result.analysis.syntax, ...result.analysis.constructions, ].map((item) => item.id); - const selectedId = get().selectedId; + const { selectedId, dirty } = get(); + set({ dirty: false, analysis: result.analysis, selectedId: selectedId && ids.includes(selectedId) ? selectedId : null, }); onChange(result.analysis); + + if (dirty) onDirtyChange?.(false); } + return result; }, })); diff --git a/src/features/grammar-analysis-edit/ui/AnalysisEditorProvider.tsx b/src/features/grammar-analysis-edit/ui/AnalysisEditorProvider.tsx index 8e2b19ff..e602ecf7 100644 --- a/src/features/grammar-analysis-edit/ui/AnalysisEditorProvider.tsx +++ b/src/features/grammar-analysis-edit/ui/AnalysisEditorProvider.tsx @@ -1,6 +1,6 @@ "use client"; -import { createContext, useContext, useEffect, useRef, useState } from "react"; +import { createContext, useContext, useLayoutEffect, useRef, useState } from "react"; import { useStore } from "zustand"; import type { StoreApi } from "zustand"; import type { AnalysisEditorProviderProps, AnalysisEditorState } from "../models/interface"; @@ -20,28 +20,29 @@ export function AnalysisEditorProvider({ children, }: AnalysisEditorProviderProps) { // 부모가 콜백을 변경해도 편집 상태를 초기화하지 않고 최신 수신자에게 알린다. - const onChangeRef = useRef(onChange); - useEffect(() => { - onChangeRef.current = onChange; - }, [onChange]); + const callbacks = useRef({ onChange, onDirtyChange }); + + useLayoutEffect(() => { + callbacks.current = { onChange, onDirtyChange }; + }, [onChange, onDirtyChange]); const [store] = useState(() => createAnalysisEditorStore({ initialAnalysis, - onChange: (analysis) => onChangeRef.current(analysis), + + onChange: (analysis) => callbacks.current.onChange(analysis), + + onDirtyChange: (dirty) => callbacks.current.onDirtyChange?.(dirty), }), ); - useEffect(() => { - onDirtyChange?.(store.getState().dirty); - return store.subscribe((state, previous) => { - if (state.dirty !== previous.dirty) onDirtyChange?.(state.dirty); - }); - }, [store, onDirtyChange]); + return {children}; } export function useAnalysisEditorStore(): StoreApi { const store = useContext(Context); + if (!store) throw new Error("AnalysisEditorProvider is required"); + return store; } diff --git a/src/features/grammar-example-generation/index.ts b/src/features/grammar-example-generation/index.ts index fbe870ee..64362000 100644 --- a/src/features/grammar-example-generation/index.ts +++ b/src/features/grammar-example-generation/index.ts @@ -1,4 +1,5 @@ export { GrammarExampleManager } from "./ui/GrammarExampleManager"; + export type { GrammarExampleManagerProps, GenerateExamplesCommand, diff --git a/src/features/grammar-example-generation/models/errors.ts b/src/features/grammar-example-generation/models/errors.ts index f4f92640..4ed0ced3 100644 --- a/src/features/grammar-example-generation/models/errors.ts +++ b/src/features/grammar-example-generation/models/errors.ts @@ -1,22 +1,21 @@ import { GrammarNotePersistenceError } from "@/entities/grammar-note"; +import type { GrammarNotePersistenceErrorCode } from "@/entities/grammar-note"; -const messages = new Map([ - ["VERSION_CONFLICT", "노트가 변경되었습니다. 최신 노트를 불러온 뒤 다시 시도해 주세요."], - ["UNAUTHORIZED", "로그인 후 다시 시도해 주세요."], - ["NOT_FOUND", "노트를 찾을 수 없습니다."], - ["rate_limited", "AI 요청 한도에 도달했습니다. 잠시 후 다시 시도해 주세요."], - ["not_invited", "AI 기능을 사용할 권한이 없습니다."], -]); +export type ExampleErrorCode = + | GrammarNotePersistenceErrorCode + | "NOT_INVITED" + | "RATE_LIMITED" + | "FAILED" + | "GENERATION_FAILED" + | "SAVE_FAILED" + | "INVALID_SELECTION"; -export function grammarExampleErrorMessage(error: unknown): string { - const code = - error instanceof GrammarNotePersistenceError - ? error.code - : error instanceof Error - ? error.message - : "UNKNOWN"; - return ( - messages.get(code) ?? - "예문 작업을 완료하지 못했습니다. 기존 내용은 유지됩니다. 다시 시도해 주세요." - ); +export function grammarExampleErrorCode(error: unknown): ExampleErrorCode { + if (error instanceof GrammarNotePersistenceError) return error.code; + + if (error instanceof Error && error.message === "not_invited") return "NOT_INVITED"; + + if (error instanceof Error && error.message === "rate_limited") return "RATE_LIMITED"; + + return "FAILED"; } diff --git a/src/features/grammar-example-generation/models/exampleAdoption.ts b/src/features/grammar-example-generation/models/exampleAdoption.ts new file mode 100644 index 00000000..18455d7b --- /dev/null +++ b/src/features/grammar-example-generation/models/exampleAdoption.ts @@ -0,0 +1,38 @@ +import { + GrammarNotePersistenceError, + type GrammarNote, + type GrammarExample, +} from "@/entities/grammar-note"; + +/** 동일 저장 재시도는 버전이 바뀌어도 허용하되, 일부 채택·내용 변경은 새 저장으로 검사한다. */ +export function getExampleAdoptionStatus( + note: GrammarNote, + candidates: readonly GrammarExample[], + expectedVersion: number, +): "already-saved" | "new" { + if (new Set(candidates.map((candidate) => candidate.id)).size !== candidates.length) + throw new Error("DUPLICATE_CANDIDATE"); + + // 응답을 받지 못한 저장 재시도: 동일 ID와 내용이 이미 채택되었다면 버전을 다시 올리지 않는다. + const alreadySaved = candidates.every((candidate) => + note.examples.some( + (saved) => + saved.id === candidate.id && + saved.sentence === candidate.sentence && + saved.translation === candidate.translation && + saved.targetExplanation === candidate.targetExplanation && + saved.reviewStatus === "reviewed", + ), + ); + + if (alreadySaved) return "already-saved"; + + if (note.version !== expectedVersion) throw new GrammarNotePersistenceError("VERSION_CONFLICT"); + + const existingIds = new Set(note.examples.map((example) => example.id)); + + if (candidates.some((candidate) => existingIds.has(candidate.id))) + throw new Error("DUPLICATE_CANDIDATE"); + + return "new"; +} diff --git a/src/features/grammar-example-generation/models/interface.ts b/src/features/grammar-example-generation/models/interface.ts index cb4ec544..a2066859 100644 --- a/src/features/grammar-example-generation/models/interface.ts +++ b/src/features/grammar-example-generation/models/interface.ts @@ -1,24 +1,30 @@ +import type { ExampleErrorCode } from "./errors"; import type { GrammarExample, GrammarNote, GrammarNoteRepositoryPort, } from "@/entities/grammar-note"; + export interface GenerateExamplesCommand { noteId: string; expectedVersion: number; count: 1 | 3; } + export interface SaveExamplesCommand { noteId: string; expectedVersion: number; candidates: readonly GrammarExample[]; } -export type ExampleResult = { ok: true; data: T } | { ok: false; message: string }; + +export type ExampleResult = { ok: true; data: T } | { ok: false; code: ExampleErrorCode }; + export interface ExampleDependencies { repository: GrammarNoteRepositoryPort; generate: (note: GrammarNote, count: 1 | 3) => Promise; consumeRequest: () => Promise<"allowed" | "not_invited" | "rate_limited">; } + export interface GrammarExampleManagerProps { note: GrammarNote; generate: (command: GenerateExamplesCommand) => Promise>; @@ -26,12 +32,13 @@ export interface GrammarExampleManagerProps { onUpdated: (note: GrammarNote) => void; onBack?: () => void; } + export interface ExampleState { note: GrammarNote; candidates: readonly GrammarExample[]; selected: readonly string[]; pending: string | null; - error: string; + error: ExampleErrorCode | null; dirty: boolean; change: ( id: string, diff --git a/src/features/grammar-example-generation/models/schema.ts b/src/features/grammar-example-generation/models/schema.ts index d45692bb..8d4a9f82 100644 --- a/src/features/grammar-example-generation/models/schema.ts +++ b/src/features/grammar-example-generation/models/schema.ts @@ -1,5 +1,6 @@ import { z } from "zod"; import { grammarExampleSchema } from "@/entities/grammar-note"; + export const generateExamplesCommandSchema = z .object({ noteId: z.string().uuid(), @@ -7,6 +8,7 @@ export const generateExamplesCommandSchema = z count: z.union([z.literal(1), z.literal(3)]), }) .strict(); + export const saveExamplesCommandSchema = z .object({ noteId: z.string().uuid(), @@ -14,7 +16,9 @@ export const saveExamplesCommandSchema = z candidates: z.array(grammarExampleSchema).min(1).max(3), }) .strict(); + const text = z.string().min(1).max(4000); + export const exampleOutputSchema = z .object({ examples: z diff --git a/src/features/grammar-example-generation/services/actions/exampleActions.ts b/src/features/grammar-example-generation/services/actions/exampleActions.ts index 4630517f..734a3b71 100644 --- a/src/features/grammar-example-generation/services/actions/exampleActions.ts +++ b/src/features/grammar-example-generation/services/actions/exampleActions.ts @@ -1,13 +1,16 @@ "use server"; + import type { GenerateExamplesCommand, SaveExamplesCommand } from "../../models/interface"; import { executeExampleAction } from "../server/executeExampleAction"; import { generateExamples } from "../generateExamples"; import { saveExamples } from "../saveExamples"; + export async function requestGrammarExamples(command: GenerateExamplesCommand) { return executeExampleAction("grammar.examples.generate", (dependencies) => generateExamples(command, dependencies), ); } + export async function saveGrammarExamples(command: SaveExamplesCommand) { return executeExampleAction("grammar.examples.save", (dependencies) => saveExamples(command, dependencies.repository), diff --git a/src/features/grammar-example-generation/services/createExampleStore.ts b/src/features/grammar-example-generation/services/createExampleStore.ts index 20953068..e05c1ba2 100644 --- a/src/features/grammar-example-generation/services/createExampleStore.ts +++ b/src/features/grammar-example-generation/services/createExampleStore.ts @@ -1,25 +1,31 @@ import { createStore } from "zustand/vanilla"; import { grammarExampleSchema } from "@/entities/grammar-note"; import type { ExampleState, GrammarExampleManagerProps } from "../models/interface"; + export function createExampleStore(dependencies: GrammarExampleManagerProps) { // 재생성 중 사용자가 후보를 수정할 수 있으므로, 수정 이전에 시작한 응답은 적용하지 않는다. let generation = 0; + return createStore((set, get) => ({ note: dependencies.note, candidates: [], selected: [], pending: null, - error: "", + error: null, dirty: false, + cancel: () => { generation++; }, + discard: () => { generation++; - set({ candidates: [], selected: [], pending: null, error: "", dirty: false }); + set({ candidates: [], selected: [], pending: null, error: null, dirty: false }); }, + change: (id, field, value) => { if (get().pending === "save") return; + generation++; set((state) => ({ candidates: state.candidates.map((candidate) => @@ -32,6 +38,7 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) { dirty: true, })); }, + select: (id, selected) => set((state) => ({ selected: selected @@ -39,29 +46,41 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) { : state.selected.filter((value) => value !== id), dirty: true, })), + generate: async (id) => { const state = get(); + if (state.pending) return; + if (id && !state.candidates.some((candidate) => candidate.id === id)) return; + const currentGeneration = ++generation; - set({ pending: id ?? "all", error: "" }); + + set({ pending: id ?? "all", error: null }); + try { const result = await dependencies.generate({ noteId: state.note.id, expectedVersion: state.note.version, count: id ? 1 : 3, }); + if (currentGeneration !== generation) return; + if (!result.ok) { - set({ pending: null, error: result.message }); + set({ pending: null, error: result.code }); + return; } + const candidates = result.data.map((candidate) => grammarExampleSchema.parse(candidate)); + if ( candidates.length !== (id ? 1 : 3) || new Set(candidates.map((candidate) => candidate.id)).size !== candidates.length ) throw new Error("INVALID_CANDIDATES"); + if ( id && state.candidates.some( @@ -69,6 +88,7 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) { ) ) throw new Error("DUPLICATE_CANDIDATE"); + set((current) => ({ candidates: id ? current.candidates.map((candidate) => @@ -83,34 +103,44 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) { if (currentGeneration === generation) set({ pending: null, - error: "예문 생성에 실패했습니다. 기존 후보를 유지했으니 다시 생성해 주세요.", + error: "GENERATION_FAILED", }); } }, + save: async () => { const state = get(); + if (state.pending) return; + const candidates = state.candidates.filter((candidate) => state.selected.includes(candidate.id), ); + if ( !candidates.length || candidates.some((candidate) => !grammarExampleSchema.safeParse(candidate).success) ) { - set({ error: "저장할 예문을 선택하고 문장·뜻·어법 설명을 모두 입력해 주세요." }); + set({ error: "INVALID_SELECTION" }); + return; } - set({ pending: "save", error: "" }); + + set({ pending: "save", error: null }); + try { const result = await dependencies.save({ noteId: state.note.id, expectedVersion: state.note.version, candidates, }); + if (!result.ok) { - set({ pending: null, error: result.message }); + set({ pending: null, error: result.code }); + return; } + set((current) => ({ note: result.data, candidates: current.candidates.filter( @@ -124,7 +154,7 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) { } catch { set({ pending: null, - error: "예문을 저장하지 못했습니다. 선택과 수정 내용을 유지했습니다. 다시 저장해 주세요.", + error: "SAVE_FAILED", }); } }, diff --git a/src/features/grammar-example-generation/services/createValidatedCandidates.ts b/src/features/grammar-example-generation/services/createValidatedCandidates.ts new file mode 100644 index 00000000..eebf5c1c --- /dev/null +++ b/src/features/grammar-example-generation/services/createValidatedCandidates.ts @@ -0,0 +1,40 @@ +import { grammarExampleSchema, type GrammarNote } from "@/entities/grammar-note"; +import { exampleOutputSchema } from "../models/schema"; + +/** 생성 개수·중복·기존 문장 재사용 정책을 검증한 후보만 편집 화면에 전달한다. */ +export function createValidatedCandidates( + output: unknown, + note: GrammarNote, + expectedCount: 1 | 3, +) { + const response = exampleOutputSchema.parse(output); + + if (response.examples.length !== expectedCount) throw new Error("INVALID_EXAMPLE_COUNT"); + + const candidates = response.examples.map((example) => + grammarExampleSchema.parse({ + ...example, + id: crypto.randomUUID(), + reviewStatus: "needs-review", + }), + ); + + if ( + new Set(candidates.map((candidate) => candidate.sentence.trim().toLowerCase())).size !== + candidates.length + ) + throw new Error("DUPLICATE_EXAMPLES"); + + const existingSentences = new Set( + [note.source.sentence, ...note.examples.map((example) => example.sentence)].map((sentence) => + sentence.trim().toLowerCase(), + ), + ); + + if ( + candidates.some((candidate) => existingSentences.has(candidate.sentence.trim().toLowerCase())) + ) + throw new Error("REPEATED_EXAMPLES"); + + return candidates; +} diff --git a/src/features/grammar-example-generation/services/generateExamples.ts b/src/features/grammar-example-generation/services/generateExamples.ts index a9f024d0..debd5615 100644 --- a/src/features/grammar-example-generation/services/generateExamples.ts +++ b/src/features/grammar-example-generation/services/generateExamples.ts @@ -1,7 +1,8 @@ -import { grammarExampleSchema } from "@/entities/grammar-note"; import type { ExampleDependencies } from "../models/interface"; -import { exampleOutputSchema, generateExamplesCommandSchema } from "../models/schema"; +import { generateExamplesCommandSchema } from "../models/schema"; +import { createValidatedCandidates } from "./createValidatedCandidates"; import { loadTargetNote } from "./loadTargetNote"; + export async function generateExamples(input: unknown, dependencies: ExampleDependencies) { // 1. 식별자와 버전을 검사하고 소유권이 적용된 저장소에서 목표 어법을 읽는다. const command = generateExamplesCommandSchema.parse(input); @@ -11,30 +12,10 @@ export async function generateExamples(input: unknown, dependencies: ExampleDepe command.expectedVersion, ); const permission = await dependencies.consumeRequest(); + if (permission !== "allowed") throw new Error(permission); - // 2. 외부 응답의 구조와 요청 개수를 검사한 뒤 서버가 후보 식별자를 부여한다. - const response = exampleOutputSchema.parse(await dependencies.generate(note, command.count)); - if (response.examples.length !== command.count) throw new Error("INVALID_EXAMPLE_COUNT"); - const candidates = response.examples.map((example) => - grammarExampleSchema.parse({ - ...example, - id: crypto.randomUUID(), - reviewStatus: "needs-review", - }), - ); - if ( - new Set(candidates.map((candidate) => candidate.sentence.trim().toLowerCase())).size !== - candidates.length - ) - throw new Error("DUPLICATE_EXAMPLES"); - const existingSentences = new Set( - [note.source.sentence, ...note.examples.map((example) => example.sentence)].map((sentence) => - sentence.trim().toLowerCase(), - ), - ); - if ( - candidates.some((candidate) => existingSentences.has(candidate.sentence.trim().toLowerCase())) - ) - throw new Error("REPEATED_EXAMPLES"); - return candidates; + + const output = await dependencies.generate(note, command.count); + + return createValidatedCandidates(output, note, command.count); } diff --git a/src/features/grammar-example-generation/services/loadTargetNote.ts b/src/features/grammar-example-generation/services/loadTargetNote.ts index 4430f4b5..8945f103 100644 --- a/src/features/grammar-example-generation/services/loadTargetNote.ts +++ b/src/features/grammar-example-generation/services/loadTargetNote.ts @@ -2,13 +2,17 @@ import { GrammarNotePersistenceError, type GrammarNoteRepositoryPort, } from "@/entities/grammar-note"; + export async function loadTargetNote( repository: GrammarNoteRepositoryPort, id: string, expectedVersion: number, ) { const note = await repository.findById(id); + if (!note) throw new GrammarNotePersistenceError("NOT_FOUND"); + if (note.version !== expectedVersion) throw new GrammarNotePersistenceError("VERSION_CONFLICT"); + return note; } diff --git a/src/features/grammar-example-generation/services/saveExamples.ts b/src/features/grammar-example-generation/services/saveExamples.ts index 70a1ec2c..5e517e8a 100644 --- a/src/features/grammar-example-generation/services/saveExamples.ts +++ b/src/features/grammar-example-generation/services/saveExamples.ts @@ -2,32 +2,19 @@ import { GrammarNotePersistenceError, type GrammarNoteRepositoryPort, } from "@/entities/grammar-note"; +import { getExampleAdoptionStatus } from "../models/exampleAdoption"; import { saveExamplesCommandSchema } from "../models/schema"; + export async function saveExamples(input: unknown, repository: GrammarNoteRepositoryPort) { const command = saveExamplesCommandSchema.parse(input); const note = await repository.findById(command.noteId); + if (!note) throw new GrammarNotePersistenceError("NOT_FOUND"); - if ( - new Set(command.candidates.map((candidate) => candidate.id)).size !== command.candidates.length - ) - throw new Error("DUPLICATE_CANDIDATE"); - // 응답을 받지 못한 저장 재시도: 동일 ID와 내용이 이미 채택되었다면 버전을 다시 올리지 않는다. - const alreadySaved = command.candidates.every((candidate) => - note.examples.some( - (saved) => - saved.id === candidate.id && - saved.sentence === candidate.sentence && - saved.translation === candidate.translation && - saved.targetExplanation === candidate.targetExplanation && - saved.reviewStatus === "reviewed", - ), - ); - if (alreadySaved) return note; - if (note.version !== command.expectedVersion) - throw new GrammarNotePersistenceError("VERSION_CONFLICT"); - const existingIds = new Set(note.examples.map((example) => example.id)); - if (command.candidates.some((candidate) => existingIds.has(candidate.id))) - throw new Error("DUPLICATE_CANDIDATE"); + + const adoption = getExampleAdoptionStatus(note, command.candidates, command.expectedVersion); + + if (adoption === "already-saved") return note; + return repository.update({ id: note.id, expectedVersion: command.expectedVersion, diff --git a/src/features/grammar-example-generation/services/server/executeExampleAction.ts b/src/features/grammar-example-generation/services/server/executeExampleAction.ts index 62da348c..0c773dd5 100644 --- a/src/features/grammar-example-generation/services/server/executeExampleAction.ts +++ b/src/features/grammar-example-generation/services/server/executeExampleAction.ts @@ -1,11 +1,13 @@ import "server-only"; import { GrammarNotePersistenceError, GrammarNoteRepository } from "@/entities/grammar-note"; +import { getAuthenticatedUser } from "@/shared/lib/supabase/getAuthenticatedUser"; import { createSupabaseServerClient } from "@/shared/lib/supabase/server"; import { observeOperation } from "@/shared/lib/logging/observeOperation"; import { recordOperationEvent } from "@/shared/lib/logging/pino"; import type { ExampleDependencies, ExampleResult } from "../../models/interface"; -import { grammarExampleErrorMessage } from "../../models/errors"; +import { grammarExampleErrorCode } from "../../models/errors"; import { requestExampleOutput } from "./requestExampleOutput"; + export async function executeExampleAction( operation: string, execute: (dependencies: ExampleDependencies) => Promise, @@ -15,29 +17,36 @@ export async function executeExampleAction( operation, resourceId: "grammar-note", recordEvent: recordOperationEvent, + execute: async () => { const supabase = await createSupabaseServerClient(); - const { data: auth, error } = await supabase.auth.getUser(); - if (error || !auth.user) throw new GrammarNotePersistenceError("UNAUTHORIZED"); + const user = await getAuthenticatedUser(supabase); + + if (!user) throw new GrammarNotePersistenceError("UNAUTHORIZED"); + return execute({ repository: new GrammarNoteRepository(supabase), generate: requestExampleOutput, + consumeRequest: async () => { const { data, error: quotaError } = await supabase.rpc("consume_ai_request", { p_operation: "analysis", }); + if ( quotaError || (data !== "allowed" && data !== "not_invited" && data !== "rate_limited") ) throw new Error("QUOTA_FAILED"); + return data; }, }); }, }); + return { ok: true, data }; } catch (error) { - return { ok: false, message: grammarExampleErrorMessage(error) }; + return { ok: false, code: grammarExampleErrorCode(error) }; } } diff --git a/src/features/grammar-example-generation/services/server/requestExampleOutput.ts b/src/features/grammar-example-generation/services/server/requestExampleOutput.ts index 8e7ba333..ce5bdc17 100644 --- a/src/features/grammar-example-generation/services/server/requestExampleOutput.ts +++ b/src/features/grammar-example-generation/services/server/requestExampleOutput.ts @@ -3,6 +3,7 @@ import { zodTextFormat } from "openai/helpers/zod"; import type { GrammarNote } from "@/entities/grammar-note"; import { getOpenAIEvaluationModel, getOpenAIServerClient } from "@/shared/lib/openai/server"; import { exampleOutputSchema } from "../../models/schema"; + export async function requestExampleOutput(note: GrammarNote, count: 1 | 3): Promise { const response = await getOpenAIServerClient().responses.parse( { @@ -29,5 +30,6 @@ export async function requestExampleOutput(note: GrammarNote, count: 1 | 3): Pro }, { timeout: 60000, maxRetries: 0 }, ); + return response.output_parsed; } diff --git a/src/features/grammar-example-generation/ui/ExampleActions.tsx b/src/features/grammar-example-generation/ui/ExampleActions.tsx index f6624578..220eb18a 100644 --- a/src/features/grammar-example-generation/ui/ExampleActions.tsx +++ b/src/features/grammar-example-generation/ui/ExampleActions.tsx @@ -1,6 +1,9 @@ "use client"; + import { Button } from "@/shared/components/atomics/button/Button"; +import { exampleErrorMessage } from "./errorMessage"; import { useExamples } from "./ExampleProvider"; + export function ExampleActions() { const pending = useExamples((s) => s.pending); const error = useExamples((s) => s.error); @@ -8,6 +11,7 @@ export function ExampleActions() { const count = useExamples((s) => s.candidates.length); const generate = useExamples((s) => s.generate); const save = useExamples((s) => s.save); + return (
@@ -26,7 +30,7 @@ export function ExampleActions() {
{error && (

- {error} + {exampleErrorMessage(error)}

)} {pending && ( diff --git a/src/features/grammar-example-generation/ui/ExampleCandidateCard.tsx b/src/features/grammar-example-generation/ui/ExampleCandidateCard.tsx index 0e566ac3..ac71486b 100644 --- a/src/features/grammar-example-generation/ui/ExampleCandidateCard.tsx +++ b/src/features/grammar-example-generation/ui/ExampleCandidateCard.tsx @@ -1,13 +1,16 @@ "use client"; + import { useId } from "react"; import { Textarea } from "@/shared/components/atomics/textarea/Textarea"; import { Button } from "@/shared/components/atomics/button/Button"; import { useExamples } from "./ExampleProvider"; + const fields = [ { field: "sentence", label: "영어 예문" }, { field: "translation", label: "한국어 뜻" }, { field: "targetExplanation", label: "목표 어법 설명" }, ] as const; + export function ExampleCandidateCard({ id, number }: { id: string; number: number }) { const formId = useId(); const candidate = useExamples((s) => s.candidates.find((candidate) => candidate.id === id)); @@ -16,7 +19,9 @@ export function ExampleCandidateCard({ id, number }: { id: string; number: numbe const change = useExamples((s) => s.change); const select = useExamples((s) => s.select); const generate = useExamples((s) => s.generate); + if (!candidate) return null; + return (
diff --git a/src/features/grammar-example-generation/ui/ExampleCandidates.tsx b/src/features/grammar-example-generation/ui/ExampleCandidates.tsx index 392d98be..42e5f2ce 100644 --- a/src/features/grammar-example-generation/ui/ExampleCandidates.tsx +++ b/src/features/grammar-example-generation/ui/ExampleCandidates.tsx @@ -1,9 +1,12 @@ "use client"; + import { useShallow } from "zustand/react/shallow"; import { useExamples } from "./ExampleProvider"; import { ExampleCandidateCard } from "./ExampleCandidateCard"; + export function ExampleCandidates() { const ids = useExamples(useShallow((s) => s.candidates.map((candidate) => candidate.id))); + return (
{ids.map((id, index) => ( diff --git a/src/features/grammar-example-generation/ui/ExampleProvider.tsx b/src/features/grammar-example-generation/ui/ExampleProvider.tsx index 54880e88..51e50baf 100644 --- a/src/features/grammar-example-generation/ui/ExampleProvider.tsx +++ b/src/features/grammar-example-generation/ui/ExampleProvider.tsx @@ -1,25 +1,46 @@ "use client"; -import { createContext, useContext, useEffect, useRef, useState, type ReactNode } from "react"; + +import { + createContext, + useContext, + useEffect, + useLayoutEffect, + useRef, + useState, + type ReactNode, +} from "react"; import { useStore, type StoreApi } from "zustand"; import type { ExampleState, GrammarExampleManagerProps } from "../models/interface"; import { createExampleStore } from "../services/createExampleStore"; + const Context = createContext | null>(null); + export function ExampleProvider({ children, - ...props + note, + generate, + save, + onUpdated, + onBack, }: GrammarExampleManagerProps & { children: ReactNode }) { - const latest = useRef(props); - useEffect(() => { - latest.current = props; - }, [props]); + const latest = useRef({ generate, save, onUpdated }); + + useLayoutEffect(() => { + latest.current = { generate, save, onUpdated }; + }, [generate, save, onUpdated]); const [store] = useState(() => createExampleStore({ - ...props, + note, + onBack, + generate: (command) => latest.current.generate(command), + save: (command) => latest.current.save(command), + onUpdated: (note) => latest.current.onUpdated(note), }), ); + useEffect(() => () => store.getState().cancel(), [store]); useEffect(() => { function beforeUnload(event: BeforeUnloadEvent) { @@ -28,13 +49,19 @@ export function ExampleProvider({ event.returnValue = ""; } } + window.addEventListener("beforeunload", beforeUnload); + return () => window.removeEventListener("beforeunload", beforeUnload); }, [store]); + return {children}; } + export function useExamples(selector: (state: ExampleState) => T) { const store = useContext(Context); + if (!store) throw new Error("ExampleProvider가 필요합니다."); + return useStore(store, selector); } diff --git a/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx b/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx index 023efd3c..ffbe1e9e 100644 --- a/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx +++ b/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx @@ -1,4 +1,5 @@ "use client"; + import { useState } from "react"; import { Button } from "@/shared/components/atomics/button/Button"; import { ConfirmDialog } from "@/shared/components/ui/ConfirmDialog"; @@ -6,15 +7,18 @@ import type { GrammarExampleManagerProps } from "../models/interface"; import { ExampleProvider, useExamples } from "./ExampleProvider"; import { ExampleCandidates } from "./ExampleCandidates"; import { ExampleActions } from "./ExampleActions"; + function ExampleBack({ onBack }: { onBack?: () => void }) { const [confirm, setConfirm] = useState(false); const dirty = useExamples((s) => s.dirty); const saving = useExamples((s) => s.pending === "save"); const discard = useExamples((s) => s.discard); + function leave() { discard(); onBack?.(); } + return ( <> + + +
+ ); +} diff --git a/src/views/grammar-library/ui/GrammarNoteList.tsx b/src/views/grammar-library/ui/GrammarNoteList.tsx new file mode 100644 index 00000000..de247cd1 --- /dev/null +++ b/src/views/grammar-library/ui/GrammarNoteList.tsx @@ -0,0 +1,80 @@ +import Link from "next/link"; +import type { GrammarNoteListProps } from "../models/interface"; +import { grammarLibraryHref } from "../services/libraryQuery"; +import { getPaginationItems } from "@/shared/utils/pagination"; + +export function GrammarNoteList({ data, query }: GrammarNoteListProps) { + const returnTo = grammarLibraryHref({ page: data.page, query }); + const pages = Math.max(1, Math.ceil(data.total / data.pageSize)); + + return ( +
+

{data.total}개의 어법 노트

+ {data.items.length === 0 ? ( +
+

+ {query ? "검색 결과가 없습니다" : "첫 어법 노트를 만들어보세요"} +

+

+ {query + ? "다른 제목이나 문장으로 검색해보세요." + : "배운 문장과 핵심 어법을 기록하고 연습하세요."} +

+
+ ) : ( +
    + {data.items.map((note) => ( +
  • + +
    +

    {note.title}

    + + → + +
    +

    {note.sentence}

    +
    + {note.tags.map((tag) => ( + + {tag} + + ))} +
    + +
  • + ))} +
+ )} + {pages > 1 && ( + + )} +
+ ); +}