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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 12 additions & 22 deletions src/app/api/kamis/prices/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { NextResponse } from "next/server";
import { FALLBACK_PRICE_SNAPSHOT } from "@/entities/price/lib/fallback-snapshot";
import type { PriceListResponse, PriceQuoteRaw, PriceSource } from "@/entities/price/model/types";

const KAMIS_BASE_URL = "http://www.kamis.or.kr/service/price/xml.do";
Expand Down Expand Up @@ -63,13 +62,9 @@ async function fetchKamisItem(
const price = Number(raw?.price ?? raw?.dpr1);
if (!raw || !Number.isFinite(price) || price <= 0) return null;

const fallback = FALLBACK_PRICE_SNAPSHOT.find((item) => item.itemName === itemName);
return {
itemName,
unit: "kg",
price,
baselinePrice: fallback?.baselinePrice ?? price,
};
// 기간별(전주 대비) 조회는 아직 붙이지 않아 실제 이력값이 없다 — price를 그대로
// baselinePrice로 채워 "변동 없음"으로 나오게 한다. 가짜 증감률을 만들지 않기 위함.
return { itemName, unit: "kg", price, baselinePrice: price };
} catch {
return null;
} finally {
Expand All @@ -83,29 +78,24 @@ export async function GET() {

if (!certKey || !certId) {
return NextResponse.json<PriceListResponse>({
items: FALLBACK_PRICE_SNAPSHOT,
source: "fallback",
items: [],
source: "unavailable",
fetchedAt: new Date().toISOString(),
});
}

const itemNames = Object.keys(KAMIS_ITEM_CODE_MAP);
const results = await Promise.all(
FALLBACK_PRICE_SNAPSHOT.map((fallbackItem) =>
fetchKamisItem(fallbackItem.itemName, certKey, certId),
),
itemNames.map((itemName) => fetchKamisItem(itemName, certKey, certId)),
);

let liveCount = 0;
const items: PriceQuoteRaw[] = results.map((result, index) => {
if (result) {
liveCount += 1;
return result;
}
return FALLBACK_PRICE_SNAPSHOT[index];
});
// 서버가 실제로 응답한 품목만 내려준다 — 조회 실패 품목은 목록에서 제외(대체값 없음).
const items: PriceQuoteRaw[] = results.filter(
(result): result is PriceQuoteRaw => result !== null,
);

const source: PriceSource =
liveCount === 0 ? "fallback" : liveCount === items.length ? "kamis" : "mixed";
items.length === 0 ? "unavailable" : items.length === itemNames.length ? "kamis" : "partial";

return NextResponse.json<PriceListResponse>({
items,
Expand Down
19 changes: 16 additions & 3 deletions src/entities/meal/api/diet.api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,29 @@ import type {
UpdateDietRequest,
} from "../model/types";

// The calendar matches diets to day cells by exact "YYYY-MM-DD" string equality,
// but the server may serialize dietDate as a datetime ("2026-07-07T00:00:00") or
// without zero padding ("2026-7-7") — normalize at the API boundary.
function normalizeDietDate(value: string): string {
const match = /^(\d{4})-(\d{1,2})-(\d{1,2})/.exec(value);
if (!match) return value;
return `${match[1]}-${match[2].padStart(2, "0")}-${match[3].padStart(2, "0")}`;
}

function withNormalizedDate<T extends { dietDate: string }>(diet: T): T {
return { ...diet, dietDate: normalizeDietDate(diet.dietDate) };
}

// GET /diets — 식단 목록 조회.
export async function getDiets(): Promise<DietListItem[]> {
const response = await instance.get<DietListItem[]>("/diets", { requiresAuth: true });
return Array.isArray(response.data) ? response.data : [];
return Array.isArray(response.data) ? response.data.map(withNormalizedDate) : [];
}

// GET /diets/{dietId} — 식단 단건 조회.
export async function getDiet(dietId: number): Promise<Diet> {
const response = await instance.get<Diet>(`/diets/${dietId}`, { requiresAuth: true });
return response.data;
return withNormalizedDate(response.data);
}

// POST /diets — 식단 작성. Returns 204 (or 201 on the AI-callback path); refetch after.
Expand All @@ -33,7 +46,7 @@ export async function updateDiet(dietId: number, payload: UpdateDietRequest): Pr
const response = await instance.patch<Diet>(`/diets/${dietId}`, payload, {
requiresAuth: true,
});
return response.data;
return withNormalizedDate(response.data);
}

// DELETE /diets/{dietId} — 식단 삭제. Returns 204.
Expand Down
9 changes: 2 additions & 7 deletions src/entities/price/api/price.api.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { FALLBACK_PRICE_SNAPSHOT } from "../lib/fallback-snapshot";
import { getSubstitutes } from "../lib/substitutes";
import { computeChangeRatePercent, isSpiking } from "../lib/spike";
import type { PriceListResponse, PriceQuote, PriceQuoteRaw, PriceSource } from "../model/types";

Expand All @@ -9,7 +7,6 @@ function enrich(raw: PriceQuoteRaw, source: PriceSource): PriceQuote {
...raw,
changeRatePercent,
isSpiking: isSpiking(changeRatePercent),
substituteItems: getSubstitutes(raw.itemName),
source,
};
}
Expand All @@ -24,9 +21,7 @@ export async function getPricesApi(): Promise<{ items: PriceQuote[]; source: Pri
const data = (await response.json()) as PriceListResponse;
return { items: data.items.map((item) => enrich(item, data.source)), source: data.source };
} catch {
return {
items: FALLBACK_PRICE_SNAPSHOT.map((item) => enrich(item, "fallback")),
source: "fallback",
};
// 서버 응답을 받지 못하면 빈 목록을 반환한다 — 대체 데이터는 만들지 않는다.
return { items: [], source: "unavailable" };
}
}
5 changes: 1 addition & 4 deletions src/entities/price/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
export type { PriceQuote, PriceQuoteRaw, PriceSource, PriceListResponse } from "./model/types";
export { usePriceStore } from "./model/price.store";
export { getPricesApi } from "./api/price.api";
export { FALLBACK_PRICE_SNAPSHOT } from "./lib/fallback-snapshot";
export { SUBSTITUTE_MAP, getSubstitutes } from "./lib/substitutes";
export { SPIKE_THRESHOLD_PERCENT, computeChangeRatePercent, isSpiking } from "./lib/spike";
export { computeSubstitutionSavings, totalSubstitutionSavings } from "./lib/savings";
export type { CostLine, SubstitutionSaving } from "./lib/savings";
export { priceSourceLabel } from "./lib/source-label";
15 changes: 0 additions & 15 deletions src/entities/price/lib/fallback-snapshot.ts

This file was deleted.

52 changes: 0 additions & 52 deletions src/entities/price/lib/savings.ts

This file was deleted.

16 changes: 16 additions & 0 deletions src/entities/price/lib/source-label.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import type { PriceSource } from "../model/types";

// 하드코딩된 대체 가격은 없다 — 서버가 실제로 응답한 품목만 존재하므로, 가격 기반
// 수치를 보여줄 땐 몇 개 품목이 실시간으로 조회됐는지 항상 함께 표시한다.
export function priceSourceLabel(source: PriceSource | null): string {
switch (source) {
case "kamis":
return "KAMIS 실시간 시세 기준";
case "partial":
return "일부 품목만 KAMIS 실시간 시세 조회됨";
case "unavailable":
return "실시간 시세 미연동 (가격 데이터 없음)";
default:
return "가격 데이터 연동 대기";
}
}
10 changes: 0 additions & 10 deletions src/entities/price/lib/substitutes.ts

This file was deleted.

10 changes: 6 additions & 4 deletions src/entities/price/model/types.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
// KAMIS(농산물유통정보) 실시간 가격 — 키 없거나 API 장애 시 폴백 스냅샷으로 대체된다.
export type PriceSource = "kamis" | "fallback" | "mixed";
// KAMIS(농산물유통정보) 실시간 가격 — 인증키 미설정/전체 조회 실패 시 items가 빈 배열로 온다.
// 하드코딩된 대체 가격은 없음: 서버가 실제로 응답한 값만 내려준다.
export type PriceSource = "kamis" | "partial" | "unavailable";

// /api/kamis/prices가 반환하는 원본 가격 행 (증감률·급등여부는 클라이언트에서 파생).
export interface PriceQuoteRaw {
itemName: string;
unit: string;
price: number; // 현재 kg당 단가
baselinePrice: number; // 직전 기준 단가 (전주/전월 등)
// 직전 기준 단가. KAMIS 기간별 조회를 아직 붙이지 않아 실제 이력 비교값이 없으므로
// 항상 price와 동일하게 채워 "변동 없음"으로 표시한다 — 가짜 증감률을 만들지 않기 위함.
baselinePrice: number;
}

export interface PriceQuote extends PriceQuoteRaw {
changeRatePercent: number; // (price - baselinePrice) / baselinePrice * 100
isSpiking: boolean;
substituteItems: string[];
source: PriceSource;
}

Expand Down
23 changes: 21 additions & 2 deletions src/features/ai-meal-generator/model/generator.store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ export const useGeneratorStore = create<GeneratorState>((set, get) => ({
if (seq === generationSeq) set({ status: "done", result });
};

// Snapshot the month's diet count so the summary reports only what the
// job newly created — pre-existing (e.g. manual) diets must not count.
const beforeCount = await countDietsInMonth(month).catch(() => 0);

try {
// POST returns the job id right away; poll until the job settles.
const job = await generateAiMealPlanApi({ month });
Expand All @@ -87,7 +91,17 @@ export const useGeneratorStore = create<GeneratorState>((set, get) => ({

const { status } = await getAiGenerationApi(job.id);
if (status === "SUCCEEDED") {
finish({ month, totalMeals: await countDietsInMonth(month) });
const created = Math.max(0, (await countDietsInMonth(month)) - beforeCount);
if (created === 0) {
finish({
month,
totalMeals: 0,
error:
"생성 작업은 완료됐지만 새로 저장된 식단이 없어요. 서버(백엔드) 생성 작업 확인이 필요해요.",
});
return;
}
finish({ month, totalMeals: created });
return;
}
if (status === "FAILED") {
Expand All @@ -107,7 +121,12 @@ export const useGeneratorStore = create<GeneratorState>((set, get) => ({
if (errorStatus(err) === 409) {
const totalMeals = await countDietsInMonth(month).catch(() => 0);
if (totalMeals > 0) {
finish({ month, totalMeals });
finish({
month,
totalMeals,
notice:
"이번 달 식단은 이미 생성되어 있어요. 아래 요약은 이전에 생성된 식단 기준이에요. '식단 관리'에서 확인·수정할 수 있어요.",
});
return;
}
finish({
Expand Down
5 changes: 4 additions & 1 deletion src/features/ai-meal-generator/model/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,14 @@ export interface AiGenerationResponse {
}

// Summary assembled on the client once polling finishes: month comes from the
// request conditions, totalMeals from counting /diets entries in that month.
// request conditions, totalMeals from diffing the /diets count in that month
// before and after the job (409 path: the pre-existing count instead).
export interface GeneratorResult {
month: string;
totalMeals: number;
validationErrors?: unknown[];
budgetInfo?: Record<string, unknown>;
error?: string;
// Non-error context shown with the summary (e.g. "이미 생성된 월" 안내).
notice?: string;
}
13 changes: 7 additions & 6 deletions src/features/ai-meal-generator/ui/ActionBar.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"use client";

import { CheckIcon, RotateCcwIcon } from "@/shared/ui";
import Link from "next/link";
import { CalendarIcon, RotateCcwIcon } from "@/shared/ui";
import { useGeneratorStore } from "../model/generator.store";

export function ActionBar() {
Expand All @@ -18,13 +19,13 @@ export function ActionBar() {
<RotateCcwIcon size={14} />
다시 생성
</button>
<button
type="button"
<Link
href="/meal"
className="inline-flex items-center gap-1.5 rounded-lg bg-blue-600 px-3 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-blue-700 active:bg-blue-800"
>
<CheckIcon size={14} />
식단표에 적용
</button>
<CalendarIcon size={14} />
식단 관리에서 확인
</Link>
</div>
);
}
10 changes: 1 addition & 9 deletions src/features/order-plan-calc/lib/use-order-plan-items.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
daysUntilExpiry,
EXPIRY_SOON_DAYS,
} from "@/entities/ingredient";
import { usePriceStore, getSubstitutes, type PriceSource } from "@/entities/price";
import { usePriceStore, type PriceSource } from "@/entities/price";
import {
computeOrderPlanItems,
useOrderPlanCalcStore,
Expand Down Expand Up @@ -66,14 +66,6 @@ export function useOrderPlanItems(recipesOverride?: RecipeIngredient[]): UseOrde

if (isInSeason(recipe.ingredientName, month)) return `${month}월 제철`;

const quote = priceItems.find((q) => q.itemName === recipe.ingredientName);
if (quote?.isSpiking) {
const substitutes = getSubstitutes(recipe.ingredientName);
return substitutes.length > 0
? `KAMIS 가격 급등 — ${substitutes.join("·")} 대체 검토`
: "KAMIS 가격 급등";
}

return orderQuantity === 0 ? "재고 충분" : "발주 필요";
};

Expand Down
8 changes: 2 additions & 6 deletions src/features/order-plan-calc/ui/OrderPlanCalcTable.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"use client";

import { useOrderPlanCalcStore } from "@/entities/order-plan";
import { priceSourceLabel } from "@/entities/price";
import { FormulaHint } from "@/shared/ui";
import { useOrderPlanItems } from "../lib/use-order-plan-items";

Expand Down Expand Up @@ -46,12 +47,7 @@ export function OrderPlanCalcTable() {

{priceSource && (
<span className="ml-auto text-xs text-zinc-400">
단가 출처:{" "}
{priceSource === "kamis"
? "KAMIS 실시간"
: priceSource === "mixed"
? "KAMIS + 캐시"
: "캐시 스냅샷"}
단가 출처: {priceSourceLabel(priceSource)}
</span>
)}
</div>
Expand Down
Loading
Loading