123213213

This commit is contained in:
DDD1542
2026-04-09 12:35:34 +09:00
parent 4e05ee5e21
commit b982cb8db2
10 changed files with 1666 additions and 570 deletions
@@ -0,0 +1 @@
- generic [ref=e2]: "{\"success\": false, \"error\": \"Invalid endpoint\"}"
@@ -0,0 +1,27 @@
- generic [ref=e3]:
- generic [ref=e5]:
- generic [ref=e6]:
- heading "📦 판매품목 목록" [level=3] [ref=e7]
- generic [ref=e8]:
- text:
- strong [ref=e9]: "0"
- text:
- combobox [ref=e10]:
- option "⚙️ Group by" [selected]
- option "통화"
- option "단위"
- option "상태"
- generic [ref=e11]:
- generic [ref=e12] [cursor=pointer]:
- checkbox "미사용 포함" [ref=e13]
- generic [ref=e14]: 미사용 포함
- button " 품목 추가" [ref=e15]
- button "✏️ 수정" [disabled] [ref=e16]
- button "⏸️ 사용/미사용" [disabled] [ref=e17]
- generic [ref=e20]:
- generic [ref=e21]:
- heading "🏢 거래처별 정보" [level=3] [ref=e22]
- button " 거래처 추가" [disabled] [ref=e23]
- generic [ref=e25]:
- generic [ref=e26]: 📭
- generic [ref=e27]: 왼쪽에서 품목을 선택하세요
@@ -0,0 +1,27 @@
- generic [ref=e3]:
- generic [ref=e5]:
- generic [ref=e6]:
- heading "📦 판매품목 목록" [level=3] [ref=e7]
- generic [ref=e8]:
- text:
- strong [ref=e9]: "0"
- text:
- combobox [ref=e10]:
- option "⚙️ Group by" [selected]
- option "통화"
- option "단위"
- option "상태"
- generic [ref=e11]:
- generic [ref=e12] [cursor=pointer]:
- checkbox "미사용 포함" [ref=e13]
- generic [ref=e14]: 미사용 포함
- button " 품목 추가" [ref=e15]
- button "✏️ 수정" [disabled] [ref=e16]
- button "⏸️ 사용/미사용" [disabled] [ref=e17]
- generic [ref=e20]:
- generic [ref=e21]:
- heading "🏢 거래처별 정보" [level=3] [ref=e22]
- button " 거래처 추가" [disabled] [ref=e23]
- generic [ref=e25]:
- generic [ref=e26]: 📭
- generic [ref=e27]: 왼쪽에서 품목을 선택하세요
@@ -0,0 +1,26 @@
- generic [ref=e3]:
- generic [ref=e5]:
- generic [ref=e6]:
- heading "🏢 거래처 목록" [level=3] [ref=e7]
- generic [ref=e8]:
- text:
- strong [ref=e9]: "0"
- text:
- combobox [ref=e10] [cursor=pointer]:
- option "⚙️ Group by" [selected]
- option "거래 유형"
- option "상태"
- generic [ref=e11]:
- generic [ref=e12] [cursor=pointer]:
- checkbox "미사용 포함" [ref=e13]
- generic [ref=e14]: 미사용 포함
- button " 거래처 등록" [ref=e15]
- button "✏️ 수정" [disabled] [ref=e16]
- button "⏸️ 사용/미사용" [disabled] [ref=e17]
- generic [ref=e20]:
- generic [ref=e21]:
- heading "📦 거래처별 품목 정보" [level=3] [ref=e22]
- button " 품목 추가" [disabled] [ref=e23]
- generic [ref=e25]:
- generic [ref=e26]: 📭
- generic [ref=e27]: 왼쪽에서 거래처를 선택하세요
+26
View File
@@ -0,0 +1,26 @@
- generic [ref=e3]:
- generic [ref=e5]:
- generic [ref=e6]:
- heading "🏢 거래처 목록" [level=3] [ref=e7]
- generic [ref=e8]:
- text: 총
- strong [ref=e9]: "0"
- text: 개
- combobox [ref=e10] [cursor=pointer]:
- option "⚙️ Group by" [selected]
- option "거래 유형"
- option "상태"
- generic [ref=e11]:
- generic [ref=e12] [cursor=pointer]:
- checkbox "미사용 포함" [ref=e13]
- generic [ref=e14]: 미사용 포함
- button " 거래처 등록" [ref=e15]
- button "✏️ 수정" [disabled] [ref=e16]
- button "⏸️ 사용/미사용" [disabled] [ref=e17]
- generic [ref=e20]:
- generic [ref=e21]:
- heading "📦 거래처별 품목 정보" [level=3] [ref=e22]
- button " 품목 추가" [disabled] [ref=e23]
- generic [ref=e25]:
- generic [ref=e26]: 📭
- generic [ref=e27]: 왼쪽에서 거래처를 선택하세요
File diff suppressed because it is too large Load Diff
@@ -808,13 +808,12 @@ export default function CustomerManagementPage() {
};
// 품목 검색
const searchItems = async () => {
const searchItems = useCallback(async () => {
setItemSearchLoading(true);
try {
const filters: any[] = [
{ columnName: "division", operator: "contains", value: "CAT_ML8ZFVEL_1TOR" },
];
if (itemSearchKeyword) filters.push({ columnName: "item_name", operator: "contains", value: itemSearchKeyword });
const res = await apiClient.post(`/table-management/tables/item_info/data`, {
page: 1, size: 500,
dataFilter: { enabled: true, filters },
@@ -823,21 +822,41 @@ export default function CustomerManagementPage() {
const allItems = res.data?.data?.data || res.data?.data?.rows || [];
setItemTotalCount(allItems.length);
const existingItemIds = new Set(priceItems.map((p: any) => p.item_id || p.item_number));
const kw = itemSearchKeyword.toLowerCase();
const seenNumbers = new Set<string>();
const deduped = allItems.filter((item: any) => {
if (existingItemIds.has(item.item_number) || existingItemIds.has(item.id)) return false;
if (item.item_number && seenNumbers.has(item.item_number)) return false;
if (item.item_number) seenNumbers.add(item.item_number);
if (kw) {
const name = (item.item_name || "").toLowerCase();
const code = (item.item_number || "").toLowerCase();
if (!name.includes(kw) && !code.includes(kw)) return false;
}
return true;
});
setItemSearchResults(deduped);
} catch { /* skip */ } finally { setItemSearchLoading(false); }
};
}, [itemSearchKeyword, priceItems]);
// 실시간 검색 (2글자 이상)
useEffect(() => {
if (!itemSelectOpen) return;
if (itemSearchKeyword.length > 0 && itemSearchKeyword.length < 2) return;
searchItems();
}, [itemSearchKeyword, itemSelectOpen]);
// 품목 선택 완료 → 상세 입력 모달로 전환
const goToItemDetail = () => {
const selected = itemSearchResults.filter((i) => itemCheckedIds.has(i.id));
if (selected.length === 0) { toast.error("품목을 선택해주세요."); return; }
const raw = itemSearchResults.filter((i) => itemCheckedIds.has(i.id));
if (raw.length === 0) { toast.error("품목을 선택해주세요."); return; }
const seenKeys = new Set<string>();
const selected = raw.filter((i) => {
const k = i.item_number || i.id;
if (seenKeys.has(k)) return false;
seenKeys.add(k);
return true;
});
setSelectedItemsForDetail(selected);
const mappings: typeof itemMappings = {};
const prices: typeof itemPrices = {};
@@ -1027,8 +1046,11 @@ export default function CustomerManagementPage() {
const isEditingExisting = !!editItemData;
setSaving(true);
try {
const processedKeys = new Set<string>();
for (const item of selectedItemsForDetail) {
const itemKey = item.item_number || item.id;
if (processedKeys.has(itemKey)) continue;
processedKeys.add(itemKey);
const mappingRows = itemMappings[itemKey] || [];
if (isEditingExisting && editItemData?.id) {
@@ -1095,7 +1117,7 @@ export default function CustomerManagementPage() {
// 단가 upsert
const priceRows = (itemPrices[itemKey] || []).filter((p) =>
(p.base_price && Number(p.base_price) > 0) || p.start_date
p.base_price || p.start_date || p.currency_code || p.base_price_type
);
const usedPriceIds = new Set<string>();
for (let pi = 0; pi < priceRows.length; pi++) {
@@ -1165,7 +1187,7 @@ export default function CustomerManagementPage() {
}
const priceRows = (itemPrices[itemKey] || []).filter((p) =>
(p.base_price && Number(p.base_price) > 0) || p.start_date
p.base_price || p.start_date || p.currency_code || p.base_price_type
);
for (const price of priceRows) {
await apiClient.post(`/table-management/tables/${PRICE_TABLE}/add`, {
@@ -1197,40 +1219,63 @@ export default function CustomerManagementPage() {
}
};
// 품목 매핑 삭제
// 품목 매핑 해제 — 선택한 품목의 모든 매핑 + 단가에서 customer_id를 null 처리
const handlePriceItemDelete = async () => {
if (priceCheckedIds.length === 0) return;
const ok = await confirm(`선택한 ${priceCheckedIds.length}개 품목 매핑제하시겠습니까?`, {
description: "관련된 단가 정보도 함께 삭제됩니다.",
variant: "destructive", confirmText: "제",
const ok = await confirm(`선택한 ${priceCheckedIds.length}개 품목의 연결제하시겠습니까?`, {
description: "해당 품목의 거래처 연결이 해제됩니다. (데이터는 유지)",
variant: "destructive", confirmText: "제",
});
if (!ok) return;
try {
for (const mappingId of priceCheckedIds) {
const itemIds = priceCheckedIds.map((mid) => {
const group = Object.values(priceGroups).find((g) => g.master.id === mid);
return group?.master.item_id || group?.master.item_number || "";
}).filter(Boolean);
for (const itemId of itemIds) {
// 해당 품목의 모든 매핑 조회 → customer_id null 처리
const mapRes = await apiClient.post(`/table-management/tables/${MAPPING_TABLE}/data`, {
page: 1, size: 500,
dataFilter: { enabled: true, filters: [
{ columnName: "customer_id", operator: "equals", value: selectedCustomer!.customer_code },
{ columnName: "item_id", operator: "equals", value: itemId },
]}, autoFilter: true,
});
const allMappings = mapRes.data?.data?.data || mapRes.data?.data?.rows || [];
for (const m of allMappings) {
await apiClient.put(`/table-management/tables/${MAPPING_TABLE}/edit`, {
originalData: { id: m.id },
updatedData: { customer_id: null },
});
}
// 해당 품목의 모든 단가 조회 → customer_id null 처리
try {
const priceRes = await apiClient.post(`/table-management/tables/${PRICE_TABLE}/data`, {
page: 1, size: 500,
dataFilter: { enabled: true, filters: [{ columnName: "mapping_id", operator: "equals", value: mappingId }] },
autoFilter: true,
dataFilter: { enabled: true, filters: [
{ columnName: "customer_id", operator: "equals", value: selectedCustomer!.customer_code },
{ columnName: "item_id", operator: "equals", value: itemId },
]}, autoFilter: true,
});
const prices = priceRes.data?.data?.data || priceRes.data?.data?.rows || [];
if (prices.length > 0) {
await apiClient.delete(`/table-management/tables/${PRICE_TABLE}/delete`, {
data: prices.map((p: any) => ({ id: p.id })),
for (const p of prices) {
await apiClient.put(`/table-management/tables/${PRICE_TABLE}/edit`, {
originalData: { id: p.id },
updatedData: { customer_id: null },
});
}
} catch { /* skip */ }
}
await apiClient.delete(`/table-management/tables/${MAPPING_TABLE}/delete`, {
data: priceCheckedIds.map((id) => ({ id })),
});
toast.success(`${priceCheckedIds.length}개 품목 매핑이 삭제되었습니다.`);
toast.success(`${priceCheckedIds.length}개 품목의 연결이 해제되었습니다.`);
setPriceCheckedIds([]);
const cid = selectedCustomerId;
setSelectedCustomerId(null);
setTimeout(() => setSelectedCustomerId(cid), 50);
} catch {
toast.error("제에 실패했습니다.");
toast.error("연결 해제에 실패했습니다.");
}
};
@@ -2386,7 +2431,7 @@ export default function CustomerManagementPage() {
{itemSearchLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <><Search className="w-4 h-4 mr-1" /> </>}
</Button>
</div>
<div className="overflow-auto max-h-[350px] border rounded-lg">
<div className="overflow-auto h-[350px] border rounded-lg">
<Table noWrapper>
<TableHeader className="sticky top-0 z-10">
<TableRow className="bg-muted hover:bg-muted h-10">
@@ -14,27 +14,129 @@ import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from "@/components/ui/dialog";
import { Checkbox } from "@/components/ui/checkbox";
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "@/components/ui/resizable";
import { Plus, Trash2, Save, Loader2, FileSpreadsheet, Download, Pencil, Users, Package, Search, X, Settings2 } from "lucide-react";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { ImageUpload } from "@/components/common/ImageUpload";
import {
Plus, Trash2, Save, Loader2, FileSpreadsheet, Download, Pencil, Users, Package,
Search, X, Settings2, GripVertical, ChevronRight, ChevronDown, Coins,
Check, ChevronsUpDown,
} from "lucide-react";
import {
DndContext, closestCenter, PointerSensor, useSensor, useSensors, DragEndEvent,
} from "@dnd-kit/core";
import { SortableContext, verticalListSortingStrategy, useSortable, arrayMove } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { cn } from "@/lib/utils";
import { apiClient } from "@/lib/api/client";
import { useAuth } from "@/hooks/useAuth";
import { toast } from "sonner";
import { useConfirmDialog } from "@/components/common/ConfirmDialog";
import { ExcelUploadModal } from "@/components/common/ExcelUploadModal";
import { MultiTableExcelUploadModal } from "@/components/common/MultiTableExcelUploadModal";
import { autoDetectMultiTableConfig, TableChainConfig } from "@/lib/api/multiTableExcel";
import { exportToExcel } from "@/lib/utils/excelExport";
import { TableSettingsModal } from "@/components/common/TableSettingsModal";
import { useTableSettings } from "@/hooks/useTableSettings";
import { DynamicSearchFilter, FilterValue } from "@/components/common/DynamicSearchFilter";
import { EDataTable, EDataTableColumn } from "@/components/common/EDataTable";
// 검색 가능한 카테고리 콤보박스
function CategoryCombobox({ options, value, onChange, placeholder }: {
options: { code: string; label: string }[];
value: string;
onChange: (v: string) => void;
placeholder: string;
}) {
const [open, setOpen] = useState(false);
const selected = options.find((o) => o.code === value);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button variant="outline" role="combobox" aria-expanded={open} className="h-9 w-full justify-between font-normal">
<span className="truncate">{selected?.label || <span className="text-muted-foreground">{placeholder}</span>}</span>
<ChevronsUpDown className="ml-2 h-3.5 w-3.5 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="p-0" style={{ width: "var(--radix-popover-trigger-width)" }} align="start">
<Command>
<CommandInput placeholder="검색..." className="h-8" />
<CommandList>
<CommandEmpty> </CommandEmpty>
<CommandGroup className="max-h-[200px] overflow-auto">
{options.map((opt) => (
<CommandItem key={opt.code} value={opt.label} onSelect={() => { onChange(opt.code); setOpen(false); }}>
<Check className={cn("mr-2 h-3.5 w-3.5", value === opt.code ? "opacity-100" : "opacity-0")} />
{opt.label}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}
// 다중 선택 카테고리 콤보박스
function MultiCategoryCombobox({ options, value, onChange, placeholder }: {
options: { code: string; label: string }[];
value: string;
onChange: (v: string) => void;
placeholder: string;
}) {
const [open, setOpen] = useState(false);
const selectedCodes = value ? value.split(",").map((c) => c.trim()).filter(Boolean) : [];
const selectedLabels = selectedCodes.map((code) => options.find((o) => o.code === code)?.label || code).filter(Boolean);
const toggle = (code: string) => {
const next = selectedCodes.includes(code)
? selectedCodes.filter((c) => c !== code)
: [...selectedCodes, code];
onChange(next.join(","));
};
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button variant="outline" role="combobox" aria-expanded={open} className="h-9 w-full justify-between font-normal">
<span className="truncate">
{selectedLabels.length > 0
? selectedLabels.join(", ")
: <span className="text-muted-foreground">{placeholder}</span>}
</span>
<ChevronsUpDown className="ml-2 h-3.5 w-3.5 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="p-0" style={{ width: "var(--radix-popover-trigger-width)" }} align="start">
<Command>
<CommandInput placeholder="검색..." className="h-8" />
<CommandList>
<CommandEmpty> </CommandEmpty>
<CommandGroup className="max-h-[200px] overflow-auto">
{options.map((opt) => (
<CommandItem key={opt.code} value={opt.label} onSelect={() => toggle(opt.code)}>
<Check className={cn("mr-2 h-3.5 w-3.5", selectedCodes.includes(opt.code) ? "opacity-100" : "opacity-0")} />
{opt.label}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}
const ITEM_TABLE = "item_info";
const MAPPING_TABLE = "customer_item_mapping";
const CUSTOMER_TABLE = "customer_mng";
const PRICE_TABLE = "customer_item_prices";
// 숫자 포맷 헬퍼
const formatNum = (val: any): string => {
@@ -54,13 +156,59 @@ const ITEM_GRID_COLUMNS = [
{ key: "status", label: "상태" },
];
const FORM_FIELDS = [
{ key: "item_number", label: "품목코드", type: "text", required: true, disabled: true, placeholder: "자동 채번" },
{ key: "item_name", label: "품명", type: "text", required: true },
{ key: "division", label: "관리품목", type: "multi-category" },
{ key: "type", label: "품목구분", type: "category" },
{ key: "size", label: "규격", type: "text" },
{ key: "unit", label: "단위", type: "category" },
{ key: "material", label: "재질", type: "category" },
{ key: "status", label: "상태", type: "category" },
{ key: "weight", label: "중량", type: "text", placeholder: "숫자 입력 (예: 3.5)" },
{ key: "volum", label: "부피", type: "text", placeholder: "숫자 입력 (예: 100)" },
{ key: "specific_gravity", label: "비중", type: "text", placeholder: "숫자 입력 (예: 7.85)" },
{ key: "inventory_unit", label: "재고단위", type: "category" },
{ key: "selling_price", label: "판매가격", type: "text" },
{ key: "standard_price", label: "기준단가", type: "text" },
{ key: "currency_code", label: "통화", type: "category" },
{ key: "user_type01", label: "대분류", type: "category" },
{ key: "user_type02", label: "중분류", type: "category" },
{ key: "lead_time", label: "생산 리드타임(일)", type: "text", placeholder: "숫자 입력 (예: 7)" },
{ key: "image", label: "품목 이미지", type: "image" },
{ key: "meno", label: "메모", type: "textarea" },
];
const CATEGORY_COLUMNS_FOR_MODAL = [
"division", "type", "unit", "material", "status",
"inventory_unit", "currency_code", "user_type01", "user_type02",
];
function SortableMappingRow({ id, children }: { id: string; children: React.ReactNode }) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id });
const style: React.CSSProperties = {
transform: CSS.Transform.toString(transform), transition,
opacity: isDragging ? 0.5 : 1,
};
return (
<div ref={setNodeRef} style={style} className="flex gap-2 items-center">
<div {...attributes} {...listeners} className="cursor-grab text-muted-foreground/40 hover:text-muted-foreground shrink-0">
<GripVertical className="h-3.5 w-3.5" />
</div>
{children}
</div>
);
}
export default function SalesItemPage() {
const { user } = useAuth();
const { confirm, ConfirmDialogComponent, isConfirmOpenRef } = useConfirmDialog();
const ts = useTableSettings("c16-sales-item", ITEM_TABLE, ITEM_GRID_COLUMNS);
const dndSensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }));
// 좌측: 품목
const [items, setItems] = useState<any[]>([]);
const [rawItems, setRawItems] = useState<any[]>([]);
const [itemLoading, setItemLoading] = useState(false);
const [itemCount, setItemCount] = useState(0);
const [selectedItemId, setSelectedItemId] = useState<string | null>(null);
@@ -70,8 +218,10 @@ export default function SalesItemPage() {
// 우측: 거래처
const [customerItems, setCustomerItems] = useState<any[]>([]);
const [priceGroups, setPriceGroups] = useState<Record<string, { master: any; details: any[] }>>({});
const [customerLoading, setCustomerLoading] = useState(false);
const [customerCheckedIds, setCustomerCheckedIds] = useState<string[]>([]);
const [expandedItems, setExpandedItems] = useState<Set<string>>(new Set());
// 카테고리
const [categoryOptions, setCategoryOptions] = useState<Record<string, { code: string; label: string; isDefault?: boolean }[]>>({});
@@ -84,14 +234,17 @@ export default function SalesItemPage() {
const [custSearchLoading, setCustSearchLoading] = useState(false);
const [custCheckedIds, setCustCheckedIds] = useState<Set<string>>(new Set());
// 품목 수정 모달
// 품목 등록/수정 모달
const [editItemOpen, setEditItemOpen] = useState(false);
const [editItemForm, setEditItemForm] = useState<Record<string, any>>({});
const [isEditMode, setIsEditMode] = useState(false);
const [editId, setEditId] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
// 엑셀
const [excelUploadOpen, setExcelUploadOpen] = useState(false);
const [excelChainConfig, setExcelChainConfig] = useState<TableChainConfig | null>(null);
const [excelDetecting, setExcelDetecting] = useState(false);
// 거래처 상세 입력 모달 (거래처 품번/품명 + 단가)
const [custDetailOpen, setCustDetailOpen] = useState(false);
@@ -164,6 +317,7 @@ export default function SalesItemPage() {
autoFilter: true,
});
const raw = res.data?.data?.data || res.data?.data?.rows || [];
setRawItems(raw);
const CATS = ["unit", "material", "division", "type", "status", "inventory_unit", "currency_code", "user_type01", "user_type02"];
const data = raw.map((r: any) => {
const converted = { ...r };
@@ -189,8 +343,15 @@ export default function SalesItemPage() {
// 우측: 거래처 목록 조회
useEffect(() => {
if (!selectedItem?.item_number) { setCustomerItems([]); setCustomerCheckedIds([]); return; }
if (!selectedItem?.item_number) {
setCustomerItems([]);
setPriceGroups({});
setCustomerCheckedIds([]);
setExpandedItems(new Set());
return;
}
setCustomerCheckedIds([]);
setExpandedItems(new Set());
const itemKey = selectedItem.item_number;
const fetchCustomerItems = async () => {
setCustomerLoading(true);
@@ -223,7 +384,7 @@ export default function SalesItemPage() {
let allPrices: any[] = [];
if (mappings.length > 0) {
try {
const priceRes = await apiClient.post(`/table-management/tables/customer_item_prices/data`, {
const priceRes = await apiClient.post(`/table-management/tables/${PRICE_TABLE}/data`, {
page: 1, size: 500,
dataFilter: { enabled: true, filters: [
{ columnName: "item_id", operator: "equals", value: itemKey },
@@ -234,36 +395,57 @@ export default function SalesItemPage() {
} catch { /* skip */ }
}
// 4. 거래처별 중복 제거 + 오늘 날짜 기준 단가 매칭
// 4. 거래처 기준 그룹핑 — master: 첫 매핑 + 현재 단가, details: 전체 단가 리스트
const priceResolve = (col: string, code: string) => {
if (!code) return "";
return priceCategoryOptions[col]?.find((o: any) => o.code === code)?.label || code;
};
const today = new Date().toISOString().split("T")[0];
const now = new Date();
const today = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
const grouped: Record<string, { master: any; details: any[] }> = {};
const flatItems: any[] = [];
const seenCustIds = new Set<string>();
const sortedMappings = [...mappings].sort((a: any, b: any) => (a.customer_id || "").localeCompare(b.customer_id || ""));
setCustomerItems(sortedMappings.map((m: any) => {
for (const m of mappings) {
const custKey = m.customer_id || "";
const isFirstOfGroup = !seenCustIds.has(custKey);
if (custKey) seenCustIds.add(custKey);
if (seenCustIds.has(custKey)) continue; // 거래처당 첫 매핑만 마스터
seenCustIds.add(custKey);
const custPriceList = allPrices.filter((p: any) => p.customer_id === custKey);
const custInfo = custMap[custKey] || {};
const custPriceList = allPrices
.filter((p: any) => p.customer_id === custKey)
.sort((a: any, b: any) => (a.start_date || "").localeCompare(b.start_date || ""));
const todayPrice = custPriceList.find((p: any) =>
(!p.start_date || p.start_date <= today) && (!p.end_date || p.end_date >= today)
) || custPriceList[0] || {};
return {
const masterRow = {
...m,
customer_code: isFirstOfGroup ? custKey : "",
customer_name: isFirstOfGroup ? (custMap[custKey]?.customer_name || "") : "",
customer_item_code: m.customer_item_code || "",
customer_item_name: m.customer_item_name || "",
customer_code: custKey,
customer_name: custInfo.customer_name || "",
base_price_type: priceResolve("base_price_type", todayPrice.base_price_type || ""),
base_price: todayPrice.base_price || "",
discount_type: priceResolve("discount_type", todayPrice.discount_type || ""),
discount_value: todayPrice.discount_value || "",
calculated_price: todayPrice.calculated_price || todayPrice.unit_price || "",
currency_code: priceResolve("currency_code", todayPrice.currency_code || ""),
};
// 단가 리스트 (라벨 변환)
const priceDetails = custPriceList.map((p: any) => ({
...p,
base_price_type_label: priceResolve("base_price_type", p.base_price_type || ""),
discount_type_label: priceResolve("discount_type", p.discount_type || ""),
currency_label: priceResolve("currency_code", p.currency_code || ""),
is_current: (!p.start_date || p.start_date <= today) && (!p.end_date || p.end_date >= today),
}));
grouped[custKey] = { master: masterRow, details: priceDetails };
flatItems.push(masterRow);
}
setPriceGroups(grouped);
setCustomerItems(flatItems);
} catch (err) {
console.error("거래처 조회 실패:", err);
} finally {
@@ -336,6 +518,17 @@ export default function SalesItemPage() {
}));
};
const handleMappingDragEnd = (custKey: string, event: DragEndEvent) => {
const { active, over } = event;
if (!over || active.id === over.id) return;
setCustMappings((prev) => {
const arr = [...(prev[custKey] || [])];
const oldIdx = arr.findIndex((r) => r._id === active.id);
const newIdx = arr.findIndex((r) => r._id === over.id);
return { ...prev, [custKey]: arrayMove(arr, oldIdx, newIdx) };
});
};
const addPriceRow = (custKey: string) => {
setCustPrices((prev) => ({
...prev,
@@ -565,30 +758,65 @@ export default function SalesItemPage() {
}
};
// 품목 수정
const openEditItem = () => {
if (!selectedItem) return;
setEditItemForm({ ...selectedItem });
// 채번 미리보기 로드
const loadNumberingPreview = async () => {
try {
const ruleRes = await apiClient.get(`/numbering-rules/by-column/${ITEM_TABLE}/item_number`);
const rule = ruleRes.data?.data;
if (rule?.ruleId) {
const previewRes = await apiClient.post(`/numbering-rules/${rule.ruleId}/preview`, { formData: {} });
return previewRes.data?.data?.generatedCode || "";
}
} catch { /* 채번 규칙 없으면 무시 */ }
return "";
};
// 품목 등록 모달 열기
const openRegisterModal = async () => {
setEditItemForm({});
setIsEditMode(false);
setEditId(null);
setEditItemOpen(true);
const code = await loadNumberingPreview();
if (code) setEditItemForm(prev => ({ ...prev, item_number: code }));
};
// 품목 수정 모달 열기
const openEditItem = (item?: any) => {
const target = item || selectedItem;
if (!target) return;
const raw = rawItems.find((r) => r.id === target.id) || target;
setEditItemForm({ ...raw });
setIsEditMode(true);
setEditId(target.id);
setEditItemOpen(true);
};
// 품목 저장 (등록 + 수정 통합)
const handleEditSave = async () => {
if (!editItemForm.id) return;
if (!editItemForm.item_name) {
toast.error("품명은 필수 입력이에요.");
return;
}
setSaving(true);
try {
if (isEditMode && editId) {
const { id, created_date, updated_date, writer, company_code, ...updateFields } = editItemForm;
await apiClient.put(`/table-management/tables/${ITEM_TABLE}/edit`, {
originalData: { id: editItemForm.id },
updatedData: {
selling_price: editItemForm.selling_price || null,
standard_price: editItemForm.standard_price || null,
currency_code: editItemForm.currency_code || null,
},
originalData: { id: editId },
updatedData: updateFields,
});
toast.success("수정되었습니다.");
toast.success("수정되었어요.");
} else {
const { id, created_date, updated_date, ...insertFields } = editItemForm;
await apiClient.post(`/table-management/tables/${ITEM_TABLE}/add`, { id: crypto.randomUUID(), ...insertFields });
toast.success("등록되었어요.");
}
setEditItemOpen(false);
fetchItems();
} catch (err: any) {
toast.error(err.response?.data?.message || "수정에 실패했습니다.");
console.error("저장 실패:", err);
toast.error(err.response?.data?.message || "저장에 실패했어요.");
} finally {
setSaving(false);
}
@@ -670,8 +898,22 @@ export default function SalesItemPage() {
{/* 액션 버튼 영역 */}
<div className="flex items-center gap-2 px-4 shrink-0">
<div className="flex gap-1.5 ml-auto">
<Button variant="outline" size="sm" className="h-8" onClick={() => setExcelUploadOpen(true)}>
<FileSpreadsheet className="w-3.5 h-3.5 mr-1" />
<Button
variant="outline" size="sm" className="h-8" disabled={excelDetecting}
onClick={async () => {
setExcelDetecting(true);
try {
const result = await autoDetectMultiTableConfig(ITEM_TABLE);
if (result.success && result.data) {
setExcelChainConfig(result.data);
setExcelUploadOpen(true);
} else {
toast.error(result.message || "테이블 구조 분석 실패");
}
} catch { toast.error("테이블 구조 분석 중 오류"); } finally { setExcelDetecting(false); }
}}
>
{excelDetecting ? <Loader2 className="w-3.5 h-3.5 mr-1 animate-spin" /> : <FileSpreadsheet className="w-3.5 h-3.5 mr-1" />}
</Button>
<Button variant="outline" size="sm" className="h-8" onClick={handleExcelDownload}>
@@ -697,7 +939,10 @@ export default function SalesItemPage() {
</span>
</div>
<div className="flex items-center gap-1.5">
<Button variant="outline" size="sm" disabled={!selectedItemId} onClick={openEditItem}>
<Button size="sm" onClick={openRegisterModal}>
<Plus className="w-3.5 h-3.5 mr-1" />
</Button>
<Button variant="outline" size="sm" disabled={!selectedItemId} onClick={() => openEditItem()}>
<Pencil className="w-3.5 h-3.5 mr-1" />
</Button>
<Button variant="outline" size="sm" onClick={() => ts.setOpen(true)}>
@@ -715,7 +960,7 @@ export default function SalesItemPage() {
emptyMessage="등록된 판매품목이 없어요"
selectedId={selectedItemId}
onSelect={(id) => setSelectedItemId(id)}
onRowDoubleClick={() => openEditItem()}
onRowDoubleClick={(row) => openEditItem(row)}
showRowNumber
showPagination
defaultPageSize={20}
@@ -746,8 +991,8 @@ export default function SalesItemPage() {
<div className="flex items-center gap-2.5 px-4">
<Users className="w-3.5 h-3.5 text-muted-foreground" />
<span className="text-xs font-semibold"> </span>
{customerItems.length > 0 && (
<Badge variant="secondary" className="ml-0.5 text-[10px] px-1.5 py-0">{customerItems.length}</Badge>
{Object.keys(priceGroups).length > 0 && (
<Badge variant="secondary" className="ml-0.5 text-[10px] px-1.5 py-0">{Object.keys(priceGroups).length}</Badge>
)}
</div>
<div className="flex gap-1.5">
@@ -770,69 +1015,172 @@ export default function SalesItemPage() {
{/* 거래처 테이블 */}
<div className="flex-1 min-h-0 overflow-auto pt-px">
{customerLoading ? (
<div className="flex items-center justify-center h-full">
<Loader2 className="w-5 h-5 animate-spin text-muted-foreground" />
</div>
) : customerItems.length === 0 ? (
<div className="flex items-center justify-center h-full text-sm text-muted-foreground">
</div>
) : (
<Table noWrapper>
<Table>
<TableHeader className="sticky top-0 z-10">
<TableRow className="bg-muted hover:bg-muted h-10">
<TableHead className="w-[40px] text-center px-2">
<Checkbox
<input
type="checkbox"
className="rounded"
checked={customerItems.length > 0 && customerCheckedIds.length === customerItems.length}
onCheckedChange={(checked) => {
if (checked === true) setCustomerCheckedIds(customerItems.map((c) => c.id));
else setCustomerCheckedIds([]);
}}
onChange={(e) => setCustomerCheckedIds(e.target.checked ? customerItems.map((c) => c.id) : [])}
/>
</TableHead>
<TableHead className="w-[110px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>
<TableHead className="min-w-[120px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>
<TableHead className="w-[100px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>
<TableHead className="w-[100px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>
<TableHead className="w-[80px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>
<TableHead className="w-[80px] text-right text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>
<TableHead className="w-[70px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>
<TableHead className="w-[60px] text-right text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>
<TableHead className="w-[80px] text-right text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>
<TableHead className="w-[50px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{customerItems.map((row) => (
{customerLoading ? (
<TableRow>
<TableCell colSpan={11} className="text-center py-8">
<Loader2 className="w-5 h-5 animate-spin mx-auto text-muted-foreground" />
</TableCell>
</TableRow>
) : Object.keys(priceGroups).length === 0 ? (
<TableRow>
<TableCell colSpan={11} className="text-center py-8 text-muted-foreground text-sm">
</TableCell>
</TableRow>
) : Object.entries(priceGroups).map(([custKey, group]) => {
const isExpanded = expandedItems.has(custKey);
const m = group.master;
const isChecked = customerCheckedIds.includes(m.id);
return (
<React.Fragment key={custKey}>
{/* 마스터 행 */}
<TableRow
key={row.id}
className={cn(
"cursor-pointer h-[41px]",
customerCheckedIds.includes(row.id) ? "bg-primary/[0.08]" : "hover:bg-accent"
"cursor-pointer border-l-[3px] border-l-transparent h-[41px]",
isChecked && "bg-primary/5 border-l-primary"
)}
onClick={() => {
setExpandedItems((prev) => {
const next = new Set(prev);
if (next.has(custKey)) next.delete(custKey); else next.add(custKey);
return next;
});
}}
onDoubleClick={() => openEditCust(m)}
>
<TableCell
className="text-center px-2"
onClick={(e) => {
e.stopPropagation();
setCustomerCheckedIds((prev) =>
prev.includes(row.id) ? prev.filter((id) => id !== row.id) : [...prev, row.id]
prev.includes(m.id) ? prev.filter((id) => id !== m.id) : [...prev, m.id]
);
}}
onDoubleClick={() => openEditCust(row)}
>
<TableCell className="text-center px-2">
<Checkbox
checked={customerCheckedIds.includes(row.id)}
onCheckedChange={() => {}}
/>
<input type="checkbox" className="rounded" checked={isChecked} readOnly />
</TableCell>
<TableCell className="text-[13px] font-mono text-muted-foreground">{row.customer_code}</TableCell>
<TableCell className="text-sm text-foreground">{row.customer_name}</TableCell>
<TableCell className="text-[13px] text-muted-foreground">{row.customer_item_code}</TableCell>
<TableCell className="text-[13px] text-muted-foreground">{row.customer_item_name}</TableCell>
<TableCell className="text-[13px] text-right font-mono text-muted-foreground">{formatNum(row.base_price)}</TableCell>
<TableCell className="text-[13px] text-right font-mono text-foreground font-semibold">{formatNum(row.calculated_price)}</TableCell>
<TableCell className="text-[13px] text-muted-foreground">{row.currency_code}</TableCell>
<TableCell className="text-[13px] font-mono text-muted-foreground">
<div className="flex items-center gap-1">
{isExpanded
? <ChevronDown className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
: <ChevronRight className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
}
{m.customer_code}
</div>
</TableCell>
<TableCell className="text-[13px]">{m.customer_name}</TableCell>
<TableCell className="text-[13px]">{m.customer_item_code}</TableCell>
<TableCell className="text-[13px]">{m.customer_item_name}</TableCell>
<TableCell className="text-[13px]">{m.base_price_type}</TableCell>
<TableCell className="text-[13px] text-right">
{m.base_price ? Number(m.base_price).toLocaleString() : ""}
</TableCell>
<TableCell className="text-[13px]">{m.discount_type}</TableCell>
<TableCell className="text-[13px] text-right">{m.discount_value ? Number(m.discount_value).toLocaleString() : ""}</TableCell>
<TableCell className="text-[13px] text-right font-semibold">
{m.calculated_price ? Number(m.calculated_price).toLocaleString() : ""}
</TableCell>
<TableCell className="text-[13px]">{m.currency_code}</TableCell>
</TableRow>
))}
{/* 현재 단가 카드 (펼쳤을 때) */}
{isExpanded && (() => {
const cp = group.details.find((p) => p.is_current) || group.details[0];
if (!cp) return (
<TableRow className="border-l-[3px] border-l-primary/30">
<TableCell colSpan={11} className="py-3 px-4 text-xs text-muted-foreground"> </TableCell>
</TableRow>
);
return (
<TableRow className="border-l-[3px] border-l-primary/30">
<TableCell colSpan={11} className="px-4 py-3">
<div className="border border-primary/20 rounded-lg bg-card overflow-hidden">
{/* 카드 헤더 */}
<div className="flex items-center justify-between px-4 py-2 bg-primary/[0.04] border-b border-primary/10">
<div className="flex items-center gap-2">
<Coins className="w-3.5 h-3.5 text-primary" />
<span className="text-xs font-semibold"> </span>
<Badge variant="secondary" className="text-[9px] px-1.5 py-0 bg-primary/10 text-primary"></Badge>
</div>
{group.details.length > 1 && (
<span className="text-[10px] text-muted-foreground"> {group.details.length} </span>
)}
</div>
{/* 카드 내용 */}
<div className="px-5 py-3.5 flex items-end gap-0 text-[13px]">
<div className="flex flex-col pr-5 border-r border-border/30">
<span className="text-[10px] text-muted-foreground/50 font-medium mb-1"></span>
<span className="font-mono text-muted-foreground text-xs">
{cp.start_date ? String(cp.start_date).split("T")[0] : "—"} ~ {cp.end_date ? String(cp.end_date).split("T")[0] : "—"}
</span>
</div>
<div className="flex flex-col px-5 border-r border-border/30">
<span className="text-[10px] text-muted-foreground/50 font-medium mb-1"></span>
<span>{cp.base_price_type_label || "-"}</span>
</div>
<div className="flex flex-col px-5 border-r border-border/30">
<span className="text-[10px] text-muted-foreground/50 font-medium mb-1"></span>
<span className="font-mono font-medium">{cp.base_price ? Number(cp.base_price).toLocaleString() : "-"}</span>
</div>
<div className="flex flex-col px-5 border-r border-border/30">
<span className="text-[10px] text-muted-foreground/50 font-medium mb-1"></span>
<span>{cp.discount_type_label && cp.discount_type_label !== "할인없음" ? cp.discount_type_label : "-"}</span>
</div>
<div className="flex flex-col px-5 border-r border-border/30">
<span className="text-[10px] text-muted-foreground/50 font-medium mb-1"></span>
<span className="font-mono">{cp.discount_value ? Number(cp.discount_value).toLocaleString() : "-"}</span>
</div>
<div className="flex flex-col px-5">
<span className="text-[10px] text-muted-foreground/50 font-medium mb-1"></span>
<span>
{cp.rounding_unit_value
? (priceCategoryOptions["rounding_unit_value"]?.find((o) => o.code === cp.rounding_unit_value)?.label || cp.rounding_unit_value)
: "-"}
</span>
</div>
<span className="text-primary/50 px-4 pb-0.5 text-lg"></span>
<div className="flex flex-col pl-1">
<span className="text-[10px] text-muted-foreground/50 font-medium mb-1"></span>
<span className="text-base font-bold font-mono text-foreground">
{(cp.calculated_price || cp.unit_price) ? Number(cp.calculated_price || cp.unit_price).toLocaleString() : "-"}
<span className="text-xs font-normal text-muted-foreground ml-1.5">{cp.currency_label}</span>
</span>
</div>
</div>
</div>
</TableCell>
</TableRow>
);
})()}
</React.Fragment>
);
})}
</TableBody>
</Table>
)}
</div>
</>
)}
@@ -841,73 +1189,88 @@ export default function SalesItemPage() {
</ResizablePanelGroup>
</div>
{/* ── 품목 수정 모달 ── */}
{/* ── 품목 등록/수정 모달 ── */}
<Dialog open={editItemOpen} onOpenChange={setEditItemOpen}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle> </DialogTitle>
<DialogContent className="sm:max-w-[600px] w-[95vw] max-h-[90vh] flex flex-col p-0 overflow-hidden">
<DialogHeader className="shrink-0 px-6 pt-5 pb-3 border-b">
<DialogTitle>{isEditMode ? "품목 수정" : "품목 등록"}</DialogTitle>
<DialogDescription>
{editItemForm.item_number || ""} {editItemForm.item_name || ""}
{isEditMode ? "품목 정보를 수정해요." : "새로운 품목을 등록해요."}
</DialogDescription>
</DialogHeader>
<div className="grid grid-cols-2 gap-4 py-4">
{/* 품목 기본정보 (읽기 전용) */}
{[
{ key: "item_number", label: "품목코드" },
{ key: "item_name", label: "품명" },
{ key: "size", label: "규격" },
{ key: "unit", label: "단위" },
{ key: "material", label: "재질" },
{ key: "status", label: "상태" },
].map((f) => (
<div key={f.key} className="space-y-1.5">
<Label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">{f.label}</Label>
<Input value={editItemForm[f.key] || ""} className="h-9 bg-muted/50" disabled />
</div>
))}
<div className="col-span-2 border-t my-1" />
{/* 판매 설정 (수정 가능) */}
<div className="space-y-1.5">
<Label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide"></Label>
<Input
value={editItemForm.selling_price || ""}
onChange={(e) => setEditItemForm((p) => ({ ...p, selling_price: e.target.value }))}
placeholder="판매가격을 입력해주세요"
className="h-9"
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide"></Label>
<Input
value={editItemForm.standard_price || ""}
onChange={(e) => setEditItemForm((p) => ({ ...p, standard_price: e.target.value }))}
placeholder="기준단가를 입력해주세요"
className="h-9"
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide"></Label>
<Select
value={editItemForm.currency_code || ""}
onValueChange={(v) => setEditItemForm((p) => ({ ...p, currency_code: v }))}
<div className="flex-1 overflow-y-auto">
<div className="grid grid-cols-2 gap-4 p-6">
{FORM_FIELDS.map((field) => (
<div
key={field.key}
className={cn("space-y-1.5", (field.type === "textarea" || field.type === "image") && "col-span-2")}
>
<SelectTrigger className="h-9">
<SelectValue placeholder="통화를 선택해주세요" />
</SelectTrigger>
<SelectContent>
{(categoryOptions["currency_code"] || []).map((o) => (
<SelectItem key={o.code} value={o.code}>{o.label}</SelectItem>
<Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
{field.label}
{field.required && <span className="text-destructive ml-1">*</span>}
</Label>
{field.type === "image" ? (
<ImageUpload
value={editItemForm[field.key] || ""}
onChange={(v) => setEditItemForm((prev) => ({ ...prev, [field.key]: v }))}
tableName={ITEM_TABLE}
recordId={editItemForm.id || ""}
columnName={field.key}
height="h-32"
/>
) : field.type === "multi-category" ? (
<MultiCategoryCombobox
options={categoryOptions[field.key] || []}
value={editItemForm[field.key] || ""}
onChange={(v) => setEditItemForm((prev) => ({ ...prev, [field.key]: v }))}
placeholder={`${field.label} 선택`}
/>
) : field.type === "category" ? (
<CategoryCombobox
options={categoryOptions[field.key] || []}
value={editItemForm[field.key] || ""}
onChange={(v) => setEditItemForm((prev) => ({ ...prev, [field.key]: v }))}
placeholder={`${field.label} 선택`}
/>
) : field.type === "textarea" ? (
<Textarea
value={editItemForm[field.key] || ""}
onChange={(e) => setEditItemForm((prev) => ({ ...prev, [field.key]: e.target.value }))}
placeholder={field.label}
rows={3}
/>
) : ["selling_price", "standard_price"].includes(field.key) ? (
<Input
value={editItemForm[field.key] ? Number(String(editItemForm[field.key]).replace(/,/g, "")).toLocaleString() : ""}
onChange={(e) => {
const raw = e.target.value.replace(/[^\d.-]/g, "");
setEditItemForm((prev) => ({ ...prev, [field.key]: raw }));
}}
placeholder={field.placeholder || field.label}
className="h-9 text-right"
/>
) : (
<Input
value={editItemForm[field.key] || ""}
onChange={(e) => setEditItemForm((prev) => ({ ...prev, [field.key]: e.target.value }))}
placeholder={field.placeholder || (field.disabled ? "자동 채번" : field.label)}
disabled={field.disabled && !isEditMode}
className="h-9"
/>
)}
</div>
))}
</SelectContent>
</Select>
</div>
</div>
<DialogFooter>
<DialogFooter className="shrink-0 border-t px-6 py-3">
<Button variant="outline" onClick={() => setEditItemOpen(false)}></Button>
<Button onClick={handleEditSave} disabled={saving}>
{saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
{saving
? <Loader2 className="w-4 h-4 mr-1.5 animate-spin" />
: <Save className="w-4 h-4 mr-1.5" />
}
</Button>
</DialogFooter>
@@ -1050,9 +1413,15 @@ export default function SalesItemPage() {
<div className="space-y-2">
{mappingRows.length === 0 ? (
<div className="text-xs text-muted-foreground py-2"> </div>
) : mappingRows.map((mRow, mIdx) => (
<div key={mRow._id} className="flex gap-2 items-center">
<span className="text-xs text-muted-foreground w-4 shrink-0">{mIdx + 1}</span>
) : (
<DndContext
sensors={dndSensors}
collisionDetection={closestCenter}
onDragEnd={(e) => handleMappingDragEnd(custKey, e)}
>
<SortableContext items={mappingRows.map((r) => r._id)} strategy={verticalListSortingStrategy}>
{mappingRows.map((mRow) => (
<SortableMappingRow key={mRow._id} id={mRow._id}>
<Input
value={mRow.customer_item_code}
onChange={(e) => updateMappingRow(custKey, mRow._id, "customer_item_code", e.target.value)}
@@ -1072,8 +1441,11 @@ export default function SalesItemPage() {
>
<X className="h-3 w-3" />
</Button>
</div>
</SortableMappingRow>
))}
</SortableContext>
</DndContext>
)}
</div>
</div>
@@ -1248,13 +1620,14 @@ export default function SalesItemPage() {
/>
{/* 엑셀 업로드 */}
<ExcelUploadModal
{excelChainConfig && (
<MultiTableExcelUploadModal
open={excelUploadOpen}
onOpenChange={setExcelUploadOpen}
tableName={ITEM_TABLE}
userId={user?.userId}
config={excelChainConfig}
onSuccess={() => fetchItems()}
/>
)}
{ConfirmDialogComponent}
</div>
@@ -15,7 +15,7 @@ import {
Plus, Trash2, Save, Loader2, FileSpreadsheet, Download,
ClipboardList, Pencil, Search, X, Package, ChevronDown,
ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight,
Settings2,
Settings2, GripVertical,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { apiClient } from "@/lib/api/client";
@@ -28,6 +28,11 @@ import { useTableSettings } from "@/hooks/useTableSettings";
import { TableSettingsModal } from "@/components/common/TableSettingsModal";
import { DynamicSearchFilter, FilterValue } from "@/components/common/DynamicSearchFilter";
import { EDataTable, EDataTableColumn } from "@/components/common/EDataTable";
import {
DndContext, closestCenter, PointerSensor, useSensor, useSensors, DragEndEvent,
} from "@dnd-kit/core";
import { SortableContext, horizontalListSortingStrategy, useSortable, arrayMove } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
const MASTER_TABLE = "purchase_order_mng";
const DETAIL_TABLE = "purchase_detail";
@@ -84,6 +89,42 @@ const GRID_COLUMNS_CONFIG = [
{ key: "memo", label: "메모" },
];
const MODAL_DETAIL_COLUMNS = [
{ key: "item_code", label: "품번", width: "w-[120px]" },
{ key: "item_name", label: "품명", width: "w-[120px]" },
{ key: "supplier", label: "공급업체", width: "w-[150px]" },
{ key: "spec", label: "규격", width: "w-[80px]" },
{ key: "unit", label: "단위", width: "w-[60px]" },
{ key: "order_qty", label: "발주수량", width: "w-[90px]" },
{ key: "received_qty", label: "입고수량", width: "w-[90px]" },
{ key: "remain_qty", label: "잔량", width: "w-[80px]" },
{ key: "unit_price", label: "단가", width: "w-[100px]" },
{ key: "amount", label: "금액", width: "w-[100px]" },
{ key: "due_date", label: "납기일", width: "w-[160px]" },
{ key: "memo", label: "메모", width: "w-[120px]" },
];
const MODAL_COL_ORDER_KEY = "purchase_order_modal_col_order";
function SortableModalHead({ col }: { col: { key: string; label: string; width: string } }) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: col.key });
const style: React.CSSProperties = {
transform: CSS.Transform.toString(transform),
transition,
opacity: isDragging ? 0.5 : 1,
};
return (
<TableHead ref={setNodeRef} style={style} className={cn(col.width, "text-[11px] font-bold uppercase tracking-wide text-muted-foreground select-none")}>
<div className="inline-flex items-center gap-1">
<div {...attributes} {...listeners} className="cursor-grab text-muted-foreground/40 hover:text-muted-foreground shrink-0">
<GripVertical className="h-3 w-3" />
</div>
<span className="truncate">{col.label}</span>
</div>
</TableHead>
);
}
export default function PurchaseOrderPage() {
const { user } = useAuth();
const { confirm, ConfirmDialogComponent } = useConfirmDialog();
@@ -121,8 +162,43 @@ export default function PurchaseOrderPage() {
// 테이블 설정
const ts = useTableSettings("c16-purchase-order", DETAIL_TABLE, GRID_COLUMNS_CONFIG);
// 모달 품목 테이블 컬럼 순서 (드래그 재정렬)
const [modalColumns, setModalColumns] = useState(MODAL_DETAIL_COLUMNS);
const modalSensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 8 } }));
useEffect(() => {
const saved = localStorage.getItem(MODAL_COL_ORDER_KEY);
if (saved) {
try {
const order = JSON.parse(saved) as string[];
const reordered = order.map((key) => MODAL_DETAIL_COLUMNS.find((c) => c.key === key)).filter(Boolean) as typeof MODAL_DETAIL_COLUMNS;
const remaining = MODAL_DETAIL_COLUMNS.filter((c) => !order.includes(c.key));
setModalColumns([...reordered, ...remaining]);
} catch { /* skip */ }
}
}, []);
const handleModalDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
if (!over || active.id === over.id) return;
setModalColumns((prev) => {
const oldIndex = prev.findIndex((c) => c.key === active.id);
const newIndex = prev.findIndex((c) => c.key === over.id);
const next = arrayMove(prev, oldIndex, newIndex);
localStorage.setItem(MODAL_COL_ORDER_KEY, JSON.stringify(next.map((c) => c.key)));
return next;
});
};
const isReadOnly = masterForm.status === "입고완료" || masterForm.status === "취소";
const visibleModalColumns = useMemo(() => {
return modalColumns.filter((col) => {
if (col.key === "supplier" && masterForm.input_mode !== "itemFirst") return false;
return true;
});
}, [modalColumns, masterForm.input_mode]);
// 카테고리 로드
useEffect(() => {
const loadCategories = async () => {
@@ -672,6 +748,89 @@ export default function PurchaseOrderPage() {
setDetailRows((prev) => prev.filter((_, i) => i !== idx));
};
const renderDetailCell = (col: { key: string }, row: any, idx: number) => {
switch (col.key) {
case "item_code":
return <TableCell key={col.key} className="text-[13px] font-mono max-w-[120px]"><span className="block truncate" title={row.item_code}>{row.item_code}</span></TableCell>;
case "item_name":
return <TableCell key={col.key} className="text-[13px] max-w-[120px]"><span className="block truncate" title={row.item_name}>{row.item_name}</span></TableCell>;
case "supplier":
return (
<TableCell key={col.key}>
{isReadOnly ? (
<span className="text-xs">{(categoryOptions["supplier_code"] || []).find(o => o.code === row.supplier_code)?.label || row.supplier_code || "-"}</span>
) : (
<Select value={row.supplier_code || ""} onValueChange={(v) => {
const supp = categoryOptions["supplier_code"]?.find(o => o.code === v);
const name = supp?.label.replace(` (${v})`, "") || "";
updateDetailRow(idx, "supplier_code", v);
updateDetailRow(idx, "supplier_name", name);
}}>
<SelectTrigger className="h-8 text-xs"><SelectValue placeholder="공급업체" /></SelectTrigger>
<SelectContent>
{(categoryOptions["supplier_code"] || []).map(o => (
<SelectItem key={o.code} value={o.code}>{o.label}</SelectItem>
))}
</SelectContent>
</Select>
)}
</TableCell>
);
case "spec":
return <TableCell key={col.key} className="text-[13px] text-muted-foreground">{row.spec}</TableCell>;
case "unit":
return <TableCell key={col.key} className="text-[13px]">{row.unit}</TableCell>;
case "order_qty":
return (
<TableCell key={col.key}>
{isReadOnly ? (
<span className="text-xs text-right font-mono block">{row.order_qty ? Number(row.order_qty).toLocaleString() : ""}</span>
) : (
<Input value={formatNumber(row.order_qty || "")} onChange={(e) => updateDetailRow(idx, "order_qty", parseNumber(e.target.value))} className="h-8 text-xs text-right font-mono" />
)}
</TableCell>
);
case "received_qty":
return <TableCell key={col.key} className="text-[13px] text-right font-mono text-muted-foreground">{row.received_qty ? Number(row.received_qty).toLocaleString() : "0"}</TableCell>;
case "remain_qty":
return <TableCell key={col.key} className="text-[13px] text-right font-mono">{row.remain_qty ? Number(row.remain_qty).toLocaleString() : "0"}</TableCell>;
case "unit_price":
return (
<TableCell key={col.key}>
{isReadOnly ? (
<span className="text-xs text-right font-mono block">{row.unit_price ? Number(row.unit_price).toLocaleString() : ""}</span>
) : (
<Input value={formatNumber(row.unit_price || "")} onChange={(e) => updateDetailRow(idx, "unit_price", parseNumber(e.target.value))} className="h-8 text-xs text-right font-mono" />
)}
</TableCell>
);
case "amount":
return <TableCell key={col.key} className="text-[13px] text-right font-mono font-semibold">{row.amount ? Number(row.amount).toLocaleString() : ""}</TableCell>;
case "due_date":
return (
<TableCell key={col.key}>
{isReadOnly ? (
<span className="text-xs">{row.due_date}</span>
) : (
<Input type="date" value={row.due_date || ""} onChange={(e) => updateDetailRow(idx, "due_date", e.target.value)} className="h-8 text-xs" />
)}
</TableCell>
);
case "memo":
return (
<TableCell key={col.key}>
{isReadOnly ? (
<span className="text-xs">{row.memo}</span>
) : (
<Input value={row.memo || ""} onChange={(e) => updateDetailRow(idx, "memo", e.target.value)} className="h-8 text-xs" />
)}
</TableCell>
);
default:
return null;
}
};
const handleExcelDownload = async () => {
if (orders.length === 0) { toast.error("다운로드할 데이터가 없어요."); return; }
const data = orders.map((o) => {
@@ -1012,25 +1171,17 @@ export default function PurchaseOrderPage() {
</div>
) : (
<div className="border rounded-lg overflow-x-auto">
<DndContext sensors={modalSensors} collisionDetection={closestCenter} onDragEnd={handleModalDragEnd}>
<Table className="table-fixed">
<TableHeader className="sticky top-0 z-10">
<SortableContext items={visibleModalColumns.map((c) => c.key)} strategy={horizontalListSortingStrategy}>
<TableRow className="bg-muted hover:bg-muted">
{!isReadOnly && <TableHead className="w-[40px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>}
<TableHead className="w-[120px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>
<TableHead className="w-[120px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>
{masterForm.input_mode === "itemFirst" && (
<TableHead className="w-[150px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>
)}
<TableHead className="w-[80px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>
<TableHead className="w-[60px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>
<TableHead className="w-[90px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>
<TableHead className="w-[90px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>
<TableHead className="w-[80px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>
<TableHead className="w-[100px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>
<TableHead className="w-[100px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>
<TableHead className="w-[160px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>
<TableHead className="w-[120px] text-[11px] font-bold uppercase tracking-wide text-muted-foreground"></TableHead>
{visibleModalColumns.map((col) => (
<SortableModalHead key={col.key} col={col} />
))}
</TableRow>
</SortableContext>
</TableHeader>
<TableBody>
{detailRows.map((row, idx) => (
@@ -1042,66 +1193,12 @@ export default function PurchaseOrderPage() {
</Button>
</TableCell>
)}
<TableCell className="text-[13px] font-mono max-w-[120px]"><span className="block truncate" title={row.item_code}>{row.item_code}</span></TableCell>
<TableCell className="text-[13px] max-w-[120px]"><span className="block truncate" title={row.item_name}>{row.item_name}</span></TableCell>
{masterForm.input_mode === "itemFirst" && (
<TableCell>
{isReadOnly ? (
<span className="text-xs">{(categoryOptions["supplier_code"] || []).find(o => o.code === row.supplier_code)?.label || row.supplier_code || "-"}</span>
) : (
<Select value={row.supplier_code || ""} onValueChange={(v) => {
const supp = categoryOptions["supplier_code"]?.find(o => o.code === v);
const name = supp?.label.replace(` (${v})`, "") || "";
updateDetailRow(idx, "supplier_code", v);
updateDetailRow(idx, "supplier_name", name);
}}>
<SelectTrigger className="h-8 text-xs"><SelectValue placeholder="공급업체" /></SelectTrigger>
<SelectContent>
{(categoryOptions["supplier_code"] || []).map(o => (
<SelectItem key={o.code} value={o.code}>{o.label}</SelectItem>
))}
</SelectContent>
</Select>
)}
</TableCell>
)}
<TableCell className="text-[13px] text-muted-foreground">{row.spec}</TableCell>
<TableCell className="text-[13px]">{row.unit}</TableCell>
<TableCell>
{isReadOnly ? (
<span className="text-xs text-right font-mono block">{row.order_qty ? Number(row.order_qty).toLocaleString() : ""}</span>
) : (
<Input value={formatNumber(row.order_qty || "")} onChange={(e) => updateDetailRow(idx, "order_qty", parseNumber(e.target.value))} className="h-8 text-xs text-right font-mono" />
)}
</TableCell>
<TableCell className="text-[13px] text-right font-mono text-muted-foreground">{row.received_qty ? Number(row.received_qty).toLocaleString() : "0"}</TableCell>
<TableCell className="text-[13px] text-right font-mono">{row.remain_qty ? Number(row.remain_qty).toLocaleString() : "0"}</TableCell>
<TableCell>
{isReadOnly ? (
<span className="text-xs text-right font-mono block">{row.unit_price ? Number(row.unit_price).toLocaleString() : ""}</span>
) : (
<Input value={formatNumber(row.unit_price || "")} onChange={(e) => updateDetailRow(idx, "unit_price", parseNumber(e.target.value))} className="h-8 text-xs text-right font-mono" />
)}
</TableCell>
<TableCell className="text-[13px] text-right font-mono font-semibold">{row.amount ? Number(row.amount).toLocaleString() : ""}</TableCell>
<TableCell>
{isReadOnly ? (
<span className="text-xs">{row.due_date}</span>
) : (
<Input type="date" value={row.due_date || ""} onChange={(e) => updateDetailRow(idx, "due_date", e.target.value)} className="h-8 text-xs" />
)}
</TableCell>
<TableCell>
{isReadOnly ? (
<span className="text-xs">{row.memo}</span>
) : (
<Input value={row.memo || ""} onChange={(e) => updateDetailRow(idx, "memo", e.target.value)} className="h-8 text-xs" />
)}
</TableCell>
{visibleModalColumns.map((col) => renderDetailCell(col, row, idx))}
</TableRow>
))}
</TableBody>
</Table>
</DndContext>
</div>
)}
</div>
+57 -1
View File
@@ -777,7 +777,7 @@ function AppLayoutInner({ children }: AppLayoutProps) {
className={`${
isMobile
? (sidebarOpen ? "translate-x-0" : "-translate-x-full") + " fixed top-14 left-0 z-40 h-[calc(100vh-56px)]"
: "relative z-auto h-screen translate-x-0"
: "relative z-auto h-screen"
} border-sidebar-border bg-sidebar flex flex-col border-r transition-all duration-300 flex-shrink-0 overflow-hidden ${
!isMobile && sidebarCollapsed ? "w-16" : "w-[260px] sm:w-[220px] lg:w-[240px]"
}`}
@@ -806,11 +806,67 @@ function AppLayoutInner({ children }: AppLayoutProps) {
<PanelLeftOpen className="h-[18px] w-[18px] text-muted-foreground" />
</button>
</div>
{/* 관리 회사 + 모드 전환 + 회사 선택 */}
{(user as ExtendedUserInfo)?.userType === "SUPER_ADMIN" && (
<div className="border-border bg-muted/50 mx-3 mt-3 rounded-md border p-3">
<div className="flex items-center gap-2">
<Building2 className="text-primary h-4 w-4 shrink-0" />
<div className="min-w-0 flex-1">
<p className="text-muted-foreground text-[10px]"> </p>
<p className="truncate text-sm font-semibold" title={currentCompanyName || "로딩 중..."}>
{currentCompanyName || "로딩 중..."}
</p>
</div>
</div>
</div>
)}
{((user as ExtendedUserInfo)?.userType === "SUPER_ADMIN" ||
(user as ExtendedUserInfo)?.userType === "COMPANY_ADMIN" ||
(user as ExtendedUserInfo)?.userType === "admin") && (
<div className="border-border space-y-2 border-b p-3">
<Button
onClick={handleModeSwitch}
className={`flex w-full items-center justify-center gap-2 rounded-md px-3 py-2 text-sm font-medium transition-colors duration-150 hover:cursor-pointer ${
isAdminMode
? "border border-amber-200 bg-amber-50 text-amber-700 hover:bg-amber-100 dark:border-amber-800 dark:bg-amber-950 dark:text-amber-400"
: "border-primary/20 bg-primary/5 text-primary hover:bg-primary/10 border"
}`}
>
{isAdminMode ? (
<>
<UserCheck className="h-4 w-4" />
</>
) : (
<>
<Shield className="h-4 w-4" />
</>
)}
</Button>
{(user as ExtendedUserInfo)?.userType === "SUPER_ADMIN" && (
<Button
onClick={() => setShowCompanySwitcher(true)}
className="border-primary/20 bg-primary/5 text-primary hover:bg-primary/10 flex w-full items-center justify-center gap-2 rounded-md border px-3 py-2 text-sm font-medium transition-colors duration-150 hover:cursor-pointer"
>
<Building2 className="h-4 w-4" />
</Button>
)}
</div>
)}
<div className="flex-1 overflow-y-auto py-4">
<nav className="space-y-0.5 px-3">
{uiMenus.map((menu) => renderMenu(menu))}
</nav>
</div>
{/* 테마 토글 */}
<div className="border-border border-t px-3 py-1">
<ThemeToggle />
</div>
</div>
</>
)}