From 5aa29bf24f9ff6720788b4553d1beb7d09372d36 Mon Sep 17 00:00:00 2001
From: Wonik Choi
Date: Tue, 6 Oct 2026 02:19:17 +0900
Subject: [PATCH 01/12] feat(grammar): persist versioned practice sessions and
history (#157)
---
src/entities/grammar-session/index.ts | 24 +++
.../GrammarSessionRepository.ts | 153 ++++++++++++++++++
.../GrammarSessionRepository.test.ts | 122 ++++++++++++++
.../converters/convertGrammarSessionRow.ts | 48 ++++++
src/entities/grammar-session/models/errors.ts | 27 ++++
.../grammar-session/models/repository.ts | 36 +++++
src/entities/grammar-session/models/schema.ts | 62 +++++++
src/features/grammar-practice/index.ts | 7 +
.../grammar-practice/models/interface.ts | 4 +
.../services/actions/grammarSessionActions.ts | 63 ++++++++
src/shared/lib/supabase/database.types.ts | 71 ++++++++
.../20261007090000_grammar_sessions.sql | 147 +++++++++++++++++
supabase/tests/grammar_sessions.test.sql | 55 +++++++
13 files changed, 819 insertions(+)
create mode 100644 src/entities/grammar-session/index.ts
create mode 100644 src/entities/grammar-session/infrastructure/GrammarSessionRepository.ts
create mode 100644 src/entities/grammar-session/infrastructure/__tests__/GrammarSessionRepository.test.ts
create mode 100644 src/entities/grammar-session/models/converters/convertGrammarSessionRow.ts
create mode 100644 src/entities/grammar-session/models/errors.ts
create mode 100644 src/entities/grammar-session/models/repository.ts
create mode 100644 src/entities/grammar-session/models/schema.ts
create mode 100644 src/features/grammar-practice/index.ts
create mode 100644 src/features/grammar-practice/models/interface.ts
create mode 100644 src/features/grammar-practice/services/actions/grammarSessionActions.ts
create mode 100644 supabase/migrations/20261007090000_grammar_sessions.sql
create mode 100644 supabase/tests/grammar_sessions.test.sql
diff --git a/src/entities/grammar-session/index.ts b/src/entities/grammar-session/index.ts
new file mode 100644
index 00000000..8e8eb9af
--- /dev/null
+++ b/src/entities/grammar-session/index.ts
@@ -0,0 +1,24 @@
+export type {
+ GrammarSession,
+ GrammarSessionQuestion,
+ GrammarSessionMode,
+ GrammarSessionPhase,
+ StartGrammarSessionInput,
+ SaveGrammarAnswersInput,
+ CompleteGrammarSessionInput,
+} from "./models/schema";
+export {
+ grammarSessionSchema,
+ grammarQuestionSchema,
+ startGrammarSessionSchema,
+ 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";
diff --git a/src/entities/grammar-session/infrastructure/GrammarSessionRepository.ts b/src/entities/grammar-session/infrastructure/GrammarSessionRepository.ts
new file mode 100644
index 00000000..f27976ee
--- /dev/null
+++ b/src/entities/grammar-session/infrastructure/GrammarSessionRepository.ts
@@ -0,0 +1,153 @@
+import { z } from "zod";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import type { Database, Json } from "@/shared/lib/supabase/database.types";
+import { GrammarSessionError } from "../models/errors";
+import { convertGrammarSessionRow } from "../models/converters/convertGrammarSessionRow";
+import {
+ startGrammarSessionSchema,
+ saveGrammarAnswersSchema,
+ completeGrammarSessionSchema,
+ grammarSessionModeSchema,
+} from "../models/schema";
+import type {
+ StartGrammarSessionInput,
+ SaveGrammarAnswersInput,
+ CompleteGrammarSessionInput,
+ GrammarSessionMode,
+} from "../models/schema";
+import type {
+ GrammarSessionRepositoryPort,
+ GrammarSessionHistoryInput,
+} from "../models/repository";
+
+const uuid = z.string().uuid();
+const summarySchema = z.object({
+ id: uuid,
+ noteId: uuid,
+ title: z.string(),
+ mode: grammarSessionModeSchema,
+ startedAt: z.string(),
+ completedAt: z.string(),
+ questionCount: z.number().int().positive(),
+});
+/** 모든 호출은 사용자 세션 client로 수행하고 소유권은 DB가 확인합니다. */
+export class GrammarSessionRepository implements GrammarSessionRepositoryPort {
+ constructor(private readonly db: SupabaseClient) {}
+ private async request(
+ operation: () => PromiseLike<{ data: unknown; error: { message: string } | null }>,
+ convert: (data: unknown) => T,
+ ): Promise {
+ try {
+ const result = await operation();
+ if (result.error) {
+ const codes = [
+ "UNAUTHORIZED",
+ "NOT_FOUND",
+ "CONFLICT",
+ "INCOMPLETE",
+ "INVALID_INPUT",
+ ] as const;
+ throw new GrammarSessionError(
+ codes.find((code) => result.error?.message.includes(`GRAMMAR_SESSION_${code}`)) ??
+ "FAILED",
+ );
+ }
+ return convert(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.db.rpc("start_grammar_session", {
+ p_note_id: data.noteId,
+ p_request_id: data.requestId,
+ p_mode: data.mode,
+ }),
+ convertGrammarSessionRow,
+ );
+ }
+ async findById(id: string) {
+ uuid.parse(id);
+ return this.request(
+ () => this.db.from("grammar_sessions").select("*").eq("id", id).maybeSingle(),
+ (data) => (data === null ? null : convertGrammarSessionRow(data)),
+ );
+ }
+ async findActive(noteId: string, mode: GrammarSessionMode) {
+ uuid.parse(noteId);
+ grammarSessionModeSchema.parse(mode);
+ return this.request(
+ () =>
+ this.db
+ .from("grammar_sessions")
+ .select("*")
+ .eq("note_id", noteId)
+ .eq("mode", mode)
+ .eq("status", "active")
+ .order("started_at", { ascending: false })
+ .limit(1)
+ .maybeSingle(),
+ (data) => (data === null ? null : convertGrammarSessionRow(data)),
+ );
+ }
+ async saveAnswers(input: SaveGrammarAnswersInput) {
+ const data = saveGrammarAnswersSchema.parse(input);
+ return this.request(
+ () =>
+ this.db.rpc("save_grammar_session_answers", {
+ p_session_id: data.id,
+ p_expected_version: data.expectedVersion,
+ p_answers: data.answers,
+ p_phase: data.phase,
+ p_question_index: data.questionIndex,
+ }),
+ convertGrammarSessionRow,
+ );
+ }
+ async complete(input: CompleteGrammarSessionInput) {
+ const data = completeGrammarSessionSchema.parse(input);
+ return this.request(
+ () =>
+ this.db.rpc("complete_grammar_session", {
+ p_session_id: data.id,
+ p_expected_version: data.expectedVersion,
+ }),
+ convertGrammarSessionRow,
+ );
+ }
+ async findHistory(input: GrammarSessionHistoryInput = {}) {
+ const args = z
+ .object({
+ noteId: uuid.optional(),
+ page: z.number().int().min(1).default(1),
+ pageSize: z.number().int().min(1).max(100).default(20),
+ })
+ .parse(input);
+ return this.request(
+ () =>
+ this.db.rpc("list_grammar_session_history", {
+ p_note_id: args.noteId ?? undefined,
+ p_page: args.page,
+ p_page_size: args.pageSize,
+ }),
+ (data) => {
+ const page = z
+ .object({ items: z.array(summarySchema), total: z.number().int().nonnegative() })
+ .parse(data);
+ return { ...page, page: args.page, pageSize: args.pageSize };
+ },
+ );
+ }
+ /** 신규 문맥은 서버에서 생성·검증한 뒤 아직 답하지 않은 시험에 한 번만 고정합니다. */
+ async setExamPrompts(id: string, questions: Json) {
+ uuid.parse(id);
+ return this.request(
+ () => this.db.rpc("set_grammar_exam_prompts", { p_session_id: id, p_questions: questions }),
+ convertGrammarSessionRow,
+ );
+ }
+}
diff --git a/src/entities/grammar-session/infrastructure/__tests__/GrammarSessionRepository.test.ts b/src/entities/grammar-session/infrastructure/__tests__/GrammarSessionRepository.test.ts
new file mode 100644
index 00000000..1876952c
--- /dev/null
+++ b/src/entities/grammar-session/infrastructure/__tests__/GrammarSessionRepository.test.ts
@@ -0,0 +1,122 @@
+/** @jest-environment node */
+import { describe, expect, it, jest } from "@jest/globals";
+import { createClient } from "@supabase/supabase-js";
+import type { Database } from "@/shared/lib/supabase/database.types";
+import { GrammarSessionRepository } from "../GrammarSessionRepository";
+import { convertGrammarSessionRow } from "../../models/converters/convertGrammarSessionRow";
+const id = "11111111-1111-4111-8111-111111111111";
+function row(mode = "recall", status = "active") {
+ return {
+ id,
+ note_id: id,
+ note_version: 3,
+ snapshot: { metadata: { title: "대조" }, source: { learningNote: "not A but B" } },
+ mode,
+ status,
+ questions: [
+ {
+ id: "source",
+ kind: "existing",
+ sentence: "She is not a teacher but a doctor.",
+ translation: "그녀는 의사입니다.",
+ context: "",
+ requiredWords: [],
+ chunks: [{ id: "c1", start: 0, end: 3, meaning: "그녀는" }],
+ },
+ ],
+ answers: { "partial:source": '{"c1":"She"}' },
+ phase: mode === "recall" ? "partial" : "existing",
+ question_index: 0,
+ version: 1,
+ started_at: "2026-10-06T00:00:00Z",
+ 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), {
+ status,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ const client = createClient("https://echo-test.example", "key", {
+ 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 = convertGrammarSessionRow(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(convertGrammarSessionRow(row()).questions[0].sentence).toContain("teacher");
+ expect(convertGrammarSessionRow(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,
+ p_request_id: id,
+ p_mode: "recall",
+ });
+ });
+ it("save_sends_version_and_both_phase_drafts", async () => {
+ const { repository, fetcher } = setup(row());
+ await repository.saveAnswers({
+ id,
+ expectedVersion: 4,
+ answers: { "partial:source": "{}", "whole:source": "draft" },
+ phase: "whole",
+ questionIndex: 0,
+ });
+ expect(JSON.parse(String(fetcher.mock.calls[0][1]?.body))).toMatchObject({
+ p_expected_version: 4,
+ 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,
+ page: 3,
+ pageSize: 10,
+ });
+ });
+});
diff --git a/src/entities/grammar-session/models/converters/convertGrammarSessionRow.ts b/src/entities/grammar-session/models/converters/convertGrammarSessionRow.ts
new file mode 100644
index 00000000..eead273c
--- /dev/null
+++ b/src/entities/grammar-session/models/converters/convertGrammarSessionRow.ts
@@ -0,0 +1,48 @@
+import { z } from "zod";
+import { grammarSessionSchema } from "../schema";
+
+const rowSchema = z.object({
+ id: z.string(),
+ note_id: z.string(),
+ note_version: z.number(),
+ mode: z.string(),
+ status: z.string(),
+ snapshot: z.object({
+ metadata: z.object({ title: z.string() }),
+ source: z.object({ learningNote: z.string() }),
+ }),
+ questions: z.unknown(),
+ answers: z.unknown(),
+ phase: z.string(),
+ question_index: z.number(),
+ version: z.number(),
+ started_at: z.string(),
+ completed_at: z.string().nullable(),
+});
+/** 시험 진행 중에는 정답 문장을 클라이언트에 직렬화하지 않습니다. */
+export function convertGrammarSessionRow(input: unknown) {
+ const row = rowSchema.parse(input);
+ const session = grammarSessionSchema.parse({
+ id: row.id,
+ noteId: row.note_id,
+ noteVersion: row.note_version,
+ title: row.snapshot.metadata.title,
+ learningNote: row.snapshot.source.learningNote,
+ mode: row.mode,
+ status: row.status,
+ questions: row.questions,
+ answers: row.answers,
+ phase: row.phase,
+ questionIndex: row.question_index,
+ version: row.version,
+ startedAt: row.started_at,
+ completedAt: row.completed_at,
+ });
+ if (session.mode === "exam" && session.status === "active")
+ session.questions = session.questions.map((question) => ({
+ ...question,
+ sentence: null,
+ chunks: [],
+ }));
+ return session;
+}
diff --git a/src/entities/grammar-session/models/errors.ts b/src/entities/grammar-session/models/errors.ts
new file mode 100644
index 00000000..37399e03
--- /dev/null
+++ b/src/entities/grammar-session/models/errors.ts
@@ -0,0 +1,27 @@
+export class GrammarSessionError extends Error {
+ constructor(
+ readonly code:
+ | "INVALID_INPUT"
+ | "NOT_FOUND"
+ | "CONFLICT"
+ | "INCOMPLETE"
+ | "UNAUTHORIZED"
+ | "FAILED",
+ ) {
+ super(code);
+ 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/repository.ts b/src/entities/grammar-session/models/repository.ts
new file mode 100644
index 00000000..1af6fb79
--- /dev/null
+++ b/src/entities/grammar-session/models/repository.ts
@@ -0,0 +1,36 @@
+import type {
+ GrammarSession,
+ GrammarSessionMode,
+ StartGrammarSessionInput,
+ SaveGrammarAnswersInput,
+ CompleteGrammarSessionInput,
+} from "./schema";
+
+export interface GrammarSessionSummary {
+ id: string;
+ noteId: string;
+ title: string;
+ mode: GrammarSessionMode;
+ startedAt: string;
+ 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;
+ findActive(noteId: string, mode: GrammarSessionMode): Promise;
+ saveAnswers(input: SaveGrammarAnswersInput): Promise;
+ complete(input: CompleteGrammarSessionInput): Promise;
+ findHistory(input?: GrammarSessionHistoryInput): Promise;
+}
diff --git a/src/entities/grammar-session/models/schema.ts b/src/entities/grammar-session/models/schema.ts
new file mode 100644
index 00000000..350d3895
--- /dev/null
+++ b/src/entities/grammar-session/models/schema.ts
@@ -0,0 +1,62 @@
+import { z } from "zod";
+
+const text = z.string().trim().min(1).max(4000);
+export const grammarSessionModeSchema = z.enum(["recall", "exam"]);
+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"]),
+ sentence: text.nullable(),
+ translation: text,
+ context: z.string().max(4000),
+ chunks: z
+ .array(
+ z.object({
+ id: z.string(),
+ start: z.number().int().nonnegative(),
+ end: z.number().int().positive(),
+ meaning: z.string(),
+ }),
+ )
+ .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(),
+ noteVersion: z.number().int().positive(),
+ title: text,
+ learningNote: text,
+ mode: grammarSessionModeSchema,
+ status: z.enum(["active", "completed"]),
+ questions: z.array(grammarQuestionSchema).min(1).max(110),
+ answers: z.record(z.string().max(4000)),
+ phase: grammarSessionPhaseSchema,
+ questionIndex: z.number().int().nonnegative(),
+ version: z.number().int().positive(),
+ 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(),
+ answers: z.record(z.string().max(4000)),
+ phase: grammarSessionPhaseSchema,
+ questionIndex: z.number().int().nonnegative(),
+});
+export const completeGrammarSessionSchema = z.object({
+ id: z.string().uuid(),
+ expectedVersion: z.number().int().positive(),
+});
+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;
diff --git a/src/features/grammar-practice/index.ts b/src/features/grammar-practice/index.ts
new file mode 100644
index 00000000..36ec1df9
--- /dev/null
+++ b/src/features/grammar-practice/index.ts
@@ -0,0 +1,7 @@
+export type { GrammarSessionResult } from "./models/interface";
+export {
+ startGrammarSession,
+ resumeGrammarSession,
+ saveGrammarSessionAnswers,
+ completeGrammarSession,
+} from "./services/actions/grammarSessionActions";
diff --git a/src/features/grammar-practice/models/interface.ts b/src/features/grammar-practice/models/interface.ts
new file mode 100644
index 00000000..02d915aa
--- /dev/null
+++ b/src/features/grammar-practice/models/interface.ts
@@ -0,0 +1,4 @@
+import type { GrammarSession } from "@/entities/grammar-session";
+export type GrammarSessionResult =
+ | { ok: true; data: GrammarSession }
+ | { ok: false; message: string };
diff --git a/src/features/grammar-practice/services/actions/grammarSessionActions.ts b/src/features/grammar-practice/services/actions/grammarSessionActions.ts
new file mode 100644
index 00000000..6a74cf16
--- /dev/null
+++ b/src/features/grammar-practice/services/actions/grammarSessionActions.ts
@@ -0,0 +1,63 @@
+"use server";
+import { z } from "zod";
+import { createSupabaseServerClient } from "@/shared/lib/supabase/server";
+import { observeOperation } from "@/shared/lib/logging/observeOperation";
+import { recordOperationEvent } from "@/shared/lib/logging/pino";
+import {
+ GrammarSessionRepository,
+ GrammarSessionError,
+ grammarSessionErrorMessage,
+ startGrammarSessionSchema,
+ saveGrammarAnswersSchema,
+ completeGrammarSessionSchema,
+} from "@/entities/grammar-session";
+import type { GrammarSession, GrammarSessionRepositoryPort } from "@/entities/grammar-session";
+import type { GrammarSessionResult } from "../../models/interface";
+
+async function executeSessionAction(
+ operation: string,
+ execute: (repository: GrammarSessionRepositoryPort) => Promise,
+): Promise {
+ try {
+ return await observeOperation({
+ operation,
+ resourceId: "grammar-session",
+ recordEvent: recordOperationEvent,
+ execute: async () => {
+ const db = await createSupabaseServerClient();
+ const { data, error } = await db.auth.getUser();
+ if (error || !data.user) throw new GrammarSessionError("UNAUTHORIZED");
+ return { ok: true as const, data: await execute(new GrammarSessionRepository(db)) };
+ },
+ });
+ } catch (error) {
+ return {
+ ok: false,
+ message: grammarSessionErrorMessage(
+ error instanceof z.ZodError ? new GrammarSessionError("INVALID_INPUT") : error,
+ ),
+ };
+ }
+}
+export async function startGrammarSession(input: unknown): Promise {
+ return executeSessionAction("grammar.session.start", (repository) =>
+ repository.start(startGrammarSessionSchema.parse(input)),
+ );
+}
+export async function resumeGrammarSession(id: string): Promise {
+ return executeSessionAction("grammar.session.resume", async (repository) => {
+ const session = await repository.findById(z.string().uuid().parse(id));
+ if (!session) throw new GrammarSessionError("NOT_FOUND");
+ return session;
+ });
+}
+export async function saveGrammarSessionAnswers(input: unknown): Promise {
+ return executeSessionAction("grammar.session.save", (repository) =>
+ repository.saveAnswers(saveGrammarAnswersSchema.parse(input)),
+ );
+}
+export async function completeGrammarSession(input: unknown): Promise {
+ return executeSessionAction("grammar.session.complete", (repository) =>
+ repository.complete(completeGrammarSessionSchema.parse(input)),
+ );
+}
diff --git a/src/shared/lib/supabase/database.types.ts b/src/shared/lib/supabase/database.types.ts
index 34480764..ab2bc58d 100644
--- a/src/shared/lib/supabase/database.types.ts
+++ b/src/shared/lib/supabase/database.types.ts
@@ -28,6 +28,51 @@ export type Database = {
};
public: {
Tables: {
+ grammar_sessions: {
+ Row: {
+ id: string;
+ owner_id: string;
+ note_id: string;
+ note_version: number;
+ snapshot: Json;
+ mode: string;
+ status: string;
+ questions: Json;
+ answers: Json;
+ phase: string;
+ question_index: number;
+ version: number;
+ creation_request_id: string;
+ started_at: string;
+ completed_at: string | null;
+ };
+ Insert: {
+ id?: string;
+ owner_id: string;
+ note_id: string;
+ note_version: number;
+ snapshot: Json;
+ mode: string;
+ questions: Json;
+ phase: string;
+ creation_request_id: string;
+ status?: string;
+ answers?: Json;
+ question_index?: number;
+ version?: number;
+ started_at?: string;
+ completed_at?: string | null;
+ };
+ Update: {
+ answers?: Json;
+ phase?: string;
+ question_index?: number;
+ version?: number;
+ status?: string;
+ completed_at?: string | null;
+ };
+ Relationships: [];
+ };
grammar_notes: {
Row: {
id: string;
@@ -1055,6 +1100,32 @@ export type Database = {
};
};
Functions: {
+ start_grammar_session: {
+ Args: { p_note_id: string; p_request_id: string; p_mode: string };
+ Returns: Json;
+ };
+ save_grammar_session_answers: {
+ Args: {
+ p_session_id: string;
+ p_expected_version: number;
+ p_answers: Json;
+ p_phase: string;
+ p_question_index: number;
+ };
+ Returns: Json;
+ };
+ complete_grammar_session: {
+ Args: { p_session_id: string; p_expected_version: number };
+ Returns: Json;
+ };
+ list_grammar_session_history: {
+ Args: { p_note_id?: string; p_page?: number; p_page_size?: number };
+ Returns: Json;
+ };
+ set_grammar_exam_prompts: {
+ Args: { p_session_id: string; p_questions: Json };
+ Returns: Json;
+ };
is_valid_grammar_note_content: {
Args: { p_content: Json };
Returns: boolean;
diff --git a/supabase/migrations/20261007090000_grammar_sessions.sql b/supabase/migrations/20261007090000_grammar_sessions.sql
new file mode 100644
index 00000000..a3c9ebe4
--- /dev/null
+++ b/supabase/migrations/20261007090000_grammar_sessions.sql
@@ -0,0 +1,147 @@
+-- 노트 원본/버전 및 문제 순서는 생성 시 DB에서 확정하며 답안 저장은 낙관적 잠금으로 보호합니다.
+create table public.grammar_sessions (
+ id uuid primary key default gen_random_uuid(), owner_id uuid not null references auth.users(id) on delete cascade,
+ note_id uuid not null references public.grammar_notes(id), note_version integer not null,
+ snapshot jsonb not null, mode text not null check(mode in ('recall','exam')),
+ status text not null default 'active' check(status in ('active','completed')),
+ questions jsonb not null, answers jsonb not null default '{}',
+ phase text not null check(phase in ('partial','whole','existing','novel')), question_index integer not null default 0,
+ version integer not null default 1 check(version>0), creation_request_id uuid not null,
+ started_at timestamptz not null default clock_timestamp(), completed_at timestamptz,
+ unique(owner_id,creation_request_id), check((status='completed')=(completed_at is not null))
+);
+create index grammar_sessions_owner_history_idx on public.grammar_sessions(owner_id,completed_at desc,id desc);
+alter table public.grammar_sessions enable row level security;
+create policy grammar_sessions_owner_select on public.grammar_sessions for select to authenticated using(owner_id=(select auth.uid()));
+revoke all on public.grammar_sessions from public,anon,authenticated;
+grant select on public.grammar_sessions to authenticated;
+
+create function public.start_grammar_session(p_note_id uuid,p_request_id uuid,p_mode text)
+returns jsonb language plpgsql security definer set search_path='' as $$
+declare
+ v_owner uuid:=auth.uid(); v_note public.grammar_notes; v_session public.grammar_sessions;
+ v_questions jsonb; v_previous jsonb; v_order jsonb;
+begin
+ if v_owner is null then raise exception 'GRAMMAR_SESSION_UNAUTHORIZED'; end if;
+ if p_note_id is null or p_request_id is null or p_mode is null or p_mode not in ('recall','exam') then raise exception 'GRAMMAR_SESSION_INVALID_INPUT'; end if;
+ -- 같은 노트의 시작을 직렬화하여 직전 세션과 순서를 비교합니다.
+ select * into v_note from public.grammar_notes where id=p_note_id and owner_id=v_owner for update;
+ if not found then raise exception 'GRAMMAR_SESSION_NOT_FOUND'; end if;
+ select * into v_session from public.grammar_sessions where owner_id=v_owner and creation_request_id=p_request_id;
+ if found then
+ if v_session.note_id<>p_note_id or v_session.mode<>p_mode then raise exception 'GRAMMAR_SESSION_CONFLICT'; end if;
+ return to_jsonb(v_session);
+ end if;
+ select jsonb_agg(q->>'id' order by ord) into v_previous from public.grammar_sessions s,
+ lateral jsonb_array_elements(s.questions) with ordinality as a(q,ord)
+ where s.id=(select id from public.grammar_sessions where owner_id=v_owner and note_id=p_note_id and mode=p_mode order by started_at desc,id desc limit 1);
+ with questions as (
+ select jsonb_build_object('id','source','kind','existing','sentence',v_note.content#>>'{source,sentence}',
+ 'translation',v_note.content#>>'{analysis,naturalTranslation}','context','','requiredWords','[]'::jsonb,
+ 'chunks',coalesce((select jsonb_agg(jsonb_build_object('id',c->>'id','start',c#>'{range,start}','end',c#>'{range,end}','meaning',c->>'literalMeaning')) from jsonb_array_elements(v_note.content#>'{analysis,chunks}') c),'[]'::jsonb)) q
+ union all
+ select jsonb_build_object('id','example:'||(e->>'id'),'kind','existing','sentence',e->>'sentence',
+ 'translation',e->>'translation','context','','requiredWords','[]'::jsonb,'chunks','[]'::jsonb)
+ from jsonb_array_elements(v_note.content->'examples') e
+ ) select jsonb_agg(q order by random()) into v_questions from questions;
+ select jsonb_agg(q->>'id' order by ord) into v_order from jsonb_array_elements(v_questions) with ordinality as a(q,ord);
+ -- 두 문항 이상일 때 우연히 이전 순서와 같으면 회전하여 반복 순서를 피합니다.
+ if jsonb_array_length(v_questions)>1 and v_order=v_previous then v_questions=(v_questions-0)||jsonb_build_array(v_questions->0); end if;
+ insert into public.grammar_sessions(owner_id,note_id,note_version,snapshot,mode,questions,phase,creation_request_id)
+ values(v_owner,p_note_id,v_note.version,v_note.content,p_mode,v_questions,case when p_mode='recall' then 'partial' else 'existing' end,p_request_id)
+ on conflict(owner_id,creation_request_id) do nothing returning * into v_session;
+ if not found then
+ select * into v_session from public.grammar_sessions where owner_id=v_owner and creation_request_id=p_request_id;
+ if v_session.note_id<>p_note_id or v_session.mode<>p_mode then raise exception 'GRAMMAR_SESSION_CONFLICT'; end if;
+ end if;
+ return to_jsonb(v_session);
+end $$;
+
+create function public.save_grammar_session_answers(p_session_id uuid,p_expected_version integer,p_answers jsonb,p_phase text,p_question_index integer)
+returns jsonb language plpgsql security definer set search_path='' as $$
+declare v_owner uuid:=auth.uid();v_session public.grammar_sessions;v_key text;v_answer jsonb;v_phase text;v_id text;
+begin
+ if v_owner is null then raise exception 'GRAMMAR_SESSION_UNAUTHORIZED'; end if;
+ select * into v_session from public.grammar_sessions where id=p_session_id and owner_id=v_owner for update;
+ if not found then raise exception 'GRAMMAR_SESSION_NOT_FOUND'; end if;
+ if p_expected_version is null or p_expected_version<1 or jsonb_typeof(p_answers) is distinct from 'object'
+ or p_phase is null or p_question_index is null or p_question_index<0 or p_question_index>=jsonb_array_length(v_session.questions)
+ or (v_session.mode='recall' and p_phase not in ('partial','whole')) or (v_session.mode='exam' and p_phase not in ('existing','novel')) then raise exception 'GRAMMAR_SESSION_INVALID_INPUT'; end if;
+ for v_key,v_answer in select * from jsonb_each(p_answers) loop
+ v_phase=split_part(v_key,':',1);v_id=substring(v_key from length(v_phase)+2);
+ if jsonb_typeof(v_answer) is distinct from 'string' or length(v_answer#>>'{}')>4000
+ or (v_session.mode='recall' and v_phase not in ('partial','whole')) or (v_session.mode='exam' and v_phase not in ('existing','novel'))
+ or not exists(select 1 from jsonb_array_elements(v_session.questions) q where q->>'id'=v_id and (v_session.mode='recall' or q->>'kind'=v_phase))
+ then raise exception 'GRAMMAR_SESSION_INVALID_INPUT'; end if;
+ end loop;
+ -- 응답 유실 후 같은 내용의 재시도는 버전을 다시 올리지 않습니다.
+ if v_session.answers=p_answers and v_session.phase=p_phase and v_session.question_index=p_question_index then return to_jsonb(v_session); end if;
+ if v_session.status<>'active' or v_session.version<>p_expected_version then raise exception 'GRAMMAR_SESSION_CONFLICT'; end if;
+ update public.grammar_sessions set answers=p_answers,phase=p_phase,question_index=p_question_index,version=version+1 where id=v_session.id returning * into v_session;
+ return to_jsonb(v_session);
+end $$;
+
+create function public.complete_grammar_session(p_session_id uuid,p_expected_version integer)
+returns jsonb language plpgsql security definer set search_path='' as $$
+declare v_owner uuid:=auth.uid();v_session public.grammar_sessions;v_question jsonb;v_key text;
+begin
+ if v_owner is null then raise exception 'GRAMMAR_SESSION_UNAUTHORIZED'; end if;
+ select * into v_session from public.grammar_sessions where id=p_session_id and owner_id=v_owner for update;
+ if not found then raise exception 'GRAMMAR_SESSION_NOT_FOUND'; end if;
+ -- 완료 응답이 유실되어도 동일 sessionId는 다시 집계하지 않습니다.
+ if v_session.status='completed' then return to_jsonb(v_session); end if;
+ if p_expected_version is null or v_session.version<>p_expected_version then raise exception 'GRAMMAR_SESSION_CONFLICT'; end if;
+ if v_session.mode='exam' and not exists(select 1 from jsonb_array_elements(v_session.questions) q where q->>'kind'='novel') then raise exception 'GRAMMAR_SESSION_INCOMPLETE'; end if;
+ for v_question in select value from jsonb_array_elements(v_session.questions) loop
+ v_key=(case when v_session.mode='recall' then 'whole' else v_question->>'kind' end)||':'||(v_question->>'id');
+ if coalesce(v_session.answers->>v_key,'') !~ '[^[:space:]]' then raise exception 'GRAMMAR_SESSION_INCOMPLETE'; end if;
+ end loop;
+ update public.grammar_sessions set status='completed',completed_at=clock_timestamp(),version=version+1 where id=v_session.id returning * into v_session;
+ return to_jsonb(v_session);
+end $$;
+
+create function public.list_grammar_session_history(p_note_id uuid default null,p_page integer default 1,p_page_size integer default 20)
+returns jsonb language plpgsql stable security definer set search_path='' as $$
+declare v_owner uuid:=auth.uid();v_result jsonb;
+begin
+ if v_owner is null then raise exception 'GRAMMAR_SESSION_UNAUTHORIZED'; end if;
+ if p_page is null or p_page<1 or p_page_size is null or p_page_size not between 1 and 100 then raise exception 'GRAMMAR_SESSION_INVALID_INPUT'; end if;
+ with matching as materialized(select * from public.grammar_sessions where owner_id=v_owner and status='completed' and (p_note_id is null or note_id=p_note_id)),
+ page as(select * from matching order by completed_at desc,id desc limit p_page_size offset (p_page::bigint-1)*p_page_size)
+ select jsonb_build_object('total',(select count(*) from matching),'items',coalesce((select jsonb_agg(jsonb_build_object(
+ 'id',id,'noteId',note_id,'title',snapshot#>>'{metadata,title}','mode',mode,'startedAt',started_at,'completedAt',completed_at,'questionCount',jsonb_array_length(questions)) order by completed_at desc,id desc) from page),'[]'::jsonb)) into v_result;
+ return v_result;
+end $$;
+
+-- 신규 시험 문맥은 시작 후 한 번만 고정하며, 답안을 쓰기 시작한 세션은 변경할 수 없습니다.
+create function public.set_grammar_exam_prompts(p_session_id uuid,p_questions jsonb)
+returns jsonb language plpgsql security definer set search_path='' as $$
+declare v_owner uuid:=auth.uid();v_session public.grammar_sessions;v_q jsonb;v_word jsonb;v_ids text[]:='{}';
+begin
+ if v_owner is null then raise exception 'GRAMMAR_SESSION_UNAUTHORIZED'; end if;
+ select * into v_session from public.grammar_sessions where id=p_session_id and owner_id=v_owner for update;
+ if not found then raise exception 'GRAMMAR_SESSION_NOT_FOUND'; end if;
+ if v_session.mode<>'exam' then raise exception 'GRAMMAR_SESSION_INVALID_INPUT'; end if;
+ if exists(select 1 from jsonb_array_elements(v_session.questions) q where q->>'kind'='novel') then return to_jsonb(v_session); end if;
+ if v_session.status<>'active' or v_session.answers<>'{}'::jsonb then raise exception 'GRAMMAR_SESSION_CONFLICT'; end if;
+ if jsonb_typeof(p_questions) is distinct from 'array' then raise exception 'GRAMMAR_SESSION_INVALID_INPUT'; end if;
+ if jsonb_array_length(p_questions) not between 1 and 3 then raise exception 'GRAMMAR_SESSION_INVALID_INPUT'; end if;
+ for v_q in select value from jsonb_array_elements(p_questions) loop
+ if jsonb_typeof(v_q) is distinct from 'object' or v_q->>'kind' is distinct from 'novel'
+ or coalesce(v_q->>'id','') !~ '^novel:[1-3]$' or v_q->>'id'=any(v_ids)
+ or v_q->'sentence' is distinct from 'null'::jsonb or v_q->'chunks' is distinct from '[]'::jsonb
+ or jsonb_typeof(v_q->'context') is distinct from 'string' or length(v_q->>'context') not between 1 and 4000
+ or jsonb_typeof(v_q->'translation') is distinct from 'string' or length(v_q->>'translation') not between 1 and 4000
+ or jsonb_typeof(v_q->'requiredWords') is distinct from 'array' then raise exception 'GRAMMAR_SESSION_INVALID_INPUT'; end if;
+ if jsonb_array_length(v_q->'requiredWords') not between 1 and 12 then raise exception 'GRAMMAR_SESSION_INVALID_INPUT'; end if;
+ v_ids=array_append(v_ids,v_q->>'id');
+ for v_word in select value from jsonb_array_elements(v_q->'requiredWords') loop
+ if jsonb_typeof(v_word->'word') is distinct from 'string' or length(v_word->>'word') not between 1 and 4000
+ or jsonb_typeof(v_word->'meaning') is distinct from 'string' or length(v_word->>'meaning') not between 1 and 4000 then raise exception 'GRAMMAR_SESSION_INVALID_INPUT'; end if;
+ end loop;
+ end loop;
+ update public.grammar_sessions set questions=questions||p_questions,version=version+1 where id=v_session.id returning * into v_session;
+ return to_jsonb(v_session);
+end $$;
+revoke all on function public.start_grammar_session(uuid,uuid,text),public.save_grammar_session_answers(uuid,integer,jsonb,text,integer),public.complete_grammar_session(uuid,integer),public.list_grammar_session_history(uuid,integer,integer),public.set_grammar_exam_prompts(uuid,jsonb) from public,anon,authenticated;
+grant execute on function public.start_grammar_session(uuid,uuid,text),public.save_grammar_session_answers(uuid,integer,jsonb,text,integer),public.complete_grammar_session(uuid,integer),public.list_grammar_session_history(uuid,integer,integer),public.set_grammar_exam_prompts(uuid,jsonb) to authenticated;
diff --git a/supabase/tests/grammar_sessions.test.sql b/supabase/tests/grammar_sessions.test.sql
new file mode 100644
index 00000000..3e31649e
--- /dev/null
+++ b/supabase/tests/grammar_sessions.test.sql
@@ -0,0 +1,55 @@
+begin;
+create extension if not exists pgtap with schema extensions;
+select no_plan();
+insert into auth.users(id) values ('15151515-1111-4111-8111-111111111111'),('15151515-2222-4222-8222-222222222222');
+create function pg_temp.grammar_content(p_title text default 'Not A but B') returns jsonb
+language sql immutable as $$
+ select jsonb_build_object(
+ 'source', jsonb_build_object('sentence','She is not a teacher but a doctor.','learningNote','not A but B 대조','revision',0),
+ 'metadata', jsonb_build_object('source','ai','sourceRevision',0,'title',p_title,'tags',jsonb_build_array('대조'),'grammarKey',null),
+ 'analysis', jsonb_build_object('sourceText','She is not a teacher but a doctor.','sourceRevision',0,
+ 'chunks',jsonb_build_array(jsonb_build_object('id','c1','range',jsonb_build_object('start',0,'end',34),'literalMeaning','그녀는 교사가 아니라 의사입니다.','explanation','대조')),
+ 'syntax','[]'::jsonb,'constructions','[]'::jsonb,'naturalTranslation','그녀는 교사가 아니라 의사입니다.','reviewStatus','reviewed'),
+ 'examples','[]'::jsonb);
+$$;
+
+create temporary table session_test(label text primary key,value jsonb);
+grant all on session_test to authenticated;
+set local role authenticated;
+select set_config('request.jwt.claim.sub','15151515-1111-4111-8111-111111111111',true);
+insert into session_test values('note',public.create_grammar_note('25252525-1111-4111-8111-111111111111',pg_temp.grammar_content()));
+insert into session_test select 'single',public.start_grammar_session((value->>'id')::uuid,'25252525-2222-4222-8222-222222222222','recall') from session_test where label='note';
+select is((select jsonb_array_length(value->'questions') from session_test where label='single'),1,'one sentence starts successfully');
+select is((select value->'snapshot' from session_test where label='single'),pg_temp.grammar_content(),'snapshot comes from saved note');
+select is((select value#>>'{questions,0,chunks,0,id}' from session_test where label='single'),'c1','source semantic chunks are frozen');
+select is(public.start_grammar_session((select (value->>'id')::uuid from session_test where label='note'),'25252525-2222-4222-8222-222222222222','recall'),(select value from session_test where label='single'),'retry retains same session and order');
+select throws_ok($q$select public.complete_grammar_session((select (value->>'id')::uuid from session_test where label='single'),1)$q$,'P0001','GRAMMAR_SESSION_INCOMPLETE','unanswered session cannot complete');
+insert into session_test select 'saved',public.save_grammar_session_answers((value->>'id')::uuid,1,'{"partial:source":"{\"c1\":\"draft\"}","whole:source":"She is a doctor."}','whole',0) from session_test where label='single';
+select is(public.save_grammar_session_answers((select (value->>'id')::uuid from session_test where label='single'),1,'{"partial:source":"{\"c1\":\"draft\"}","whole:source":"She is a doctor."}','whole',0),(select value from session_test where label='saved'),'answer retry is idempotent');
+select throws_ok($q$select public.save_grammar_session_answers((select (value->>'id')::uuid from session_test where label='single'),1,'{"whole:source":"Changed"}','whole',0)$q$,'P0001','GRAMMAR_SESSION_CONFLICT','stale draft cannot overwrite new answers');
+select throws_ok($q$select public.save_grammar_session_answers((select (value->>'id')::uuid from session_test where label='single'),2,'{"whole:unknown":"answer"}','whole',0)$q$,'P0001','GRAMMAR_SESSION_INVALID_INPUT','unknown question answer rejected');
+insert into session_test select 'completed',public.complete_grammar_session((value->>'id')::uuid,2) from session_test where label='single';
+select is(public.complete_grammar_session((select (value->>'id')::uuid from session_test where label='single'),2),(select value from session_test where label='completed'),'completion retry retains original timestamp and version');
+select is((public.list_grammar_session_history()->>'total')::integer,1,'completion is counted once');
+select is((select value->'questions' from session_test where label='completed'),(select value->'questions' from session_test where label='single'),'completion retains order and source');
+select throws_ok($q$update public.grammar_sessions set answers='{}'$q$,'42501',null,'direct writes cannot bypass validation');
+insert into session_test select 'changed-note',public.update_grammar_note((value->>'id')::uuid,1,jsonb_set(pg_temp.grammar_content('Changed'),'{examples}','[{"id":"e1","sentence":"He is not lazy but tired.","translation":"그는 게으른 게 아니라 피곤합니다.","targetExplanation":"not A but B","reviewStatus":"reviewed"}]')) from session_test where label='note';
+select is((select snapshot#>>'{metadata,title}' from public.grammar_sessions limit 1),'Not A but B','editing the note never changes frozen metadata');
+insert into session_test select 'multi1',public.start_grammar_session((value->>'id')::uuid,'25252525-3333-4333-8333-333333333333','recall') from session_test where label='note';
+insert into session_test select 'multi2',public.start_grammar_session((value->>'id')::uuid,'25252525-4444-4444-8444-444444444444','recall') from session_test where label='note';
+select isnt((select value->'questions' from session_test where label='multi1'),(select value->'questions' from session_test where label='multi2'),'new multi-question session avoids previous order');
+select is((public.list_grammar_session_history()->>'total')::integer,1,'active and abandoned sessions do not count');
+select is((public.list_grammar_session_history(null,99,20)->>'total')::integer,1,'empty history page retains total');
+insert into session_test select 'exam',public.start_grammar_session((value->>'id')::uuid,'25252525-5555-4555-8555-555555555555','exam') from session_test where label='note';
+insert into session_test select 'exam-ready',public.set_grammar_exam_prompts((value->>'id')::uuid,'[{"id":"novel:1","kind":"novel","sentence":null,"translation":"새로운 상황","context":"친구의 직업을 정정하세요.","chunks":[],"requiredWords":[{"word":"engineer","meaning":"기술자"}]}]') from session_test where label='exam';
+select is((select jsonb_array_length(value->'questions') from session_test where label='exam-ready'),3,'exam freezes existing and novel questions');
+select is(public.set_grammar_exam_prompts((select (value->>'id')::uuid from session_test where label='exam'), '[]'),(select value from session_test where label='exam-ready'),'retry never replaces already frozen novel question');
+select set_config('request.jwt.claim.sub','15151515-2222-4222-8222-222222222222',true);
+select is((select count(*) from public.grammar_sessions),0::bigint,'RLS hides other owner sessions');
+select throws_ok($q$select public.complete_grammar_session((select (value->>'id')::uuid from session_test where label='single'),1)$q$,'P0001','GRAMMAR_SESSION_NOT_FOUND','other owner cannot complete');
+select throws_ok($q$select public.start_grammar_session((select (value->>'id')::uuid from session_test where label='note'),'25252525-6666-4666-8666-666666666666','recall')$q$,'P0001','GRAMMAR_SESSION_NOT_FOUND','other owner cannot snapshot note');
+select is((public.list_grammar_session_history()->>'total')::integer,0,'history excludes other owner');
+select set_config('request.jwt.claim.sub','',true);
+select throws_ok($q$select public.list_grammar_session_history()$q$,'P0001','GRAMMAR_SESSION_UNAUTHORIZED','missing identity rejected');
+select * from finish();
+rollback;
From 6906ace36071d41b9fa100d0be6a7ae2b2511010 Mon Sep 17 00:00:00 2001
From: Wonik Choi
Date: Tue, 6 Oct 2026 02:28:07 +0900
Subject: [PATCH 02/12] fix(grammar): exclude unreviewed examples from practice
snapshots (#157)
---
supabase/migrations/20261007090000_grammar_sessions.sql | 2 +-
supabase/tests/grammar_sessions.test.sql | 3 ++-
2 files changed, 3 insertions(+), 2 deletions(-)
diff --git a/supabase/migrations/20261007090000_grammar_sessions.sql b/supabase/migrations/20261007090000_grammar_sessions.sql
index a3c9ebe4..98634789 100644
--- a/supabase/migrations/20261007090000_grammar_sessions.sql
+++ b/supabase/migrations/20261007090000_grammar_sessions.sql
@@ -42,7 +42,7 @@ begin
union all
select jsonb_build_object('id','example:'||(e->>'id'),'kind','existing','sentence',e->>'sentence',
'translation',e->>'translation','context','','requiredWords','[]'::jsonb,'chunks','[]'::jsonb)
- from jsonb_array_elements(v_note.content->'examples') e
+ from jsonb_array_elements(v_note.content->'examples') e where e->>'reviewStatus'='reviewed'
) select jsonb_agg(q order by random()) into v_questions from questions;
select jsonb_agg(q->>'id' order by ord) into v_order from jsonb_array_elements(v_questions) with ordinality as a(q,ord);
-- 두 문항 이상일 때 우연히 이전 순서와 같으면 회전하여 반복 순서를 피합니다.
diff --git a/supabase/tests/grammar_sessions.test.sql b/supabase/tests/grammar_sessions.test.sql
index 3e31649e..575664b1 100644
--- a/supabase/tests/grammar_sessions.test.sql
+++ b/supabase/tests/grammar_sessions.test.sql
@@ -33,10 +33,11 @@ select is(public.complete_grammar_session((select (value->>'id')::uuid from sess
select is((public.list_grammar_session_history()->>'total')::integer,1,'completion is counted once');
select is((select value->'questions' from session_test where label='completed'),(select value->'questions' from session_test where label='single'),'completion retains order and source');
select throws_ok($q$update public.grammar_sessions set answers='{}'$q$,'42501',null,'direct writes cannot bypass validation');
-insert into session_test select 'changed-note',public.update_grammar_note((value->>'id')::uuid,1,jsonb_set(pg_temp.grammar_content('Changed'),'{examples}','[{"id":"e1","sentence":"He is not lazy but tired.","translation":"그는 게으른 게 아니라 피곤합니다.","targetExplanation":"not A but B","reviewStatus":"reviewed"}]')) from session_test where label='note';
+insert into session_test select 'changed-note',public.update_grammar_note((value->>'id')::uuid,1,jsonb_set(pg_temp.grammar_content('Changed'),'{examples}','[{"id":"e1","sentence":"He is not lazy but tired.","translation":"그는 게으른 게 아니라 피곤합니다.","targetExplanation":"not A but B","reviewStatus":"reviewed"},{"id":"draft","sentence":"Unreviewed sentence.","translation":"미확인 예문","targetExplanation":"검토 전","reviewStatus":"needs-review"}]')) from session_test where label='note';
select is((select snapshot#>>'{metadata,title}' from public.grammar_sessions limit 1),'Not A but B','editing the note never changes frozen metadata');
insert into session_test select 'multi1',public.start_grammar_session((value->>'id')::uuid,'25252525-3333-4333-8333-333333333333','recall') from session_test where label='note';
insert into session_test select 'multi2',public.start_grammar_session((value->>'id')::uuid,'25252525-4444-4444-8444-444444444444','recall') from session_test where label='note';
+select is((select jsonb_array_length(value->'questions') from session_test where label='multi1'),2,'only adopted reviewed examples become practice questions');
select isnt((select value->'questions' from session_test where label='multi1'),(select value->'questions' from session_test where label='multi2'),'new multi-question session avoids previous order');
select is((public.list_grammar_session_history()->>'total')::integer,1,'active and abandoned sessions do not count');
select is((public.list_grammar_session_history(null,99,20)->>'total')::integer,1,'empty history page retains total');
From 6b2139cad0fa06f0ece1997eff9265f57c9006d1 Mon Sep 17 00:00:00 2001
From: Wonik Choi
Date: Thu, 8 Oct 2026 18:25:45 +0900
Subject: [PATCH 03/12] fix: address grammar editor review feedback (#168)
---
.../GrammarNoteEditor.stories.tsx | 2 +-
.../GrammarAnalysisEditor.test.tsx | 19 +++++++-
.../editAnalysis.test.ts | 35 ++++++++++++++
.../GrammarNoteEditor.test.tsx | 47 +++++++++++++++++++
.../createEditorStore.test.ts | 8 ++--
.../saveGrammarNote.test.ts | 4 +-
.../grammar-analysis-edit/models/store.ts | 19 ++++++--
.../ui/AnalysisEditorProvider.tsx | 19 +++-----
.../grammar-note-editor/models/interface.ts | 11 ++++-
.../services/actions/saveGrammarNote.ts | 10 +---
.../services/createEditorStore.ts | 27 ++++++-----
.../grammar-note-editor/ui/EditorError.tsx | 31 ++++++++++++
.../grammar-note-editor/ui/EditorProvider.tsx | 26 +++++++---
.../ui/GrammarNoteEditor.tsx | 8 +---
.../grammar-editor/GrammarEditorClient.tsx | 33 +++++++++++++
.../grammar-editor/GrammarEditorView.tsx | 24 +---------
16 files changed, 239 insertions(+), 84 deletions(-)
create mode 100644 src/features/grammar-note-editor/ui/EditorError.tsx
create mode 100644 src/views/grammar-editor/GrammarEditorClient.tsx
diff --git a/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx b/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx
index 6122136c..1e5f862b 100644
--- a/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx
+++ b/src/_storybook/features/grammar-note-editor/GrammarNoteEditor.stories.tsx
@@ -54,7 +54,7 @@ export const SaveFailure: Story = {
initialNote: note,
save: fn(async () => ({
ok: false as const,
- message: "노트를 저장하지 못했습니다. 다시 저장해 주세요.",
+ code: "PERSISTENCE_FAILED",
})),
},
play: async ({ canvasElement }) => {
diff --git a/src/_tests/features/grammar-analysis-edit/GrammarAnalysisEditor.test.tsx b/src/_tests/features/grammar-analysis-edit/GrammarAnalysisEditor.test.tsx
index 721257e8..2b20386e 100644
--- a/src/_tests/features/grammar-analysis-edit/GrammarAnalysisEditor.test.tsx
+++ b/src/_tests/features/grammar-analysis-edit/GrammarAnalysisEditor.test.tsx
@@ -118,16 +118,31 @@ 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 () => {
diff --git a/src/_tests/features/grammar-analysis-edit/editAnalysis.test.ts b/src/_tests/features/grammar-analysis-edit/editAnalysis.test.ts
index 658ee212..7e68b2cb 100644
--- a/src/_tests/features/grammar-analysis-edit/editAnalysis.test.ts
+++ b/src/_tests/features/grammar-analysis-edit/editAnalysis.test.ts
@@ -190,3 +190,38 @@ 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-note-editor/GrammarNoteEditor.test.tsx b/src/_tests/features/grammar-note-editor/GrammarNoteEditor.test.tsx
index 0fc45d68..eba9dd01 100644
--- a/src/_tests/features/grammar-note-editor/GrammarNoteEditor.test.tsx
+++ b/src/_tests/features/grammar-note-editor/GrammarNoteEditor.test.tsx
@@ -3,6 +3,7 @@ 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 });
@@ -64,3 +65,49 @@ 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..fc55e7b5 100644
--- a/src/_tests/features/grammar-note-editor/createEditorStore.test.ts
+++ b/src/_tests/features/grammar-note-editor/createEditorStore.test.ts
@@ -80,7 +80,7 @@ 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);
@@ -120,11 +120,11 @@ 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();
@@ -133,6 +133,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..7b002b4a 100644
--- a/src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts
+++ b/src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts
@@ -44,7 +44,7 @@ describe("어법 저장 서버 경계", () => {
const create = jest.spyOn(GrammarNoteRepository.prototype, "create");
expect(await saveGrammarNote(command())).toEqual({
ok: false,
- message: "로그인 후 다시 저장해 주세요.",
+ code: "UNAUTHORIZED",
});
expect(create).not.toHaveBeenCalled();
});
@@ -94,7 +94,7 @@ describe("어법 저장 서버 경계", () => {
});
expect(result).toEqual({
ok: false,
- message: "다른 화면에서 노트가 변경되었습니다. 새로고침 후 다시 확인해 주세요.",
+ code: "VERSION_CONFLICT",
});
});
it("실패는 내부 이벤트로 기록하고 원문과 내부 오류를 UI에 노출하지 않는다", async () => {
diff --git a/src/features/grammar-analysis-edit/models/store.ts b/src/features/grammar-analysis-edit/models/store.ts
index 61d6126a..ad34a4ea 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,
@@ -39,20 +43,24 @@ export function createAnalysisEditorStore({ initialAnalysis, onChange }: Analysi
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 } });
@@ -72,13 +80,14 @@ export function createAnalysisEditorStore({ initialAnalysis, onChange }: Analysi
...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..fab08ee1 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,22 +20,17 @@ 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};
}
diff --git a/src/features/grammar-note-editor/models/interface.ts b/src/features/grammar-note-editor/models/interface.ts
index 86244e69..8162b773 100644
--- a/src/features/grammar-note-editor/models/interface.ts
+++ b/src/features/grammar-note-editor/models/interface.ts
@@ -3,6 +3,7 @@ import type {
GrammarMetadata,
GrammarNote,
GrammarNoteContent,
+ GrammarNotePersistenceErrorCode,
GrammarSource,
PrecheckResult,
SentenceAnalysis,
@@ -17,7 +18,9 @@ export type SaveNoteCommand = {
content: GrammarNoteContent;
existing?: { id: string; expectedVersion: number };
};
-export type SaveNoteResult = { ok: true; note: GrammarNote } | { ok: false; message: string };
+export type SaveNoteResult =
+ | { ok: true; note: GrammarNote }
+ | { ok: false; code: GrammarNotePersistenceErrorCode };
export interface GrammarNoteEditorProps {
initialNote?: GrammarNote;
analyze: (source: GrammarSource) => Promise;
@@ -30,12 +33,16 @@ export interface GrammarNoteEditorProps {
onSaved: (note: GrammarNote) => void;
onExit: () => void;
}
+export type EditorError =
+ | { code: GrammarNotePersistenceErrorCode | "ANALYSIS_FAILED" | "INVALID_ANALYSIS" }
+ | { message: string };
+
export interface EditorState {
source: GrammarSource;
result: EditorAnalysisResult | null;
stage: "input" | "review";
pending: "analysis" | "save" | null;
- error: string;
+ error: EditorError | null;
fieldErrors: Partial>;
reviewed: boolean;
analysisDirty: boolean;
diff --git a/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts b/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts
index 10cbf14e..bc075299 100644
--- a/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts
+++ b/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts
@@ -22,14 +22,6 @@ export async function saveGrammarNote(command: SaveNoteCommand): Promise
- set({ analysisDirty, ...(analysisDirty ? { dirty: true, reviewed: false } : {}) }),
+ setAnalysisDirty: (analysisDirty) => {
+ if (get().analysisDirty === analysisDirty) return;
+ set({ analysisDirty, ...(analysisDirty ? { dirty: true, reviewed: false } : {}) });
+ },
dirty: false,
changeSource: (field, value) => {
if (get().pending === "save") return;
@@ -36,7 +38,7 @@ export function createEditorStore(
pending: null,
reviewed: false,
dirty: true,
- error: "",
+ error: null,
fieldErrors: {},
}));
},
@@ -46,6 +48,7 @@ export function createEditorStore(
? {
result: { status: "analyzed", data: { ...state.result.data, analysis } },
reviewed: false,
+ analysisDirty: false,
dirty: true,
}
: {},
@@ -54,7 +57,7 @@ export function createEditorStore(
back: () => {
if (get().pending === "save") return;
generation++;
- set({ stage: "input", pending: null, error: "", analysisDirty: false });
+ set({ stage: "input", pending: null, error: null, analysisDirty: false });
},
cancel: () => {
generation++;
@@ -70,7 +73,7 @@ export function createEditorStore(
return;
}
const currentGeneration = ++generation;
- set({ pending: "analysis", error: "", fieldErrors: {} });
+ set({ pending: "analysis", error: null, fieldErrors: {} });
try {
const result = await dependencies.analyze(parsed.data);
if (currentGeneration !== generation) return;
@@ -93,13 +96,13 @@ export function createEditorStore(
pending: null,
stage: result.status === "analyzed" ? "review" : "input",
reviewed: false,
- error: result.status === "error" ? result.message : "",
+ error: result.status === "error" ? { message: result.message } : null,
});
} catch {
if (currentGeneration === generation)
set({
pending: null,
- error: "분석을 완료하지 못했습니다. 입력을 유지했으니 다시 시도해 주세요.",
+ error: { code: "ANALYSIS_FAILED" },
});
}
},
@@ -119,14 +122,14 @@ export function createEditorStore(
examples: initialNote?.examples ?? [],
});
if (!content.success) {
- set({ error: "분석과 입력을 다시 확인해 주세요." });
+ set({ error: { code: "INVALID_ANALYSIS" } });
return;
}
const signature = JSON.stringify(content.data);
// 동일 저장의 네트워크 재시도에는 동일 UUID를 보내 서버 중복 생성을 막는다.
if (saveIdentity?.content !== signature)
saveIdentity = { content: signature, id: crypto.randomUUID() };
- set({ pending: "save", error: "" });
+ set({ pending: "save", error: null });
try {
const result = await dependencies.save({
requestId: saveIdentity.id,
@@ -136,13 +139,13 @@ export function createEditorStore(
: {}),
});
if (!result.ok) {
- set({ pending: null, error: result.message });
+ set({ pending: null, error: { code: result.code } });
return;
}
set({ pending: null, dirty: false });
dependencies.onSaved(result.note);
} catch {
- set({ pending: null, error: "저장하지 못했습니다. 입력을 유지했으니 다시 저장해 주세요." });
+ set({ pending: null, error: { code: "PERSISTENCE_FAILED" } });
}
},
}));
diff --git a/src/features/grammar-note-editor/ui/EditorError.tsx b/src/features/grammar-note-editor/ui/EditorError.tsx
new file mode 100644
index 00000000..c3530336
--- /dev/null
+++ b/src/features/grammar-note-editor/ui/EditorError.tsx
@@ -0,0 +1,31 @@
+"use client";
+import { useEditor } from "./EditorProvider";
+export function EditorError() {
+ const error = useEditor((s) => s.error);
+ if (!error) return null;
+ let message: string;
+ if ("message" in error) message = error.message;
+ else {
+ switch (error.code) {
+ case "VERSION_CONFLICT":
+ message = "다른 화면에서 노트가 변경되었습니다. 새로고침 후 다시 확인해 주세요.";
+ break;
+ case "UNAUTHORIZED":
+ message = "로그인 후 다시 저장해 주세요.";
+ break;
+ case "ANALYSIS_FAILED":
+ message = "분석을 완료하지 못했습니다. 입력을 유지했으니 다시 시도해 주세요.";
+ break;
+ case "INVALID_ANALYSIS":
+ message = "분석과 입력을 다시 확인해 주세요.";
+ break;
+ default:
+ message = "저장하지 못했습니다. 입력을 유지했으니 다시 저장해 주세요.";
+ }
+ }
+ return (
+
+ {message}
+
+ );
+}
diff --git a/src/features/grammar-note-editor/ui/EditorProvider.tsx b/src/features/grammar-note-editor/ui/EditorProvider.tsx
index 220c2380..71b58a21 100644
--- a/src/features/grammar-note-editor/ui/EditorProvider.tsx
+++ b/src/features/grammar-note-editor/ui/EditorProvider.tsx
@@ -1,5 +1,13 @@
"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 } from "zustand";
import type { StoreApi } from "zustand";
import type { EditorState, GrammarNoteEditorProps } from "../models/interface";
@@ -7,15 +15,19 @@ import { createEditorStore } from "../services/createEditorStore";
const Context = createContext | null>(null);
export function EditorProvider({
children,
- ...dependencies
+ initialNote,
+ analyze,
+ save,
+ onSaved,
}: Omit & { children: ReactNode }) {
- const latest = useRef(dependencies);
- useEffect(() => {
- latest.current = dependencies;
- }, [dependencies]);
+ const latest = useRef({ analyze, save, onSaved });
+ useLayoutEffect(() => {
+ latest.current = { analyze, save, onSaved };
+ }, [analyze, save, onSaved]);
+ // initialNote는 초기값이다. 문서 ID·버전이 바뀌면 호출부에서 key로 새 세션을 연다.
const [store] = useState(() =>
createEditorStore({
- initialNote: dependencies.initialNote,
+ initialNote,
analyze: (source) => latest.current.analyze(source),
save: (command) => latest.current.save(command),
onSaved: (note) => latest.current.onSaved(note),
diff --git a/src/features/grammar-note-editor/ui/GrammarNoteEditor.tsx b/src/features/grammar-note-editor/ui/GrammarNoteEditor.tsx
index 1efef5e0..9a78b3cc 100644
--- a/src/features/grammar-note-editor/ui/GrammarNoteEditor.tsx
+++ b/src/features/grammar-note-editor/ui/GrammarNoteEditor.tsx
@@ -4,6 +4,7 @@ import { Button } from "@/shared/components/atomics/button/Button";
import { ConfirmDialog } from "@/shared/components/ui/ConfirmDialog";
import type { GrammarNoteEditorProps } from "../models/interface";
import { EditorProvider, useEditor } from "./EditorProvider";
+import { EditorError } from "./EditorError";
import { SourceStep } from "./SourceStep";
import { ReviewStep } from "./ReviewStep";
function EditorBody({
@@ -11,16 +12,11 @@ function EditorBody({
onExit,
}: Pick) {
const stage = useEditor((s) => s.stage);
- const error = useEditor((s) => s.error);
return (
{stage === "input" ?
:
}
- {error && (
-
- {error}
-
- )}
+
);
}
diff --git a/src/views/grammar-editor/GrammarEditorClient.tsx b/src/views/grammar-editor/GrammarEditorClient.tsx
new file mode 100644
index 00000000..f31f4730
--- /dev/null
+++ b/src/views/grammar-editor/GrammarEditorClient.tsx
@@ -0,0 +1,33 @@
+"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,
+}: {
+ 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/views/grammar-editor/GrammarEditorView.tsx b/src/views/grammar-editor/GrammarEditorView.tsx
index d0fd5b91..f638d6e1 100644
--- a/src/views/grammar-editor/GrammarEditorView.tsx
+++ b/src/views/grammar-editor/GrammarEditorView.tsx
@@ -1,12 +1,6 @@
-"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";
+import { GrammarEditorClient } from "./GrammarEditorClient";
-// 다른 노트나 최신 저장 버전을 열 때 이전 초안이 섞이지 않도록 에디터 key에 ID와 버전을 함께 쓴다.
export function GrammarEditorView({
initialNote,
backHref = "/grammar",
@@ -14,9 +8,6 @@ export function GrammarEditorView({
initialNote?: GrammarNote;
backHref?: string;
}) {
- const router = useRouter();
- const returnTo =
- backHref === "/grammar" || backHref.startsWith("/grammar?") ? backHref : "/grammar";
return (
@@ -29,18 +20,7 @@ export function GrammarEditorView({
- {
- router.push(`/grammar/${note.id}?returnTo=${encodeURIComponent(returnTo)}`);
- router.refresh();
- }}
- onExit={() => router.push(returnTo)}
- />
+
);
From 29e90c52d46e77b851d631ca89646de9ebde36ef Mon Sep 17 00:00:00 2001
From: Wonik Choi
Date: Thu, 8 Oct 2026 18:49:54 +0900
Subject: [PATCH 04/12] refactor: apply shared review rules to example editing
(#169)
---
.../GrammarExampleManager.stories.tsx | 2 +-
.../GrammarExampleManager.test.tsx | 38 +++++++++++++++++++
.../createExampleStore.test.ts | 4 +-
.../exampleActions.test.ts | 10 ++---
.../models/errors.ts | 34 +++++++----------
.../models/interface.ts | 5 ++-
.../services/createExampleStore.ts | 18 ++++-----
.../services/server/executeExampleAction.ts | 4 +-
.../ui/ExampleActions.tsx | 3 +-
.../ui/ExampleProvider.tsx | 27 +++++++++----
.../ui/GrammarExampleManager.tsx | 2 +-
.../ui/errorMessage.ts | 23 +++++++++++
12 files changed, 120 insertions(+), 50 deletions(-)
create mode 100644 src/_tests/features/grammar-example-generation/GrammarExampleManager.test.tsx
create mode 100644 src/features/grammar-example-generation/ui/errorMessage.ts
diff --git a/src/_storybook/features/grammar-example-generation/GrammarExampleManager.stories.tsx b/src/_storybook/features/grammar-example-generation/GrammarExampleManager.stories.tsx
index c23634cb..f5d226ec 100644
--- a/src/_storybook/features/grammar-example-generation/GrammarExampleManager.stories.tsx
+++ b/src/_storybook/features/grammar-example-generation/GrammarExampleManager.stories.tsx
@@ -55,7 +55,7 @@ export const Retry: Story = {
play: async ({ canvasElement, args }) => {
args.generate.mockResolvedValueOnce({
ok: false,
- message: "생성에 실패했습니다. 다시 생성해 주세요.",
+ code: "FAILED",
});
const canvas = within(canvasElement);
await userEvent.click(canvas.getByRole("button", { name: "예문 3개 생성" }));
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..7f3196d0
--- /dev/null
+++ b/src/_tests/features/grammar-example-generation/GrammarExampleManager.test.tsx
@@ -0,0 +1,38 @@
+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..d5db6aad 100644
--- a/src/_tests/features/grammar-example-generation/createExampleStore.test.ts
+++ b/src/_tests/features/grammar-example-generation/createExampleStore.test.ts
@@ -24,11 +24,11 @@ describe("예문 초안 이벤트", () => {
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();
diff --git a/src/_tests/features/grammar-example-generation/exampleActions.test.ts b/src/_tests/features/grammar-example-generation/exampleActions.test.ts
index a1ae9573..4225c298 100644
--- a/src/_tests/features/grammar-example-generation/exampleActions.test.ts
+++ b/src/_tests/features/grammar-example-generation/exampleActions.test.ts
@@ -64,10 +64,10 @@ describe("예문 서버 액션 권한", () => {
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,7 +75,7 @@ describe("예문 서버 액션 권한", () => {
expectedVersion: 1,
count: 3,
});
- expect(result).toEqual({ ok: false, message });
+ expect(result).toEqual({ ok: false, code });
expect(requestExampleOutput).not.toHaveBeenCalled();
});
it("한도 조회 실패를 허용으로 처리하지 않는다", async () => {
diff --git a/src/features/grammar-example-generation/models/errors.ts b/src/features/grammar-example-generation/models/errors.ts
index f4f92640..203bb768 100644
--- a/src/features/grammar-example-generation/models/errors.ts
+++ b/src/features/grammar-example-generation/models/errors.ts
@@ -1,22 +1,16 @@
import { GrammarNotePersistenceError } from "@/entities/grammar-note";
-
-const messages = new Map([
- ["VERSION_CONFLICT", "노트가 변경되었습니다. 최신 노트를 불러온 뒤 다시 시도해 주세요."],
- ["UNAUTHORIZED", "로그인 후 다시 시도해 주세요."],
- ["NOT_FOUND", "노트를 찾을 수 없습니다."],
- ["rate_limited", "AI 요청 한도에 도달했습니다. 잠시 후 다시 시도해 주세요."],
- ["not_invited", "AI 기능을 사용할 권한이 없습니다."],
-]);
-
-export function grammarExampleErrorMessage(error: unknown): string {
- const code =
- error instanceof GrammarNotePersistenceError
- ? error.code
- : error instanceof Error
- ? error.message
- : "UNKNOWN";
- return (
- messages.get(code) ??
- "예문 작업을 완료하지 못했습니다. 기존 내용은 유지됩니다. 다시 시도해 주세요."
- );
+import type { GrammarNotePersistenceErrorCode } from "@/entities/grammar-note";
+export type ExampleErrorCode =
+ | GrammarNotePersistenceErrorCode
+ | "NOT_INVITED"
+ | "RATE_LIMITED"
+ | "FAILED"
+ | "GENERATION_FAILED"
+ | "SAVE_FAILED"
+ | "INVALID_SELECTION";
+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/interface.ts b/src/features/grammar-example-generation/models/interface.ts
index cb4ec544..eb16bcfd 100644
--- a/src/features/grammar-example-generation/models/interface.ts
+++ b/src/features/grammar-example-generation/models/interface.ts
@@ -1,3 +1,4 @@
+import type { ExampleErrorCode } from "./errors";
import type {
GrammarExample,
GrammarNote,
@@ -13,7 +14,7 @@ export interface SaveExamplesCommand {
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;
@@ -31,7 +32,7 @@ export interface ExampleState {
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/services/createExampleStore.ts b/src/features/grammar-example-generation/services/createExampleStore.ts
index 20953068..0a464464 100644
--- a/src/features/grammar-example-generation/services/createExampleStore.ts
+++ b/src/features/grammar-example-generation/services/createExampleStore.ts
@@ -9,14 +9,14 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) {
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;
@@ -44,7 +44,7 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) {
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,
@@ -53,7 +53,7 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) {
});
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));
@@ -83,7 +83,7 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) {
if (currentGeneration === generation)
set({
pending: null,
- error: "예문 생성에 실패했습니다. 기존 후보를 유지했으니 다시 생성해 주세요.",
+ error: "GENERATION_FAILED",
});
}
},
@@ -97,10 +97,10 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) {
!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,
@@ -108,7 +108,7 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) {
candidates,
});
if (!result.ok) {
- set({ pending: null, error: result.message });
+ set({ pending: null, error: result.code });
return;
}
set((current) => ({
@@ -124,7 +124,7 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) {
} catch {
set({
pending: null,
- error: "예문을 저장하지 못했습니다. 선택과 수정 내용을 유지했습니다. 다시 저장해 주세요.",
+ error: "SAVE_FAILED",
});
}
},
diff --git a/src/features/grammar-example-generation/services/server/executeExampleAction.ts b/src/features/grammar-example-generation/services/server/executeExampleAction.ts
index 62da348c..a5180a83 100644
--- a/src/features/grammar-example-generation/services/server/executeExampleAction.ts
+++ b/src/features/grammar-example-generation/services/server/executeExampleAction.ts
@@ -4,7 +4,7 @@ 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,
@@ -38,6 +38,6 @@ export async function executeExampleAction(
});
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/ui/ExampleActions.tsx b/src/features/grammar-example-generation/ui/ExampleActions.tsx
index f6624578..c8068564 100644
--- a/src/features/grammar-example-generation/ui/ExampleActions.tsx
+++ b/src/features/grammar-example-generation/ui/ExampleActions.tsx
@@ -1,5 +1,6 @@
"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);
@@ -26,7 +27,7 @@ export function ExampleActions() {
{error && (
- {error}
+ {exampleErrorMessage(error)}
)}
{pending && (
diff --git a/src/features/grammar-example-generation/ui/ExampleProvider.tsx b/src/features/grammar-example-generation/ui/ExampleProvider.tsx
index 54880e88..52176f5b 100644
--- a/src/features/grammar-example-generation/ui/ExampleProvider.tsx
+++ b/src/features/grammar-example-generation/ui/ExampleProvider.tsx
@@ -1,20 +1,33 @@
"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),
diff --git a/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx b/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx
index 023efd3c..04b9ef63 100644
--- a/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx
+++ b/src/features/grammar-example-generation/ui/GrammarExampleManager.tsx
@@ -39,7 +39,7 @@ function ExampleBack({ onBack }: { onBack?: () => void }) {
/** 노트 ID로 생명주기를 구분한다. 선택 저장 후 남은 후보 보존을 위해 버전 변경으로 재마운트하지 않는다. */
export function GrammarExampleManager({ onBack, ...props }: GrammarExampleManagerProps) {
return (
-
+
diff --git a/src/features/grammar-example-generation/ui/errorMessage.ts b/src/features/grammar-example-generation/ui/errorMessage.ts
new file mode 100644
index 00000000..727452f3
--- /dev/null
+++ b/src/features/grammar-example-generation/ui/errorMessage.ts
@@ -0,0 +1,23 @@
+import type { ExampleErrorCode } from "../models/errors";
+export function exampleErrorMessage(code: ExampleErrorCode): string {
+ switch (code) {
+ case "VERSION_CONFLICT":
+ return "노트가 변경되었습니다. 최신 노트를 불러온 뒤 다시 시도해 주세요.";
+ case "UNAUTHORIZED":
+ return "로그인 후 다시 시도해 주세요.";
+ case "NOT_FOUND":
+ return "노트를 찾을 수 없습니다.";
+ case "RATE_LIMITED":
+ return "AI 요청 한도에 도달했습니다. 잠시 후 다시 시도해 주세요.";
+ case "NOT_INVITED":
+ return "AI 기능을 사용할 권한이 없습니다.";
+ case "GENERATION_FAILED":
+ return "예문 생성에 실패했습니다. 기존 후보를 유지했으니 다시 생성해 주세요.";
+ case "SAVE_FAILED":
+ return "예문을 저장하지 못했습니다. 선택과 수정 내용을 유지했습니다. 다시 저장해 주세요.";
+ case "INVALID_SELECTION":
+ return "저장할 예문을 선택하고 문장·뜻·어법 설명을 모두 입력해 주세요.";
+ default:
+ return "예문 작업을 완료하지 못했습니다. 기존 내용은 유지됩니다. 다시 시도해 주세요.";
+ }
+}
From 7a160e3a8db7ddf5cd4896cbe3e8cabf3136b9e7 Mon Sep 17 00:00:00 2001
From: Wonik Choi
Date: Thu, 8 Oct 2026 18:51:09 +0900
Subject: [PATCH 05/12] refactor: keep audio error presentation in UI (#171)
---
.../GrammarAudioButton.stories.tsx | 2 +-
.../features/grammar-audio/audioCache.test.ts | 5 ++++-
.../grammar-audio/requestGrammarAudio.test.ts | 12 +++++++++++-
.../grammar-audio/useGrammarAudio.test.tsx | 3 ++-
src/features/grammar-audio/models/interface.ts | 9 ++++++++-
.../services/actions/requestGrammarAudio.ts | 18 ++++++++++--------
.../grammar-audio/services/useGrammarAudio.ts | 16 +++++++++-------
.../grammar-audio/ui/GrammarAudioButton.tsx | 7 ++++---
src/features/grammar-audio/ui/errorMessage.ts | 10 ++++++++++
9 files changed, 59 insertions(+), 23 deletions(-)
create mode 100644 src/features/grammar-audio/ui/errorMessage.ts
diff --git a/src/_storybook/features/grammar-audio/GrammarAudioButton.stories.tsx b/src/_storybook/features/grammar-audio/GrammarAudioButton.stories.tsx
index 1007f167..e713a54e 100644
--- a/src/_storybook/features/grammar-audio/GrammarAudioButton.stories.tsx
+++ b/src/_storybook/features/grammar-audio/GrammarAudioButton.stories.tsx
@@ -6,7 +6,7 @@ const meta = {
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;
diff --git a/src/_tests/features/grammar-audio/audioCache.test.ts b/src/_tests/features/grammar-audio/audioCache.test.ts
index 11fc7bac..6d9b7b91 100644
--- a/src/_tests/features/grammar-audio/audioCache.test.ts
+++ b/src/_tests/features/grammar-audio/audioCache.test.ts
@@ -12,7 +12,10 @@ describe("grammar audio content cache", () => {
});
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..64cba289 100644
--- a/src/_tests/features/grammar-audio/requestGrammarAudio.test.ts
+++ b/src/_tests/features/grammar-audio/requestGrammarAudio.test.ts
@@ -62,7 +62,7 @@ describe("authenticated saved sentence audio action", () => {
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();
@@ -82,6 +82,16 @@ describe("authenticated saved sentence audio action", () => {
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);
diff --git a/src/_tests/features/grammar-audio/useGrammarAudio.test.tsx b/src/_tests/features/grammar-audio/useGrammarAudio.test.tsx
index c05c0752..f7ebbdc9 100644
--- a/src/_tests/features/grammar-audio/useGrammarAudio.test.tsx
+++ b/src/_tests/features/grammar-audio/useGrammarAudio.test.tsx
@@ -69,11 +69,12 @@ describe("grammar audio lifecycle", () => {
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/features/grammar-audio/models/interface.ts b/src/features/grammar-audio/models/interface.ts
index 2889c26f..a2407406 100644
--- a/src/features/grammar-audio/models/interface.ts
+++ b/src/features/grammar-audio/models/interface.ts
@@ -3,9 +3,16 @@ 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"
diff --git a/src/features/grammar-audio/services/actions/requestGrammarAudio.ts b/src/features/grammar-audio/services/actions/requestGrammarAudio.ts
index 7ba2aab5..d56ed6c1 100644
--- a/src/features/grammar-audio/services/actions/requestGrammarAudio.ts
+++ b/src/features/grammar-audio/services/actions/requestGrammarAudio.ts
@@ -24,11 +24,10 @@ export async function requestGrammarAudio(input: unknown): Promise {
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();
@@ -40,10 +39,13 @@ export async function requestGrammarAudio(input: unknown): Promise("idle");
- const [message, setMessage] = useState("");
+ const [error, setError] = useState(null);
const generation = useRef(0);
const audio = useRef(null);
const speech = useRef | null>(null);
@@ -23,6 +24,7 @@ export function useGrammarAudio({ input, generate }: GrammarAudioButtonProps) {
}
useEffect(() => {
speech.current = null;
+ setError(null);
setStatus("idle");
const lifecycleGeneration = generation;
return () => {
@@ -41,7 +43,7 @@ export function useGrammarAudio({ input, generate }: GrammarAudioButtonProps) {
release.current?.();
release.current = null;
const currentGeneration = ++generation.current;
- setMessage("");
+ setError(null);
release.current = claimGrammarPlayback(stop);
let data = speech.current;
if (!data) {
@@ -50,7 +52,7 @@ export function useGrammarAudio({ input, generate }: GrammarAudioButtonProps) {
const result = await generate(input);
if (currentGeneration !== generation.current) return;
if (!result.ok) {
- setMessage(result.message);
+ setError(result.code);
setStatus("generation-error");
return;
}
@@ -58,7 +60,7 @@ export function useGrammarAudio({ input, generate }: GrammarAudioButtonProps) {
speech.current = result;
} catch {
if (currentGeneration !== generation.current) return;
- setMessage("음성 생성 요청에 실패했습니다.");
+ setError("GENERATION_FAILED");
setStatus("generation-error");
return;
}
@@ -71,7 +73,7 @@ export function useGrammarAudio({ input, generate }: GrammarAudioButtonProps) {
};
player.onerror = () => {
if (currentGeneration === generation.current) {
- setMessage("음성을 재생하지 못했습니다.");
+ setError("PLAYBACK_FAILED");
setStatus("playback-error");
}
};
@@ -83,9 +85,9 @@ export function useGrammarAudio({ input, generate }: GrammarAudioButtonProps) {
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..27ae6518 100644
--- a/src/features/grammar-audio/ui/GrammarAudioButton.tsx
+++ b/src/features/grammar-audio/ui/GrammarAudioButton.tsx
@@ -1,8 +1,9 @@
"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..85016b0a
--- /dev/null
+++ b/src/features/grammar-audio/ui/errorMessage.ts
@@ -0,0 +1,10 @@
+import type { GrammarAudioErrorCode } from "../models/interface";
+export const grammarAudioErrorMessages: Record = {
+ INVALID_INPUT: "음성 요청을 확인해주세요.",
+ UNAUTHORIZED: "로그인 후 다시 시도해주세요.",
+ NOT_INVITED: "AI 음성 이용 권한이 필요합니다.",
+ RATE_LIMITED: "음성 요청 한도에 도달했습니다. 잠시 후 다시 시도해주세요.",
+ GENERATION_FAILED:
+ "음성을 생성하지 못했습니다. 노트가 변경되었다면 새로고침 후 다시 생성해주세요.",
+ PLAYBACK_FAILED: "음성을 재생하지 못했습니다. 재생 버튼을 다시 눌러주세요.",
+};
From bf85fd72a3a2e0e6f7b864433d280618c72f0f23 Mon Sep 17 00:00:00 2001
From: Wonik Choi
Date: Thu, 8 Oct 2026 18:52:21 +0900
Subject: [PATCH 06/12] refactor: return session error codes at server boundary
(#172)
---
.../grammarSessionActions.test.ts | 33 +++++++++++++++++++
src/entities/grammar-session/index.ts | 3 +-
src/entities/grammar-session/models/errors.ts | 13 --------
.../grammar-session/ui/errorMessage.ts | 12 +++++++
.../grammar-practice/models/interface.ts | 4 +--
.../services/actions/grammarSessionActions.ts | 10 +++---
6 files changed, 55 insertions(+), 20 deletions(-)
create mode 100644 src/_tests/features/grammar-practice/grammarSessionActions.test.ts
create mode 100644 src/entities/grammar-session/ui/errorMessage.ts
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..6acac44e
--- /dev/null
+++ b/src/_tests/features/grammar-practice/grammarSessionActions.test.ts
@@ -0,0 +1,33 @@
+/** @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/entities/grammar-session/index.ts b/src/entities/grammar-session/index.ts
index 8e8eb9af..1cc20d25 100644
--- a/src/entities/grammar-session/index.ts
+++ b/src/entities/grammar-session/index.ts
@@ -21,4 +21,5 @@ export type {
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/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/ui/errorMessage.ts b/src/entities/grammar-session/ui/errorMessage.ts
new file mode 100644
index 00000000..2104ad2b
--- /dev/null
+++ b/src/entities/grammar-session/ui/errorMessage.ts
@@ -0,0 +1,12 @@
+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-practice/models/interface.ts b/src/features/grammar-practice/models/interface.ts
index 02d915aa..3b5b6022 100644
--- a/src/features/grammar-practice/models/interface.ts
+++ b/src/features/grammar-practice/models/interface.ts
@@ -1,4 +1,4 @@
-import type { GrammarSession } from "@/entities/grammar-session";
+import type { GrammarSession, GrammarSessionError } from "@/entities/grammar-session";
export type GrammarSessionResult =
| { ok: true; data: GrammarSession }
- | { ok: false; message: string };
+ | { ok: false; code: GrammarSessionError["code"] };
diff --git a/src/features/grammar-practice/services/actions/grammarSessionActions.ts b/src/features/grammar-practice/services/actions/grammarSessionActions.ts
index ea9798b0..8e3ef693 100644
--- a/src/features/grammar-practice/services/actions/grammarSessionActions.ts
+++ b/src/features/grammar-practice/services/actions/grammarSessionActions.ts
@@ -6,7 +6,6 @@ import { recordOperationEvent } from "@/shared/lib/logging/pino";
import {
GrammarSessionRepository,
GrammarSessionError,
- grammarSessionErrorMessage,
startGrammarSessionSchema,
saveGrammarAnswersSchema,
completeGrammarSessionSchema,
@@ -33,9 +32,12 @@ async function executeSessionAction(
} catch (error) {
return {
ok: false,
- message: grammarSessionErrorMessage(
- error instanceof z.ZodError ? new GrammarSessionError("INVALID_INPUT") : error,
- ),
+ code:
+ error instanceof z.ZodError
+ ? "INVALID_INPUT"
+ : error instanceof GrammarSessionError
+ ? error.code
+ : "FAILED",
};
}
}
From 50963961f637c9a86bd489d89b255e34a0a52b4a Mon Sep 17 00:00:00 2001
From: Wonik Choi
Date: Thu, 8 Oct 2026 18:58:55 +0900
Subject: [PATCH 07/12] style: separate logical blocks for PR #169
---
.../GrammarExampleManager.stories.tsx | 13 ++++++++
.../GrammarExampleManager.test.tsx | 2 ++
.../createExampleStore.test.ts | 20 +++++++++++++
.../exampleActions.test.ts | 21 +++++++++++++
.../exampleServices.test.ts | 24 +++++++++++++++
.../grammar-example-generation/fixtures.ts | 1 +
.../grammar-example-generation/index.ts | 1 +
.../models/errors.ts | 5 ++++
.../models/interface.ts | 6 ++++
.../models/schema.ts | 4 +++
.../services/actions/exampleActions.ts | 3 ++
.../services/createExampleStore.ts | 30 +++++++++++++++++++
.../services/generateExamples.ts | 9 ++++++
.../services/loadTargetNote.ts | 4 +++
.../services/saveExamples.ts | 9 ++++++
.../services/server/executeExampleAction.ts | 8 +++++
.../services/server/requestExampleOutput.ts | 2 ++
.../ui/ExampleActions.tsx | 3 ++
.../ui/ExampleCandidateCard.tsx | 5 ++++
.../ui/ExampleCandidates.tsx | 3 ++
.../ui/ExampleProvider.tsx | 14 +++++++++
.../ui/GrammarExampleManager.tsx | 5 ++++
.../ui/errorMessage.ts | 1 +
23 files changed, 193 insertions(+)
diff --git a/src/_storybook/features/grammar-example-generation/GrammarExampleManager.stories.tsx b/src/_storybook/features/grammar-example-generation/GrammarExampleManager.stories.tsx
index f5d226ec..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,
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/_tests/features/grammar-example-generation/GrammarExampleManager.test.tsx b/src/_tests/features/grammar-example-generation/GrammarExampleManager.test.tsx
index 7f3196d0..af759e9f 100644
--- a/src/_tests/features/grammar-example-generation/GrammarExampleManager.test.tsx
+++ b/src/_tests/features/grammar-example-generation/GrammarExampleManager.test.tsx
@@ -7,6 +7,7 @@ import {
} from "@/features/grammar-example-generation";
import { createEditorNote } from "../grammar-note-editor/fixtures";
import { createExampleCandidates } from "./fixtures";
+
describe("예문 편집 세션", () => {
it("같은 노트의 버전 갱신에는 초안을 유지하고 최신 콜백을 쓰며 다른 노트에는 초기화한다", async () => {
const note = createEditorNote();
@@ -20,6 +21,7 @@ describe("예문 편집 세션", () => {
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." },
diff --git a/src/_tests/features/grammar-example-generation/createExampleStore.test.ts b/src/_tests/features/grammar-example-generation/createExampleStore.test.ts
index d5db6aad..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,11 +17,14 @@ 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);
@@ -30,10 +34,13 @@ describe("예문 초안 이벤트", () => {
expect(store.getState().selected).toEqual(["candidate-0"]);
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 4225c298..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,11 +73,13 @@ 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", "NOT_INVITED"],
["rate_limited", "RATE_LIMITED"],
@@ -75,9 +92,11 @@ describe("예문 서버 액션 권한", () => {
expectedVersion: 1,
count: 3,
});
+
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..09e5e0ee 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,11 +144,13 @@ 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();
});
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/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 203bb768..4ed0ced3 100644
--- a/src/features/grammar-example-generation/models/errors.ts
+++ b/src/features/grammar-example-generation/models/errors.ts
@@ -1,5 +1,6 @@
import { GrammarNotePersistenceError } from "@/entities/grammar-note";
import type { GrammarNotePersistenceErrorCode } from "@/entities/grammar-note";
+
export type ExampleErrorCode =
| GrammarNotePersistenceErrorCode
| "NOT_INVITED"
@@ -8,9 +9,13 @@ export type ExampleErrorCode =
| "GENERATION_FAILED"
| "SAVE_FAILED"
| "INVALID_SELECTION";
+
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/interface.ts b/src/features/grammar-example-generation/models/interface.ts
index eb16bcfd..a2066859 100644
--- a/src/features/grammar-example-generation/models/interface.ts
+++ b/src/features/grammar-example-generation/models/interface.ts
@@ -4,22 +4,27 @@ import type {
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; 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>;
@@ -27,6 +32,7 @@ export interface GrammarExampleManagerProps {
onUpdated: (note: GrammarNote) => void;
onBack?: () => void;
}
+
export interface ExampleState {
note: GrammarNote;
candidates: readonly GrammarExample[];
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 0a464464..e05c1ba2 100644
--- a/src/features/grammar-example-generation/services/createExampleStore.ts
+++ b/src/features/grammar-example-generation/services/createExampleStore.ts
@@ -1,9 +1,11 @@
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: [],
@@ -11,15 +13,19 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) {
pending: null,
error: null,
dirty: false,
+
cancel: () => {
generation++;
},
+
discard: () => {
generation++;
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: 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.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) =>
@@ -87,30 +107,40 @@ export function createExampleStore(dependencies: GrammarExampleManagerProps) {
});
}
},
+
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: "INVALID_SELECTION" });
+
return;
}
+
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.code });
+
return;
}
+
set((current) => ({
note: result.data,
candidates: current.candidates.filter(
diff --git a/src/features/grammar-example-generation/services/generateExamples.ts b/src/features/grammar-example-generation/services/generateExamples.ts
index a9f024d0..97cb0b53 100644
--- a/src/features/grammar-example-generation/services/generateExamples.ts
+++ b/src/features/grammar-example-generation/services/generateExamples.ts
@@ -2,6 +2,7 @@ import { grammarExampleSchema } from "@/entities/grammar-note";
import type { ExampleDependencies } from "../models/interface";
import { exampleOutputSchema, generateExamplesCommandSchema } from "../models/schema";
import { loadTargetNote } from "./loadTargetNote";
+
export async function generateExamples(input: unknown, dependencies: ExampleDependencies) {
// 1. 식별자와 버전을 검사하고 소유권이 적용된 저장소에서 목표 어법을 읽는다.
const command = generateExamplesCommandSchema.parse(input);
@@ -11,10 +12,14 @@ 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,
@@ -22,19 +27,23 @@ export async function generateExamples(input: unknown, dependencies: ExampleDepe
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/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..d8e2aa6a 100644
--- a/src/features/grammar-example-generation/services/saveExamples.ts
+++ b/src/features/grammar-example-generation/services/saveExamples.ts
@@ -3,14 +3,18 @@ import {
type GrammarNoteRepositoryPort,
} from "@/entities/grammar-note";
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(
@@ -22,12 +26,17 @@ export async function saveExamples(input: unknown, repository: GrammarNoteReposi
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");
+
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 a5180a83..03723935 100644
--- a/src/features/grammar-example-generation/services/server/executeExampleAction.ts
+++ b/src/features/grammar-example-generation/services/server/executeExampleAction.ts
@@ -6,6 +6,7 @@ import { recordOperationEvent } from "@/shared/lib/logging/pino";
import type { ExampleDependencies, ExampleResult } from "../../models/interface";
import { grammarExampleErrorCode } from "../../models/errors";
import { requestExampleOutput } from "./requestExampleOutput";
+
export async function executeExampleAction(
operation: string,
execute: (dependencies: ExampleDependencies) => Promise,
@@ -15,27 +16,34 @@ 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");
+
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, 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 c8068564..220eb18a 100644
--- a/src/features/grammar-example-generation/ui/ExampleActions.tsx
+++ b/src/features/grammar-example-generation/ui/ExampleActions.tsx
@@ -1,7 +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);
@@ -9,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 (
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 52176f5b..51e50baf 100644
--- a/src/features/grammar-example-generation/ui/ExampleProvider.tsx
+++ b/src/features/grammar-example-generation/ui/ExampleProvider.tsx
@@ -1,4 +1,5 @@
"use client";
+
import {
createContext,
useContext,
@@ -11,7 +12,9 @@ import {
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,
note,
@@ -21,6 +24,7 @@ export function ExampleProvider({
onBack,
}: GrammarExampleManagerProps & { children: ReactNode }) {
const latest = useRef({ generate, save, onUpdated });
+
useLayoutEffect(() => {
latest.current = { generate, save, onUpdated };
}, [generate, save, onUpdated]);
@@ -28,11 +32,15 @@ export function ExampleProvider({
createExampleStore({
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) {
@@ -41,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 04b9ef63..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 (
<>