feat: 견적 V2 품목 검색 API 연동 및 수동 품목 관리 개선

- ItemSearchModal: API 프록시 라우트 연동, 검색 유효성 검사 (영문/한글 1자 이상)
- items.ts: HttpOnly 쿠키 인증을 위한 프록시 라우트 사용
- LocationDetailPanel: 수동 품목 추가 시 subtotals/grouped_items 동시 업데이트
- QuoteRegistrationV2: 견적 산출 시 수동 추가 품목(is_manual) 보존
- 상세별 합계에서 수동 추가 품목이 카테고리별로 표시되도록 개선
This commit is contained in:
2026-01-27 14:28:17 +09:00
parent 815ed9267e
commit 05fd5b32f2
6 changed files with 389 additions and 105 deletions

View File

@@ -1,14 +1,15 @@
/**
* 품목 검색 모달
*
* - 품목 코드로 검색
* - 품목 코드/이름으로 검색
* - 품목 목록에서 선택
* - API 연동
*/
"use client";
import { useState, useMemo } from "react";
import { Search, X } from "lucide-react";
import { useState, useEffect, useMemo, useCallback } from "react";
import { Search, X, Loader2 } from "lucide-react";
import {
Dialog,
@@ -17,17 +18,8 @@ import {
DialogTitle,
} from "../ui/dialog";
import { Input } from "../ui/input";
// =============================================================================
// 목데이터 - 품목 목록
// =============================================================================
const MOCK_ITEMS = [
{ code: "KSS01", name: "스크린", description: "방화스크린 기본형" },
{ code: "KSS02", name: "스크린", description: "방화스크린 고급형" },
{ code: "KSS03", name: "슬랫", description: "방화슬랫 기본형" },
{ code: "KSS04", name: "스크린", description: "방화스크린 특수형" },
];
import { fetchItems } from "@/lib/api/items";
import type { ItemMaster, ItemType } from "@/types/item";
// =============================================================================
// Props
@@ -36,8 +28,10 @@ const MOCK_ITEMS = [
interface ItemSearchModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onSelectItem: (item: { code: string; name: string }) => void;
onSelectItem: (item: { code: string; name: string; specification?: string }) => void;
tabLabel?: string;
/** 품목 유형 필터 (예: 'RM', 'SF', 'FG') */
itemType?: string;
}
// =============================================================================
@@ -49,42 +43,103 @@ export function ItemSearchModal({
onOpenChange,
onSelectItem,
tabLabel,
itemType,
}: ItemSearchModalProps) {
const [searchQuery, setSearchQuery] = useState("");
const [items, setItems] = useState<ItemMaster[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// 검색 필터링
const filteredItems = useMemo(() => {
if (!searchQuery) return MOCK_ITEMS;
const query = searchQuery.toLowerCase();
return MOCK_ITEMS.filter(
(item) =>
item.code.toLowerCase().includes(query) ||
item.name.toLowerCase().includes(query) ||
item.description.toLowerCase().includes(query)
);
}, [searchQuery]);
// 품목 목록 조회
const loadItems = useCallback(async (search?: string) => {
setIsLoading(true);
setError(null);
try {
const data = await fetchItems({
search: search || undefined,
itemType: itemType as ItemType | undefined,
per_page: 50,
});
setItems(data);
} catch (err) {
console.error("[ItemSearchModal] 품목 조회 오류:", err);
setError("품목 목록을 불러오는데 실패했습니다.");
setItems([]);
} finally {
setIsLoading(false);
}
}, [itemType]);
const handleSelect = (item: (typeof MOCK_ITEMS)[0]) => {
onSelectItem({ code: item.code, name: item.name });
// 검색어 유효성 검사: 영문 1자 이상 또는 한글 1자 이상
const isValidSearchQuery = useCallback((query: string) => {
if (!query) return false;
// 영문 1자 이상 또는 한글 1자 이상
const hasEnglish = /[a-zA-Z]/.test(query);
const hasKorean = /[가-힣ㄱ-ㅎㅏ-ㅣ]/.test(query);
return hasEnglish || hasKorean;
}, []);
// 모달 열릴 때 초기화 (자동 로드 안함)
useEffect(() => {
if (open) {
setItems([]);
setError(null);
}
}, [open]);
// 검색어 변경 시 디바운스 검색 (유효한 검색어만)
useEffect(() => {
if (!open) return;
// 검색어가 유효하지 않으면 결과 초기화
if (!isValidSearchQuery(searchQuery)) {
setItems([]);
return;
}
const timer = setTimeout(() => {
loadItems(searchQuery);
}, 300);
return () => clearTimeout(timer);
}, [searchQuery, open, loadItems, isValidSearchQuery]);
// 검색 결과 그대로 사용 (서버에서 이미 필터링됨)
const filteredItems = items;
const handleSelect = (item: ItemMaster) => {
onSelectItem({
code: item.itemCode,
name: item.itemName,
specification: item.specification || undefined,
});
onOpenChange(false);
setSearchQuery("");
};
const handleClose = () => {
onOpenChange(false);
setSearchQuery("");
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[400px]">
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle> </DialogTitle>
<DialogTitle>
{tabLabel && <span className="text-sm font-normal text-gray-500 ml-2">({tabLabel})</span>}
</DialogTitle>
</DialogHeader>
{/* 검색 입력 */}
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
<Input
placeholder="원하는 검색..."
placeholder="품목코드 또는 품목명 검색..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10"
className="pl-10 pr-10"
/>
{searchQuery && (
<button
@@ -97,31 +152,58 @@ export function ItemSearchModal({
</div>
{/* 품목 목록 */}
<div className="max-h-[300px] overflow-y-auto border rounded-lg divide-y">
{filteredItems.length === 0 ? (
<div className="max-h-[400px] overflow-y-auto border rounded-lg">
{isLoading ? (
<div className="flex items-center justify-center p-8 text-gray-500">
<Loader2 className="h-5 w-5 animate-spin mr-2" />
<span> ...</span>
</div>
) : error ? (
<div className="p-4 text-center text-red-500 text-sm">
{error}
</div>
) : filteredItems.length === 0 ? (
<div className="p-4 text-center text-gray-500 text-sm">
{!searchQuery
? "품목코드 또는 품목명을 입력하세요"
: !isValidSearchQuery(searchQuery)
? "영문 또는 한글 1자 이상 입력하세요"
: "검색 결과가 없습니다"}
</div>
) : (
filteredItems.map((item) => (
<div
key={item.code}
onClick={() => handleSelect(item)}
className="p-3 hover:bg-blue-50 cursor-pointer transition-colors"
>
<div className="flex items-center justify-between">
<div>
<span className="font-semibold text-gray-900">{item.code}</span>
<span className="ml-2 text-sm text-gray-500">{item.name}</span>
<div className="divide-y">
{filteredItems.map((item, index) => (
<div
key={item.id ?? `${item.itemCode}-${index}`}
onClick={() => handleSelect(item)}
className="p-3 hover:bg-blue-50 cursor-pointer transition-colors"
>
<div className="flex items-center justify-between">
<div>
<span className="font-semibold text-gray-900">{item.itemCode}</span>
<span className="ml-2 text-sm text-gray-600">{item.itemName}</span>
</div>
{item.unit && (
<span className="text-xs text-gray-400 bg-gray-100 px-2 py-0.5 rounded">
{item.unit}
</span>
)}
</div>
{item.specification && (
<p className="text-xs text-gray-400 mt-1">{item.specification}</p>
)}
</div>
{item.description && (
<p className="text-xs text-gray-400 mt-1">{item.description}</p>
)}
</div>
))
))}
</div>
)}
</div>
{/* 품목 개수 표시 */}
{!isLoading && !error && (
<div className="text-xs text-gray-400 text-right">
{filteredItems.length}
</div>
)}
</DialogContent>
</Dialog>
);