[feat] negodata: 협력사↔상품 매핑(취급상품·공급유형) + 견적 픽리스트 서버검색 콤보박스
- partner.supplier_items 매핑테이블 신설: supply_type(0없음/1유통/2제조/3총판), 부분 유니크 인덱스(soft-delete 인지). quotations.supplier_type와 의미단위 달라 컬럼명 supply_type. - 백엔드: supplier_item CRUD/service/router(/v1/supplier-item, by-supplier·by-item·create·bulk·update·delete). 소유권 company 스코프. ErrorType.SUPPLIER_ITEM_NOT_FOUND 추가. - DDL: 01-schema/04-alter(날짜접미 리네임) + dev DB 반영. - 프론트(feature): 협력사 엑셀 '취급상품' 컬럼(콤마 상품명→일괄매핑, 이름 미매칭 스킵+리포트, 유형 안받고 없음), 협력사 상세 취급상품 관리(추가/삭제/유형변경 즉시반영), 견적모달 협력사 리스트에 선택상품 공급유형 배지. - 재사용 서버검색 Combobox 신설 → 취급상품·견적상품·협력사초청·협상카드 픽리스트에 적용(size 100 캡 해소, 검색은 서버 ILIKE). 견적 선택상품 파생값은 useGetItem 단건조회로 안정화. - orval 재생성(supplier-item 클라이언트/모델). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
ed175c5b65
commit
43dbcbcd96
37 files changed
+1871
-91
No files matched your search
@@ -18,17 +18,26 @@ type RawRow = {
|
||||
managerName: string;
|
||||
managerEmail: string;
|
||||
totalRevenue: string;
|
||||
products: string; // 취급상품 — 상품명 콤마(,) 나열. 업로드 시 매핑테이블로 들어간다.
|
||||
};
|
||||
|
||||
type ValidatedRow = RawRow & { status: '정상' | '오류'; message: string };
|
||||
|
||||
// 업로드 양식 한 줄(예시 행)
|
||||
type TemplateRow = { name: string; code: string; managerName: string; managerEmail: string; totalRevenue: string };
|
||||
type TemplateRow = { name: string; code: string; managerName: string; managerEmail: string; totalRevenue: string; products: string };
|
||||
|
||||
// 협력사 1건 + 그 협력사에 매핑할 취급상품명 리스트.
|
||||
export type PartnerUploadRow = { supplier: SupplierCreate; products: string[] };
|
||||
// 일괄 등록 결과 — 협력사 등록 실패(행별) + 이름 미매칭으로 건너뛴 취급상품명들.
|
||||
export type PartnerBulkResult = { failures: BulkFailure[]; unmatchedProducts: string[] };
|
||||
|
||||
// "상품A, 상품B" → ['상품A','상품B'] (공백/빈값 제거).
|
||||
const splitNames = (s: string): string[] => s.split(',').map((t) => t.trim()).filter(Boolean);
|
||||
|
||||
type ExcelUploadModalProps = {
|
||||
open: boolean;
|
||||
partners: Partner[]; // 코드 중복 검사용
|
||||
onConfirm: (rows: SupplierCreate[]) => Promise<BulkFailure[]>;
|
||||
onConfirm: (rows: PartnerUploadRow[]) => Promise<PartnerBulkResult>;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
@@ -82,8 +91,9 @@ export function downloadPartnerTemplate() {
|
||||
{ header: '담당자명', value: (r) => r.managerName },
|
||||
{ header: '담당자이메일', value: (r) => r.managerEmail },
|
||||
{ header: '총매출액', value: (r) => r.totalRevenue },
|
||||
{ header: '취급상품', value: (r) => r.products },
|
||||
],
|
||||
[{ name: '예시) (주)한빛정밀', code: 'PART-EXAMPLE-001', managerName: '김철수 과장', managerEmail: 'cs.kim@example.com', totalRevenue: '5000000000' }],
|
||||
[{ name: '예시) (주)한빛정밀', code: 'PART-EXAMPLE-001', managerName: '김철수 과장', managerEmail: 'cs.kim@example.com', totalRevenue: '5000000000', products: '고압 에어 컴프레서, 스테인리스 볼밸브' }],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -124,6 +134,7 @@ export function ExcelUploadModal({ open, partners, onConfirm, onClose }: ExcelUp
|
||||
managerName: r['담당자명'] ?? '',
|
||||
managerEmail: r['담당자이메일'] ?? '',
|
||||
totalRevenue: r['총매출액'] ?? '',
|
||||
products: r['취급상품'] ?? '',
|
||||
}));
|
||||
setExcelFile(file.name);
|
||||
setRows(loaded);
|
||||
@@ -147,7 +158,7 @@ export function ExcelUploadModal({ open, partners, onConfirm, onClose }: ExcelUp
|
||||
};
|
||||
|
||||
// 인라인 편집 — 원본 필드만 갱신(재검증은 파생이 처리)
|
||||
const handleUpdateField = (id: string, field: 'name' | 'code' | 'managerName' | 'managerEmail', value: string) => {
|
||||
const handleUpdateField = (id: string, field: 'name' | 'code' | 'managerName' | 'managerEmail' | 'products', value: string) => {
|
||||
setRows((cur) => cur.map((row) => (row.id === id ? { ...row, [field]: value } : row)));
|
||||
};
|
||||
|
||||
@@ -162,10 +173,16 @@ export function ExcelUploadModal({ open, partners, onConfirm, onClose }: ExcelUp
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const failures = await onConfirm(validRows.map(toSupplierCreate));
|
||||
const { failures, unmatchedProducts } = await onConfirm(
|
||||
validRows.map((r) => ({ supplier: toSupplierCreate(r), products: splitNames(r.products) })),
|
||||
);
|
||||
const okCount = validRows.length - failures.length;
|
||||
// 이름이 회사 상품목록에 없어 매핑 못한 취급상품 — 스킵하고 결과에 부기(결정: 미매칭은 스킵+리포트).
|
||||
const unmatchedNote = unmatchedProducts.length
|
||||
? ` · 미매칭 취급상품 ${unmatchedProducts.length}건 건너뜀(${unmatchedProducts.slice(0, 5).join(', ')}${unmatchedProducts.length > 5 ? '…' : ''})`
|
||||
: '';
|
||||
if (failures.length === 0) {
|
||||
showToast(`총 ${okCount}개 협력사가 서버에 일괄 등록되었습니다.`, 'success');
|
||||
showToast(`총 ${okCount}개 협력사가 서버에 일괄 등록되었습니다.${unmatchedNote}`, unmatchedProducts.length ? 'info' : 'success');
|
||||
close();
|
||||
return;
|
||||
}
|
||||
@@ -175,7 +192,7 @@ export function ExcelUploadModal({ open, partners, onConfirm, onClose }: ExcelUp
|
||||
const okCodes = new Set(validRows.map((r) => r.code).filter((c) => failMap[c] === undefined));
|
||||
setServerErrors(failMap);
|
||||
setRows((cur) => cur.filter((r) => !okCodes.has(r.code)));
|
||||
showToast(`${okCount}건 등록 완료 · ${failures.length}건 서버 검증 실패(중복코드 등)`, 'error');
|
||||
showToast(`${okCount}건 등록 완료 · ${failures.length}건 서버 검증 실패(중복코드 등)${unmatchedNote}`, 'error');
|
||||
} catch (err) {
|
||||
showToast(err instanceof Error ? err.message : '엑셀 일괄 등록 실패', 'error');
|
||||
}
|
||||
@@ -271,6 +288,7 @@ export function ExcelUploadModal({ open, partners, onConfirm, onClose }: ExcelUp
|
||||
<TableHead className="p-2 font-semibold">협력사코드 *</TableHead>
|
||||
<TableHead className="p-2 font-semibold">담당자명 *</TableHead>
|
||||
<TableHead className="p-2 font-semibold">담당자 이메일 *</TableHead>
|
||||
<TableHead className="p-2 font-semibold">취급상품 (,로 구분)</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody className="divide-y divide-border">
|
||||
@@ -331,6 +349,15 @@ export function ExcelUploadModal({ open, partners, onConfirm, onClose }: ExcelUp
|
||||
onChange={(e) => handleUpdateField(row.id, 'managerEmail', e.target.value)}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="p-2">
|
||||
<Input
|
||||
type="text"
|
||||
className="bg-muted/20 hover:bg-muted/50 text-foreground"
|
||||
value={row.products}
|
||||
onChange={(e) => handleUpdateField(row.id, 'products', e.target.value)}
|
||||
placeholder="상품명, 상품명"
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
|
||||
@@ -9,6 +9,7 @@ import { Typography } from '@/components/ui/typography';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Sheet } from '@/components/ui/sheet';
|
||||
import { SupplierItemsManager } from './SupplierItemsManager';
|
||||
import { type Partner } from '../types';
|
||||
|
||||
const schema = z.object({
|
||||
@@ -189,6 +190,9 @@ export function PartnerFormSheet({
|
||||
{errors.managerPhone && <p className="text-[10px] text-rose-500">{errors.managerPhone.message}</p>}
|
||||
</div>
|
||||
|
||||
{/* 취급상품 관리 — 수정 모드(협력사 확정)에서만. 추가/삭제/유형변경은 즉시 서버 반영. */}
|
||||
{mode === 'edit' && partner && <SupplierItemsManager supplierId={partner.supplier_id} />}
|
||||
|
||||
{/* Buttons wrapper */}
|
||||
<div className="pt-4 flex items-center gap-2 border-t border-border mt-8 justify-between">
|
||||
{mode === 'edit' && partner && (
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import { useState } from 'react';
|
||||
import { Plus, Trash2 } from 'lucide-react';
|
||||
import { useListItems } from '@/api/generated/item/item';
|
||||
import { SupplierType } from '@/api/generated/model';
|
||||
import { Typography } from '@/components/ui/typography';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Combobox, type ComboOption } from '@/components/ui/combobox';
|
||||
import { SUPPLIER_TYPE_OPTIONS, supplierTypeLabel } from '@/lib/enumLabels';
|
||||
import { showToast } from '@/lib/notify';
|
||||
import { useSupplierItems } from '../hooks/useSupplierItems';
|
||||
|
||||
// 협력사 상세의 취급상품 관리 섹션 — 상품 추가/삭제 + 공급유형(제조/유통/총판/없음) 수정.
|
||||
// 각 조작은 즉시 서버 반영(협력사 기본정보 저장과 독립).
|
||||
export function SupplierItemsManager({ supplierId }: { supplierId: string }) {
|
||||
const { items, isLoading, addItem, changeType, removeItem } = useSupplierItems(supplierId);
|
||||
const [q, setQ] = useState('');
|
||||
const catalogQuery = useListItems({ search: q || undefined, size: 30 }); // 서버검색(상품 100개 이상도 검색으로 도달)
|
||||
|
||||
const [pickItemId, setPickItemId] = useState('');
|
||||
const [pickLabel, setPickLabel] = useState('');
|
||||
const [pickType, setPickType] = useState(String(SupplierType.NONE)); // 기본 없음(0)
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const mappedIds = new Set(items.map((m) => m.item_id));
|
||||
const options: ComboOption[] = (catalogQuery.data?.items ?? [])
|
||||
.filter((it) => !mappedIds.has(it.item_id))
|
||||
.map((it) => ({ id: it.item_id, label: `${it.name}${it.code ? ` [${it.code}]` : ''}` }));
|
||||
|
||||
const handleAdd = async () => {
|
||||
if (!pickItemId) {
|
||||
showToast('추가할 상품을 선택하세요.', 'error');
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
await addItem(pickItemId, Number(pickType));
|
||||
setPickItemId('');
|
||||
setPickLabel('');
|
||||
setQ('');
|
||||
showToast('취급상품이 추가되었습니다.', 'success');
|
||||
} catch (err) {
|
||||
showToast(err instanceof Error ? err.message : '취급상품 추가 실패', 'error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleChangeType = async (supplierItemId: string, v: string) => {
|
||||
try {
|
||||
await changeType(supplierItemId, Number(v));
|
||||
} catch {
|
||||
showToast('공급유형 변경에 실패했습니다.', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemove = async (supplierItemId: string) => {
|
||||
try {
|
||||
await removeItem(supplierItemId);
|
||||
showToast('취급상품이 삭제되었습니다.', 'info');
|
||||
} catch {
|
||||
showToast('취급상품 삭제에 실패했습니다.', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="pt-4 border-t border-border space-y-2">
|
||||
<Typography as="label" variant="label">취급상품 ({items.length})</Typography>
|
||||
|
||||
{/* 추가 행 — 상품 + 공급유형 선택 후 추가 */}
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex-1 min-w-0">
|
||||
<Combobox
|
||||
id="supplier-item-pick"
|
||||
options={options}
|
||||
loading={catalogQuery.isLoading}
|
||||
onQueryChange={setQ}
|
||||
value={pickItemId || undefined}
|
||||
selectedLabel={pickLabel}
|
||||
onSelect={(opt) => { setPickItemId(opt.id); setPickLabel(opt.label); }}
|
||||
placeholder="취급상품으로 추가할 상품 검색..."
|
||||
searchPlaceholder="상품명·코드로 검색..."
|
||||
emptyText="일치하는 상품이 없습니다"
|
||||
/>
|
||||
</div>
|
||||
<div className="w-24 shrink-0">
|
||||
<Select value={pickType} onValueChange={(v) => setPickType(v ?? String(SupplierType.NONE))}>
|
||||
<SelectTrigger id="supplier-item-pick-type" className="w-full">
|
||||
<SelectValue>{(value) => supplierTypeLabel(Number(value))}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{SUPPLIER_TYPE_OPTIONS.map((o) => (
|
||||
<SelectItem key={o.value} value={String(o.value)}>{o.label}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Button type="button" size="sm" onClick={handleAdd} disabled={busy || !pickItemId}>
|
||||
<Plus />
|
||||
추가
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 현재 취급상품 목록 */}
|
||||
<div className="border border-border rounded divide-y divide-border max-h-48 overflow-y-auto">
|
||||
{isLoading ? (
|
||||
<Typography as="p" variant="small" className="p-3 text-muted-foreground text-[11px]">불러오는 중…</Typography>
|
||||
) : items.length === 0 ? (
|
||||
<Typography as="p" variant="small" className="p-3 text-muted-foreground text-[11px]">등록된 취급상품이 없습니다.</Typography>
|
||||
) : (
|
||||
items.map((m) => (
|
||||
<div key={m.supplier_item_id} className="flex items-center justify-between gap-2 p-2">
|
||||
<div className="min-w-0">
|
||||
<Typography as="span" variant="small" className="font-semibold block truncate">{m.item_name}</Typography>
|
||||
{m.item_code && (
|
||||
<Typography as="span" variant="small" className="text-muted-foreground text-[10px]">{m.item_code}</Typography>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5 shrink-0">
|
||||
<div className="w-24">
|
||||
<Select value={String(m.supply_type)} onValueChange={(v) => handleChangeType(m.supplier_item_id, v ?? String(SupplierType.NONE))}>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue>{(value) => supplierTypeLabel(Number(value))}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{SUPPLIER_TYPE_OPTIONS.map((o) => (
|
||||
<SelectItem key={o.value} value={String(o.value)}>{o.label}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleRemove(m.supplier_item_id)}
|
||||
title="취급상품 삭제"
|
||||
className="p-1 rounded text-muted-foreground hover:text-rose-600 hover:bg-rose-500/10 cursor-pointer"
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -5,12 +5,14 @@ import {
|
||||
updateSupplier,
|
||||
deleteSupplier,
|
||||
} from '@/api/generated/supplier/supplier';
|
||||
import { bulkMapSupplierItems } from '@/api/generated/supplier-item/supplier-item';
|
||||
import type { ListSuppliersParams } from '@/api/generated/model/listSuppliersParams';
|
||||
import type { ReqCreateSupplier } from '@/api/generated/model/reqCreateSupplier';
|
||||
import type { ReqUpdateSupplier } from '@/api/generated/model/reqUpdateSupplier';
|
||||
import type { ResSupplier } from '@/api/generated/model/resSupplier';
|
||||
import type { SupplierData } from '@/api/generated/model/supplierData';
|
||||
import type { BulkFailure } from '@/lib/excel';
|
||||
import type { PartnerUploadRow, PartnerBulkResult } from '../components/ExcelUploadModal';
|
||||
import type { Partner } from '../types';
|
||||
|
||||
// 엑셀 중복검사 모달이 참조하는 "전체 협력사"용 메타 쿼리(최대 100건).
|
||||
@@ -54,18 +56,33 @@ export function usePartners(params: ListSuppliersParams) {
|
||||
};
|
||||
// 엑셀 일괄 등록 — 행별로 순차 생성하되 실패해도 멈추지 않고 사유를 모은다.
|
||||
// 서버 DB 검증(중복코드 등)에 걸린 행은 BulkFailure 로 반환 → 모달이 해당 행만 사유와 함께 남긴다.
|
||||
const bulkCreate = async (rows: ReqCreateSupplier[]): Promise<BulkFailure[]> => {
|
||||
// 등록 성공 시 취급상품(상품명 리스트)을 매핑테이블로 밀어넣는다. 이름 미매칭분은 서버가 스킵하고 돌려줘 리포트한다.
|
||||
const bulkCreate = async (rows: PartnerUploadRow[]): Promise<PartnerBulkResult> => {
|
||||
const failures: BulkFailure[] = [];
|
||||
for (const row of rows) {
|
||||
const unmatched = new Set<string>();
|
||||
for (const { supplier, products } of rows) {
|
||||
try {
|
||||
const msg = supplierError(await createSupplier(row));
|
||||
if (msg) failures.push({ code: row.code ?? '', message: msg });
|
||||
const res = await createSupplier(supplier);
|
||||
const msg = supplierError(res);
|
||||
if (msg) {
|
||||
failures.push({ code: supplier.code ?? '', message: msg });
|
||||
continue;
|
||||
}
|
||||
const newId = res.supplier?.supplier_id;
|
||||
if (newId && products.length) {
|
||||
try {
|
||||
const mapRes = await bulkMapSupplierItems(newId, { names: products });
|
||||
(mapRes.unmatched ?? []).forEach((n) => unmatched.add(n));
|
||||
} catch {
|
||||
// 취급상품 매핑 실패는 협력사 등록 자체를 되돌리지 않는다(등록은 성공 처리).
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
failures.push({ code: row.code ?? '', message: err instanceof Error ? err.message : '등록 실패' });
|
||||
failures.push({ code: supplier.code ?? '', message: err instanceof Error ? err.message : '등록 실패' });
|
||||
}
|
||||
}
|
||||
await refresh();
|
||||
return failures;
|
||||
return { failures, unmatchedProducts: [...unmatched] };
|
||||
};
|
||||
|
||||
// 테이블(현재 페이지) 협력사 + 서버 전체 건수.
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
useListSupplierItems,
|
||||
createSupplierItem,
|
||||
updateSupplyType,
|
||||
deleteSupplierItem,
|
||||
getListSupplierItemsQueryKey,
|
||||
} from '@/api/generated/supplier-item/supplier-item';
|
||||
import type { SupplierItemData } from '@/api/generated/model/supplierItemData';
|
||||
|
||||
// 협력사 취급상품(매핑) 서버 데이터 + CRUD. 협력사 상세(PartnerFormSheet)에서 쓴다.
|
||||
// supplierId 가 없으면(신규 등록 폼) 쿼리는 비활성.
|
||||
export function useSupplierItems(supplierId: string | undefined) {
|
||||
const queryClient = useQueryClient();
|
||||
const listQuery = useListSupplierItems(supplierId ?? '', { query: { enabled: !!supplierId } });
|
||||
|
||||
const refresh = () =>
|
||||
supplierId
|
||||
? queryClient.invalidateQueries({ queryKey: getListSupplierItemsQueryKey(supplierId) })
|
||||
: Promise.resolve();
|
||||
|
||||
const items: SupplierItemData[] = listQuery.data?.supplier_items ?? [];
|
||||
|
||||
const addItem = async (itemId: string, supplyType: number) => {
|
||||
if (!supplierId) return;
|
||||
const res = await createSupplierItem({ supplier_id: supplierId, item_id: itemId, supply_type: supplyType });
|
||||
const r = res.result;
|
||||
if (r && r.success === false) {
|
||||
throw new Error(r.desc === 'DB_ALREADY_SAME_KEY' ? '이미 등록된 취급상품입니다.' : r.desc || '취급상품 추가 실패');
|
||||
}
|
||||
await refresh();
|
||||
};
|
||||
|
||||
const changeType = async (supplierItemId: string, supplyType: number) => {
|
||||
await updateSupplyType(supplierItemId, { supply_type: supplyType });
|
||||
await refresh();
|
||||
};
|
||||
|
||||
const removeItem = async (supplierItemId: string) => {
|
||||
await deleteSupplierItem(supplierItemId);
|
||||
await refresh();
|
||||
};
|
||||
|
||||
return { items, isLoading: listQuery.isLoading, addItem, changeType, removeItem };
|
||||
}
|
||||
@@ -1,12 +1,18 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import { X, PlusSquare, ArrowRight, Loader2, Gavel } from 'lucide-react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { useGetSupplierLastType } from '@/api/generated/quotation/quotation';
|
||||
import { useListItemSupplyTypes } from '@/api/generated/supplier-item/supplier-item';
|
||||
import { useListItems, useGetItem } from '@/api/generated/item/item';
|
||||
import { useListSuppliers } from '@/api/generated/supplier/supplier';
|
||||
import { useListCards } from '@/api/generated/card/card';
|
||||
import { mapCardData } from '@/features/cards/types';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Typography, typographyVariants } from '@/components/ui/typography';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Combobox, type ComboOption } from '@/components/ui/combobox';
|
||||
import type { Product, Partner, QuotationSetting, NegotiationCard } from '../types';
|
||||
import type { CreateQuotationInput } from '../hooks/useQuotations';
|
||||
import { QuotationType } from '@/api/generated/model';
|
||||
@@ -88,11 +94,71 @@ export function QuotationCreateModal({
|
||||
}, [renegoSupplierId, prevSupplierType]);
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
// ── 픽리스트 서버검색(상품/협력사/카드) — size 캡 없이 검색으로 도달. 미검색이면 부모가 넘긴 목록으로 기본 노출.
|
||||
const [productQ, setProductQ] = useState('');
|
||||
const [productLabel, setProductLabel] = useState('');
|
||||
const [supplierQ, setSupplierQ] = useState('');
|
||||
const [cardQ, setCardQ] = useState('');
|
||||
const productSearch = useListItems({ search: productQ || undefined, size: 30 });
|
||||
const supplierSearch = useListSuppliers({ search: supplierQ || undefined, size: 30 });
|
||||
const cardSearch = useListCards({ search: cardQ || undefined, size: 30 });
|
||||
|
||||
// 선택 상품은 검색으로 목록이 좁혀져도 파생값(목표가 후보)이 안 깨지게 id로 단건 조회한다.
|
||||
const selItem = useGetItem(productId, { query: { enabled: !!productId } }).data?.item ?? null;
|
||||
// 인터넷최저가·매입가·판매가는 상품 속성 — 모달에선 읽기전용으로만 보여주고, 수정은 상품 상세에서 한다.
|
||||
const selectedProduct = products.find((p) => p.id === productId);
|
||||
const internetLowest = selectedProduct?.internet_lowest_price ?? null;
|
||||
const purchase = selectedProduct?.purchase_price ?? null;
|
||||
const selling = selectedProduct?.selling_price ?? null;
|
||||
const internetLowest = selItem?.internet_lowest_price ?? null;
|
||||
const purchase = selItem?.purchase_price ?? null;
|
||||
const selling = selItem?.selling_price ?? null;
|
||||
|
||||
// 선택 상품의 협력사별 공급유형(제조/유통/총판/없음) — 협력사 리스트에 배지로 덧붙인다(리스트 자체는 재조회 안 함).
|
||||
const supplyTypeQuery = useListItemSupplyTypes(productId, { query: { enabled: !!productId } });
|
||||
const supplyTypeBySupplier = useMemo(() => {
|
||||
const m = new Map<string, number>();
|
||||
(supplyTypeQuery.data?.suppliers ?? []).forEach((s) => m.set(s.supplier_id, s.supply_type));
|
||||
return m;
|
||||
}, [supplyTypeQuery.data]);
|
||||
|
||||
// 콤보박스 옵션 — 미검색이면 부모 목록, 검색 중이면 서버결과.
|
||||
const productOptions: ComboOption[] = productQ
|
||||
? (productSearch.data?.items ?? []).map((it) => ({ id: it.item_id, label: `${it.name}${it.code ? ` [${it.code}]` : ''}` }))
|
||||
: products.map((p) => ({ id: p.id ?? '', label: `${p.name}${p.code ? ` [${p.code}]` : ''}` }));
|
||||
|
||||
const supplierRows = supplierQ
|
||||
? (supplierSearch.data?.suppliers ?? []).map((sp) => ({ id: sp.supplier_id, name: sp.name, email: sp.manager_email ?? '' }))
|
||||
: partners.map((p) => ({ id: p.id ?? '', name: p.name, email: p.managerEmail ?? '' }));
|
||||
const supplierOptions: ComboOption[] = supplierRows.map((s) => ({
|
||||
id: s.id,
|
||||
label: s.name,
|
||||
node: (
|
||||
<div className="flex items-center justify-between gap-2 w-full">
|
||||
<div className="min-w-0">
|
||||
<Typography as="span" variant="small" className="font-semibold block truncate">{s.name}</Typography>
|
||||
<Typography as="span" variant="small" className="text-muted-foreground">이메일: {s.email}</Typography>
|
||||
</div>
|
||||
{productId && <SupplyTypeBadge type={supplyTypeBySupplier.get(s.id)} />}
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
const cardRows = cardQ ? (cardSearch.data?.cards ?? []).map(mapCardData) : cards;
|
||||
const cardOptions: ComboOption[] = cardRows
|
||||
.filter((c) => !c.isWildcard || c.status === 'ACTIVE')
|
||||
.map((card) => ({
|
||||
id: card.id,
|
||||
label: card.title,
|
||||
node: (
|
||||
<div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Typography as="span" variant="small" className="text-muted-foreground font-mono block leading-none">{card.code}</Typography>
|
||||
<span className={`text-[9px] font-mono px-1.5 py-0.5 rounded leading-none ${card.isWildcard ? 'bg-amber-50 text-amber-700' : 'bg-zinc-100 text-zinc-600'}`}>
|
||||
{card.isWildcard ? '와일드' : '협상'}
|
||||
</span>
|
||||
</div>
|
||||
<Typography as="span" variant="small" className="mt-1 block leading-tight">{card.title}</Typography>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
// 상품에 산정 후보가 있는지(인터넷=공통, 매입·판매=재 한정). 없으면 MD가가 유일한 후보 → 필수가 된다.
|
||||
const mdNum = Number(mdPrice) || 0;
|
||||
const hasItemCandidate = internetLowest != null || (isReType && (purchase != null || selling != null));
|
||||
@@ -247,25 +313,18 @@ export function QuotationCreateModal({
|
||||
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="label">상품</Typography>
|
||||
<Select value={productId} onValueChange={(v) => setProductId(v ?? '')}>
|
||||
<SelectTrigger id="wizard-product" className="w-full">
|
||||
<SelectValue>
|
||||
{(value) => {
|
||||
const p = products.find((pp) => pp.id === value);
|
||||
return p
|
||||
? `${p.name} [${p.code}] (기준가: ₩${(p.price ?? 0).toLocaleString()})`
|
||||
: '협상 대상 상품을 고르세요...';
|
||||
}}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{products.filter((p) => p.status === 'ACTIVE').map((p) => (
|
||||
<SelectItem key={p.id} value={p.id}>
|
||||
{p.name} [{p.code}] (기준가: ₩{(p.price ?? 0).toLocaleString()})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Combobox
|
||||
id="wizard-product"
|
||||
options={productOptions}
|
||||
loading={productSearch.isLoading}
|
||||
onQueryChange={setProductQ}
|
||||
value={productId || undefined}
|
||||
selectedLabel={productLabel}
|
||||
onSelect={(opt) => { setProductId(opt.id); setProductLabel(opt.label); }}
|
||||
placeholder="협상 대상 상품을 고르세요..."
|
||||
searchPlaceholder="상품명·코드로 검색..."
|
||||
emptyText="일치하는 상품이 없습니다"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* MD 제시가 — 입력 시 목표가로 사용. 상품에 다른 후보가 없으면 유일 후보라 필수. */}
|
||||
@@ -328,30 +387,19 @@ export function QuotationCreateModal({
|
||||
{step === 2 && (
|
||||
<div className="space-y-3">
|
||||
<Typography as="span" variant="label" className="block">협력사 초청 ({oneToOne ? '단일선택' : '다중선택'})</Typography>
|
||||
<div className="border border-border rounded overflow-hidden max-h-56 overflow-y-auto divide-y divide-border bg-background">
|
||||
{partners.map((part) => {
|
||||
const isChecked = selectedPartnerIds.includes(part.id ?? '');
|
||||
return (
|
||||
<label
|
||||
key={part.id}
|
||||
className="flex items-center justify-between p-3 hover:bg-muted/30 cursor-pointer transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-2.5">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isChecked}
|
||||
onChange={() => togglePartner(part.id ?? '')}
|
||||
className="accent-primary h-4 w-4"
|
||||
/>
|
||||
<div>
|
||||
<Typography as="span" variant="small" className="font-semibold block">{part.name}</Typography>
|
||||
<Typography as="span" variant="small" className="text-muted-foreground">이메일: {part.managerEmail}</Typography>
|
||||
</div>
|
||||
</div>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{/* 서버검색 다중선택 — 각 행에 선택 상품 취급유형 배지(미매핑=미취급). oneToOne이면 togglePartner가 단일로 강제. */}
|
||||
<Combobox
|
||||
variant="inline"
|
||||
multiple
|
||||
values={selectedPartnerIds}
|
||||
options={supplierOptions}
|
||||
loading={supplierSearch.isLoading}
|
||||
onQueryChange={setSupplierQ}
|
||||
onToggle={(opt) => togglePartner(opt.id)}
|
||||
searchPlaceholder="협력사명·코드·담당자 검색..."
|
||||
emptyText="협력사가 없습니다"
|
||||
maxListHeight="max-h-56"
|
||||
/>
|
||||
|
||||
{/* 협력사 유형 — 항상 노출(처음부터 입력 가능). 재협상(1:1)이면 선택 협력사의 직전 견적 값으로 자동 디폴트. */}
|
||||
<div className="space-y-1 pt-3 border-t border-border/40">
|
||||
@@ -454,35 +502,18 @@ export function QuotationCreateModal({
|
||||
<Typography as="span" variant="small" className="block text-[10px] text-muted-foreground">
|
||||
1:1 협상에서 AI 협상봇이 발동할 카드입니다.
|
||||
</Typography>
|
||||
<div className="grid grid-cols-2 gap-2 max-h-72 overflow-y-auto">
|
||||
{cards.filter((c) => !c.isWildcard || c.status === 'ACTIVE').map((card) => {
|
||||
const isChecked = selectedCardIds.includes(card.id);
|
||||
return (
|
||||
<div
|
||||
key={card.id}
|
||||
onClick={() => toggleCard(card.id)}
|
||||
className={`p-2.5 rounded border cursor-pointer transition-all flex items-start gap-2 ${
|
||||
isChecked ? 'bg-primary/5 border-primary font-bold' : 'bg-background border-border hover:bg-muted/10'
|
||||
}`}
|
||||
>
|
||||
<input type="checkbox" checked={isChecked} readOnly className="accent-primary h-3.5 w-3.5 mt-0.5" />
|
||||
<div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Typography as="span" variant="small" className="text-muted-foreground font-mono block leading-none">{card.code}</Typography>
|
||||
<span
|
||||
className={`text-[9px] font-mono px-1.5 py-0.5 rounded leading-none ${
|
||||
card.isWildcard ? 'bg-amber-50 text-amber-700' : 'bg-zinc-100 text-zinc-600'
|
||||
}`}
|
||||
>
|
||||
{card.isWildcard ? '와일드' : '협상'}
|
||||
</span>
|
||||
</div>
|
||||
<Typography as="span" variant="small" className="mt-1 block leading-tight">{card.title}</Typography>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<Combobox
|
||||
variant="inline"
|
||||
multiple
|
||||
values={selectedCardIds}
|
||||
options={cardOptions}
|
||||
loading={cardSearch.isLoading}
|
||||
onQueryChange={setCardQ}
|
||||
onToggle={(opt) => toggleCard(opt.id)}
|
||||
searchPlaceholder="카드명·번호·스크립트 검색..."
|
||||
emptyText="협상카드가 없습니다"
|
||||
maxListHeight="max-h-72"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -529,6 +560,22 @@ export function QuotationCreateModal({
|
||||
|
||||
// ── 헬퍼 컴포넌트 (메인 아래) ──────────────────────────────────────────────
|
||||
|
||||
// 협력사 취급유형 배지 — type undefined = 이 상품 미취급, 그 외 SupplierType 라벨(제조/유통/총판/없음).
|
||||
function SupplyTypeBadge({ type }: { type?: number }) {
|
||||
if (type === undefined) {
|
||||
return (
|
||||
<Typography as="span" variant="small" className="text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground shrink-0">
|
||||
미취급
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Typography as="span" variant="small" className="text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary font-semibold shrink-0">
|
||||
{supplierTypeLabel(type)}
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
|
||||
// 세그먼트 컨트롤 — 소수의 명명된 이산 선택(진행 방식·대상)에 라디오보다 명확. 값은 문자열.
|
||||
function Segmented({
|
||||
options,
|
||||
|
||||
Reference in new issue
Block a user