From 31d99bc58d403f7db96f35d43c984fc89ad2c084 Mon Sep 17 00:00:00 2001 From: Lee Sanghyun <59863112+dev-ant@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:34:03 +0900 Subject: [PATCH 1/3] feat: add auction item detail pages --- package-lock.json | 4 +- package.json | 2 +- .../auction-history/AuctionHistoryClient.tsx | 33 +- .../[auctionBuyId]/page.test.tsx | 27 + .../auction-history/[auctionBuyId]/page.tsx | 43 ++ src/app/(main)/auction-history/page.test.tsx | 59 +++ .../AuctionRealtimeClient.tsx | 33 +- .../[auctionId]/page.test.tsx | 27 + .../auction-realtime/[auctionId]/page.tsx | 43 ++ src/app/api/statistics/daily/items/route.ts | 47 +- src/app/api/statistics/items-route.test.ts | 86 ++++ src/app/api/statistics/weekly/items/route.ts | 54 +- .../auction-common/AuctionDetailView.test.tsx | 119 +++++ .../page/auction-common/AuctionDetailView.tsx | 225 ++++++++ .../auction-common/AuctionItemSearch.test.tsx | 55 ++ .../page/auction-common/AuctionItemSearch.tsx | 145 ++++++ .../AuctionHistoryList.test.tsx | 61 +++ .../auction-history/AuctionHistoryList.tsx | 486 +++++++----------- .../page/auction-history/SearchFilterCard.tsx | 31 ++ .../AuctionRealtimeList.test.tsx | 40 ++ .../auction-realtime/AuctionRealtimeList.tsx | 414 +++++++-------- .../auction-realtime/SearchFilterCard.tsx | 31 ++ .../statistics/StatisticsSummaryCards.tsx | 6 +- src/components/ui/popover.tsx | 8 +- .../useAuctionItemPreviewPreference.test.ts | 21 + src/hooks/useAuctionItemPreviewPreference.ts | 31 ++ src/lib/auction/detail.test.ts | 221 ++++++++ src/lib/auction/detail.ts | 255 +++++++++ 28 files changed, 2035 insertions(+), 572 deletions(-) create mode 100644 src/app/(main)/auction-history/[auctionBuyId]/page.test.tsx create mode 100644 src/app/(main)/auction-history/[auctionBuyId]/page.tsx create mode 100644 src/app/(main)/auction-realtime/[auctionId]/page.test.tsx create mode 100644 src/app/(main)/auction-realtime/[auctionId]/page.tsx create mode 100644 src/app/api/statistics/items-route.test.ts create mode 100644 src/components/page/auction-common/AuctionDetailView.test.tsx create mode 100644 src/components/page/auction-common/AuctionDetailView.tsx create mode 100644 src/components/page/auction-common/AuctionItemSearch.test.tsx create mode 100644 src/components/page/auction-common/AuctionItemSearch.tsx create mode 100644 src/components/page/auction-history/AuctionHistoryList.test.tsx create mode 100644 src/components/page/auction-realtime/AuctionRealtimeList.test.tsx create mode 100644 src/hooks/useAuctionItemPreviewPreference.test.ts create mode 100644 src/hooks/useAuctionItemPreviewPreference.ts create mode 100644 src/lib/auction/detail.test.ts create mode 100644 src/lib/auction/detail.ts diff --git a/package-lock.json b/package-lock.json index e88832f..6747c31 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "devnogi-front", - "version": "1.0.8", + "version": "1.0.9", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "devnogi-front", - "version": "1.0.8", + "version": "1.0.9", "dependencies": { "@hookform/resolvers": "^5.1.1", "@radix-ui/react-checkbox": "^1.3.3", diff --git a/package.json b/package.json index eaa35f4..3ce17a7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "devnogi-front", - "version": "1.0.8", + "version": "1.0.9", "private": true, "scripts": { "dev": "next dev", diff --git a/src/app/(main)/auction-history/AuctionHistoryClient.tsx b/src/app/(main)/auction-history/AuctionHistoryClient.tsx index 909e4af..a1a82eb 100644 --- a/src/app/(main)/auction-history/AuctionHistoryClient.tsx +++ b/src/app/(main)/auction-history/AuctionHistoryClient.tsx @@ -12,6 +12,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import CategorySection from "@/components/commons/Category"; import CategoryDropdown from "@/components/commons/CategoryDropdown"; import { MetalwareFilterItem } from "@/components/commons/MetalwareSearchFilter"; +import AuctionItemSearch from "@/components/page/auction-common/AuctionItemSearch"; import AuctionHistoryList from "@/components/page/auction-history/AuctionHistoryList"; import MobileFilterChips from "@/components/page/auction-history/MobileFilterChips"; import MobileFilterModal from "@/components/page/auction-history/MobileFilterModal"; @@ -33,7 +34,9 @@ import { Skeleton } from "@/components/ui/skeleton"; import { ItemCategory } from "@/data/item-category"; import { useAuctionHistory } from "@/hooks/useAuctionHistory"; import { useAuctionHistoryLayout } from "@/hooks/useAuctionHistoryLayout"; +import { useAuctionItemPreviewPreference } from "@/hooks/useAuctionItemPreviewPreference"; import { useItemCategories } from "@/hooks/useItemCategories"; +import { ItemInfo } from "@/hooks/useItemInfos"; import { AuctionHistorySearchParams } from "@/types/auction-history"; import { ActiveFilter } from "@/types/search-filter"; @@ -524,6 +527,8 @@ export default function Page() { } = useAuctionHistoryLayout(); const { data, isLoading, isFetching } = useAuctionHistory(searchParams); + const { isPreviewEnabled, setIsPreviewEnabled } = + useAuctionItemPreviewPreference(); const allItems = data?.items ?? []; const meta = data?.meta; @@ -726,6 +731,25 @@ export default function Page() { }); }; + const handleItemSearch = (name: string, selectedItem?: ItemInfo) => { + setItemName(name); + if (selectedItem) { + setSelectedCategory( + `${selectedItem.topCategory}/${selectedItem.subCategory}`, + ); + } + setSearchParams((prev) => { + const next = { ...prev, page: 1 }; + if (name) next.itemName = name; + else delete next.itemName; + if (selectedItem) { + next.itemTopCategory = selectedItem.topCategory; + next.itemSubCategory = selectedItem.subCategory; + } + return normalizeCategorySelection(next); + }); + }; + const handleToggleExpand = (categoryId: string) => { setExpandedIds((prev) => { const newSet = new Set(prev); @@ -1019,6 +1043,7 @@ export default function Page() { }`} >
+ {showMobileFilter && (
- + {isFetching && !isLoading && (
@@ -1173,6 +1202,8 @@ export default function Page() { layoutMode={layoutMode} isExactItemName={!!searchParams.isExactItemName} onExactItemNameChange={handleExactItemNameChange} + isItemPreviewEnabled={isPreviewEnabled} + onItemPreviewEnabledChange={setIsPreviewEnabled} /> )} diff --git a/src/app/(main)/auction-history/[auctionBuyId]/page.test.tsx b/src/app/(main)/auction-history/[auctionBuyId]/page.test.tsx new file mode 100644 index 0000000..fecb884 --- /dev/null +++ b/src/app/(main)/auction-history/[auctionBuyId]/page.test.tsx @@ -0,0 +1,27 @@ +import { getAuctionDetail } from "@/lib/auction/detail"; + +import { generateMetadata } from "./page"; + +jest.mock("@/lib/auction/detail", () => ({ + getAuctionDetail: jest.fn(), + safeReturnTo: jest.fn(), +})); + +describe("auction history detail metadata", () => { + it("uses the exact item title without the global template", async () => { + jest.mocked(getAuctionDetail).mockResolvedValue({ + status: "available", + source: "history", + record: { itemName: "테스트 검" }, + dailyStatistics: [], + weeklyStatistics: [], + } as never); + const metadata = await generateMetadata({ + params: Promise.resolve({ auctionBuyId: "history-1" }), + searchParams: Promise.resolve({}), + }); + expect(metadata.title).toEqual({ + absolute: "테스트 검 거래 내역 | 마비노기", + }); + }); +}); diff --git a/src/app/(main)/auction-history/[auctionBuyId]/page.tsx b/src/app/(main)/auction-history/[auctionBuyId]/page.tsx new file mode 100644 index 0000000..95b73f1 --- /dev/null +++ b/src/app/(main)/auction-history/[auctionBuyId]/page.tsx @@ -0,0 +1,43 @@ +import type { Metadata } from "next"; + +import AuctionDetailView from "@/components/page/auction-common/AuctionDetailView"; +import { getAuctionDetail, safeReturnTo } from "@/lib/auction/detail"; + +interface PageProps { + params: Promise<{ auctionBuyId: string }>; + searchParams: Promise<{ return_to?: string | string[] }>; +} + +export const dynamic = "force-dynamic"; + +export async function generateMetadata({ + params, +}: PageProps): Promise { + const { auctionBuyId } = await params; + const result = await getAuctionDetail("history", auctionBuyId); + return { + title: { + absolute: result.record + ? `${result.record.itemName} 거래 내역 | 마비노기` + : "경매장 거래 내역 | 마비노기", + }, + robots: + result.status === "available" + ? undefined + : { index: false, follow: false }, + }; +} + +export default async function AuctionHistoryDetailPage({ + params, + searchParams, +}: PageProps) { + const [{ auctionBuyId }, query] = await Promise.all([params, searchParams]); + const result = await getAuctionDetail("history", auctionBuyId); + return ( + + ); +} diff --git a/src/app/(main)/auction-history/page.test.tsx b/src/app/(main)/auction-history/page.test.tsx index ea4a038..f542c59 100644 --- a/src/app/(main)/auction-history/page.test.tsx +++ b/src/app/(main)/auction-history/page.test.tsx @@ -95,6 +95,35 @@ jest.mock("@/components/page/auction-history/AuctionHistoryList", () => { }; }); +jest.mock("@/components/page/auction-common/AuctionItemSearch", () => { + return function MockAuctionItemSearch({ + onSearch, + }: { + onSearch: ( + name: string, + item?: { name: string; topCategory: string; subCategory: string }, + ) => void; + }) { + return ( +
+ + + +
+ ); + }; +}); + function response(names: string[]) { return Response.json({ success: true, @@ -210,6 +239,36 @@ describe("TradeLogPage", () => { ); }); + it("아이템 직접 검색, 자동완성 선택, 초기화 시 페이지를 1로 되돌린다", async () => { + mockUrlParams = new URLSearchParams({ page: "3", itemName: "이전 검색" }); + fetchSpy.mockImplementation(() => Promise.resolve(response(["result"]))); + renderPage(); + await waitFor(() => expect(lastQuery().get("page")).toBe("3")); + + fireEvent.click(screen.getByRole("button", { name: "Direct Search" })); + await waitFor(() => { + expect(lastQuery().get("page")).toBe("1"); + expect(lastQuery().get("itemName")).toBe("직접 검색"); + }); + + fireEvent.click( + screen.getByRole("button", { name: "Autocomplete Search" }), + ); + await waitFor(() => { + expect(lastQuery().get("page")).toBe("1"); + expect(lastQuery().get("itemName")).toBe("롱소드"); + expect(lastQuery().get("itemTopCategory")).toBe("근거리 장비"); + expect(lastQuery().get("itemSubCategory")).toBe("검"); + }); + + fireEvent.click(screen.getByRole("button", { name: "Clear Search" })); + await waitFor(() => { + expect(lastQuery().get("page")).toBe("1"); + expect(lastQuery().has("itemName")).toBe(false); + expect(lastQuery().get("itemTopCategory")).toBe("근거리 장비"); + }); + }); + it("API 오류가 나면 로딩을 마치고 빈 목록을 렌더링한다", async () => { fetchSpy.mockRejectedValue(new Error("API Error")); renderPage(); diff --git a/src/app/(main)/auction-realtime/AuctionRealtimeClient.tsx b/src/app/(main)/auction-realtime/AuctionRealtimeClient.tsx index 01e44f8..f3bd772 100644 --- a/src/app/(main)/auction-realtime/AuctionRealtimeClient.tsx +++ b/src/app/(main)/auction-realtime/AuctionRealtimeClient.tsx @@ -12,6 +12,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import CategorySection from "@/components/commons/Category"; import CategoryDropdown from "@/components/commons/CategoryDropdown"; import { MetalwareFilterItem } from "@/components/commons/MetalwareSearchFilter"; +import AuctionItemSearch from "@/components/page/auction-common/AuctionItemSearch"; import AuctionRealtimeList from "@/components/page/auction-realtime/AuctionRealtimeList"; import MobileFilterChips from "@/components/page/auction-realtime/MobileFilterChips"; import MobileFilterModal from "@/components/page/auction-realtime/MobileFilterModal"; @@ -32,8 +33,10 @@ import { Checkbox } from "@/components/ui/checkbox"; import { Skeleton } from "@/components/ui/skeleton"; import { ItemCategory } from "@/data/item-category"; import { useAuctionHistoryLayout } from "@/hooks/useAuctionHistoryLayout"; +import { useAuctionItemPreviewPreference } from "@/hooks/useAuctionItemPreviewPreference"; import { useAuctionRealtime } from "@/hooks/useAuctionRealtime"; import { useItemCategories } from "@/hooks/useItemCategories"; +import { ItemInfo } from "@/hooks/useItemInfos"; import { AuctionRealtimeSearchParams } from "@/types/auction-realtime"; import { ActiveFilter } from "@/types/search-filter"; @@ -499,6 +502,8 @@ export default function Page() { } = useAuctionHistoryLayout(); const { data, isLoading, isFetching } = useAuctionRealtime(searchParams); + const { isPreviewEnabled, setIsPreviewEnabled } = + useAuctionItemPreviewPreference(); const allItems = data?.items ?? []; const meta = data?.meta; @@ -696,6 +701,25 @@ export default function Page() { }); }; + const handleItemSearch = (name: string, selectedItem?: ItemInfo) => { + setItemName(name); + if (selectedItem) { + setSelectedCategory( + `${selectedItem.topCategory}/${selectedItem.subCategory}`, + ); + } + setSearchParams((prev) => { + const next = { ...prev, page: 1 }; + if (name) next.itemName = name; + else delete next.itemName; + if (selectedItem) { + next.itemTopCategory = selectedItem.topCategory; + next.itemSubCategory = selectedItem.subCategory; + } + return normalizeCategorySelection(next); + }); + }; + const handleToggleExpand = (categoryId: string) => { setExpandedIds((prev) => { const newSet = new Set(prev); @@ -966,6 +990,7 @@ export default function Page() { }`} >
+ {showMobileFilter && (
- + {isFetching && !isLoading && (
@@ -1118,6 +1147,8 @@ export default function Page() { layoutMode={layoutMode} isExactItemName={!!searchParams.isExactItemName} onExactItemNameChange={handleExactItemNameChange} + isItemPreviewEnabled={isPreviewEnabled} + onItemPreviewEnabledChange={setIsPreviewEnabled} /> )} diff --git a/src/app/(main)/auction-realtime/[auctionId]/page.test.tsx b/src/app/(main)/auction-realtime/[auctionId]/page.test.tsx new file mode 100644 index 0000000..c94533a --- /dev/null +++ b/src/app/(main)/auction-realtime/[auctionId]/page.test.tsx @@ -0,0 +1,27 @@ +import { getAuctionDetail } from "@/lib/auction/detail"; + +import { generateMetadata } from "./page"; + +jest.mock("@/lib/auction/detail", () => ({ + getAuctionDetail: jest.fn(), + safeReturnTo: jest.fn(), +})); + +describe("auction realtime detail metadata", () => { + it("uses the exact item title without the global template", async () => { + jest.mocked(getAuctionDetail).mockResolvedValue({ + status: "available", + source: "realtime", + record: { itemName: "테스트 검" }, + dailyStatistics: [], + weeklyStatistics: [], + } as never); + const metadata = await generateMetadata({ + params: Promise.resolve({ auctionId: "10" }), + searchParams: Promise.resolve({}), + }); + expect(metadata.title).toEqual({ + absolute: "테스트 검 실시간 거래 | 마비노기", + }); + }); +}); diff --git a/src/app/(main)/auction-realtime/[auctionId]/page.tsx b/src/app/(main)/auction-realtime/[auctionId]/page.tsx new file mode 100644 index 0000000..d94bbfe --- /dev/null +++ b/src/app/(main)/auction-realtime/[auctionId]/page.tsx @@ -0,0 +1,43 @@ +import type { Metadata } from "next"; + +import AuctionDetailView from "@/components/page/auction-common/AuctionDetailView"; +import { getAuctionDetail, safeReturnTo } from "@/lib/auction/detail"; + +interface PageProps { + params: Promise<{ auctionId: string }>; + searchParams: Promise<{ return_to?: string | string[] }>; +} + +export const dynamic = "force-dynamic"; + +export async function generateMetadata({ + params, +}: PageProps): Promise { + const { auctionId } = await params; + const result = await getAuctionDetail("realtime", auctionId); + return { + title: { + absolute: result.record + ? `${result.record.itemName} 실시간 거래 | 마비노기` + : "경매장 실시간 거래 | 마비노기", + }, + robots: + result.status === "available" + ? undefined + : { index: false, follow: false }, + }; +} + +export default async function AuctionRealtimeDetailPage({ + params, + searchParams, +}: PageProps) { + const [{ auctionId }, query] = await Promise.all([params, searchParams]); + const result = await getAuctionDetail("realtime", auctionId); + return ( + + ); +} diff --git a/src/app/api/statistics/daily/items/route.ts b/src/app/api/statistics/daily/items/route.ts index 4a4384f..96e536a 100644 --- a/src/app/api/statistics/daily/items/route.ts +++ b/src/app/api/statistics/daily/items/route.ts @@ -7,22 +7,57 @@ import { createServerAxios } from "@/lib/api/server"; export const dynamic = "force-dynamic"; export const revalidate = 300; +interface RawDailyStatistic { + itemName: string; + dateAuctionBuy: string; + minPrice: number; + maxPrice: number; + avgPrice: number; + totalVolume: number; + totalQuantity: number; +} + export async function GET(request: NextRequest) { const { searchParams } = new URL(request.url); const params = { itemName: searchParams.get("itemName") ?? "", subCategory: searchParams.get("subCategory") ?? "", topCategory: searchParams.get("topCategory") ?? "", - dateFrom: searchParams.get("dateFrom") ?? undefined, - dateTo: searchParams.get("dateTo") ?? undefined, + startDate: searchParams.get("dateFrom") ?? undefined, + endDate: searchParams.get("dateTo") ?? undefined, }; try { const axios = createServerAxios(request); - const { data, status } = await axios.get(STATISTICS_DAILY_ITEMS_ENDPOINT, { - params, - }); - return NextResponse.json(data, { status }); + const { data, status } = await axios.get( + STATISTICS_DAILY_ITEMS_ENDPOINT, + { + params, + }, + ); + const normalized = data.map((item) => ({ + itemName: item.itemName, + itemTopCategory: params.topCategory, + itemSubCategory: params.subCategory, + date: item.dateAuctionBuy, + minPrice: item.minPrice, + maxPrice: item.maxPrice, + avgPrice: + item.totalQuantity > 0 + ? item.totalVolume / item.totalQuantity + : Number(item.avgPrice), + totalVolume: item.totalVolume, + totalQuantity: item.totalQuantity, + })); + return NextResponse.json( + { + success: true, + code: "COMMON_SUCCESS", + message: "요청이 성공적으로 처리되었습니다.", + data: normalized, + }, + { status }, + ); } catch (error: unknown) { if ((error as AxiosError).isAxiosError) { const axiosError = error as AxiosError; diff --git a/src/app/api/statistics/items-route.test.ts b/src/app/api/statistics/items-route.test.ts new file mode 100644 index 0000000..e17e207 --- /dev/null +++ b/src/app/api/statistics/items-route.test.ts @@ -0,0 +1,86 @@ +import { NextRequest } from "next/server"; + +import { createServerAxios } from "@/lib/api/server"; + +import { GET as getDaily } from "./daily/items/route"; +import { GET as getWeekly } from "./weekly/items/route"; + +jest.mock("@/lib/api/server", () => ({ createServerAxios: jest.fn() })); + +describe("item statistics BFF normalization", () => { + const get = jest.fn(); + + beforeEach(() => { + get.mockReset(); + jest.mocked(createServerAxios).mockReturnValue({ get } as never); + }); + + it("maps daily date params and returns weighted averages", async () => { + get.mockResolvedValue({ + status: 200, + data: [ + { + itemName: "검", + dateAuctionBuy: "2026-11-01", + minPrice: 100, + maxPrice: 300, + avgPrice: 999, + totalVolume: 600, + totalQuantity: 3, + }, + ], + }); + const response = await getDaily( + new NextRequest( + "http://localhost/api/statistics/daily/items?itemName=%EA%B2%80&topCategory=%EC%9E%A5%EB%B9%84&subCategory=%EA%B2%80&dateFrom=2026-10-07&dateTo=2026-11-05", + ), + ); + const body = await response.json(); + expect(get).toHaveBeenCalledWith(expect.any(String), { + params: expect.objectContaining({ + startDate: "2026-10-07", + endDate: "2026-11-05", + }), + }); + expect(body.data[0]).toMatchObject({ + date: "2026-11-01", + avgPrice: 200, + itemTopCategory: "장비", + itemSubCategory: "검", + }); + }); + + it("normalizes weekly dates and weighted averages", async () => { + get.mockResolvedValue({ + status: 200, + data: [ + { + itemName: "검", + weekStartDate: "2026-11-02", + minPrice: 100, + maxPrice: 300, + avgPrice: 999, + totalVolume: 1000, + totalQuantity: 4, + }, + ], + }); + const response = await getWeekly( + new NextRequest( + "http://localhost/api/statistics/weekly/items?itemName=%EA%B2%80&topCategory=%EC%9E%A5%EB%B9%84&subCategory=%EA%B2%80&dateFrom=2026-07-09&dateTo=2026-11-05", + ), + ); + const body = await response.json(); + expect(get).toHaveBeenCalledWith(expect.any(String), { + params: expect.objectContaining({ + startDate: "2026-07-09", + endDate: "2026-11-05", + }), + }); + expect(body.data[0]).toMatchObject({ + weekStart: "2026-11-02", + weekEnd: "2026-11-08", + avgPrice: 250, + }); + }); +}); diff --git a/src/app/api/statistics/weekly/items/route.ts b/src/app/api/statistics/weekly/items/route.ts index 2a260b2..c64db1d 100644 --- a/src/app/api/statistics/weekly/items/route.ts +++ b/src/app/api/statistics/weekly/items/route.ts @@ -7,22 +7,64 @@ import { createServerAxios } from "@/lib/api/server"; export const dynamic = "force-dynamic"; export const revalidate = 300; +interface RawWeeklyStatistic { + itemName: string; + weekStartDate: string; + minPrice: number; + maxPrice: number; + avgPrice: number; + totalVolume: number; + totalQuantity: number; +} + +function weekEnd(start: string) { + const value = new Date(`${start}T00:00:00Z`); + value.setUTCDate(value.getUTCDate() + 6); + return value.toISOString().slice(0, 10); +} + export async function GET(request: NextRequest) { const { searchParams } = new URL(request.url); const params = { itemName: searchParams.get("itemName") ?? "", subCategory: searchParams.get("subCategory") ?? "", topCategory: searchParams.get("topCategory") ?? "", - dateFrom: searchParams.get("dateFrom") ?? undefined, - dateTo: searchParams.get("dateTo") ?? undefined, + startDate: searchParams.get("dateFrom") ?? undefined, + endDate: searchParams.get("dateTo") ?? undefined, }; try { const axios = createServerAxios(request); - const { data, status } = await axios.get(STATISTICS_WEEKLY_ITEMS_ENDPOINT, { - params, - }); - return NextResponse.json(data, { status }); + const { data, status } = await axios.get( + STATISTICS_WEEKLY_ITEMS_ENDPOINT, + { + params, + }, + ); + const normalized = data.map((item) => ({ + itemName: item.itemName, + itemTopCategory: params.topCategory, + itemSubCategory: params.subCategory, + weekStart: item.weekStartDate, + weekEnd: weekEnd(item.weekStartDate), + minPrice: item.minPrice, + maxPrice: item.maxPrice, + avgPrice: + item.totalQuantity > 0 + ? item.totalVolume / item.totalQuantity + : Number(item.avgPrice), + totalVolume: item.totalVolume, + totalQuantity: item.totalQuantity, + })); + return NextResponse.json( + { + success: true, + code: "COMMON_SUCCESS", + message: "요청이 성공적으로 처리되었습니다.", + data: normalized, + }, + { status }, + ); } catch (error: unknown) { if ((error as AxiosError).isAxiosError) { const axiosError = error as AxiosError; diff --git a/src/components/page/auction-common/AuctionDetailView.test.tsx b/src/components/page/auction-common/AuctionDetailView.test.tsx new file mode 100644 index 0000000..ce35d18 --- /dev/null +++ b/src/components/page/auction-common/AuctionDetailView.test.tsx @@ -0,0 +1,119 @@ +import { fireEvent, render, screen } from "@testing-library/react"; + +import { AuctionDetailResult } from "@/lib/auction/detail"; + +import AuctionDetailView from "./AuctionDetailView"; + +const refresh = jest.fn(); + +jest.mock("next/navigation", () => ({ + useRouter: () => ({ refresh }), +})); +jest.mock("@/components/page/auction-history/ItemOptionPopover", () => { + return function MockOptions() { + return
옵션 정보
; + }; +}); +jest.mock("@/components/page/statistics/StatisticsSummaryCards", () => { + return function MockSummary() { + return
시세 요약
; + }; +}); +jest.mock("@/components/page/statistics/PriceChart", () => { + return function MockPriceChart() { + return
가격 차트
; + }; +}); +jest.mock("@/components/page/statistics/VolumeChart", () => { + return function MockVolumeChart() { + return
거래량 차트
; + }; +}); + +const baseResult: AuctionDetailResult = { + status: "available", + source: "history", + record: { + itemName: "롱소드", + itemDisplayName: "강한 롱소드", + itemCount: 1, + auctionPricePerUnit: 1000, + dateAuctionBuy: "2026-11-05T10:00:00", + auctionBuyId: "history-1", + itemSubCategory: "검", + itemTopCategory: "근거리 장비", + itemOptions: [], + }, + dailyStatistics: [], + weeklyStatistics: [], + itemInfoStatus: "empty", + dailyStatus: "empty", + weeklyStatus: "empty", +}; + +describe("AuctionDetailView section states", () => { + beforeEach(() => refresh.mockClear()); + + it("shows retry controls for failed item info and the failed current period", () => { + render( + , + ); + + expect( + screen.getByText("아이템 정보를 불러오지 못했습니다."), + ).toBeInTheDocument(); + expect( + screen.getByText("선택한 기간의 시세 정보를 불러오지 못했습니다."), + ).toBeInTheDocument(); + expect( + screen.queryByText("시세 데이터가 없습니다."), + ).not.toBeInTheDocument(); + const retryButtons = screen.getAllByRole("button", { name: "다시 시도" }); + fireEvent.click(retryButtons[0]); + fireEvent.click(retryButtons[1]); + expect(refresh).toHaveBeenCalledTimes(2); + }); + + it("shows empty messages without retry controls for successful empty responses", () => { + render( + , + ); + + expect( + screen.getByText("등록된 아이템 정보가 없습니다."), + ).toBeInTheDocument(); + expect(screen.getByText("시세 데이터가 없습니다.")).toBeInTheDocument(); + expect( + screen.queryByRole("button", { name: "다시 시도" }), + ).not.toBeInTheDocument(); + }); + + it("shows the status for the selected statistics period only", () => { + render( + , + ); + + expect(screen.getByText("시세 데이터가 없습니다.")).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "최근 120일" })); + expect( + screen.getByText("선택한 기간의 시세 정보를 불러오지 못했습니다."), + ).toBeInTheDocument(); + expect( + screen.queryByText("시세 데이터가 없습니다."), + ).not.toBeInTheDocument(); + }); +}); diff --git a/src/components/page/auction-common/AuctionDetailView.tsx b/src/components/page/auction-common/AuctionDetailView.tsx new file mode 100644 index 0000000..ba9164a --- /dev/null +++ b/src/components/page/auction-common/AuctionDetailView.tsx @@ -0,0 +1,225 @@ +"use client"; + +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; + +import ItemOptionPopover from "@/components/page/auction-history/ItemOptionPopover"; +import PriceChart from "@/components/page/statistics/PriceChart"; +import StatisticsSummaryCards from "@/components/page/statistics/StatisticsSummaryCards"; +import VolumeChart from "@/components/page/statistics/VolumeChart"; +import { AuctionDetailResult, AuctionRecord } from "@/lib/auction/detail"; +import { ItemInfoResponse } from "@/types/item-info"; + +interface Props { + result: AuctionDetailResult; + returnTo: string; +} + +function dateLabel(value: string) { + return new Intl.DateTimeFormat("ko-KR", { + dateStyle: "medium", + timeStyle: "short", + }).format(new Date(value)); +} +function DetailField({ + label, + value, +}: { + label: string; + value: string | number | null | undefined; +}) { + if (value === null || value === undefined || value === "") return null; + return ( +
+
{label}
+
+ {value} +
+
+ ); +} + +function RecordFacts({ record }: { record: AuctionRecord }) { + const history = "dateAuctionBuy" in record; + return ( +
+ + + + + {history ? ( + + ) : ( + <> + + + + )} +
+ ); +} + +function ItemMetadata({ info }: { info: ItemInfoResponse }) { + return ( +
+ + + + + + + + + +
+ ); +} + +export default function AuctionDetailView({ result, returnTo }: Props) { + const router = useRouter(); + const [period, setPeriod] = useState<"daily" | "weekly">("daily"); + if (result.status !== "available" || !result.record) { + const message = + result.source === "realtime" && result.status === "not-found" + ? "판매가 종료되었거나 최신 목록에서 제외되었습니다." + : result.status === "not-found" + ? "거래 내역을 찾을 수 없습니다." + : "상세 정보를 불러오지 못했습니다."; + return ( +
+

{message}

+ + 목록으로 돌아가기 + +
+ ); + } + const record = result.record; + const statistics = + period === "daily" ? result.dailyStatistics : result.weeklyStatistics; + const statisticsStatus = + period === "daily" ? result.dailyStatus : result.weeklyStatus; + return ( +
+
+
+

+ {result.source === "history" + ? "경매장 거래 내역" + : "경매장 실시간 거래"} +

+

+ {record.itemName} +

+
+ + 목록으로 돌아가기 + +
+
+

거래 기본 정보

+ +
+ +
+
+
+

아이템 정보

+ {result.itemInfoStatus === "available" && result.itemInfo ? ( + + ) : result.itemInfoStatus === "error" ? ( +
+

+ 아이템 정보를 불러오지 못했습니다. +

+ +
+ ) : ( +

+ 등록된 아이템 정보가 없습니다. +

+ )} +
+
+
+

시세 정보

+
+ {(["daily", "weekly"] as const).map((value) => ( + + ))} +
+
+ {statisticsStatus === "error" ? ( +
+

+ 선택한 기간의 시세 정보를 불러오지 못했습니다. +

+ +
+ ) : statisticsStatus === "empty" ? ( +

+ 시세 데이터가 없습니다. +

+ ) : ( + <> + + + + + )} +
+
+ ); +} diff --git a/src/components/page/auction-common/AuctionItemSearch.test.tsx b/src/components/page/auction-common/AuctionItemSearch.test.tsx new file mode 100644 index 0000000..ed31481 --- /dev/null +++ b/src/components/page/auction-common/AuctionItemSearch.test.tsx @@ -0,0 +1,55 @@ +import { fireEvent, render, screen } from "@testing-library/react"; + +import AuctionItemSearch from "./AuctionItemSearch"; + +jest.mock("@/hooks/useItemInfos", () => ({ + useItemInfos: () => ({ + data: [ + { name: "롱소드", topCategory: "근거리 장비", subCategory: "검" }, + { name: "숏소드", topCategory: "근거리 장비", subCategory: "검" }, + ], + isLoading: false, + }), +})); + +describe("AuctionItemSearch", () => { + it("submits direct input", () => { + const onSearch = jest.fn(); + render(); + + fireEvent.change(screen.getByLabelText("아이템 검색"), { + target: { value: " 임의의 검 " }, + }); + fireEvent.click(screen.getByRole("button", { name: "검색" })); + + expect(onSearch).toHaveBeenCalledWith("임의의 검"); + }); + + it("applies the selected autocomplete item and its categories", () => { + const onSearch = jest.fn(); + render(); + + fireEvent.change(screen.getByLabelText("아이템 검색"), { + target: { value: "롱" }, + }); + fireEvent.mouseDown(screen.getByRole("option", { name: /롱소드/ })); + + expect(onSearch).toHaveBeenCalledWith("롱소드", { + name: "롱소드", + topCategory: "근거리 장비", + subCategory: "검", + }); + }); + + it("clears the active item search immediately", () => { + const onSearch = jest.fn(); + render(); + + fireEvent.click( + screen.getByRole("button", { name: "아이템 검색어 지우기" }), + ); + + expect(onSearch).toHaveBeenCalledWith(""); + expect(screen.getByLabelText("아이템 검색")).toHaveValue(""); + }); +}); diff --git a/src/components/page/auction-common/AuctionItemSearch.tsx b/src/components/page/auction-common/AuctionItemSearch.tsx new file mode 100644 index 0000000..9e5e562 --- /dev/null +++ b/src/components/page/auction-common/AuctionItemSearch.tsx @@ -0,0 +1,145 @@ +"use client"; + +import { Search, X } from "lucide-react"; +import { + FormEvent, + KeyboardEvent, + useEffect, + useMemo, + useRef, + useState, +} from "react"; + +import Autocomplete from "@/components/commons/Autocomplete"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { ItemInfo, useItemInfos } from "@/hooks/useItemInfos"; + +interface AuctionItemSearchProps { + value: string; + onSearch: (itemName: string, selectedItem?: ItemInfo) => void; +} + +export default function AuctionItemSearch({ + value, + onSearch, +}: AuctionItemSearchProps) { + const [inputValue, setInputValue] = useState(value); + const [isOpen, setIsOpen] = useState(false); + const [selectedIndex, setSelectedIndex] = useState(-1); + const inputRef = useRef(null); + const { data: items = [], isLoading } = useItemInfos(); + + useEffect(() => setInputValue(value), [value]); + + const filteredItems = useMemo(() => { + const term = inputValue.trim().toLowerCase(); + if (!term) return []; + return (Array.isArray(items) ? items : []) + .filter((item) => item.name.toLowerCase().includes(term)) + .slice(0, 10); + }, [inputValue, items]); + + const submit = (event: FormEvent) => { + event.preventDefault(); + setIsOpen(false); + setSelectedIndex(-1); + onSearch(inputValue.trim()); + }; + + const handleKeyDown = (event: KeyboardEvent) => { + if (event.key === "Enter" && selectedIndex >= 0) { + const selected = filteredItems[selectedIndex]; + if (selected) { + event.preventDefault(); + setInputValue(selected.name); + setIsOpen(false); + setSelectedIndex(-1); + onSearch(selected.name, selected); + } + return; + } + if (event.key === "ArrowDown") { + event.preventDefault(); + setSelectedIndex((current) => + Math.min(current + 1, filteredItems.length - 1), + ); + } else if (event.key === "ArrowUp") { + event.preventDefault(); + setSelectedIndex((current) => Math.max(current - 1, -1)); + } else if (event.key === "Escape") { + setIsOpen(false); + setSelectedIndex(-1); + } + }; + + return ( +
+ +
+
+
+ +
+
+ ); +} diff --git a/src/components/page/auction-history/AuctionHistoryList.test.tsx b/src/components/page/auction-history/AuctionHistoryList.test.tsx new file mode 100644 index 0000000..b2f011e --- /dev/null +++ b/src/components/page/auction-history/AuctionHistoryList.test.tsx @@ -0,0 +1,61 @@ +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; + +import { AuctionHistoryItem } from "@/hooks/useAuctionHistory"; + +import AuctionHistoryList from "./AuctionHistoryList"; + +jest.mock("next/navigation", () => ({ + usePathname: () => "/auction-history", + useSearchParams: () => new URLSearchParams("page=3&item_name=%EA%B2%80"), +})); + +const item: AuctionHistoryItem = { + itemName: "검 (붉은색)", + itemDisplayName: "강한 검 (붉은색)", + itemCount: 1, + auctionPricePerUnit: 1000, + dateAuctionBuy: "2026-11-05T10:00:00", + auctionBuyId: "history-1", + itemSubCategory: "검", + itemTopCategory: "근거리 장비", + itemOptions: [], +}; + +describe("AuctionHistoryList", () => { + it("links mobile and desktop rows to detail while preserving the list URL", () => { + render(); + const links = screen.getAllByRole("link", { name: /검/ }); + expect(links).toHaveLength(2); + expect(links[0]).toHaveAttribute( + "href", + expect.stringContaining("/auction-history/history-1?return_to="), + ); + const href = new URL( + links[0].getAttribute("href") ?? "", + "http://localhost", + ); + expect(decodeURIComponent(href.searchParams.get("return_to") ?? "")).toBe( + "/auction-history?page=3&item_name=검", + ); + expect(screen.getByText("강한")).toBeInTheDocument(); + expect(screen.getByText("#붉은색")).toBeInTheDocument(); + fireEvent.mouseEnter(screen.getByText("강한 검 (붉은색)")); + expect(screen.queryByText("가격 : 1,000 Gold")).not.toBeInTheDocument(); + }); + + it("opens the desktop preview on item-name hover and row focus when enabled", async () => { + render(); + const desktopName = screen.getByText("강한 검 (붉은색)"); + + fireEvent.mouseEnter(desktopName); + expect(await screen.findByText("가격 : 1,000 Gold")).toBeInTheDocument(); + + fireEvent.mouseLeave(desktopName); + await waitFor(() => + expect(screen.queryByText("가격 : 1,000 Gold")).not.toBeInTheDocument(), + ); + const desktopLink = screen.getAllByRole("link", { name: /검/ })[1]; + fireEvent.focus(desktopLink); + expect(await screen.findByText("가격 : 1,000 Gold")).toBeInTheDocument(); + }); +}); diff --git a/src/components/page/auction-history/AuctionHistoryList.tsx b/src/components/page/auction-history/AuctionHistoryList.tsx index 4272041..352d09e 100644 --- a/src/components/page/auction-history/AuctionHistoryList.tsx +++ b/src/components/page/auction-history/AuctionHistoryList.tsx @@ -1,10 +1,14 @@ "use client"; +import Link from "next/link"; +import { usePathname, useSearchParams } from "next/navigation"; +import { useState } from "react"; + import { Badge } from "@/components/ui/badge"; import { Popover, + PopoverAnchor, PopoverContent, - PopoverTrigger, } from "@/components/ui/popover"; import { AuctionHistoryItem } from "@/hooks/useAuctionHistory"; @@ -13,332 +17,196 @@ import ItemOptionPopover from "./ItemOptionPopover"; interface AuctionHistoryListProps { items: AuctionHistoryItem[]; isLoading?: boolean; + previewEnabled?: boolean; +} + +function formatPrice(price: number) { + if (price === 0) return "0"; + const eok = Math.floor(price / 100000000); + const man = Math.floor((price % 100000000) / 10000); + const rest = price % 10000; + return [ + eok > 0 ? `${eok}억` : "", + man > 0 ? `${man.toLocaleString("ko-KR")}만` : "", + rest > 0 || (eok === 0 && man === 0) ? rest.toLocaleString("ko-KR") : "", + ] + .filter(Boolean) + .join(" "); +} + +function formatDateShort(value: string) { + return new Intl.DateTimeFormat("ko-KR", { + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + hour12: false, + }).format(new Date(value)); +} + +function itemNameWithoutAttributes(itemName: string) { + return itemName.replace(/\s*\([^)]*\)/g, "").trim(); +} + +function itemAttributes(itemName: string) { + return (itemName.match(/\(([^)]+)\)/g) ?? []).map((value) => + value.replace(/[()]/g, "").trim(), + ); +} + +function enchantPrefix(displayName: string, itemName: string) { + return displayName.replace(itemName, "").trim(); +} + +function HistoryDesktopRow({ + item, + href, + previewEnabled, +}: { + item: AuctionHistoryItem; + href: string; + previewEnabled: boolean; +}) { + const [open, setOpen] = useState(false); + return ( + + previewEnabled && setOpen(true)} + onBlur={() => setOpen(false)} + > +
+ + previewEnabled && setOpen(true)} + onMouseLeave={() => setOpen(false)} + > + {item.itemDisplayName} + + +
+
+ + {item.itemSubCategory} + +
+
+ {formatPrice(item.auctionPricePerUnit)} + + G + +
+
+ {formatDateShort(item.dateAuctionBuy)} +
+
+ {item.itemCount} +
+ + {previewEnabled ? ( + event.preventDefault()} + > + + + ) : null} +
+ ); } export default function AuctionHistoryList({ items, isLoading = false, + previewEnabled = true, }: AuctionHistoryListProps) { - if (isLoading) { - return ( - <> - {/* Mobile Skeleton */} -
-
-
- {Array.from({ length: 6 }).map((_, index) => ( -
- {/* 1st Line: Enchant skeleton */} -
- {/* 2nd Line: Item name + price */} -
-
-
-
- {/* 3rd Line: Tags + date */} -
-
-
-
-
-
-
-
- ))} -
-
-
+ const pathname = usePathname(); + const searchParams = useSearchParams(); + const returnTo = `${pathname}${searchParams.size ? `?${searchParams.toString()}` : ""}`; + const hrefFor = (id: string) => + `/auction-history/${encodeURIComponent(id)}?${new URLSearchParams({ return_to: returnTo })}`; - {/* Desktop Skeleton */} -
- {/* Table Header */} -
-
- 아이템 이름 -
-
- 카테고리 -
-
- 가격 -
-
- 거래일시 -
-
- 수량 -
-
- {/* Skeleton Rows */} -
- {Array.from({ length: 8 }).map((_, index) => ( -
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- ))} -
-
- + if (isLoading) + return ( +
+ 로딩 중... +
); - } - - if (items.length === 0) { + if (items.length === 0) return ( -
-
-

- 검색 결과가 없습니다. -

-

- 다른 검색 조건으로 시도해보세요. -

-
+
+

+ 검색 결과가 없습니다. +

+

+ 다른 검색 조건으로 시도해보세요. +

); - } - - const formatPrice = (price: number) => { - if (price === 0) return "0"; - - const eok = Math.floor(price / 100000000); // 억 - const man = Math.floor((price % 100000000) / 10000); // 만 - const rest = price % 10000; // 나머지 - - const parts: string[] = []; - - if (eok > 0) { - parts.push(`${eok}억`); - } - - if (man > 0) { - parts.push(`${man.toLocaleString("ko-KR")}만`); - } - - if (rest > 0 || parts.length === 0) { - parts.push(rest.toLocaleString("ko-KR")); - } - - return parts.join(" "); - }; - - const formatDateShort = (dateString: string) => { - const date = new Date(dateString); - return new Intl.DateTimeFormat("ko-KR", { - month: "2-digit", - day: "2-digit", - hour: "2-digit", - minute: "2-digit", - hour12: false, - }).format(date); - }; - - // Extract enchant prefix from display name (축복받은|신성한 + 접두/접미 인챈트) - const getEnchantPrefix = (displayName: string, itemName: string) => { - // Remove itemName from displayName to get the enchant prefix - const prefix = displayName.replace(itemName, "").trim(); - return prefix || null; - }; - - // Extract pure item name without parentheses and their content - const getItemNameWithoutAttributes = (itemName: string) => { - return itemName.replace(/\s*\([^)]*\)/g, "").trim(); - }; - - // Extract attributes from parentheses in item name - const getItemAttributes = (itemName: string) => { - const matches = itemName.match(/\(([^)]+)\)/g); - if (!matches) return []; - return matches.map((match) => match.replace(/[()]/g, "").trim()); - }; return ( <> - {/* Mobile List Layout */} -
-
-
- {items.map((item, index) => ( - - -
- {/* 1st Line: Enchants (축복받은/신성한 + 접두/접미 인챈트) - 항상 공간 유지 */} -
- {getEnchantPrefix(item.itemDisplayName, item.itemName) || - "\u00A0"} -
- - {/* 2nd Line: Pure Item Name (Left) + Price (Right) */} -
-

- {getItemNameWithoutAttributes(item.itemName)} -

-
- - {formatPrice(item.auctionPricePerUnit)} - - - G - -
-
- - {/* 3rd Line: Attribute Tags (Left) + Date (Right) */} -
-
- {getItemAttributes(item.itemName).length > 0 ? ( - getItemAttributes(item.itemName).map((attr, idx) => ( - - #{attr} - - )) - ) : ( - - )} -
-
- {item.itemCount > 1 && ( - - ×{item.itemCount} - - )} - - - - - {formatDateShort(item.dateAuctionBuy)} - -
-
-
-
- - - - -
- ))} -
+
+
+ {items.map((item) => ( + +
+ {enchantPrefix(item.itemDisplayName, item.itemName) || "\u00A0"} +
+
+

+ {itemNameWithoutAttributes(item.itemName)} +

+ + {formatPrice(item.auctionPricePerUnit)}{" "} + + G + + +
+
+ + {itemAttributes(item.itemName) + .map((value) => `#${value}`) + .join(" ")} + + + {formatDateShort(item.dateAuctionBuy)} + {item.itemCount > 1 ? ` · ×${item.itemCount}` : ""} + +
+ + ))}
- - {/* Desktop Table Layout */} -
- {/* Table Header */} -
-
- 아이템 이름 -
-
- 카테고리 -
-
- 가격 -
-
- 거래일시 -
-
- 수량 -
+
+
+
아이템 이름
+
카테고리
+
가격
+
거래일시
+
수량
- - {/* Table Body */}
- {items.map((item, index) => ( - - -
- {/* Item Name */} -
-
- - {item.itemDisplayName} - -
-
- - {/* Category */} -
- - {item.itemSubCategory} - -
- - {/* Price */} -
- - {formatPrice(item.auctionPricePerUnit)} - - - G - -
- - {/* Date */} -
- {formatDateShort(item.dateAuctionBuy)} -
- - {/* Count */} -
- {item.itemCount} -
-
-
- - - - -
+ {items.map((item) => ( + ))}
diff --git a/src/components/page/auction-history/SearchFilterCard.tsx b/src/components/page/auction-history/SearchFilterCard.tsx index 4e9a566..e238b41 100644 --- a/src/components/page/auction-history/SearchFilterCard.tsx +++ b/src/components/page/auction-history/SearchFilterCard.tsx @@ -45,6 +45,8 @@ interface SearchFilterCardProps { /** 아이템명 완전 일치 검색 여부 */ isExactItemName?: boolean; onExactItemNameChange?: (value: boolean) => void; + isItemPreviewEnabled?: boolean; + onItemPreviewEnabledChange?: (value: boolean) => void; } type DatePreset = "1week" | "1month" | "3months"; @@ -89,6 +91,8 @@ export default function SearchFilterCard({ layoutMode = "desktop", isExactItemName = false, onExactItemNameChange, + isItemPreviewEnabled = true, + onItemPreviewEnabledChange, }: SearchFilterCardProps) { // 레이아웃 모드에 따른 필터 카드 위치 계산 // 데스크탑(3-column): 간격 6px → 50% - 448 - 6 - 256 = 50% - 710px @@ -576,6 +580,33 @@ export default function SearchFilterCard({ + + {/* Price & Date Combined Filter - Compact */}
{/* Price Section */} diff --git a/src/components/page/auction-realtime/AuctionRealtimeList.test.tsx b/src/components/page/auction-realtime/AuctionRealtimeList.test.tsx new file mode 100644 index 0000000..d878d7e --- /dev/null +++ b/src/components/page/auction-realtime/AuctionRealtimeList.test.tsx @@ -0,0 +1,40 @@ +import { fireEvent, render, screen } from "@testing-library/react"; + +import { AuctionRealtimeItem } from "@/hooks/useAuctionRealtime"; + +import AuctionRealtimeList from "./AuctionRealtimeList"; + +jest.mock("next/navigation", () => ({ + usePathname: () => "/auction-realtime", + useSearchParams: () => new URLSearchParams("page=2&itemName=%EA%B2%80"), +})); + +const item: AuctionRealtimeItem = { + itemName: "검 (붉은색)", + itemDisplayName: "축복받은 검 (붉은색)", + itemCount: 2, + auctionPricePerUnit: 2500, + dateAuctionRegister: "2026-11-05T09:00:00", + dateAuctionExpire: "2026-11-05T12:00:00", + auctionId: "realtime-1", + itemSubCategory: "검", + itemTopCategory: "근거리 장비", + itemOptions: [], +}; + +describe("AuctionRealtimeList", () => { + it("keeps the mobile card details and links one tap to detail without a popup", () => { + render(); + + const links = screen.getAllByRole("link", { name: /검/ }); + expect(links).toHaveLength(2); + expect(links[0]).toHaveAttribute( + "href", + expect.stringContaining("/auction-realtime/realtime-1?return_to="), + ); + expect(screen.getByText("축복받은")).toBeInTheDocument(); + expect(screen.getByText("#붉은색")).toBeInTheDocument(); + fireEvent.click(links[0]); + expect(screen.queryByText("가격 : 2,500 Gold")).not.toBeInTheDocument(); + }); +}); diff --git a/src/components/page/auction-realtime/AuctionRealtimeList.tsx b/src/components/page/auction-realtime/AuctionRealtimeList.tsx index 7abaedd..715d414 100644 --- a/src/components/page/auction-realtime/AuctionRealtimeList.tsx +++ b/src/components/page/auction-realtime/AuctionRealtimeList.tsx @@ -1,273 +1,209 @@ "use client"; +import Link from "next/link"; +import { usePathname, useSearchParams } from "next/navigation"; +import { useState } from "react"; + import ItemOptionPopover from "@/components/page/auction-history/ItemOptionPopover"; import { Badge } from "@/components/ui/badge"; import { Popover, + PopoverAnchor, PopoverContent, - PopoverTrigger, } from "@/components/ui/popover"; import { AuctionRealtimeItem } from "@/hooks/useAuctionRealtime"; interface AuctionRealtimeListProps { items: AuctionRealtimeItem[]; isLoading?: boolean; + previewEnabled?: boolean; +} + +function formatPrice(price: number) { + if (price === 0) return "0"; + const eok = Math.floor(price / 100000000), + man = Math.floor((price % 100000000) / 10000), + rest = price % 10000; + return [ + eok > 0 ? `${eok}억` : "", + man > 0 ? `${man.toLocaleString("ko-KR")}만` : "", + rest > 0 || (eok === 0 && man === 0) ? rest.toLocaleString("ko-KR") : "", + ] + .filter(Boolean) + .join(" "); +} + +function formatDateShort(value: string) { + return new Intl.DateTimeFormat("ko-KR", { + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + hour12: false, + }).format(new Date(value)); +} + +function enchantPrefix(displayName: string, itemName: string) { + return displayName.replace(itemName, "").trim(); +} + +function itemNameWithoutAttributes(itemName: string) { + return itemName.replace(/\s*\([^)]*\)/g, "").trim(); +} + +function itemAttributes(itemName: string) { + return (itemName.match(/\(([^)]+)\)/g) ?? []).map((value) => + value.replace(/[()]/g, "").trim(), + ); +} + +function RealtimeDesktopRow({ + item, + href, + previewEnabled, +}: { + item: AuctionRealtimeItem; + href: string; + previewEnabled: boolean; +}) { + const [open, setOpen] = useState(false); + return ( + + previewEnabled && setOpen(true)} + onBlur={() => setOpen(false)} + > +
+ + previewEnabled && setOpen(true)} + onMouseLeave={() => setOpen(false)} + > + {item.itemDisplayName} + + +
+
+ + {item.itemSubCategory} + +
+
+ {formatPrice(item.auctionPricePerUnit)} + + G + +
+
+ {formatDateShort(item.dateAuctionExpire)} +
+
+ {item.itemCount} +
+ + {previewEnabled ? ( + event.preventDefault()} + > + + + ) : null} +
+ ); } export default function AuctionRealtimeList({ items, isLoading = false, + previewEnabled = true, }: AuctionRealtimeListProps) { - if (isLoading) { + const pathname = usePathname(), + searchParams = useSearchParams(); + const returnTo = `${pathname}${searchParams.size ? `?${searchParams.toString()}` : ""}`; + const hrefFor = (id: string) => + `/auction-realtime/${encodeURIComponent(id)}?${new URLSearchParams({ return_to: returnTo })}`; + if (isLoading) return ( -
-
-
로딩 중...
-
+
+ 로딩 중...
); - } - - if (items.length === 0) { + if (items.length === 0) return ( -
-
-

- 검색 결과가 없습니다. -

-

- 다른 검색 조건으로 시도해보세요. -

-
+
+

+ 검색 결과가 없습니다. +

+

+ 다른 검색 조건으로 시도해보세요. +

); - } - - const formatPrice = (price: number) => { - if (price === 0) return "0"; - - const eok = Math.floor(price / 100000000); // 억 - const man = Math.floor((price % 100000000) / 10000); // 만 - const rest = price % 10000; // 나머지 - - const parts: string[] = []; - - if (eok > 0) { - parts.push(`${eok}억`); - } - - if (man > 0) { - parts.push(`${man.toLocaleString("ko-KR")}만`); - } - - if (rest > 0 || parts.length === 0) { - parts.push(rest.toLocaleString("ko-KR")); - } - - return parts.join(" "); - }; - - const formatDateShort = (dateString: string) => { - const date = new Date(dateString); - return new Intl.DateTimeFormat("ko-KR", { - month: "2-digit", - day: "2-digit", - hour: "2-digit", - minute: "2-digit", - hour12: false, - }).format(date); - }; - - // Extract enchant prefix from display name (축복받은|신성한 + 접두/접미 인챈트) - const getEnchantPrefix = (displayName: string, itemName: string) => { - // Remove itemName from displayName to get the enchant prefix - const prefix = displayName.replace(itemName, "").trim(); - return prefix || null; - }; - - // Extract pure item name without parentheses and their content - const getItemNameWithoutAttributes = (itemName: string) => { - return itemName.replace(/\s*\([^)]*\)/g, "").trim(); - }; - - // Extract attributes from parentheses in item name - const getItemAttributes = (itemName: string) => { - const matches = itemName.match(/\(([^)]+)\)/g); - if (!matches) return []; - return matches.map((match) => match.replace(/[()]/g, "").trim()); - }; - return ( <> - {/* Mobile List Layout */} -
-
-
- {items.map((item, index) => ( - - -
- {/* 1st Line: Enchants (축복받은/신성한 + 접두/접미 인챈트) - 항상 공간 유지 */} -
- {getEnchantPrefix(item.itemDisplayName, item.itemName) || - "\u00A0"} -
- - {/* 2nd Line: Pure Item Name (Left) + Price (Right) */} -
-

- {getItemNameWithoutAttributes(item.itemName)} -

-
- - {formatPrice(item.auctionPricePerUnit)} - - - G - -
-
- - {/* 3rd Line: Attribute Tags (Left) + Date (Right) */} -
-
- {getItemAttributes(item.itemName).length > 0 ? ( - getItemAttributes(item.itemName).map((attr, idx) => ( - - #{attr} - - )) - ) : ( - - )} -
-
- {item.itemCount > 1 && ( - - ×{item.itemCount} - - )} - - - - - {formatDateShort(item.dateAuctionExpire)} - -
-
-
-
- - - - -
- ))} -
+
+
+ {items.map((item) => ( + +
+ {enchantPrefix(item.itemDisplayName, item.itemName) || "\u00A0"} +
+
+

+ {itemNameWithoutAttributes(item.itemName)} +

+ + {formatPrice(item.auctionPricePerUnit)}{" "} + + G + + +
+
+ + {itemAttributes(item.itemName) + .map((value) => `#${value}`) + .join(" ")} + + + {formatDateShort(item.dateAuctionExpire)} + {item.itemCount > 1 ? ` · ×${item.itemCount}` : ""} + +
+ + ))}
- - {/* Desktop Table Layout */} -
- {/* Table Header */} -
-
- 아이템 이름 -
-
- 카테고리 -
-
- 가격 -
-
- 만료일시 -
-
- 수량 -
+
+
+
아이템 이름
+
카테고리
+
가격
+
만료일시
+
수량
- - {/* Table Body */}
- {items.map((item, index) => ( - - -
- {/* Item Name */} -
-
- - {item.itemDisplayName} - -
-
- - {/* Category */} -
- - {item.itemSubCategory} - -
- - {/* Price */} -
- - {formatPrice(item.auctionPricePerUnit)} - - - G - -
- - {/* Date - 만료일시 */} -
- {formatDateShort(item.dateAuctionExpire)} -
- - {/* Count */} -
- {item.itemCount} -
-
-
- - - - -
+ {items.map((item) => ( + ))}
diff --git a/src/components/page/auction-realtime/SearchFilterCard.tsx b/src/components/page/auction-realtime/SearchFilterCard.tsx index 8a457db..2f26d0e 100644 --- a/src/components/page/auction-realtime/SearchFilterCard.tsx +++ b/src/components/page/auction-realtime/SearchFilterCard.tsx @@ -36,6 +36,8 @@ interface SearchFilterCardProps { /** 아이템명 완전 일치 검색 여부 */ isExactItemName?: boolean; onExactItemNameChange?: (value: boolean) => void; + isItemPreviewEnabled?: boolean; + onItemPreviewEnabledChange?: (value: boolean) => void; } interface BasicFilters { @@ -50,6 +52,8 @@ export default function SearchFilterCard({ layoutMode = "desktop", isExactItemName = false, onExactItemNameChange, + isItemPreviewEnabled = true, + onItemPreviewEnabledChange, }: SearchFilterCardProps) { // 레이아웃 모드에 따른 필터 카드 위치 계산 const filterRightPosition = @@ -480,6 +484,33 @@ export default function SearchFilterCard({ + + {/* Price Filter Only - 날짜 필터 없음 */}
{/* Price Section */} diff --git a/src/components/page/statistics/StatisticsSummaryCards.tsx b/src/components/page/statistics/StatisticsSummaryCards.tsx index 0ae0fd1..59e9b5f 100644 --- a/src/components/page/statistics/StatisticsSummaryCards.tsx +++ b/src/components/page/statistics/StatisticsSummaryCards.tsx @@ -17,11 +17,11 @@ export default function StatisticsSummaryCards({ }: StatisticsSummaryCardsProps) { if (data.length === 0) return null; - const overallAvg = data.reduce((sum, d) => sum + d.avgPrice, 0) / data.length; - const overallMax = Math.max(...data.map((d) => d.maxPrice)); - const overallMin = Math.min(...data.map((d) => d.minPrice)); const totalVolume = data.reduce((sum, d) => sum + d.totalVolume, 0); const totalQuantity = data.reduce((sum, d) => sum + d.totalQuantity, 0); + const overallAvg = totalQuantity > 0 ? totalVolume / totalQuantity : 0; + const overallMax = Math.max(...data.map((d) => d.maxPrice)); + const overallMin = Math.min(...data.map((d) => d.minPrice)); const cards = [ { diff --git a/src/components/ui/popover.tsx b/src/components/ui/popover.tsx index d371622..c81cd51 100644 --- a/src/components/ui/popover.tsx +++ b/src/components/ui/popover.tsx @@ -11,10 +11,10 @@ function Popover({ return ; } -function PopoverTrigger({ +function PopoverAnchor({ ...props -}: React.ComponentProps) { - return ; +}: React.ComponentProps) { + return ; } function PopoverContent({ @@ -39,4 +39,4 @@ function PopoverContent({ ); } -export { Popover, PopoverContent, PopoverTrigger }; +export { Popover, PopoverAnchor, PopoverContent }; diff --git a/src/hooks/useAuctionItemPreviewPreference.test.ts b/src/hooks/useAuctionItemPreviewPreference.test.ts new file mode 100644 index 0000000..718d4b7 --- /dev/null +++ b/src/hooks/useAuctionItemPreviewPreference.test.ts @@ -0,0 +1,21 @@ +import { act, renderHook, waitFor } from "@testing-library/react"; + +import { useAuctionItemPreviewPreference } from "./useAuctionItemPreviewPreference"; + +describe("useAuctionItemPreviewPreference", () => { + beforeEach(() => localStorage.clear()); + + it("defaults to ON and persists the shared preference", async () => { + const { result, unmount } = renderHook(() => + useAuctionItemPreviewPreference(), + ); + expect(result.current.isPreviewEnabled).toBe(true); + act(() => result.current.setIsPreviewEnabled(false)); + expect(localStorage.getItem("auction-item-preview:v1")).toBe("false"); + unmount(); + const restored = renderHook(() => useAuctionItemPreviewPreference()); + await waitFor(() => + expect(restored.result.current.isPreviewEnabled).toBe(false), + ); + }); +}); diff --git a/src/hooks/useAuctionItemPreviewPreference.ts b/src/hooks/useAuctionItemPreviewPreference.ts new file mode 100644 index 0000000..5cbe372 --- /dev/null +++ b/src/hooks/useAuctionItemPreviewPreference.ts @@ -0,0 +1,31 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; + +const STORAGE_KEY = "auction-item-preview:v1"; + +export function useAuctionItemPreviewPreference() { + const [isPreviewEnabled, setIsPreviewEnabledState] = useState(true); + + useEffect(() => { + try { + const stored = window.localStorage.getItem(STORAGE_KEY); + if (stored !== null) { + setIsPreviewEnabledState(stored === "true"); + } + } catch { + // Storage can be unavailable in private browsing. Keep the ON default. + } + }, []); + + const setIsPreviewEnabled = useCallback((enabled: boolean) => { + setIsPreviewEnabledState(enabled); + try { + window.localStorage.setItem(STORAGE_KEY, String(enabled)); + } catch { + // The in-memory preference still applies for the current page. + } + }, []); + + return { isPreviewEnabled, setIsPreviewEnabled }; +} diff --git a/src/lib/auction/detail.test.ts b/src/lib/auction/detail.test.ts new file mode 100644 index 0000000..b8ffaf0 --- /dev/null +++ b/src/lib/auction/detail.test.ts @@ -0,0 +1,221 @@ +import { getAuctionDetail, getKstDateRange, safeReturnTo } from "./detail"; + +const record = { + itemName: "롱소드", + itemDisplayName: "강한 롱소드", + itemCount: 2, + auctionPricePerUnit: 1200, + dateAuctionBuy: "2026-11-05T10:00:00", + auctionBuyId: "history-success", + itemSubCategory: "검", + itemTopCategory: "근거리 장비", + itemOptions: [], +}; + +const itemInfoPage = { + content: [ + { + name: "롱소드", + topCategory: "근거리 장비", + subCategory: "검", + description: "한손검", + inventoryWidth: 1, + inventoryHeight: 3, + inventoryMaxBundleCount: 1, + history: null, + acquisitionMethod: null, + storeSalesPrice: null, + weaponType: "검", + repair: null, + maxAlterationCount: 5, + }, + ], + totalElements: 1, + totalPages: 1, + number: 0, + size: 10, + first: true, + last: true, + empty: false, +}; + +function jsonResponse(data: unknown, status = 200) { + return { + ok: status >= 200 && status < 300, + status, + json: jest.fn().mockResolvedValue(data), + } as unknown as Response; +} + +function successFetch(input: RequestInfo | URL) { + const url = String(input); + if (url.includes("/auction-history/")) return jsonResponse(record); + if (url.includes("/item-infos/detail")) return jsonResponse(itemInfoPage); + if (url.includes("/statistics/daily/items")) + return jsonResponse([ + { + itemName: "롱소드", + dateAuctionBuy: "2026-11-05", + minPrice: 1000, + maxPrice: 1500, + avgPrice: 9999, + totalVolume: 5000, + totalQuantity: 4, + }, + ]); + return jsonResponse([ + { + itemName: "롱소드", + weekStartDate: "2026-11-02", + minPrice: 900, + maxPrice: 1600, + avgPrice: 9999, + totalVolume: 6000, + totalQuantity: 4, + }, + ]); +} + +describe("safeReturnTo", () => { + it("accepts only the matching auction list path", () => { + expect( + safeReturnTo("history", "/auction-history?page=3&item_name=%EA%B2%80"), + ).toBe("/auction-history?page=3&item_name=%EA%B2%80"); + expect(safeReturnTo("realtime", "/auction-realtime?page=2")).toBe( + "/auction-realtime?page=2", + ); + }); + + it("rejects external and cross-source return URLs", () => { + expect( + safeReturnTo("history", "https://evil.example/auction-history"), + ).toBe("/auction-history"); + expect(safeReturnTo("history", "/auction-realtime?page=2")).toBe( + "/auction-history", + ); + expect(safeReturnTo("realtime", undefined)).toBe("/auction-realtime"); + }); +}); + +describe("getKstDateRange", () => { + it("uses the Asia/Seoul calendar day across KST midnight", () => { + expect(getKstDateRange(30, new Date("2026-11-04T14:59:59Z"))).toEqual({ + startDate: "2026-10-06", + endDate: "2026-11-04", + }); + expect(getKstDateRange(30, new Date("2026-11-04T15:00:00Z"))).toEqual({ + startDate: "2026-10-07", + endDate: "2026-11-05", + }); + expect(getKstDateRange(120, new Date("2026-11-04T15:00:00Z"))).toEqual({ + startDate: "2026-07-09", + endDate: "2026-11-05", + }); + }); +}); + +describe("getAuctionDetail", () => { + const originalGatewayUrl = process.env.GATEWAY_URL; + + beforeEach(() => { + process.env.GATEWAY_URL = "http://gateway.test"; + jest.spyOn(globalThis, "fetch"); + }); + + afterEach(() => { + jest.restoreAllMocks(); + process.env.GATEWAY_URL = originalGatewayUrl; + }); + + it("loads the record and independent detail sections with bounded requests", async () => { + jest.mocked(fetch).mockImplementation(async (input) => successFetch(input)); + + const result = await getAuctionDetail("history", "success-1"); + + expect(result.status).toBe("available"); + expect(result.itemInfoStatus).toBe("available"); + expect(result.dailyStatus).toBe("available"); + expect(result.weeklyStatus).toBe("available"); + expect(result.dailyStatistics[0].avgPrice).toBe(1250); + expect(result.weeklyStatistics[0]).toMatchObject({ + avgPrice: 1500, + weekEnd: "2026-11-08", + }); + expect(fetch).toHaveBeenCalledTimes(4); + for (const [, init] of jest.mocked(fetch).mock.calls) { + expect(init?.signal).toBeInstanceOf(AbortSignal); + } + const statisticUrls = jest + .mocked(fetch) + .mock.calls.map(([input]) => String(input)) + .filter((url) => url.includes("/statistics/")); + expect(statisticUrls).toHaveLength(2); + for (const url of statisticUrls) { + const params = new URL(url).searchParams; + expect(params.get("itemName")).toBe("롱소드"); + expect(params.get("topCategory")).toBe("근거리 장비"); + expect(params.get("subCategory")).toBe("검"); + expect(params.get("startDate")).toMatch(/^\d{4}-\d{2}-\d{2}$/); + expect(params.get("endDate")).toMatch(/^\d{4}-\d{2}-\d{2}$/); + } + }); + + it("distinguishes a missing primary record from a primary timeout", async () => { + jest.mocked(fetch).mockResolvedValueOnce(jsonResponse({}, 404)); + await expect( + getAuctionDetail("history", "missing-1"), + ).resolves.toMatchObject({ status: "not-found" }); + + jest + .mocked(fetch) + .mockRejectedValueOnce(new DOMException("timed out", "TimeoutError")); + await expect( + getAuctionDetail("history", "timeout-1"), + ).resolves.toMatchObject({ status: "error" }); + + jest.mocked(fetch).mockResolvedValueOnce(jsonResponse({}, 500)); + await expect( + getAuctionDetail("history", "gateway-error-1"), + ).resolves.toMatchObject({ status: "error" }); + }); + + it("keeps successful sections when one dependent request times out", async () => { + jest.mocked(fetch).mockImplementation(async (input) => { + const url = String(input); + if (url.includes("/auction-history/")) return jsonResponse(record); + if (url.includes("/item-infos/detail")) + throw new DOMException("timed out", "TimeoutError"); + return successFetch(input); + }); + + const result = await getAuctionDetail("history", "partial-timeout-1"); + + expect(result).toMatchObject({ + status: "available", + itemInfoStatus: "error", + dailyStatus: "available", + weeklyStatus: "available", + }); + expect(result.itemInfo).toBeUndefined(); + expect(result.dailyStatistics).toHaveLength(1); + }); + + it("reports successful empty sections separately from failed sections", async () => { + jest.mocked(fetch).mockImplementation(async (input) => { + const url = String(input); + if (url.includes("/auction-history/")) return jsonResponse(record); + if (url.includes("/item-infos/detail")) + return jsonResponse({ ...itemInfoPage, content: [], empty: true }); + if (url.includes("/statistics/daily/items")) return jsonResponse([]); + throw new Error("weekly unavailable"); + }); + + const result = await getAuctionDetail("history", "empty-and-error-1"); + + expect(result).toMatchObject({ + itemInfoStatus: "empty", + dailyStatus: "empty", + weeklyStatus: "error", + }); + }); +}); diff --git a/src/lib/auction/detail.ts b/src/lib/auction/detail.ts new file mode 100644 index 0000000..b2017fa --- /dev/null +++ b/src/lib/auction/detail.ts @@ -0,0 +1,255 @@ +import { cache } from "react"; + +import { AuctionHistoryItem } from "@/hooks/useAuctionHistory"; +import { AuctionRealtimeItem } from "@/hooks/useAuctionRealtime"; +import { ItemInfoResponse, PageResponse } from "@/types/item-info"; +import { ItemDailyStatistics, ItemWeeklyStatistics } from "@/types/statistics"; + +export type AuctionDetailSource = "history" | "realtime"; +export type AuctionRecord = AuctionHistoryItem | AuctionRealtimeItem; +type DetailSectionStatus = "available" | "empty" | "error"; + +export interface AuctionDetailResult { + status: "available" | "not-found" | "error"; + source: AuctionDetailSource; + record?: AuctionRecord; + itemInfo?: ItemInfoResponse; + dailyStatistics: ItemDailyStatistics[]; + weeklyStatistics: ItemWeeklyStatistics[]; + itemInfoStatus: DetailSectionStatus; + dailyStatus: DetailSectionStatus; + weeklyStatus: DetailSectionStatus; +} + +interface ApiResponse { + success: boolean; + data: T; +} +interface RawDaily { + itemName: string; + dateAuctionBuy: string; + minPrice: number; + maxPrice: number; + avgPrice: number; + totalVolume: number; + totalQuantity: number; +} +interface RawWeekly { + itemName: string; + weekStartDate: string; + minPrice: number; + maxPrice: number; + avgPrice: number; + totalVolume: number; + totalQuantity: number; +} + +function gatewayUrl() { + const value = process.env.GATEWAY_URL; + if (!value) throw new Error("GATEWAY_URL 환경 변수가 설정되지 않았습니다."); + return value.replace(/\/$/, ""); +} + +function unwrap(value: T | ApiResponse): T { + return typeof value === "object" && value !== null && "success" in value + ? (value as ApiResponse).data + : (value as T); +} + +async function getJson(path: string, revalidate?: number): Promise { + const response = await fetch( + `${gatewayUrl()}${path}`, + revalidate + ? { next: { revalidate }, signal: AbortSignal.timeout(5000) } + : { cache: "no-store", signal: AbortSignal.timeout(5000) }, + ); + if (!response.ok) + throw Object.assign(new Error(`API 호출 실패: ${response.status}`), { + status: response.status, + }); + return unwrap((await response.json()) as T | ApiResponse); +} + +function dateString(date: Date) { + return date.toISOString().slice(0, 10); +} + +function seoulDate(now: Date) { + const parts = new Intl.DateTimeFormat("en-CA", { + timeZone: "Asia/Seoul", + year: "numeric", + month: "2-digit", + day: "2-digit", + }).formatToParts(now); + const value = Object.fromEntries( + parts.map((part) => [part.type, part.value]), + ); + return `${value.year}-${value.month}-${value.day}`; +} + +export function getKstDateRange(days: number, now: Date = new Date()) { + const endDate = seoulDate(now); + const [year, month, day] = endDate.split("-").map(Number); + const start = new Date(Date.UTC(year, month - 1, day)); + start.setUTCDate(start.getUTCDate() - (days - 1)); + return { startDate: dateString(start), endDate }; +} + +function query(values: Record) { + return new URLSearchParams( + Object.entries(values).map(([key, value]) => [key, String(value)]), + ).toString(); +} + +function weightedAverage(item: { + avgPrice: number; + totalVolume: number; + totalQuantity: number; +}) { + return item.totalQuantity > 0 + ? item.totalVolume / item.totalQuantity + : Number(item.avgPrice); +} + +function weekEnd(start: string) { + const value = new Date(`${start}T00:00:00Z`); + value.setUTCDate(value.getUTCDate() + 6); + return dateString(value); +} + +export const getAuctionDetail = cache( + async ( + source: AuctionDetailSource, + id: string, + ): Promise => { + const recordPath = + source === "history" + ? `/oab/auction-history/${encodeURIComponent(id)}` + : `/oab/auction-realtime/${encodeURIComponent(id)}`; + let record: AuctionRecord; + try { + record = await getJson(recordPath); + } catch (error) { + const status = + typeof error === "object" && error !== null && "status" in error + ? Number(error.status) + : 500; + return { + status: status === 404 ? "not-found" : "error", + source, + dailyStatistics: [], + weeklyStatistics: [], + itemInfoStatus: "empty", + dailyStatus: "empty", + weeklyStatus: "empty", + }; + } + + const itemName = record.itemName; + const topCategory = record.itemTopCategory; + const subCategory = record.itemSubCategory; + const dailyRange = getKstDateRange(30); + const weeklyRange = getKstDateRange(120); + const identity = { itemName, topCategory, subCategory }; + const itemInfoParams = query({ + name: itemName, + topCategory, + subCategory, + page: 1, + size: 10, + direction: "ASC", + }); + const dailyParams = query({ ...identity, ...dailyRange }); + const weeklyParams = query({ ...identity, ...weeklyRange }); + + const [itemInfoResult, dailyResult, weeklyResult] = + await Promise.allSettled([ + getJson>( + `/oab/api/item-infos/detail?${itemInfoParams}`, + 300, + ), + getJson(`/oab/statistics/daily/items?${dailyParams}`, 300), + getJson( + `/oab/statistics/weekly/items?${weeklyParams}`, + 300, + ), + ]); + + const dailyStatistics = + dailyResult.status === "fulfilled" + ? dailyResult.value.map((item) => ({ + itemName: item.itemName, + itemTopCategory: topCategory, + itemSubCategory: subCategory, + date: item.dateAuctionBuy, + minPrice: item.minPrice, + maxPrice: item.maxPrice, + avgPrice: weightedAverage(item), + totalVolume: item.totalVolume, + totalQuantity: item.totalQuantity, + })) + : []; + const weeklyStatistics = + weeklyResult.status === "fulfilled" + ? weeklyResult.value.map((item) => ({ + itemName: item.itemName, + itemTopCategory: topCategory, + itemSubCategory: subCategory, + weekStart: item.weekStartDate, + weekEnd: weekEnd(item.weekStartDate), + minPrice: item.minPrice, + maxPrice: item.maxPrice, + avgPrice: weightedAverage(item), + totalVolume: item.totalVolume, + totalQuantity: item.totalQuantity, + })) + : []; + + const itemInfo = + itemInfoResult.status === "fulfilled" + ? itemInfoResult.value.content[0] + : undefined; + + return { + status: "available", + source, + record, + itemInfo, + dailyStatistics, + weeklyStatistics, + itemInfoStatus: + itemInfoResult.status === "rejected" + ? "error" + : itemInfo + ? "available" + : "empty", + dailyStatus: + dailyResult.status === "rejected" + ? "error" + : dailyStatistics.length > 0 + ? "available" + : "empty", + weeklyStatus: + weeklyResult.status === "rejected" + ? "error" + : weeklyStatistics.length > 0 + ? "available" + : "empty", + }; + }, +); + +export function safeReturnTo( + source: AuctionDetailSource, + value: string | string[] | undefined, +) { + const fallback = + source === "history" ? "/auction-history" : "/auction-realtime"; + if ( + typeof value !== "string" || + (!value.startsWith(`${fallback}?`) && value !== fallback) + ) + return fallback; + if (value.startsWith("//") || value.includes("://")) return fallback; + return value; +} From 217b44e517dcafccde2e93d01d5a0673f1a16892 Mon Sep 17 00:00:00 2001 From: Lee Sanghyun <59863112+dev-ant@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:51:11 +0900 Subject: [PATCH 2/3] test: align React release contract --- scripts/workflow-contract.test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/workflow-contract.test.mjs b/scripts/workflow-contract.test.mjs index a8ddf4e..467bc3b 100644 --- a/scripts/workflow-contract.test.mjs +++ b/scripts/workflow-contract.test.mjs @@ -68,7 +68,7 @@ test("release version and immutable image contract are fixed", () => { ); const pkg = JSON.parse(read("package.json")); const lock = JSON.parse(read("package-lock.json")); - assert.equal(pkg.version, "1.0.8"); + assert.equal(pkg.version, "1.0.9"); assert.equal(lock.version, pkg.version); assert.equal(lock.packages[""].version, pkg.version); assert.match( From a425ef3f8470f5fa3ac5d07de4ede7ff70bbf43a Mon Sep 17 00:00:00 2001 From: Lee Sanghyun <59863112+dev-ant@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:54:54 +0900 Subject: [PATCH 3/3] test: align production version contract --- scripts/test-production-workflow.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/test-production-workflow.mjs b/scripts/test-production-workflow.mjs index 17a8c1a..69be9f0 100644 --- a/scripts/test-production-workflow.mjs +++ b/scripts/test-production-workflow.mjs @@ -64,7 +64,7 @@ test("production Compose requires the immutable image reference", () => { test("package and lockfile agree on the next release version", () => { const pkg = JSON.parse(read("package.json")); const lock = JSON.parse(read("package-lock.json")); - assert.equal(pkg.version, "1.0.8"); + assert.equal(pkg.version, "1.0.9"); assert.equal(lock.version, pkg.version); assert.equal(lock.packages[""].version, pkg.version); });