1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
|
"use client";
import * as React from "react";
import { useState, useMemo } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Checkbox } from "@/components/ui/checkbox";
import { ArrowUpDown, Search, Trash2 } from "lucide-react";
import { VendorPossibleMaterial, removeConfirmedMaterials } from "../vendor-possible-material-service";
import { AddConfirmedMaterial } from "./add-confirmed-material";
import { toast } from "sonner";
import { useTransition } from "react";
// formatDate 함수 제거 - YYYY-MM-DD 형식으로 직접 포맷
interface SimpleVendorMaterialsProps {
vendorId: number;
confirmedMaterials: VendorPossibleMaterial[];
vendorInputMaterials: VendorPossibleMaterial[];
onDataRefresh?: () => void;
}
type SortField = "itemCode" | "itemName" | "createdAt" | "recentPoDate" | "recentDeliveryDate" | "vendorTypeNameEn" | "recentPoNo" | "registerUserName";
type SortDirection = "asc" | "desc";
interface SortState {
field: SortField | null;
direction: SortDirection;
}
export function SimpleVendorMaterials({
vendorId,
confirmedMaterials,
vendorInputMaterials,
onDataRefresh,
}: SimpleVendorMaterialsProps) {
// 날짜를 YYYY-MM-DD 형식으로 포맷하는 함수
const formatDateToYMD = (date: Date | null | undefined): string => {
if (!date) return "-";
return date.toISOString().split('T')[0];
};
// 선택 상태 관리
const [selectedConfirmedIds, setSelectedConfirmedIds] = useState<number[]>([]);
const [isDeletePending, startDeleteTransition] = useTransition();
const [confirmedSearch, setConfirmedSearch] = useState("");
const [vendorInputSearch, setVendorInputSearch] = useState("");
const [confirmedSort, setConfirmedSort] = useState<SortState>({ field: null, direction: "asc" });
const [vendorInputSort, setVendorInputSort] = useState<SortState>({ field: null, direction: "asc" });
// 정렬 함수
const sortMaterials = (materials: VendorPossibleMaterial[], sortState: SortState) => {
if (!sortState.field) return materials;
return [...materials].sort((a, b) => {
let aValue: string | Date;
let bValue: string | Date;
switch (sortState.field) {
case "itemCode":
aValue = a.itemCode || "";
bValue = b.itemCode || "";
break;
case "itemName":
aValue = a.itemName || "";
bValue = b.itemName || "";
break;
case "createdAt":
aValue = a.createdAt;
bValue = b.createdAt;
break;
case "recentPoDate":
aValue = a.recentPoDate || new Date(0);
bValue = b.recentPoDate || new Date(0);
break;
case "recentDeliveryDate":
aValue = a.recentDeliveryDate || new Date(0);
bValue = b.recentDeliveryDate || new Date(0);
break;
case "vendorTypeNameEn":
aValue = a.vendorTypeNameEn || "";
bValue = b.vendorTypeNameEn || "";
break;
case "recentPoNo":
aValue = a.recentPoNo || "";
bValue = b.recentPoNo || "";
break;
case "registerUserName":
aValue = a.registerUserName || "";
bValue = b.registerUserName || "";
break;
default:
return 0;
}
if (aValue < bValue) return sortState.direction === "asc" ? -1 : 1;
if (aValue > bValue) return sortState.direction === "asc" ? 1 : -1;
return 0;
});
};
// 검색 필터링 함수
const filterMaterials = (materials: VendorPossibleMaterial[], searchTerm: string) => {
if (!searchTerm.trim()) return materials;
const lowercaseSearch = searchTerm.toLowerCase();
return materials.filter(material =>
(material.itemCode?.toLowerCase().includes(lowercaseSearch)) ||
(material.itemName?.toLowerCase().includes(lowercaseSearch))
);
};
const filteredAndSortedConfirmed = useMemo(() => {
const filtered = filterMaterials(confirmedMaterials, confirmedSearch);
return sortMaterials(filtered, confirmedSort);
}, [confirmedMaterials, confirmedSearch, confirmedSort]);
const filteredAndSortedVendorInput = useMemo(() => {
const filtered = filterMaterials(vendorInputMaterials, vendorInputSearch);
return sortMaterials(filtered, vendorInputSort);
}, [vendorInputMaterials, vendorInputSearch, vendorInputSort]);
// 선택 상태 관리 함수들 (필터링된 데이터 이후에 선언)
const handleSelectAllConfirmed = (checked: boolean) => {
if (checked) {
const allIds = filteredAndSortedConfirmed.map(material => material.id);
setSelectedConfirmedIds(allIds);
} else {
setSelectedConfirmedIds([]);
}
};
// 데이터 변경 시 선택 상태 정리 (유효하지 않은 ID들 제거)
React.useEffect(() => {
const validIds = confirmedMaterials.map(material => material.id);
setSelectedConfirmedIds(prev => prev.filter(id => validIds.includes(id)));
}, [confirmedMaterials]);
// 전체 선택 체크박스의 상태 계산
const isAllSelected = filteredAndSortedConfirmed.length > 0 &&
selectedConfirmedIds.length === filteredAndSortedConfirmed.length &&
filteredAndSortedConfirmed.every(material => selectedConfirmedIds.includes(material.id));
const isIndeterminate = selectedConfirmedIds.length > 0 &&
selectedConfirmedIds.length < filteredAndSortedConfirmed.length;
const handleSelectConfirmed = (id: number, checked: boolean) => {
if (checked) {
setSelectedConfirmedIds(prev => [...prev, id]);
} else {
setSelectedConfirmedIds(prev => prev.filter(selectedId => selectedId !== id));
}
};
// 삭제 함수
const handleDeleteSelected = () => {
if (selectedConfirmedIds.length === 0) {
toast.error("삭제할 항목을 선택해주세요.");
return;
}
startDeleteTransition(async () => {
const result = await removeConfirmedMaterials(vendorId, selectedConfirmedIds);
if (result.success) {
toast.success(result.message);
setSelectedConfirmedIds([]); // 선택 상태 초기화
onDataRefresh?.(); // 데이터 새로고침
} else {
toast.error(result.message);
}
});
};
// 정렬 핸들러
const handleSort = (
field: SortField,
currentSort: SortState,
setSort: React.Dispatch<React.SetStateAction<SortState>>
) => {
setSort(prev => ({
field,
direction: prev.field === field && prev.direction === "asc" ? "desc" : "asc"
}));
};
// 정렬 버튼 컴포넌트
const SortButton = ({
field,
children,
onSort
}: {
field: SortField;
children: React.ReactNode;
onSort: (field: SortField) => void;
}) => (
<Button
variant="ghost"
size="sm"
className="h-8 px-2"
onClick={() => onSort(field)}
>
{children}
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
);
return (
<div className="space-y-8">
{/* 확정정보 테이블 */}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle>확정정보</CardTitle>
<CardDescription>
구매담당자가 확정한 공급 품목 정보입니다.
</CardDescription>
</div>
<div className="flex items-center gap-2">
{selectedConfirmedIds.length > 0 && (
<Button
variant="destructive"
size="sm"
onClick={handleDeleteSelected}
disabled={isDeletePending}
className="flex items-center gap-2"
>
<Trash2 className="h-4 w-4" />
{isDeletePending ? "삭제 중..." : `삭제 (${selectedConfirmedIds.length})`}
</Button>
)}
<AddConfirmedMaterial
vendorId={vendorId}
existingConfirmedMaterials={confirmedMaterials}
onMaterialAdded={onDataRefresh}
/>
</div>
</div>
<div className="flex items-center space-x-2">
<Search className="h-4 w-4 text-muted-foreground" />
<Input
placeholder="자재그룹코드 또는 자재그룹명으로 검색..."
value={confirmedSearch}
onChange={(e) => setConfirmedSearch(e.target.value)}
className="max-w-sm"
/>
</div>
</CardHeader>
<CardContent>
<div className="rounded-md border max-h-96 overflow-auto">
<Table>
<TableHeader className="sticky top-0 bg-background z-10">
<TableRow>
<TableHead className="w-12">
<Checkbox
checked={isAllSelected}
ref={(el) => {
if (el && 'indeterminate' in el) {
el.indeterminate = isIndeterminate;
}
}}
onCheckedChange={handleSelectAllConfirmed}
aria-label="전체 선택"
/>
</TableHead>
<TableHead>
<SortButton
field="vendorTypeNameEn"
onSort={(field) => handleSort(field, confirmedSort, setConfirmedSort)}
>
업체유형
</SortButton>
</TableHead>
<TableHead>
<SortButton
field="itemCode"
onSort={(field) => handleSort(field, confirmedSort, setConfirmedSort)}
>
자재그룹코드
</SortButton>
</TableHead>
<TableHead>
<SortButton
field="itemName"
onSort={(field) => handleSort(field, confirmedSort, setConfirmedSort)}
>
자재그룹명
</SortButton>
</TableHead>
<TableHead>
<SortButton
field="recentPoNo"
onSort={(field) => handleSort(field, confirmedSort, setConfirmedSort)}
>
최근 Po No.
</SortButton>
</TableHead>
<TableHead>
<SortButton
field="recentPoDate"
onSort={(field) => handleSort(field, confirmedSort, setConfirmedSort)}
>
최근 Po일
</SortButton>
</TableHead>
<TableHead>
<SortButton
field="recentDeliveryDate"
onSort={(field) => handleSort(field, confirmedSort, setConfirmedSort)}
>
최근 납품일
</SortButton>
</TableHead>
<TableHead>
<SortButton
field="createdAt"
onSort={(field) => handleSort(field, confirmedSort, setConfirmedSort)}
>
등록일
</SortButton>
</TableHead>
<TableHead>
<SortButton
field="registerUserName"
onSort={(field) => handleSort(field, confirmedSort, setConfirmedSort)}
>
등록자명
</SortButton>
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredAndSortedConfirmed.length === 0 ? (
<TableRow>
<TableCell colSpan={9} className="text-center text-muted-foreground">
{confirmedSearch ? "검색 결과가 없습니다." : "확정된 공급품목이 없습니다."}
</TableCell>
</TableRow>
) : (
filteredAndSortedConfirmed.map((material) => (
<TableRow key={material.id}>
<TableCell>
<Checkbox
checked={selectedConfirmedIds.includes(material.id)}
onCheckedChange={(checked) => handleSelectConfirmed(material.id, checked as boolean)}
aria-label={`자재 ${material.itemCode} 선택`}
/>
</TableCell>
<TableCell>{material.vendorTypeNameEn || "-"}</TableCell>
<TableCell className="font-mono">{material.itemCode || "-"}</TableCell>
<TableCell>{material.itemName || "-"}</TableCell>
<TableCell className="font-mono">{material.recentPoNo || "-"}</TableCell>
<TableCell>{formatDateToYMD(material.recentPoDate)}</TableCell>
<TableCell>{formatDateToYMD(material.recentDeliveryDate)}</TableCell>
<TableCell>{formatDateToYMD(material.createdAt)}</TableCell>
<TableCell>{material.registerUserName || "-"}</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
<div className="mt-2 text-sm text-muted-foreground">
총 {filteredAndSortedConfirmed.length}건
</div>
</CardContent>
</Card>
{/* 업체입력정보 테이블 */}
<Card>
<CardHeader>
<CardTitle>업체입력정보</CardTitle>
<CardDescription>
업체에서 입력한 공급 가능 품목 정보입니다.
</CardDescription>
<div className="flex items-center space-x-2">
<Search className="h-4 w-4 text-muted-foreground" />
<Input
placeholder="자재그룹코드 또는 자재그룹명으로 검색..."
value={vendorInputSearch}
onChange={(e) => setVendorInputSearch(e.target.value)}
className="max-w-sm"
/>
</div>
</CardHeader>
<CardContent>
<div className="rounded-md border max-h-96 overflow-auto">
<Table>
<TableHeader className="sticky top-0 bg-background z-10">
<TableRow>
<TableHead>
<SortButton
field="vendorTypeNameEn"
onSort={(field) => handleSort(field, vendorInputSort, setVendorInputSort)}
>
업체유형
</SortButton>
</TableHead>
<TableHead>
<SortButton
field="itemCode"
onSort={(field) => handleSort(field, vendorInputSort, setVendorInputSort)}
>
자재그룹코드
</SortButton>
</TableHead>
<TableHead>
<SortButton
field="itemName"
onSort={(field) => handleSort(field, vendorInputSort, setVendorInputSort)}
>
자재그룹명
</SortButton>
</TableHead>
<TableHead>
<SortButton
field="createdAt"
onSort={(field) => handleSort(field, vendorInputSort, setVendorInputSort)}
>
등록일
</SortButton>
</TableHead>
<TableHead>
<SortButton
field="registerUserName"
onSort={(field) => handleSort(field, vendorInputSort, setVendorInputSort)}
>
등록자명
</SortButton>
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredAndSortedVendorInput.length === 0 ? (
<TableRow>
<TableCell colSpan={5} className="text-center text-muted-foreground">
{vendorInputSearch ? "검색 결과가 없습니다." : "업체입력 정보가 없습니다."}
</TableCell>
</TableRow>
) : (
filteredAndSortedVendorInput.map((material) => (
<TableRow key={material.id}>
<TableCell>{material.vendorTypeNameEn || "-"}</TableCell>
<TableCell className="font-mono">{material.itemCode || "-"}</TableCell>
<TableCell>{material.itemName || "-"}</TableCell>
<TableCell>{formatDateToYMD(material.createdAt)}</TableCell>
<TableCell>{material.registerUserName || "-"}</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
<div className="mt-2 text-sm text-muted-foreground">
총 {filteredAndSortedVendorInput.length}건
</div>
</CardContent>
</Card>
</div>
);
}
|