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 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;
+}