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
27 changes: 27 additions & 0 deletions src/_storybook/views/grammar-detail/GrammarHistory.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type { Meta, StoryObj } from "@storybook/nextjs-vite";
import { GrammarHistory } from "@/features/grammar-history";
import type { GrammarHistoryProps } from "@/features/grammar-history";

const data = {
items: [],
total: 0,
page: 1,
pageSize: 10,
};
const load: GrammarHistoryProps["load"] = async () => ({ ok: true, data });

const meta = {
title: "views/grammar/History",
component: GrammarHistory,
args: { noteId: "preview-note", load },
} satisfies Meta<typeof GrammarHistory>;

export default meta;
type Story = StoryObj<typeof meta>;

export const Cached: Story = { args: { initialData: data } };
export const Loading: Story = {
args: {
load: () => new Promise((resolve) => setTimeout(() => resolve({ ok: true, data }), 4000)),
},
};
56 changes: 50 additions & 6 deletions src/_tests/features/grammar-history/GrammarHistory.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,50 @@ describe("grammar history", () => {
expect(load).toHaveBeenCalledTimes(2);
});

it("refreshes the latest date and keeps it while paging older records", async () => {
it("reopens cached history without another request and accepts a newly completed record", async () => {
const user = userEvent.setup();
const data = { items: [], total: 0, page: 1, pageSize: 10 };
const load = jest
.fn<() => Promise<GrammarHistoryResult>>()
.mockResolvedValue({ ok: true, data });
const { rerender } = render(<GrammarHistory noteId="note" initialData={data} load={load} />);
const trigger = screen.getByRole("button", { name: "연습 기록 전체보기" });

await user.click(trigger);
expect(await screen.findByText("아직 완료한 연습이 없습니다.")).toBeVisible();
await user.keyboard("{Escape}");
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
await user.click(trigger);
expect(screen.getByText("아직 완료한 연습이 없습니다.")).toBeVisible();
expect(load).not.toHaveBeenCalled();

const completedAt = "2026-10-18T01:00:00Z";
rerender(
<GrammarHistory
noteId="note"
initialData={{
...data,
total: 1,
items: [
{
id: "session",
noteId: "note",
title: "Grammar",
mode: "recall",
startedAt: completedAt,
completedAt,
questionCount: 1,
},
],
}}
load={load}
/>,
);
expect(screen.getByText("완료한 연습 1회")).toBeVisible();
expect(load).not.toHaveBeenCalled();
});

it("keeps the latest completed date while paging older records", async () => {
const user = userEvent.setup();
const oldDate = "2026-10-01T00:00:00Z";
const latestDate = "2026-10-03T00:00:00Z";
Expand All @@ -57,13 +100,14 @@ describe("grammar history", () => {
completedAt: oldDate,
questionCount: 1,
};
const initialData = { items: [item], total: 1, page: 1, pageSize: 10 };
const initialData = {
items: [{ ...item, completedAt: latestDate }],
total: 21,
page: 1,
pageSize: 10,
};
const load = jest
.fn<() => Promise<GrammarHistoryResult>>()
.mockResolvedValueOnce({
ok: true,
data: { ...initialData, total: 21, items: [{ ...item, completedAt: latestDate }] },
})
.mockResolvedValueOnce({ ok: true, data: { ...initialData, total: 21, page: 2 } });

render(
Expand Down
12 changes: 9 additions & 3 deletions src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ jest.mock("server-only", () => ({}));
jest.mock("@/shared/lib/supabase/server", () => ({ createSupabaseServerClient: jest.fn() }));

jest.mock("@/shared/lib/logging/pino", () => ({ recordOperationEvent: jest.fn() }));
jest.mock("next/cache", () => ({ revalidatePath: jest.fn() }));

Object.defineProperty(globalThis.crypto, "randomUUID", { value: randomUUID, configurable: true });

Expand Down Expand Up @@ -74,12 +75,13 @@ describe("어법 저장 서버 경계", () => {

it("정상 저장은 동일 요청 ID와 검토 내용을 저장소에 전달한다", async () => {
const input = command();
const create = jest
.spyOn(GrammarNoteRepository.prototype, "create")
.mockResolvedValue(createEditorNote());
const note = createEditorNote();
const create = jest.spyOn(GrammarNoteRepository.prototype, "create").mockResolvedValue(note);

expect((await saveGrammarNote(input)).ok).toBe(true);
expect(create).toHaveBeenCalledWith(input);
const { revalidatePath } = await import("next/cache");
expect(revalidatePath).toHaveBeenCalledWith(`/grammar/${note.id}`);
});

it("수정 저장 응답을 잃은 재시도는 이미 저장한 동일 버전을 성공으로 돌려준다", async () => {
Expand All @@ -98,6 +100,8 @@ describe("어법 저장 서버 경계", () => {

expect(result.ok).toBe(true);
expect(update).toHaveBeenCalledTimes(1);
const { revalidatePath } = await import("next/cache");
expect(revalidatePath).toHaveBeenCalledWith(`/grammar/${note.id}`);
});

it("내용이 다른 버전 충돌을 성공으로 오인하지 않고 초안 재검토를 요청한다", async () => {
Expand All @@ -120,6 +124,8 @@ describe("어법 저장 서버 경계", () => {
ok: false,
code: "VERSION_CONFLICT",
});
const { revalidatePath } = await import("next/cache");
expect(revalidatePath).not.toHaveBeenCalled();
});

it("실패는 내부 이벤트로 기록하고 원문과 내부 오류를 UI에 노출하지 않는다", async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ jest.mock("server-only", () => ({}));
jest.mock("@/shared/lib/supabase/server", () => ({ createSupabaseServerClient: jest.fn() }));

jest.mock("@/shared/lib/logging/pino", () => ({ recordOperationEvent: jest.fn() }));
jest.mock("next/cache", () => ({ revalidateTag: jest.fn() }));
jest.mock("next/cache", () => ({ revalidateTag: jest.fn(), revalidatePath: jest.fn() }));

let createSupabaseServerClient: typeof CreateClient;

Expand Down Expand Up @@ -52,7 +52,7 @@ describe("어법 연습 완료 후 통계 캐시", () => {
} as never);
const complete = jest
.spyOn(GrammarSessionRepository.prototype, "complete")
.mockResolvedValue({} as never);
.mockResolvedValue({ noteId: "note-id" } as never);

expect(
(
Expand All @@ -63,6 +63,8 @@ describe("어법 연습 완료 후 통계 캐시", () => {
).ok,
).toBe(true);
expect(revalidateTag).toHaveBeenCalledWith("my-page-practice-stats:owner", { expire: 0 });
const { revalidatePath } = await import("next/cache");
expect(revalidatePath).toHaveBeenCalledWith("/grammar/note-id");
complete.mockRestore();
});

Expand All @@ -86,6 +88,8 @@ describe("어법 연습 완료 후 통계 캐시", () => {
).ok,
).toBe(false);
expect(revalidateTag).not.toHaveBeenCalled();
const { revalidatePath } = await import("next/cache");
expect(revalidatePath).not.toHaveBeenCalled();
complete.mockRestore();
});
});
88 changes: 88 additions & 0 deletions src/_tests/views/grammar/grammarRoutes.test.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,33 @@
/** @jest-environment node */
import { beforeEach, describe, expect, it, jest } from "@jest/globals";
import { recallSession } from "@/_tests/features/grammar-recall/fixture";
import { createEditorNote } from "@/_tests/features/grammar-note-editor/fixtures";
import { grammarReturnTo } from "@/views/grammar-detail/services/grammarReturnTo";

jest.mock("server-only", () => ({}));
jest.mock("@/shared/lib/supabase/server", () => ({ createSupabaseServerClient: jest.fn() }));
jest.mock("@supabase/supabase-js", () => ({ createClient: jest.fn(() => ({})) }));
jest.mock("next/cache", () => {
const entries = new Map<string, Promise<unknown>>();
return {
unstable_cache: jest.fn((read: (...args: unknown[]) => Promise<unknown>, keys: string[]) => {
return (...args: unknown[]) => {
const key = JSON.stringify([keys, args]);
if (!entries.has(key)) entries.set(key, read(...args));
return entries.get(key);
};
}),
__clearTestCache: () => entries.clear(),
};
});

jest.mock("next/navigation", () => ({
redirect: (url: string) => {
throw new Error(`redirect:${url}`);
},
notFound: () => {
throw new Error("not-found");
},
}));

jest.mock("@/views/grammar-session/services/loadGrammarSession", () => ({
Expand Down Expand Up @@ -106,3 +127,70 @@ describe("grammar route transitions", () => {
expect(grammarReturnTo("/grammar?q=contrast&page=2")).toBe("/grammar?q=contrast&page=2");
});
});

describe("private grammar detail", () => {
it("reuses one owner's note and history on revisit without exposing them to another owner", async () => {
const { createSupabaseServerClient } = await import("@/shared/lib/supabase/server");
const { GrammarNoteRepository } = await import("@/entities/grammar-note");
const { GrammarSessionRepository } = await import("@/entities/grammar-session");
const { __clearTestCache } = jest.requireMock<{ __clearTestCache: () => void }>("next/cache");
__clearTestCache();

let owner: string | null = "owner-a";
jest.mocked(createSupabaseServerClient).mockImplementation(
async () =>
({
auth: {
getUser: async () => ({ data: { user: owner ? { id: owner } : null }, error: null }),
getSession: async () => ({
data: {
session: owner ? { user: { id: owner }, access_token: `${owner}-token` } : null,
},
error: null,
}),
},
}) as never,
);
process.env.NEXT_PUBLIC_SUPABASE_URL = "https://example.supabase.co";
process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY = "publishable-key";

const note = { ...createEditorNote(), ownerId: "owner-a" };
const noteRead = jest
.spyOn(GrammarNoteRepository.prototype, "findById")
.mockImplementation(async (id) => (owner === "owner-a" && id === note.id ? note : null));
const historyRead = jest
.spyOn(GrammarSessionRepository.prototype, "findHistory")
.mockResolvedValue({
items: [],
total: 0,
page: 1,
pageSize: 10,
});
const { default: Page } = await import("@/app/(protected)/grammar/[id]/page");
const props = {
params: Promise.resolve({ id: note.id }),
searchParams: Promise.resolve({ returnTo: "/grammar?page=2" }),
};

try {
const first = await Page(props);
const revisit = await Page(props);
expect(first.props.note).toMatchObject({ id: note.id, ownerId: "owner-a" });
expect(revisit.props.backHref).toBe("/grammar?page=2");
expect(noteRead).toHaveBeenCalledTimes(1);
expect(historyRead).toHaveBeenCalledTimes(1);

await expect(
Page({ ...props, params: Promise.resolve({ id: "00000000-0000-4000-8000-000000000002" }) }),
).rejects.toThrow("not-found");
owner = "owner-b";
await expect(Page(props)).rejects.toThrow("not-found");
owner = null;
await expect(Page(props)).rejects.toThrow("not-found");
} finally {
noteRead.mockRestore();
historyRead.mockRestore();
jest.mocked(createSupabaseServerClient).mockReset();
}
});
});
9 changes: 5 additions & 4 deletions src/app/(protected)/grammar/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { GrammarDetailView, loadGrammarNote, grammarReturnTo } from "@/views/grammar-detail";
import { getGrammarHistory } from "@/features/grammar-history/services/actions/getGrammarHistory";
import { GrammarDetailView, grammarReturnTo } from "@/views/grammar-detail";
import { loadCachedGrammarDetailNote } from "@/views/grammar-detail/services/loadGrammarNote";
import { getCachedGrammarDetailHistory } from "@/features/grammar-history/services/actions/getGrammarHistory";

export default async function GrammarNotePage({
params,
Expand All @@ -9,8 +10,8 @@ export default async function GrammarNotePage({
searchParams: Promise<{ returnTo?: string | string[] }>;
}) {
const [{ id }, query] = await Promise.all([params, searchParams]);
const note = await loadGrammarNote(id);
const history = await getGrammarHistory(id, 1);
const note = await loadCachedGrammarDetailNote(id);
const history = await getCachedGrammarDetailHistory(id);

return (
<GrammarDetailView
Expand Down
29 changes: 29 additions & 0 deletions src/features/grammar-history/services/actions/getGrammarHistory.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
"use server";

import { z } from "zod";
import { unstable_cache } from "next/cache";
import { GrammarSessionRepository, GrammarSessionError } from "@/entities/grammar-session";
import { createSupabaseServerClient } from "@/shared/lib/supabase/server";
import { observeOperation } from "@/shared/lib/logging/observeOperation";
import { recordOperationEvent } from "@/shared/lib/logging/pino";
import { getPrivateGrammarCacheClient } from "@/shared/lib/query/grammarDetailCache";
import type { GrammarHistoryResult } from "../../models/interface";

export async function getGrammarHistory(noteId: string, page = 1): Promise<GrammarHistoryResult> {
Expand Down Expand Up @@ -35,3 +37,30 @@ export async function getGrammarHistory(noteId: string, page = 1): Promise<Gramm
return { ok: false, code: "LOAD_FAILED" };
}
}

export async function getCachedGrammarDetailHistory(noteId: string): Promise<GrammarHistoryResult> {
try {
const id = z.string().uuid().parse(noteId);
const access = await getPrivateGrammarCacheClient();
if (!access) throw new GrammarSessionError("UNAUTHORIZED");

const read = unstable_cache(
() =>
new GrammarSessionRepository(access.client).findHistory({
noteId: id,
page: 1,
pageSize: 10,
}),
["grammar-detail-history", access.ownerId, id],
{ revalidate: 60 },
);
return await observeOperation({
operation: "grammar.history",
resourceId: "grammar-note",
recordEvent: recordOperationEvent,
execute: async () => ({ ok: true as const, data: await read() }),
});
} catch {
return { ok: false, code: "LOAD_FAILED" };
}
}
8 changes: 8 additions & 0 deletions src/features/grammar-history/services/useGrammarHistory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@ export function useGrammarHistory({ noteId, initialData, load }: GrammarHistoryP
};
}, []);

useEffect(() => {
generation.current++;
setData(initialData);
setLatestCompletedAt(initialData?.page === 1 ? initialData.items[0]?.completedAt : undefined);
setBusy(false);
setError(null);
}, [initialData]);

async function refresh(page = 1) {
const currentGeneration = ++generation.current;

Expand Down
4 changes: 2 additions & 2 deletions src/features/grammar-history/ui/GrammarHistory.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,15 @@ function HistoryForNote(props: GrammarHistoryProps) {
function changeOpen(next: boolean) {
setOpen(next);

if (next) void refresh(1);
if (next && (!data || error)) void refresh(1);
}

return (
<section aria-label="연습 기록" className="space-y-4 border-t border-practice-line pt-7">
<h2 className="text-lg font-medium text-practice-ink">나의 연습</h2>
<p className="text-sm text-practice-secondary">
{data ? `완료한 연습 ${total}회` : "완료한 연습 기록을 확인해보세요."}
{last && ` · 최근 ${formatGrammarPracticeDate(last)}`}
<span>{last && ` · 최근 ${formatGrammarPracticeDate(last)}`}</span>
</p>
<Dialog open={open} onOpenChange={changeOpen}>
<DialogTrigger asChild>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { GrammarNotePersistenceError, GrammarNoteRepository } from "@/entities/g
import { createSupabaseServerClient } from "@/shared/lib/supabase/server";
import { observeOperation } from "@/shared/lib/logging/observeOperation";
import { recordOperationEvent } from "@/shared/lib/logging/pino";
import { invalidateGrammarDetail } from "@/shared/lib/query/grammarDetailCache";
import { persistReviewedNote } from "../persistReviewedNote";
import type { SaveNoteCommand, SaveNoteResult } from "../../models/interface";

Expand All @@ -26,6 +27,7 @@ export async function saveGrammarNote(command: SaveNoteCommand): Promise<SaveNot
},
});

invalidateGrammarDetail(note.id);
return { ok: true, note };
} catch (error) {
const code = error instanceof GrammarNotePersistenceError ? error.code : "PERSISTENCE_FAILED";
Expand Down
Loading
Loading