diff --git a/src/_storybook/features/grammar-audio/GrammarAudioButton.stories.tsx b/src/_storybook/features/grammar-audio/GrammarAudioButton.stories.tsx index 1007f167..eab2190f 100644 --- a/src/_storybook/features/grammar-audio/GrammarAudioButton.stories.tsx +++ b/src/_storybook/features/grammar-audio/GrammarAudioButton.stories.tsx @@ -1,19 +1,24 @@ import type { Meta, StoryObj } from "@storybook/nextjs-vite"; import { expect, fn, userEvent, within } from "storybook/test"; import { GrammarAudioButton } from "@/features/grammar-audio"; + const meta = { title: "Features/Grammar/Audio", component: GrammarAudioButton, args: { input: { noteId: "note", sentenceId: "source", noteVersion: 1 }, - generate: fn(async () => ({ ok: false as const, message: "음성 생성에 실패했습니다." })), + generate: fn(async () => ({ ok: false as const, code: "GENERATION_FAILED" as const })), }, } satisfies Meta; + export default meta; + type Story = StoryObj; + export const GenerateFailure: Story = { play: async ({ canvasElement, args }) => { const canvas = within(canvasElement); + await userEvent.click(canvas.getByRole("button", { name: "문장 듣기" })); await expect(canvas.getByRole("alert")).toHaveTextContent("음성 생성에 실패"); await userEvent.click(canvas.getByRole("button", { name: "음성 다시 생성" })); 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/features/grammar-recall/GrammarRecall.stories.tsx b/src/_storybook/features/grammar-recall/GrammarRecall.stories.tsx new file mode 100644 index 00000000..dfd59330 --- /dev/null +++ b/src/_storybook/features/grammar-recall/GrammarRecall.stories.tsx @@ -0,0 +1,53 @@ +import type { Meta, StoryObj } from "@storybook/nextjs-vite"; +import { expect, fn, userEvent, waitFor, within } from "storybook/test"; +import { GrammarRecall, RecallSession } from "@/features/grammar-recall"; +import { recallSession } from "@/_tests/features/grammar-recall/fixture"; + +const meta = { + title: "Features/Grammar/Recall", + component: RecallSession, + render: (args) => ( + + + + ), + args: { + initialSession: recallSession(), + save: fn(async () => ({ + ok: false as const, + code: "FAILED" as const, + })), + complete: fn(async () => ({ ok: false as const, code: "FAILED" as const })), + onComplete: fn(), + onExit: fn(), + }, + + beforeEach: () => { + sessionStorage.clear(); + }, +} satisfies Meta; + +export default meta; + +type Story = StoryObj; + +export const Partial: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + + await userEvent.type(canvas.getByLabelText("이다"), "is"); + await userEvent.tab(); + await expect(canvas.getByLabelText("교사가 아니라 의사")).toHaveFocus(); + await userEvent.type( + canvas.getByLabelText("교사가 아니라 의사"), + "not a teacher but a doctor.", + ); + await expect(canvas.queryByText("She is not a teacher but a doctor.")).not.toBeInTheDocument(); + await userEvent.click(canvas.getByRole("button", { name: "정답 보기" })); + await waitFor(() => + expect(canvas.getByText("She is not a teacher but a doctor.")).toBeVisible(), + ); + }, +}; + +export const Whole: Story = { args: { initialSession: { ...recallSession(), phase: "whole" } } }; diff --git a/src/_storybook/views/grammar-library/GrammarNoteList.stories.tsx b/src/_storybook/views/grammar-library/GrammarNoteList.stories.tsx index f87f370f..c013cd94 100644 --- a/src/_storybook/views/grammar-library/GrammarNoteList.stories.tsx +++ b/src/_storybook/views/grammar-library/GrammarNoteList.stories.tsx @@ -1,19 +1,25 @@ 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", @@ -35,8 +41,10 @@ export const Notes: Story = { ], }, }, + 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"), diff --git a/src/_tests/app/grammar/GrammarEditorClient.test.tsx b/src/_tests/app/grammar/GrammarEditorClient.test.tsx new file mode 100644 index 00000000..561f0428 --- /dev/null +++ b/src/_tests/app/grammar/GrammarEditorClient.test.tsx @@ -0,0 +1,71 @@ +import { beforeEach, describe, expect, it, jest } from "@jest/globals"; +import { fireEvent, render, screen } from "@testing-library/react"; +import type { useRouter } from "next/navigation"; +import type { GrammarNoteEditorProps } from "@/features/grammar-note-editor"; +import { createEditorNote } from "@/_tests/features/grammar-note-editor/fixtures"; + +jest.mock("next/navigation", () => ({ useRouter: jest.fn() })); +jest.mock("@/features/grammar-analysis-edit", () => ({ GrammarAnalysisEditor: () => null })); +jest.mock("@/features/grammar-analysis/services/actions/requestGrammarAnalysis", () => ({ + requestGrammarAnalysis: jest.fn(), +})); +jest.mock("@/features/grammar-note-editor/services/actions/saveGrammarNote", () => ({ + saveGrammarNote: jest.fn(), +})); +jest.mock("@/features/grammar-note-editor", () => ({ + GrammarNoteEditor: ({ onSaved, onExit }: GrammarNoteEditorProps) => ( + <> + + + + ), +})); + +const push = jest.fn["push"]>(); +const refresh = jest.fn["refresh"]>(); + +beforeEach(async () => { + const { useRouter } = await import("next/navigation"); + jest.clearAllMocks(); + jest.mocked(useRouter).mockReturnValue({ + push, + refresh, + back: jest.fn(), + forward: jest.fn(), + replace: jest.fn(), + prefetch: jest.fn(), + }); +}); + +describe("editor route navigation", () => { + it("opens the saved note with the list context and refreshes server data", async () => { + const { GrammarEditorClient } = + await import("@/app/(protected)/grammar/_components/GrammarEditorClient"); + render(); + fireEvent.click(screen.getByRole("button", { name: "저장 성공" })); + expect(push).toHaveBeenCalledWith( + `/grammar/${createEditorNote().id}?returnTo=%2Fgrammar%3Fq%3Dcontrast%26page%3D2`, + ); + expect(refresh).toHaveBeenCalledTimes(1); + }); + + it("returns from a new note to the filtered list", async () => { + const { GrammarEditorClient } = + await import("@/app/(protected)/grammar/_components/GrammarEditorClient"); + render(); + fireEvent.click(screen.getByRole("button", { name: "나가기" })); + expect(push).toHaveBeenCalledWith("/grammar?q=contrast&page=2"); + expect(refresh).not.toHaveBeenCalled(); + }); + + it.each([undefined, "https://example.com", "/grammar/other"])( + "falls back to the list for an absent or invalid return path: %s", + async (backHref) => { + const { GrammarEditorClient } = + await import("@/app/(protected)/grammar/_components/GrammarEditorClient"); + render(); + fireEvent.click(screen.getByRole("button", { name: "나가기" })); + expect(push).toHaveBeenCalledWith("/grammar"); + }, + ); +}); 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-audio/audio.test.ts b/src/_tests/features/grammar-audio/audio.test.ts index 74ea98fe..d5843c66 100644 --- a/src/_tests/features/grammar-audio/audio.test.ts +++ b/src/_tests/features/grammar-audio/audio.test.ts @@ -3,6 +3,7 @@ import type { GrammarNote } from "@/entities/grammar-note"; import { createGrammarAnalysis } from "@/_tests/fixtures/grammarAnalysis"; import { resolveGrammarAudioText } from "@/features/grammar-audio/services/resolveGrammarAudioText"; import { claimGrammarPlayback } from "@/features/grammar-audio/services/playbackCoordinator"; + const note: GrammarNote = { id: "note", ownerId: "owner", @@ -26,6 +27,7 @@ const note: GrammarNote = { }, ], }; + describe("saved grammar audio", () => { it("resolves only source or adopted saved examples", () => { expect( @@ -35,6 +37,7 @@ describe("saved grammar audio", () => { resolveGrammarAudioText(note, { noteId: "note", sentenceId: "example", noteVersion: 2 }), ).toBe(note.examples[0].sentence); }); + it("rejects stale versions, missing notes, unreviewed and arbitrary sentences", () => { expect(() => resolveGrammarAudioText(note, { noteId: "note", sentenceId: "source", noteVersion: 1 }), @@ -52,14 +55,17 @@ describe("saved grammar audio", () => { ), ).toThrow(); }); + it("stops the current player when another sentence claims playback", () => { const first = jest.fn(), second = jest.fn(); const releaseFirst = claimGrammarPlayback(first); const releaseSecond = claimGrammarPlayback(second); + expect(first).toHaveBeenCalledTimes(1); releaseFirst(); const releaseThird = claimGrammarPlayback(jest.fn()); + expect(second).toHaveBeenCalledTimes(1); releaseSecond(); releaseThird(); diff --git a/src/_tests/features/grammar-audio/audioCache.test.ts b/src/_tests/features/grammar-audio/audioCache.test.ts index 11fc7bac..4e02c799 100644 --- a/src/_tests/features/grammar-audio/audioCache.test.ts +++ b/src/_tests/features/grammar-audio/audioCache.test.ts @@ -1,18 +1,26 @@ /** @jest-environment node */ import { describe, it, expect, jest } from "@jest/globals"; + jest.mock("server-only", () => ({})); + describe("grammar audio content cache", () => { it("isolates owner and invalidates text or model changes", async () => { const { grammarAudioCacheKey: key } = await import("@/features/grammar-audio/services/audioCache"); const original = key("owner", "sentence", "model"); + expect(key("other", "sentence", "model")).not.toBe(original); expect(key("owner", "edited", "model")).not.toBe(original); expect(key("owner", "sentence", "new-model")).not.toBe(original); }); + it("deduplicates concurrent generation and does not cache failure", async () => { const { cachedGrammarAudio } = await import("@/features/grammar-audio/services/audioCache"); - const generate = jest.fn(async () => ({ ok: false as const, message: "failed" })); + const generate = jest.fn(async () => ({ + ok: false as const, + code: "GENERATION_FAILED" as const, + })); + await Promise.all([ cachedGrammarAudio("unique", generate), cachedGrammarAudio("unique", generate), diff --git a/src/_tests/features/grammar-audio/requestGrammarAudio.test.ts b/src/_tests/features/grammar-audio/requestGrammarAudio.test.ts index 2704b929..9c68aea6 100644 --- a/src/_tests/features/grammar-audio/requestGrammarAudio.test.ts +++ b/src/_tests/features/grammar-audio/requestGrammarAudio.test.ts @@ -3,10 +3,15 @@ import { beforeEach, describe, expect, it, jest } from "@jest/globals"; import type { OpenAITTSProvider } from "@/shared/lib/tts/server"; import type { GrammarNote } from "@/entities/grammar-note"; import { createGrammarAnalysis } from "@/_tests/fixtures/grammarAnalysis"; + jest.mock("server-only", () => ({})); + jest.mock("@/shared/lib/supabase/server", () => ({ createSupabaseServerClient: jest.fn() })); + jest.mock("@/shared/lib/logging/pino", () => ({ recordOperationEvent: jest.fn() })); + jest.mock("@/shared/lib/openai/server", () => ({ getOpenAITTSModel: () => "tts-test" })); + jest.mock("@/shared/lib/tts/server", () => ({ OpenAITTSProvider: jest.fn().mockImplementation(() => ({ speak: jest.fn(async () => ({ @@ -17,11 +22,13 @@ jest.mock("@/shared/lib/tts/server", () => ({ })), })), })); + const input = { noteId: "00000000-0000-4000-8000-000000000001", sentenceId: "source", noteVersion: 1, }; + const note: GrammarNote = { id: input.noteId, ownerId: "owner", @@ -37,6 +44,7 @@ const note: GrammarNote = { analysis: createGrammarAnalysis(), examples: [], }; + async function dependencies() { const { createSupabaseServerClient } = await import("@/shared/lib/supabase/server"); const { GrammarNoteRepository } = await import("@/entities/grammar-note"); @@ -45,47 +53,70 @@ async function dependencies() { await import("@/features/grammar-audio/services/actions/requestGrammarAudio"); const getUser = jest.fn(async () => ({ data: { user: { id: "audio-owner" } }, error: null })); const rpc = jest.fn(async () => ({ data: "allowed", error: null })); + jest .mocked(createSupabaseServerClient) .mockResolvedValue({ auth: { getUser }, rpc } as unknown as Awaited< ReturnType >); const findById = jest.spyOn(GrammarNoteRepository.prototype, "findById").mockResolvedValue(note); + return { requestGrammarAudio, getUser, rpc, findById, OpenAITTSProvider }; } + describe("authenticated saved sentence audio action", () => { beforeEach(() => { jest.clearAllMocks(); }); + it("rejects unauthenticated requests before loading notes or spending quota", async () => { const deps = await dependencies(); + deps.getUser.mockResolvedValueOnce({ data: { user: null }, error: null } as unknown as Awaited< ReturnType >); - expect((await deps.requestGrammarAudio(input)).ok).toBe(false); + expect(await deps.requestGrammarAudio(input)).toEqual({ ok: false, code: "UNAUTHORIZED" }); expect(deps.findById).not.toHaveBeenCalled(); expect(deps.rpc).not.toHaveBeenCalled(); expect(deps.OpenAITTSProvider).not.toHaveBeenCalled(); }); + it("rejects unowned notes and stale revisions before quota or provider", async () => { const deps = await dependencies(); + deps.findById.mockResolvedValueOnce(null); expect((await deps.requestGrammarAudio(input)).ok).toBe(false); expect((await deps.requestGrammarAudio({ ...input, noteVersion: 2 })).ok).toBe(false); expect(deps.rpc).not.toHaveBeenCalled(); expect(deps.OpenAITTSProvider).not.toHaveBeenCalled(); }); + it("rejects arbitrary client text and exhausted quota without generating", async () => { const deps = await dependencies(); + expect((await deps.requestGrammarAudio({ ...input, text: "untrusted" })).ok).toBe(false); deps.rpc.mockResolvedValueOnce({ data: "rate_limited", error: null }); expect((await deps.requestGrammarAudio(input)).ok).toBe(false); expect(deps.OpenAITTSProvider).not.toHaveBeenCalled(); }); + + it.each([ + ["not_invited", "NOT_INVITED"], + ["rate_limited", "RATE_LIMITED"], + ["unexpected", "GENERATION_FAILED"], + ])("returns %s as a code without spending provider cost", async (permission, code) => { + const deps = await dependencies(); + + deps.rpc.mockResolvedValueOnce({ data: permission, error: null }); + expect(await deps.requestGrammarAudio(input)).toEqual({ ok: false, code }); + expect(deps.OpenAITTSProvider).not.toHaveBeenCalled(); + }); + it("reuses authenticated content cache and sends only stored text to TTS", async () => { const deps = await dependencies(); const first = await deps.requestGrammarAudio(input); const second = await deps.requestGrammarAudio(input); + expect(first.ok).toBe(true); expect(second).toEqual(first); expect(deps.findById).toHaveBeenCalledTimes(2); @@ -95,6 +126,7 @@ describe("authenticated saved sentence audio action", () => { OpenAITTSProvider, "speak" >; + expect(instance.speak).toHaveBeenCalledWith({ text: note.source.sentence, voice: "alloy", diff --git a/src/_tests/features/grammar-audio/useGrammarAudio.test.tsx b/src/_tests/features/grammar-audio/useGrammarAudio.test.tsx index c05c0752..c54ed69e 100644 --- a/src/_tests/features/grammar-audio/useGrammarAudio.test.tsx +++ b/src/_tests/features/grammar-audio/useGrammarAudio.test.tsx @@ -2,17 +2,22 @@ import { describe, it, expect, jest, beforeEach, afterEach } from "@jest/globals import { act, renderHook } from "@testing-library/react"; import { useGrammarAudio } from "@/features/grammar-audio/services/useGrammarAudio"; import type { GrammarAudioResult } from "@/features/grammar-audio"; + const input = { noteId: "note", sentenceId: "source", noteVersion: 1 }; + const speech = { ok: true as const, audioBase64: "audio", mimeType: "audio/mpeg" as const, cacheKey: "key", }; + const originalAudio = globalThis.Audio; + describe("grammar audio lifecycle", () => { const play = jest.fn<() => Promise>(); const pause = jest.fn(); + beforeEach(() => { play.mockReset().mockResolvedValue(); pause.mockReset(); @@ -26,28 +31,33 @@ describe("grammar audio lifecycle", () => { afterEach(() => { globalThis.Audio = originalAudio; }); + it("retries playback using generated audio without another generation", async () => { play.mockRejectedValueOnce(new Error("blocked")); const generate = jest.fn<() => Promise>().mockResolvedValue(speech); const { result } = renderHook(() => useGrammarAudio({ input, generate })); + await act(() => result.current.play()); expect(result.current.status).toBe("playback-error"); await act(() => result.current.play()); expect(result.current.status).toBe("playing"); expect(generate).toHaveBeenCalledTimes(1); }); + it("invalidates audio after a saved note version change", async () => { const generate = jest.fn<() => Promise>().mockResolvedValue(speech); const { result, rerender } = renderHook( ({ version }) => useGrammarAudio({ input: { ...input, noteVersion: version }, generate }), { initialProps: { version: 1 } }, ); + await act(() => result.current.play()); rerender({ version: 2 }); expect(pause).toHaveBeenCalled(); await act(() => result.current.play()); expect(generate).toHaveBeenCalledTimes(2); }); + it("ignores generation that finishes after unmount", async () => { let resolve!: (value: GrammarAudioResult) => void; const generate = () => @@ -56,6 +66,7 @@ describe("grammar audio lifecycle", () => { }); const { result, unmount } = renderHook(() => useGrammarAudio({ input, generate })); let pending!: Promise; + act(() => { pending = result.current.play(); }); @@ -66,14 +77,17 @@ describe("grammar audio lifecycle", () => { }); expect(play).not.toHaveBeenCalled(); }); + it("retries generation failure rather than treating it as playback failure", async () => { const generate = jest .fn<() => Promise>() - .mockResolvedValueOnce({ ok: false, message: "failed" }) + .mockResolvedValueOnce({ ok: false, code: "GENERATION_FAILED" }) .mockResolvedValueOnce(speech); const { result } = renderHook(() => useGrammarAudio({ input, generate })); + await act(() => result.current.play()); expect(result.current.status).toBe("generation-error"); + expect(result.current.error).toBe("GENERATION_FAILED"); await act(() => result.current.play()); expect(result.current.status).toBe("playing"); expect(generate).toHaveBeenCalledTimes(2); 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/features/grammar-practice/grammarSessionActions.test.ts b/src/_tests/features/grammar-practice/grammarSessionActions.test.ts new file mode 100644 index 00000000..e0f0d58f --- /dev/null +++ b/src/_tests/features/grammar-practice/grammarSessionActions.test.ts @@ -0,0 +1,42 @@ +/** @jest-environment node */ +import { beforeEach, describe, expect, it, jest } from "@jest/globals"; +import { GrammarSessionRepository } from "@/entities/grammar-session"; +import type { createSupabaseServerClient as CreateClient } from "@/shared/lib/supabase/server"; +import type { startGrammarSession as StartSession } from "@/features/grammar-practice/services/actions/grammarSessionActions"; + +jest.mock("server-only", () => ({})); + +jest.mock("@/shared/lib/supabase/server", () => ({ createSupabaseServerClient: jest.fn() })); + +jest.mock("@/shared/lib/logging/pino", () => ({ recordOperationEvent: jest.fn() })); + +let createSupabaseServerClient: typeof CreateClient; + +let startGrammarSession: typeof StartSession; + +beforeEach(async () => { + ({ createSupabaseServerClient } = await import("@/shared/lib/supabase/server")); + ({ startGrammarSession } = + await import("@/features/grammar-practice/services/actions/grammarSessionActions")); + jest.clearAllMocks(); +}); + +describe("연습 액션 오류 계약", () => { + it("비로그인은 저장소를 호출하지 않고 UI 문구 대신 권한 코드를 반환한다", async () => { + jest.mocked(createSupabaseServerClient).mockResolvedValue({ + auth: { getUser: async () => ({ data: { user: null }, error: null }) }, + } as never); + const start = jest.spyOn(GrammarSessionRepository.prototype, "start"); + + expect(await startGrammarSession({})).toEqual({ ok: false, code: "UNAUTHORIZED" }); + expect(start).not.toHaveBeenCalled(); + start.mockRestore(); + }); + + it("알 수 없는 내부 오류는 응답에 노출하지 않는다", async () => { + jest + .mocked(createSupabaseServerClient) + .mockRejectedValue(new Error("secret connection details")); + expect(await startGrammarSession({})).toEqual({ ok: false, code: "FAILED" }); + }); +}); diff --git a/src/_tests/features/grammar-recall/GrammarRecall.test.tsx b/src/_tests/features/grammar-recall/GrammarRecall.test.tsx new file mode 100644 index 00000000..b96e48d0 --- /dev/null +++ b/src/_tests/features/grammar-recall/GrammarRecall.test.tsx @@ -0,0 +1,140 @@ +import { describe, it, expect, jest, beforeEach } from "@jest/globals"; +import { render, screen, fireEvent, waitFor } from "@testing-library/react"; +import { RecallSession } from "@/features/grammar-recall"; +import type { SaveGrammarAnswersInput } from "@/entities/grammar-session"; +import type { RecallActionResult } from "@/features/grammar-recall"; +import { recallSession } from "./fixture"; + +describe("recall workflow", () => { + beforeEach(() => sessionStorage.clear()); + + it("does not expose the whole answer before reveal and keeps typed input after save failure", async () => { + const session = { ...recallSession(), phase: "whole" as const }; + const save = jest + .fn<() => Promise>() + .mockResolvedValue({ ok: false, code: "FAILED" as const }); + + render( + Promise>()} + onComplete={jest.fn()} + onExit={jest.fn()} + />, + ); + expect(screen.queryByText(session.questions[0].sentence!)).not.toBeInTheDocument(); + fireEvent.change(screen.getByRole("textbox"), { target: { value: "My own answer." } }); + fireEvent.click(screen.getByRole("button", { name: "정답 보기" })); + fireEvent.click(screen.getByRole("radio", { name: "다시 볼게요" })); + fireEvent.click(screen.getByRole("button", { name: "연습 완료" })); + await waitFor(() => + expect(screen.getByRole("alert")).toHaveTextContent("연습을 저장하지 못했습니다"), + ); + expect(screen.getByRole("textbox")).toHaveValue("My own answer."); + expect(save).toHaveBeenCalledWith( + expect.objectContaining({ + answers: expect.objectContaining({ "whole:source": "My own answer." }), + }), + ); + }); + + it("saves before exiting and remains on page when saving fails", async () => { + const exit = jest.fn(); + const save = jest + .fn<() => Promise>() + .mockResolvedValue({ ok: false, code: "FAILED" as const }); + + render( + Promise>()} + onComplete={jest.fn()} + onExit={exit} + />, + ); + fireEvent.change(screen.getByLabelText("이다"), { target: { value: "is" } }); + fireEvent.click(screen.getByRole("button", { name: "저장하고 노트로" })); + await waitFor(() => expect(screen.getByRole("alert")).toBeVisible()); + expect(exit).not.toHaveBeenCalled(); + expect(screen.getByLabelText("이다")).toHaveValue("is"); + }); + + it("preserves both phase answers when returning and completes only after saving", async () => { + const session = recallSession(); + const save = jest + .fn<(input: SaveGrammarAnswersInput) => Promise>() + .mockImplementation(async (input) => ({ + ok: true, + data: { + ...session, + answers: input.answers, + phase: input.phase, + questionIndex: input.questionIndex, + version: input.expectedVersion + 1, + }, + })); + const completed = { + ...session, + status: "completed" as const, + completedAt: "2026-10-01T01:00:00Z", + }; + const complete = jest + .fn<() => Promise>() + .mockResolvedValue({ ok: true, data: completed }); + const onComplete = jest.fn(); + + render( + , + ); + fireEvent.change(screen.getByLabelText("이다"), { target: { value: "is" } }); + fireEvent.change(screen.getByLabelText("교사가 아니라 의사"), { + target: { value: "not a teacher but a doctor." }, + }); + fireEvent.click(screen.getByRole("button", { name: "정답 보기" })); + fireEvent.click(screen.getByRole("radio", { name: "기억했어요" })); + fireEvent.click(screen.getByRole("button", { name: "다음" })); + const whole = await screen.findByRole("textbox", { name: "영어 문장을 작성해주세요" }); + + fireEvent.change(whole, { target: { value: "She is not a teacher but a doctor." } }); + fireEvent.click(screen.getByRole("button", { name: "이전" })); + await waitFor(() => expect(screen.getByLabelText("이다")).toHaveValue("is")); + expect(screen.getByLabelText("교사가 아니라 의사")).toHaveValue("not a teacher but a doctor."); + fireEvent.click(screen.getByRole("button", { name: "정답 보기" })); + fireEvent.click(screen.getByRole("button", { name: "다음" })); + await waitFor(() => + expect(screen.getByRole("textbox")).toHaveValue("She is not a teacher but a doctor."), + ); + fireEvent.click(screen.getByRole("button", { name: "정답 보기" })); + fireEvent.click(screen.getByRole("button", { name: "연습 완료" })); + await waitFor(() => expect(onComplete).toHaveBeenCalledWith(completed)); + expect(complete).toHaveBeenCalledTimes(1); + expect(save.mock.calls.at(-1)?.[0].answers).toEqual( + expect.objectContaining({ "whole:source": "She is not a teacher but a doctor." }), + ); + }); +}); + +it("preserves a same-session draft and resets when opening a different session", () => { + const session = { ...recallSession(), phase: "whole" as const }; + const props = { + save: jest.fn<() => Promise>(), + complete: jest.fn<() => Promise>(), + onComplete: jest.fn(), + onExit: jest.fn(), + }; + const { rerender } = render(); + + fireEvent.change(screen.getByRole("textbox"), { target: { value: "My draft" } }); + rerender(); + expect(screen.getByRole("textbox")).toHaveValue("My draft"); + rerender(); + expect(screen.getByRole("textbox")).toHaveValue(""); +}); diff --git a/src/_tests/features/grammar-recall/fixture.ts b/src/_tests/features/grammar-recall/fixture.ts new file mode 100644 index 00000000..dc8110eb --- /dev/null +++ b/src/_tests/features/grammar-recall/fixture.ts @@ -0,0 +1,34 @@ +import type { GrammarSession } from "@/entities/grammar-session"; + +export function recallSession(): GrammarSession { + return { + id: "00000000-0000-4000-8000-000000000001", + noteId: "00000000-0000-4000-8000-000000000002", + noteVersion: 1, + title: "not A but B", + learningNote: "A가 아니라 B", + mode: "recall", + status: "active", + questions: [ + { + id: "source", + kind: "existing", + sentence: "She is not a teacher but a doctor.", + translation: "그녀는 교사가 아니라 의사입니다.", + context: "", + requiredWords: [], + chunks: [ + { id: "subject", start: 0, end: 4, meaning: "그녀는" }, + { id: "verb", start: 4, end: 7, meaning: "이다" }, + { id: "contrast", start: 7, end: 34, meaning: "교사가 아니라 의사" }, + ], + }, + ], + answers: {}, + phase: "partial", + questionIndex: 0, + version: 1, + startedAt: "2026-10-01T00:00:00Z", + completedAt: null, + }; +} diff --git a/src/_tests/features/grammar-recall/recallDraft.test.ts b/src/_tests/features/grammar-recall/recallDraft.test.ts new file mode 100644 index 00000000..8ad20a8b --- /dev/null +++ b/src/_tests/features/grammar-recall/recallDraft.test.ts @@ -0,0 +1,54 @@ +import { describe, it, expect, beforeEach } from "@jest/globals"; +import { recallSession } from "./fixture"; +import { + createRecallSegments, + readRecallDraft, + persistRecallDraft, + mergeRecallDraftIntoAnswers, +} from "@/features/grammar-recall/services/recallDraft"; + +describe("recall drafts and semantic blanks", () => { + beforeEach(() => sessionStorage.clear()); + + it("uses stable semantic chunks without losing whitespace or punctuation", () => { + const question = recallSession().questions[0]; + const segments = createRecallSegments(question); + + expect(segments.map((s) => s.text).join("")).toBe(question.sentence); + expect(segments.filter((s) => s.hidden).map((s) => s.id)).toEqual(["verb", "contrast"]); + }); + + it("uses whole sentence recall when an example has no verified chunks", () => { + const question = { ...recallSession().questions[0], chunks: [] }; + + expect(createRecallSegments(question)).toEqual([ + { id: "source-whole", text: question.sentence, meaning: question.translation, hidden: true }, + ]); + }); + + it("restores unsent input on refresh but discards draft from a different saved revision", () => { + const session = recallSession(); + const draft = { values: { contrast: "my answer" }, whole: "", assessment: null }; + + persistRecallDraft(session, draft); + expect(readRecallDraft(session)).toEqual(draft); + expect(readRecallDraft({ ...session, version: 2 }).values).toEqual({}); + }); + + it("preserves both phases and self assessment in checkpoint payload", () => { + const session = { + ...recallSession(), + phase: "whole" as const, + answers: { "partial:other": "old" }, + }; + const answers = mergeRecallDraftIntoAnswers(session, { + values: { verb: "is" }, + whole: "She is a doctor.", + assessment: "again", + }); + + expect(answers["whole:source"]).toBe("She is a doctor."); + expect(answers["partial:other"]).toBe("old"); + expect(JSON.parse(answers["partial:source"]).assessment).toBe("again"); + }); +}); 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 index 655537e0..877ddb4c 100644 --- a/src/_tests/views/grammar-library/GrammarLibraryPage.test.tsx +++ b/src/_tests/views/grammar-library/GrammarLibraryPage.test.tsx @@ -4,34 +4,43 @@ 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 index b998bac7..8d7e46db 100644 --- a/src/_tests/views/grammar-library/libraryQuery.test.ts +++ b/src/_tests/views/grammar-library/libraryQuery.test.ts @@ -3,15 +3,18 @@ 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, diff --git a/src/app/(protected)/grammar/(list)/error.tsx b/src/app/(protected)/grammar/(list)/error.tsx index 0df07d43..06b11217 100644 --- a/src/app/(protected)/grammar/(list)/error.tsx +++ b/src/app/(protected)/grammar/(list)/error.tsx @@ -1,5 +1,7 @@ "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)/page.tsx b/src/app/(protected)/grammar/(list)/page.tsx index b81fbb03..8a50782b 100644 --- a/src/app/(protected)/grammar/(list)/page.tsx +++ b/src/app/(protected)/grammar/(list)/page.tsx @@ -6,17 +6,21 @@ import { 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/app/(protected)/grammar/_components/GrammarEditorClient.tsx b/src/app/(protected)/grammar/_components/GrammarEditorClient.tsx new file mode 100644 index 00000000..a037e506 --- /dev/null +++ b/src/app/(protected)/grammar/_components/GrammarEditorClient.tsx @@ -0,0 +1,35 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import type { GrammarNote } from "@/entities/grammar-note"; +import { GrammarAnalysisEditor } from "@/features/grammar-analysis-edit"; +import { requestGrammarAnalysis } from "@/features/grammar-analysis/services/actions/requestGrammarAnalysis"; +import { GrammarNoteEditor } from "@/features/grammar-note-editor"; +import { saveGrammarNote } from "@/features/grammar-note-editor/services/actions/saveGrammarNote"; + +export function GrammarEditorClient({ + initialNote, + backHref = "/grammar", +}: { + initialNote?: GrammarNote; + backHref?: string; +}) { + const router = useRouter(); + const returnTo = + backHref === "/grammar" || backHref.startsWith("/grammar?") ? backHref : "/grammar"; + + return ( + { + router.push(`/grammar/${note.id}?returnTo=${encodeURIComponent(returnTo)}`); + router.refresh(); + }} + onExit={() => router.push(returnTo)} + /> + ); +} diff --git a/src/app/(protected)/grammar/new/page.tsx b/src/app/(protected)/grammar/new/page.tsx index c2550834..960bfa74 100644 --- a/src/app/(protected)/grammar/new/page.tsx +++ b/src/app/(protected)/grammar/new/page.tsx @@ -1,5 +1,7 @@ import { PageContainer } from "@/widgets/app-shell"; import { GrammarEditorView } from "@/views/grammar-editor"; +import { GrammarEditorClient } from "../_components/GrammarEditorClient"; + export default async function NewGrammarNotePage({ searchParams, }: { @@ -8,7 +10,9 @@ export default async function NewGrammarNotePage({ const { returnTo } = await searchParams; return ( - + + + ); } diff --git a/src/entities/grammar-session/index.ts b/src/entities/grammar-session/index.ts index 8e8eb9af..29050567 100644 --- a/src/entities/grammar-session/index.ts +++ b/src/entities/grammar-session/index.ts @@ -7,6 +7,7 @@ export type { SaveGrammarAnswersInput, CompleteGrammarSessionInput, } from "./models/schema"; + export { grammarSessionSchema, grammarQuestionSchema, @@ -14,11 +15,16 @@ export { saveGrammarAnswersSchema, completeGrammarSessionSchema, } from "./models/schema"; + export type { GrammarSessionRepositoryPort, GrammarSessionHistoryInput, GrammarSessionHistory, GrammarSessionSummary, } from "./models/repository"; + export { GrammarSessionRepository } from "./infrastructure/GrammarSessionRepository"; -export { GrammarSessionError, grammarSessionErrorMessage } from "./models/errors"; + +export { GrammarSessionError } from "./models/errors"; + +export { grammarSessionErrorMessage } from "./ui/errorMessage"; diff --git a/src/entities/grammar-session/infrastructure/GrammarSessionRepository.ts b/src/entities/grammar-session/infrastructure/GrammarSessionRepository.ts index a160b9d2..81bbfe91 100644 --- a/src/entities/grammar-session/infrastructure/GrammarSessionRepository.ts +++ b/src/entities/grammar-session/infrastructure/GrammarSessionRepository.ts @@ -25,12 +25,14 @@ import type { /** 모든 호출은 사용자 세션 client로 수행하고 소유권은 DB가 확인합니다. */ export class GrammarSessionRepository implements GrammarSessionRepositoryPort { constructor(private readonly supabase: SupabaseClient) {} + private async request( operation: () => PromiseLike<{ data: unknown; error: { message: string } | null }>, mapResponse: (data: unknown) => T, ): Promise { try { const result = await operation(); + if (result.error) { const codes = [ "UNAUTHORIZED", @@ -39,19 +41,24 @@ export class GrammarSessionRepository implements GrammarSessionRepositoryPort { "INCOMPLETE", "INVALID_INPUT", ] as const; + throw new GrammarSessionError( codes.find((code) => result.error?.message.includes(`GRAMMAR_SESSION_${code}`)) ?? "FAILED", ); } + return mapResponse(result.data); } catch (error) { if (error instanceof GrammarSessionError) throw error; + throw new GrammarSessionError("FAILED"); } } + async start(input: StartGrammarSessionInput) { const data = startGrammarSessionSchema.parse(input); + return this.request( () => this.supabase.rpc("start_grammar_session", { @@ -62,16 +69,20 @@ export class GrammarSessionRepository implements GrammarSessionRepositoryPort { mapGrammarSessionRowToEntity, ); } + async findById(id: string) { grammarSessionIdSchema.parse(id); + return this.request( () => this.supabase.from("grammar_sessions").select("*").eq("id", id).maybeSingle(), (data) => (data === null ? null : mapGrammarSessionRowToEntity(data)), ); } + async findActive(noteId: string, mode: GrammarSessionMode) { grammarSessionIdSchema.parse(noteId); grammarSessionModeSchema.parse(mode); + return this.request( () => this.supabase @@ -86,8 +97,10 @@ export class GrammarSessionRepository implements GrammarSessionRepositoryPort { (data) => (data === null ? null : mapGrammarSessionRowToEntity(data)), ); } + async saveAnswers(input: SaveGrammarAnswersInput) { const data = saveGrammarAnswersSchema.parse(input); + return this.request( () => this.supabase.rpc("save_grammar_session_answers", { @@ -100,8 +113,10 @@ export class GrammarSessionRepository implements GrammarSessionRepositoryPort { mapGrammarSessionRowToEntity, ); } + async complete(input: CompleteGrammarSessionInput) { const data = completeGrammarSessionSchema.parse(input); + return this.request( () => this.supabase.rpc("complete_grammar_session", { @@ -111,8 +126,10 @@ export class GrammarSessionRepository implements GrammarSessionRepositoryPort { mapGrammarSessionRowToEntity, ); } + async findHistory(input: GrammarSessionHistoryInput = {}) { const params = findGrammarSessionHistorySchema.parse(input); + return this.request( () => this.supabase.rpc("list_grammar_session_history", { @@ -122,12 +139,15 @@ export class GrammarSessionRepository implements GrammarSessionRepositoryPort { }), (data) => { const page = grammarSessionHistoryPageSchema.parse(data); + return { ...page, page: params.page, pageSize: params.pageSize }; }, ); } + async setExamPrompts(id: string, questions: Json) { grammarSessionIdSchema.parse(id); + return this.request( () => this.supabase.rpc("set_grammar_exam_prompts", { p_session_id: id, p_questions: questions }), diff --git a/src/entities/grammar-session/infrastructure/__tests__/GrammarSessionRepository.test.ts b/src/entities/grammar-session/infrastructure/__tests__/GrammarSessionRepository.test.ts index 649da78b..0b43a220 100644 --- a/src/entities/grammar-session/infrastructure/__tests__/GrammarSessionRepository.test.ts +++ b/src/entities/grammar-session/infrastructure/__tests__/GrammarSessionRepository.test.ts @@ -4,7 +4,9 @@ import { createClient } from "@supabase/supabase-js"; import type { Database } from "@/shared/lib/supabase/database.types"; import { GrammarSessionRepository } from "../GrammarSessionRepository"; import { mapGrammarSessionRowToEntity } from "../../models/mapper"; + const id = "11111111-1111-4111-8111-111111111111"; + function row(mode = "recall", status = "active") { return { id, @@ -32,6 +34,7 @@ function row(mode = "recall", status = "active") { completed_at: status === "completed" ? "2026-10-06T01:00:00Z" : null, }; } + function setup(data: unknown, status = 200) { const fetcher = jest.fn().mockResolvedValue( new Response(JSON.stringify(data), { @@ -43,30 +46,38 @@ function setup(data: unknown, status = 200) { auth: { persistSession: false, autoRefreshToken: false }, global: { fetch: fetcher }, }); + return { repository: new GrammarSessionRepository(client), fetcher }; } + describe("Grammar session persisted contract", () => { it("active_exam_hides_reference_sentence_and_chunks", () => { const session = mapGrammarSessionRowToEntity(row("exam")); + expect(session.questions[0].sentence).toBeNull(); expect(session.questions[0].chunks).toEqual([]); expect(session.learningNote).toBe("not A but B"); }); + it("recall_and_completed_exam_keep_frozen_reference", () => { expect(mapGrammarSessionRowToEntity(row()).questions[0].sentence).toContain("teacher"); expect(mapGrammarSessionRowToEntity(row("exam", "completed")).questions[0].sentence).toContain( "teacher", ); }); + it("resume_retains_answer_drafts_and_order", async () => { const { repository } = setup(row()); const session = await repository.findById(id); + expect(session?.answers["partial:source"]).toBe('{"c1":"She"}'); expect(session?.questions.map((q) => q.id)).toEqual(["source"]); expect(session?.noteVersion).toBe(3); }); + it("start_sends_only_note_identifier_and_request_intent", async () => { const { repository, fetcher } = setup(row()); + await repository.start({ noteId: id, requestId: id, mode: "recall" }); expect(JSON.parse(String(fetcher.mock.calls[0][1]?.body))).toEqual({ p_note_id: id, @@ -74,8 +85,10 @@ describe("Grammar session persisted contract", () => { p_mode: "recall", }); }); + it("save_sends_version_and_both_phase_drafts", async () => { const { repository, fetcher } = setup(row()); + await repository.saveAnswers({ id, expectedVersion: 4, @@ -88,30 +101,40 @@ describe("Grammar session persisted contract", () => { p_answers: { "partial:source": "{}", "whole:source": "draft" }, }); }); + it.each(["CONFLICT", "UNAUTHORIZED", "INCOMPLETE", "NOT_FOUND"])( "database_%s_preserves_actionable_error_code", async (code) => { const { repository } = setup({ message: `GRAMMAR_SESSION_${code}` }, 400); + await expect(repository.complete({ id, expectedVersion: 1 })).rejects.toMatchObject({ code }); }, ); + it("transport_failure_is_sanitized", async () => { const { repository, fetcher } = setup(row()); + fetcher.mockRejectedValue(new Error("secret")); await expect( repository.start({ noteId: id, requestId: id, mode: "recall" }), ).rejects.toMatchObject({ code: "FAILED" }); }); + it("missing_session_is_distinct_from_transport_failure", async () => { const { repository } = setup(null); + await expect(repository.findById(id)).resolves.toBeNull(); }); + it("malformed_database_question_fails_closed", async () => { const { repository } = setup({ ...row(), questions: [{ id: "bad" }] }); + await expect(repository.findById(id)).rejects.toMatchObject({ code: "FAILED" }); }); + it("history_retains_total_on_empty_page", async () => { const { repository } = setup({ items: [], total: 12 }); + await expect(repository.findHistory({ page: 3, pageSize: 10 })).resolves.toEqual({ items: [], total: 12, diff --git a/src/entities/grammar-session/models/errors.ts b/src/entities/grammar-session/models/errors.ts index 37399e03..b90b2ace 100644 --- a/src/entities/grammar-session/models/errors.ts +++ b/src/entities/grammar-session/models/errors.ts @@ -12,16 +12,3 @@ export class GrammarSessionError extends Error { this.name = "GrammarSessionError"; } } -export function grammarSessionErrorMessage(error: unknown): string { - if (!(error instanceof GrammarSessionError)) - return "연습을 저장하지 못했습니다. 잠시 후 다시 시도해 주세요."; - const messages = { - INVALID_INPUT: "연습 입력을 확인해 주세요.", - NOT_FOUND: "연습을 찾을 수 없습니다.", - CONFLICT: "다른 화면에서 연습이 변경되었습니다. 연습을 다시 열어 주세요.", - INCOMPLETE: "모든 문항에 답한 뒤 완료해 주세요.", - UNAUTHORIZED: "로그인 후 다시 시도해 주세요.", - FAILED: "연습을 저장하지 못했습니다. 잠시 후 다시 시도해 주세요.", - }; - return messages[error.code]; -} diff --git a/src/entities/grammar-session/models/mapper.ts b/src/entities/grammar-session/models/mapper.ts index 6378de5c..210a6d1b 100644 --- a/src/entities/grammar-session/models/mapper.ts +++ b/src/entities/grammar-session/models/mapper.ts @@ -18,6 +18,7 @@ export function mapGrammarSessionRowToEntity(input: unknown) { startedAt: row.started_at, completedAt: row.completed_at, }); + // UI에서 숨겨도 서버 응답에는 정답이 남으므로, 진행 중인 시험은 직렬화 전에 정답과 구간을 제거한다. if (session.mode === "exam" && session.status === "active") session.questions = session.questions.map((question) => ({ @@ -25,5 +26,6 @@ export function mapGrammarSessionRowToEntity(input: unknown) { sentence: null, chunks: [], })); + return session; } diff --git a/src/entities/grammar-session/models/repository.ts b/src/entities/grammar-session/models/repository.ts index 1af6fb79..1a846ec9 100644 --- a/src/entities/grammar-session/models/repository.ts +++ b/src/entities/grammar-session/models/repository.ts @@ -15,17 +15,20 @@ export interface GrammarSessionSummary { completedAt: string; questionCount: number; } + export interface GrammarSessionHistoryInput { noteId?: string; page?: number; pageSize?: number; } + export interface GrammarSessionHistory { items: GrammarSessionSummary[]; total: number; page: number; pageSize: number; } + export interface GrammarSessionRepositoryPort { start(input: StartGrammarSessionInput): Promise; findById(id: string): Promise; diff --git a/src/entities/grammar-session/models/schema.ts b/src/entities/grammar-session/models/schema.ts index f10cde38..c32e6465 100644 --- a/src/entities/grammar-session/models/schema.ts +++ b/src/entities/grammar-session/models/schema.ts @@ -1,9 +1,13 @@ import { z } from "zod"; const text = z.string().trim().min(1).max(4000); + export const grammarSessionModeSchema = z.enum(["recall", "exam"]); + export const grammarSessionIdSchema = z.string().uuid(); + export const grammarSessionPhaseSchema = z.enum(["partial", "whole", "existing", "novel"]); + export const grammarQuestionSchema = z.object({ id: z.string().min(1).max(120), kind: z.enum(["existing", "novel"]), @@ -22,6 +26,7 @@ export const grammarQuestionSchema = z.object({ .max(200), requiredWords: z.array(z.object({ word: text, meaning: text })).max(12), }); + export const grammarSessionSchema = z.object({ id: z.string().uuid(), noteId: z.string().uuid(), @@ -38,11 +43,13 @@ export const grammarSessionSchema = z.object({ startedAt: z.string(), completedAt: z.string().nullable(), }); + export const startGrammarSessionSchema = z.object({ noteId: z.string().uuid(), requestId: z.string().uuid(), mode: grammarSessionModeSchema, }); + export const saveGrammarAnswersSchema = z.object({ id: z.string().uuid(), expectedVersion: z.number().int().positive(), @@ -50,6 +57,7 @@ export const saveGrammarAnswersSchema = z.object({ phase: grammarSessionPhaseSchema, questionIndex: z.number().int().nonnegative(), }); + export const completeGrammarSessionSchema = z.object({ id: z.string().uuid(), expectedVersion: z.number().int().positive(), @@ -60,6 +68,7 @@ export const findGrammarSessionHistorySchema = z.object({ page: z.number().int().min(1).default(1), pageSize: z.number().int().min(1).max(100).default(20), }); + const grammarSessionSummarySchema = z.object({ id: grammarSessionIdSchema, noteId: grammarSessionIdSchema, @@ -69,16 +78,24 @@ const grammarSessionSummarySchema = z.object({ completedAt: z.string(), questionCount: z.number().int().positive(), }); + export const grammarSessionHistoryPageSchema = z.object({ items: z.array(grammarSessionSummarySchema), total: z.number().int().nonnegative(), }); + export type GrammarSession = z.infer; + export type GrammarSessionQuestion = z.infer; + export type GrammarSessionMode = z.infer; + export type GrammarSessionPhase = z.infer; + export type StartGrammarSessionInput = z.infer; + export type SaveGrammarAnswersInput = z.infer; + export type CompleteGrammarSessionInput = z.infer; export const grammarSessionRowSchema = z.object({ diff --git a/src/entities/grammar-session/ui/errorMessage.ts b/src/entities/grammar-session/ui/errorMessage.ts new file mode 100644 index 00000000..21be8ab2 --- /dev/null +++ b/src/entities/grammar-session/ui/errorMessage.ts @@ -0,0 +1,14 @@ +import type { GrammarSessionError } from "../models/errors"; + +export function grammarSessionErrorMessage(code: GrammarSessionError["code"]): string { + const messages = { + INVALID_INPUT: "연습 입력을 확인해 주세요.", + NOT_FOUND: "연습을 찾을 수 없습니다.", + CONFLICT: "다른 화면에서 연습이 변경되었습니다. 연습을 다시 열어 주세요.", + INCOMPLETE: "모든 문항에 답한 뒤 완료해 주세요.", + UNAUTHORIZED: "로그인 후 다시 시도해 주세요.", + FAILED: "연습을 저장하지 못했습니다. 잠시 후 다시 시도해 주세요.", + }; + + return messages[code]; +} 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-audio/index.ts b/src/features/grammar-audio/index.ts index eae1eb05..e5881247 100644 --- a/src/features/grammar-audio/index.ts +++ b/src/features/grammar-audio/index.ts @@ -1,4 +1,5 @@ export { GrammarAudioButton } from "./ui/GrammarAudioButton"; + export type { GrammarAudioInput, GrammarAudioResult, diff --git a/src/features/grammar-audio/models/interface.ts b/src/features/grammar-audio/models/interface.ts index 2889c26f..dc1f0f95 100644 --- a/src/features/grammar-audio/models/interface.ts +++ b/src/features/grammar-audio/models/interface.ts @@ -3,15 +3,26 @@ export interface GrammarAudioInput { readonly sentenceId: string; readonly noteVersion: number; } + +export type GrammarAudioErrorCode = + | "INVALID_INPUT" + | "UNAUTHORIZED" + | "NOT_INVITED" + | "RATE_LIMITED" + | "GENERATION_FAILED" + | "PLAYBACK_FAILED"; + export type GrammarAudioResult = | { ok: true; audioBase64: string; mimeType: "audio/mpeg"; cacheKey: string } - | { ok: false; message: string }; + | { ok: false; code: GrammarAudioErrorCode }; + export type GrammarAudioStatus = | "idle" | "generating" | "playing" | "generation-error" | "playback-error"; + export interface GrammarAudioButtonProps { readonly input: GrammarAudioInput; readonly generate: (input: GrammarAudioInput) => Promise; diff --git a/src/features/grammar-audio/services/actions/requestGrammarAudio.ts b/src/features/grammar-audio/services/actions/requestGrammarAudio.ts index 7ba2aab5..19bfad69 100644 --- a/src/features/grammar-audio/services/actions/requestGrammarAudio.ts +++ b/src/features/grammar-audio/services/actions/requestGrammarAudio.ts @@ -1,4 +1,5 @@ "use server"; + import { z } from "zod"; import { GrammarNoteRepository } from "@/entities/grammar-note"; import { createSupabaseServerClient } from "@/shared/lib/supabase/server"; @@ -9,6 +10,7 @@ import { recordOperationEvent } from "@/shared/lib/logging/pino"; import type { GrammarAudioResult } from "../../models/interface"; import { resolveGrammarAudioText } from "../resolveGrammarAudioText"; import { cachedGrammarAudio, grammarAudioCacheKey } from "../audioCache"; + const schema = z .object({ noteId: z.string().uuid(), @@ -16,40 +18,52 @@ const schema = z noteVersion: z.number().int().positive(), }) .strict(); + export async function requestGrammarAudio(input: unknown): Promise { try { return await observeOperation({ operation: "grammar.audio", resourceId: "grammar-note", recordEvent: recordOperationEvent, + execute: async () => { const parsed = schema.safeParse(input); - if (!parsed.success) return { ok: false as const, message: "음성 요청을 확인해주세요." }; + + if (!parsed.success) return { ok: false as const, code: "INVALID_INPUT" as const }; + const supabase = await createSupabaseServerClient(); const { data, error } = await supabase.auth.getUser(); - if (error || !data.user) - return { ok: false as const, message: "로그인 후 다시 시도해주세요." }; + + if (error || !data.user) return { ok: false as const, code: "UNAUTHORIZED" as const }; + const note = await new GrammarNoteRepository(supabase).findById(parsed.data.noteId); const text = resolveGrammarAudioText(note, parsed.data); const model = getOpenAITTSModel(); const key = grammarAudioCacheKey(data.user.id, text, model); + return cachedGrammarAudio(key, async () => { const { data: permission, error: quotaError } = await supabase.rpc("consume_ai_request", { p_operation: "tts", }); + if (quotaError || permission !== "allowed") return { ok: false, - message: - permission === "not_invited" - ? "AI 음성 이용 권한이 필요합니다." - : "음성 요청 한도에 도달했습니다. 잠시 후 다시 시도해주세요.", + code: quotaError + ? "GENERATION_FAILED" + : permission === "not_invited" + ? "NOT_INVITED" + : permission === "rate_limited" + ? "RATE_LIMITED" + : "GENERATION_FAILED", }; + const speech = await new OpenAITTSProvider({ model }).speak({ text, voice: "alloy", speed: 1, }); + return { ok: true, audioBase64: Buffer.from(speech.audio).toString("base64"), @@ -62,7 +76,7 @@ export async function requestGrammarAudio(input: unknown): Promise }>(); + export function grammarAudioCacheKey(owner: string, text: string, model: string) { return createHash("sha256") .update(JSON.stringify([owner, text, "alloy", 1, model])) .digest("hex"); } + export async function cachedGrammarAudio( key: string, generate: () => Promise, ): Promise { const hit = cache.get(key); + if (hit && hit.expires > Date.now()) return hit.result; + if (cache.size >= 32) cache.delete(cache.keys().next().value!); + // 결과 대신 Promise를 보관해야 동시에 누른 동일 문장의 유료 생성 요청도 공유할 수 있다. const result = generate(); + cache.set(key, { expires: Date.now() + 600000, result }); + try { const value = await result; + // 실패까지 캐시하면 사용자가 재시도해도 생성 요청을 보내지 못한다. if (!value.ok) cache.delete(key); + return value; } catch (error) { cache.delete(key); diff --git a/src/features/grammar-audio/services/playbackCoordinator.ts b/src/features/grammar-audio/services/playbackCoordinator.ts index 89b47e17..163eaef2 100644 --- a/src/features/grammar-audio/services/playbackCoordinator.ts +++ b/src/features/grammar-audio/services/playbackCoordinator.ts @@ -1,8 +1,10 @@ let stopCurrent: (() => void) | null = null; + /** 노트 내 여러 버튼도 동시에 소리를 내지 않도록 재생 소유자를 한 곳에서 관리한다. */ export function claimGrammarPlayback(stop: () => void) { stopCurrent?.(); stopCurrent = stop; + return () => { if (stopCurrent === stop) stopCurrent = null; }; diff --git a/src/features/grammar-audio/services/resolveGrammarAudioText.ts b/src/features/grammar-audio/services/resolveGrammarAudioText.ts index f5532f53..aee0cab3 100644 --- a/src/features/grammar-audio/services/resolveGrammarAudioText.ts +++ b/src/features/grammar-audio/services/resolveGrammarAudioText.ts @@ -1,5 +1,6 @@ import type { GrammarNote } from "@/entities/grammar-note"; import type { GrammarAudioInput } from "../models/interface"; + /** 클라이언트 문장이 아닌, 소유권 검증을 마친 저장 노트에서만 음성 대상을 선택한다. */ export function resolveGrammarAudioText( note: GrammarNote | null, @@ -7,10 +8,14 @@ export function resolveGrammarAudioText( ): string { if (!note || note.id !== input.noteId || note.version !== input.noteVersion) throw new Error("노트가 변경되었습니다. 새로고침 후 다시 시도해주세요."); + if (input.sentenceId === "source") return note.source.sentence; + const example = note.examples.find( (item) => item.id === input.sentenceId && item.reviewStatus === "reviewed", ); + if (!example) throw new Error("저장하고 채택한 문장만 재생할 수 있습니다."); + return example.sentence; } diff --git a/src/features/grammar-audio/services/useGrammarAudio.ts b/src/features/grammar-audio/services/useGrammarAudio.ts index c4ea2da6..b9970a7a 100644 --- a/src/features/grammar-audio/services/useGrammarAudio.ts +++ b/src/features/grammar-audio/services/useGrammarAudio.ts @@ -1,18 +1,22 @@ "use client"; + import { useEffect, useRef, useState } from "react"; import type { GrammarAudioButtonProps, GrammarAudioResult, GrammarAudioStatus, + GrammarAudioErrorCode, } from "../models/interface"; import { claimGrammarPlayback } from "./playbackCoordinator"; + export function useGrammarAudio({ input, generate }: GrammarAudioButtonProps) { const [status, setStatus] = useState("idle"); - const [message, setMessage] = useState(""); + const [error, setError] = useState(null); const generation = useRef(0); const audio = useRef(null); const speech = useRef | null>(null); const release = useRef<(() => void) | null>(null); + function stop() { generation.current++; audio.current?.pause(); @@ -21,10 +25,13 @@ export function useGrammarAudio({ input, generate }: GrammarAudioButtonProps) { release.current = null; setStatus("idle"); } + useEffect(() => { speech.current = null; + setError(null); setStatus("idle"); const lifecycleGeneration = generation; + return () => { lifecycleGeneration.current++; audio.current?.pause(); @@ -32,60 +39,79 @@ export function useGrammarAudio({ input, generate }: GrammarAudioButtonProps) { release.current?.(); }; }, [input.noteId, input.sentenceId, input.noteVersion]); + async function play() { if (status === "playing") { stop(); + return; } + // 이전 소유권을 남겨 두면 재획득 시 stop이 호출되어 새 요청의 세대까지 무효화되므로 먼저 반납한다. release.current?.(); release.current = null; const currentGeneration = ++generation.current; - setMessage(""); + + setError(null); release.current = claimGrammarPlayback(stop); let data = speech.current; + if (!data) { setStatus("generating"); + try { const result = await generate(input); + if (currentGeneration !== generation.current) return; + if (!result.ok) { - setMessage(result.message); + setError(result.code); setStatus("generation-error"); + return; } + data = result; speech.current = result; } catch { if (currentGeneration !== generation.current) return; - setMessage("음성 생성 요청에 실패했습니다."); + + setError("GENERATION_FAILED"); setStatus("generation-error"); + return; } } + try { const player = new Audio(`data:${data.mimeType};base64,${data.audioBase64}`); + audio.current = player; player.onended = () => { if (currentGeneration === generation.current) stop(); }; player.onerror = () => { if (currentGeneration === generation.current) { - setMessage("음성을 재생하지 못했습니다."); + setError("PLAYBACK_FAILED"); setStatus("playback-error"); } }; await player.play(); + if (currentGeneration !== generation.current) { player.pause(); + return; } + setStatus("playing"); } catch { if (currentGeneration !== generation.current) return; - setMessage("음성을 재생하지 못했습니다. 재생 버튼을 다시 눌러주세요."); + + setError("PLAYBACK_FAILED"); setStatus("playback-error"); } } - return { status, message, play }; + + return { status, error, play }; } diff --git a/src/features/grammar-audio/ui/GrammarAudioButton.tsx b/src/features/grammar-audio/ui/GrammarAudioButton.tsx index 20a0b87a..97222e19 100644 --- a/src/features/grammar-audio/ui/GrammarAudioButton.tsx +++ b/src/features/grammar-audio/ui/GrammarAudioButton.tsx @@ -1,8 +1,12 @@ "use client"; + import type { GrammarAudioButtonProps } from "../models/interface"; +import { grammarAudioErrorMessages } from "./errorMessage"; import { useGrammarAudio } from "../services/useGrammarAudio"; + export function GrammarAudioButton(props: GrammarAudioButtonProps) { - const { status, message, play } = useGrammarAudio(props); + const { status, error, play } = useGrammarAudio(props); + return (
diff --git a/src/features/grammar-audio/ui/errorMessage.ts b/src/features/grammar-audio/ui/errorMessage.ts new file mode 100644 index 00000000..fca1728d --- /dev/null +++ b/src/features/grammar-audio/ui/errorMessage.ts @@ -0,0 +1,11 @@ +import type { GrammarAudioErrorCode } from "../models/interface"; + +export const grammarAudioErrorMessages: Record = { + INVALID_INPUT: "음성 요청을 확인해주세요.", + UNAUTHORIZED: "로그인 후 다시 시도해주세요.", + NOT_INVITED: "AI 음성 이용 권한이 필요합니다.", + RATE_LIMITED: "음성 요청 한도에 도달했습니다. 잠시 후 다시 시도해주세요.", + GENERATION_FAILED: + "음성을 생성하지 못했습니다. 노트가 변경되었다면 새로고침 후 다시 생성해주세요.", + PLAYBACK_FAILED: "음성을 재생하지 못했습니다. 재생 버튼을 다시 눌러주세요.", +}; 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 ( <>