Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/_storybook/views/PracticeHub.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
MyPageMaterialRows,
MyPageStatistics,
} from "@/views/my-page/ui/MyPageContent";
import { GrammarDifficultySetting } from "@/views/my-page/ui/GrammarDifficultySetting";
import { RolePlayEditorClient } from "@/views/role-play/ui/editor/RolePlayEditorClient";
import { MemorizationEditorClient } from "@/views/memorization/ui/editor/MemorizationEditorClient";
import { MaterialLibraryHeader } from "@/widgets/material-library/ui/MaterialLibraryHeader";
Expand Down Expand Up @@ -169,6 +170,7 @@ function Walkthrough({
else if (path === "/my-page")
content = (
<MyPageContent
difficulty={<GrammarDifficultySetting initialDifficulty={2} />}
roleplay={<MyPageMaterialRows items={roleplay} />}
memorization={<MyPageMaterialRows items={memorization} />}
statistics={
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { randomUUID } from "node:crypto";
import { beforeEach, describe, expect, it, jest } from "@jest/globals";
import { GrammarNoteRepository } from "@/entities/grammar-note";
import { UserProfileRepository } from "@/entities/user-profile";
import type { createSupabaseServerClient as CreateClient } from "@/shared/lib/supabase/server";
import type {
GenerateExamplesCommand,
Expand Down Expand Up @@ -50,6 +51,7 @@ beforeEach(async () => {
jest.restoreAllMocks();
jest.clearAllMocks();
rpc.mockResolvedValue({ data: "allowed", error: null });
jest.spyOn(UserProfileRepository.prototype, "findById").mockResolvedValue(null);
jest.mocked(createSupabaseServerClient).mockResolvedValue({
auth: { getUser: async () => ({ data: { user: { id: "owner" } }, error: null }) },
rpc,
Expand Down Expand Up @@ -112,6 +114,56 @@ describe("예문 서버 액션 권한", () => {
expect(requestExampleOutput).not.toHaveBeenCalled();
});

it("프로필이 없으면 기본 난이도 2로 예문을 생성한다", async () => {
const note = createEditorNote();
jest.spyOn(GrammarNoteRepository.prototype, "findById").mockResolvedValue(note);
jest.mocked(requestExampleOutput).mockResolvedValue({
examples: createExampleCandidates().map(({ sentence, translation, targetExplanation }) => ({
sentence,
translation,
targetExplanation,
})),
});

const result = await requestGrammarExamples({ noteId: note.id, expectedVersion: 1, count: 3 });

expect(result.ok).toBe(true);
expect(requestExampleOutput).toHaveBeenCalledWith(note, 3, 2);
});

it("저장된 난이도를 읽어 AI에 전달하며 조회 실패 시 한도를 소비하지 않는다", async () => {
const note = createEditorNote();
jest.spyOn(GrammarNoteRepository.prototype, "findById").mockResolvedValue(note);
const profile = jest.spyOn(UserProfileRepository.prototype, "findById");
profile.mockResolvedValueOnce({
id: "owner",
displayName: "Yeli",
exampleDifficulty: 3,
createdAt: new Date(),
updatedAt: new Date(),
} as never);
jest.mocked(requestExampleOutput).mockResolvedValue({
examples: createExampleCandidates().map(({ sentence, translation, targetExplanation }) => ({
sentence,
translation,
targetExplanation,
})),
});

const result = await requestGrammarExamples({ noteId: note.id, expectedVersion: 1, count: 3 });
expect(result.ok).toBe(true);
expect(requestExampleOutput).toHaveBeenCalledWith(note, 3, 3);

rpc.mockClear();
jest.mocked(requestExampleOutput).mockClear();
profile.mockRejectedValueOnce(new Error("profile unavailable"));
expect(
(await requestGrammarExamples({ noteId: note.id, expectedVersion: 1, count: 3 })).ok,
).toBe(false);
expect(rpc).not.toHaveBeenCalled();
expect(requestExampleOutput).not.toHaveBeenCalled();
});

it("선택 저장에는 AI 비용을 소비하지 않는다", async () => {
const note = createEditorNote();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,14 @@ function setup() {
const consumeRequest = jest
.fn<ExampleDependencies["consumeRequest"]>()
.mockResolvedValue("allowed");
const loadDifficulty = jest.fn<() => Promise<1 | 2 | 3>>().mockResolvedValue(2);

return {
note,
repository,
generate,
consumeRequest,
loadDifficulty,
command: { noteId: note.id, expectedVersion: 1, count: 3 as const },
};
}
Expand All @@ -44,7 +46,7 @@ describe("저장 노트 기반 예문 생성 및 채택", () => {
const deps = setup();
const result = await generateExamples(deps.command, deps);

expect(deps.generate).toHaveBeenCalledWith(deps.note, 3);
expect(deps.generate).toHaveBeenCalledWith(deps.note, 3, 2);
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);
Expand Down Expand Up @@ -82,6 +84,24 @@ describe("저장 노트 기반 예문 생성 및 채택", () => {
expect(deps.generate).not.toHaveBeenCalled();
});

it("저장된 난이도를 다음 예문 생성에 적용한다", async () => {
const deps = setup();
deps.loadDifficulty.mockResolvedValue(3);

await generateExamples(deps.command, deps);

expect(deps.generate).toHaveBeenCalledWith(deps.note, 3, 3);
});

it("난이도 조회 실패 시 요청 한도와 AI 비용을 소비하지 않는다", async () => {
const deps = setup();
deps.loadDifficulty.mockRejectedValue(new Error("profile unavailable"));

await expect(generateExamples(deps.command, deps)).rejects.toThrow("profile unavailable");
expect(deps.consumeRequest).not.toHaveBeenCalled();
expect(deps.generate).not.toHaveBeenCalled();
});

it("예문 개수가 다르거나 공백인 결과를 반환하지 않는다", async () => {
const deps = setup();

Expand Down
57 changes: 57 additions & 0 deletions src/_tests/views/my-page/GrammarDifficultySetting.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { describe, expect, it, jest, beforeEach } from "@jest/globals";

let GrammarDifficultySetting: typeof import("@/views/my-page/ui/GrammarDifficultySetting").GrammarDifficultySetting;
let saveGrammarDifficulty: typeof import("@/views/my-page/services/actions/saveGrammarDifficulty").saveGrammarDifficulty;

jest.mock("@/views/my-page/services/actions/saveGrammarDifficulty", () => ({
saveGrammarDifficulty: jest.fn(),
}));

beforeEach(async () => {
({ GrammarDifficultySetting } = await import("@/views/my-page/ui/GrammarDifficultySetting"));
({ saveGrammarDifficulty } =
await import("@/views/my-page/services/actions/saveGrammarDifficulty"));
jest.clearAllMocks();
});

describe("마이페이지 예문 난이도 설정", () => {
it("저장된 난이도를 처음부터 선택해 보여준다", () => {
render(<GrammarDifficultySetting initialDifficulty={3} />);
expect(screen.getByRole("radio", { name: /3단계/ })).toBeChecked();
});

it("기본값 2에서 1~3 중 하나를 저장하고 요청 중에는 다시 변경하거나 저장할 수 없다", async () => {
let finish!: (result: { ok: true }) => void;
jest.mocked(saveGrammarDifficulty).mockImplementation(
() =>
new Promise((resolve) => {
finish = resolve;
}),
);
render(<GrammarDifficultySetting initialDifficulty={2} />);

expect(screen.getByRole("radio", { name: /2단계/ })).toBeChecked();
fireEvent.click(screen.getByRole("radio", { name: /3단계/ }));
fireEvent.click(screen.getByRole("button", { name: /저장/ }));

expect(saveGrammarDifficulty).toHaveBeenCalledWith(3);
expect(screen.getByRole("button", { name: /저장/ })).toBeDisabled();
expect(screen.getByRole("radio", { name: /1단계/ })).toBeDisabled();
finish({ ok: true });
await waitFor(() => expect(screen.getByRole("button", { name: /저장/ })).toBeEnabled());
expect(screen.getByRole("radio", { name: /3단계/ })).toBeChecked();
});

it("저장 실패를 알리고 선택한 난이도를 유지해 재시도할 수 있다", async () => {
jest.mocked(saveGrammarDifficulty).mockResolvedValue({ ok: false, code: "FAILED" });
render(<GrammarDifficultySetting initialDifficulty={1} />);

fireEvent.click(screen.getByRole("radio", { name: /2단계/ }));
fireEvent.click(screen.getByRole("button", { name: /저장/ }));

expect(await screen.findByRole("alert")).toHaveTextContent(/저장/);
expect(screen.getByRole("radio", { name: /2단계/ })).toBeChecked();
expect(screen.getByRole("button", { name: /저장/ })).toBeEnabled();
});
});
93 changes: 93 additions & 0 deletions src/_tests/views/my-page/grammarDifficultyAction.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { beforeEach, describe, expect, it, jest } from "@jest/globals";
import type { createSupabaseServerClient as CreateClient } from "@/shared/lib/supabase/server";
import type { UserId } from "@/entities/value-object";

let createSupabaseServerClient: typeof CreateClient;

jest.mock("server-only", () => ({}));
jest.mock("@/shared/lib/supabase/server", () => ({ createSupabaseServerClient: jest.fn() }));

const save = jest.fn<() => Promise<void>>();

beforeEach(async () => {
({ createSupabaseServerClient } = await import("@/shared/lib/supabase/server"));
jest.restoreAllMocks();
jest.clearAllMocks();
jest.mocked(createSupabaseServerClient).mockResolvedValue({
auth: { getUser: async () => ({ data: { user: { id: "owner" } }, error: null }) },
} as never);
save.mockResolvedValue();
const { UserProfileRepository } = await import("@/entities/user-profile");
jest.spyOn(UserProfileRepository.prototype, "saveDifficulty").mockImplementation(save);
});

describe("예문 난이도 저장 액션", () => {
it.each([0, 4, "2", null])("범위 밖 입력 %p를 저장하지 않는다", async (value) => {
const { saveGrammarDifficulty } =
await import("@/views/my-page/services/actions/saveGrammarDifficulty");
expect(await saveGrammarDifficulty(value)).toEqual({ ok: false, code: "INVALID" });
expect(save).not.toHaveBeenCalled();
});

it("로그인하지 않은 사용자는 프로필을 수정할 수 없다", async () => {
jest.mocked(createSupabaseServerClient).mockResolvedValue({
auth: { getUser: async () => ({ data: { user: null }, error: null }) },
} as never);
const { saveGrammarDifficulty } =
await import("@/views/my-page/services/actions/saveGrammarDifficulty");

expect(await saveGrammarDifficulty(3)).toEqual({ ok: false, code: "UNAUTHORIZED" });
expect(save).not.toHaveBeenCalled();
});

it("인증된 본인의 난이도만 저장하고 저장 오류는 실패로 반환한다", async () => {
const { saveGrammarDifficulty } =
await import("@/views/my-page/services/actions/saveGrammarDifficulty");
expect(await saveGrammarDifficulty(3)).toEqual({ ok: true });
expect(save).toHaveBeenCalledWith("owner", 3);

save.mockRejectedValueOnce(new Error("database unavailable"));
expect(await saveGrammarDifficulty(1)).toEqual({ ok: false, code: "FAILED" });
});
});

describe("예문 난이도 저장소", () => {
it("기존 프로필의 다른 필드를 변경하지 않고 난이도만 갱신한다", async () => {
const { UserProfileRepository } = await import("@/entities/user-profile");
jest.restoreAllMocks();
const row = {
id: "owner",
display_name: "Yeli",
example_difficulty: 1,
created_at: "2026-10-12T00:00:00Z",
updated_at: "2026-10-12T00:00:00Z",
};
const selectQuery = {
eq: jest.fn().mockReturnValue({ maybeSingle: async () => ({ data: row, error: null }) }),
};
const updateQuery = { eq: jest.fn(async () => ({ error: null })) };
const update = jest.fn().mockReturnValue(updateQuery);
const client = { from: jest.fn().mockReturnValue({ select: () => selectQuery, update }) };
const repository = new UserProfileRepository(client as never);

await repository.saveDifficulty("owner" as UserId, 3);

expect(client.from).toHaveBeenCalledWith("user_profiles");
expect(update).toHaveBeenCalledWith({ example_difficulty: 3 });
expect(updateQuery.eq).toHaveBeenCalledWith("id", "owner");
});

it("프로필이 없는 사용자도 다른 필드를 덮어쓰지 않고 새 난이도를 저장한다", async () => {
const { UserProfileRepository } = await import("@/entities/user-profile");
jest.restoreAllMocks();
const selectQuery = {
eq: jest.fn().mockReturnValue({ maybeSingle: async () => ({ data: null, error: null }) }),
};
const insert = jest.fn(async () => ({ error: null }));
const client = { from: jest.fn().mockReturnValue({ select: () => selectQuery, insert }) };

await new UserProfileRepository(client as never).saveDifficulty("owner" as UserId, 2);

expect(insert).toHaveBeenCalledWith({ id: "owner", example_difficulty: 2 });
});
});
18 changes: 18 additions & 0 deletions src/entities/user-profile/infrastructure/UserProfileRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { EchoUserProfile } from "@/entities/user-profile/models/entity";
import { mapUserProfileRowToEntity } from "@/entities/user-profile/models/mapper";
import type { UserProfileRepositoryPort } from "@/entities/user-profile/models/repository";
import type { UserId } from "@/entities/value-object";
import type { GrammarDifficulty } from "@/entities/user-profile/models/entity";
import type { Database } from "@/shared/lib/supabase";

export class UserProfileRepository implements UserProfileRepositoryPort {
Expand All @@ -22,6 +23,23 @@ export class UserProfileRepository implements UserProfileRepositoryPort {

return data ? mapUserProfileRowToEntity(data) : null;
}

async saveDifficulty(id: UserId, difficulty: GrammarDifficulty): Promise<void> {
const { data, error: lookupError } = await this.supabase
.from("user_profiles")
.select("id")
.eq("id", id)
.maybeSingle();
if (lookupError) throw new Error("Failed to load user profile", { cause: lookupError });

const { error } = data
? await this.supabase
.from("user_profiles")
.update({ example_difficulty: difficulty })
.eq("id", id)
: await this.supabase.from("user_profiles").insert({ id, example_difficulty: difficulty });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Make first-time profile creation atomic

When a user without a profile submits their first setting concurrently from two tabs or devices, both calls can observe data === null and attempt this insert; one then fails on the user_profiles primary key and reports a save failure even though the input was valid. Use an atomic upsert that updates only example_difficulty, or otherwise handle the duplicate-key race.

Useful? React with 👍 / 👎.

if (error) throw new Error("Failed to save grammar difficulty", { cause: error });
}
}

export function createUserProfileRepository(
Expand Down
2 changes: 2 additions & 0 deletions src/entities/user-profile/models/__tests__/mapper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ describe("mapUserProfileRowToEntity", () => {
const row: UserProfileRow = {
id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
display_name: "Yeli",
example_difficulty: 3,
created_at: "2026-06-13T00:00:00.000Z",
updated_at: "2026-06-13T00:10:00.000Z",
};
Expand All @@ -17,6 +18,7 @@ describe("mapUserProfileRowToEntity", () => {
expect(entity).toMatchObject({
id: row.id,
displayName: "Yeli",
exampleDifficulty: 3,
});
expect(entity.createdAt).toEqual(new Date(row.created_at));
expect(entity.updatedAt).toEqual(new Date(row.updated_at));
Expand Down
6 changes: 6 additions & 0 deletions src/entities/user-profile/models/entity.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import type { UserId } from "@/entities/value-object";
import { z } from "zod";

export const grammarDifficultySchema = z.union([z.literal(1), z.literal(2), z.literal(3)]);
export type GrammarDifficulty = z.infer<typeof grammarDifficultySchema>;
export const DEFAULT_GRAMMAR_DIFFICULTY: GrammarDifficulty = 2;

export interface EchoUserProfile {
readonly id: UserId;
readonly displayName: string | null;
readonly exampleDifficulty: GrammarDifficulty;
readonly createdAt: Date;
readonly updatedAt: Date;
}
4 changes: 4 additions & 0 deletions src/entities/user-profile/models/mapper.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import type { EchoUserProfile } from "@/entities/user-profile/models/entity";
import type { UserId } from "@/entities/value-object";
import type { Database } from "@/shared/lib/supabase";
import { DEFAULT_GRAMMAR_DIFFICULTY, grammarDifficultySchema } from "./entity";

export type UserProfileRow = Database["public"]["Tables"]["user_profiles"]["Row"];

export function mapUserProfileRowToEntity(row: UserProfileRow): EchoUserProfile {
return {
id: row.id as UserId,
displayName: row.display_name,
exampleDifficulty: grammarDifficultySchema.parse(
row.example_difficulty ?? DEFAULT_GRAMMAR_DIFFICULTY,
),
createdAt: new Date(row.created_at),
updatedAt: new Date(row.updated_at),
};
Expand Down
2 changes: 2 additions & 0 deletions src/entities/user-profile/models/repository.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type { EchoUserProfile } from "@/entities/user-profile/models/entity";
import type { UserId } from "@/entities/value-object";
import type { GrammarDifficulty } from "./entity";

export interface UserProfileRepositoryPort {
findById(id: UserId): Promise<EchoUserProfile | null>;
saveDifficulty(id: UserId, difficulty: GrammarDifficulty): Promise<void>;
}
4 changes: 3 additions & 1 deletion src/features/grammar-example-generation/models/interface.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { ExampleErrorCode } from "./errors";
import type { GrammarDifficulty } from "@/entities/user-profile/models/entity";
import type {
GrammarExample,
GrammarNote,
Expand All @@ -21,7 +22,8 @@ export type ExampleResult<T> = { ok: true; data: T } | { ok: false; code: Exampl

export interface ExampleDependencies {
repository: GrammarNoteRepositoryPort;
generate: (note: GrammarNote, count: 1 | 3) => Promise<unknown>;
generate: (note: GrammarNote, count: 1 | 3, difficulty: GrammarDifficulty) => Promise<unknown>;
loadDifficulty: () => Promise<GrammarDifficulty>;
consumeRequest: () => Promise<"allowed" | "not_invited" | "rate_limited">;
}

Expand Down
Loading
Loading