summaryrefslogtreecommitdiff
path: root/lib/techsales-rfq/table/detail-table/rfq-detail-column.tsx
blob: fe9befe592961d5c2ce2fe3d5d64b5464399845f (plain)
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
"use client"

import * as React from "react"
import type { ColumnDef, Row } from "@tanstack/react-table";
import { formatDate } from "@/lib/utils"
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import { Checkbox } from "@/components/ui/checkbox";
import { MessageCircle, MoreHorizontal, Trash2, Paperclip, Users } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";

export interface DataTableRowAction<TData> {
  row: Row<TData>;
  type: "communicate" | "delete"; 
}

// 벤더 견적 데이터 타입 정의
export interface RfqDetailView {
  id: number
  rfqId: number
  vendorId?: number | null
  vendorName: string | null
  vendorCode: string | null
  totalPrice: string | number | null
  currency: string | null
  validUntil: Date | null
  status: string | null
  remark: string | null
  submittedAt: Date | null
  acceptedAt: Date | null
  rejectionReason: string | null
  createdAt: Date | null
  updatedAt: Date | null
  createdByName: string | null
  quotationCode?: string | null
  rfqCode?: string | null
  quotationVersion?: number | null
  vendorFlags?: {
    isCustomerPreferred?: boolean;      // 고객(선주) 선호 벤더
    isNewDiscovery?: boolean;           // 신규 발굴 벤더
    isProjectApproved?: boolean;        // Project Approved Vendor
    isShiProposal?: boolean;           // SHI Proposal Vendor
  } | null
  quotationAttachments?: Array<{
    id: number
    revisionId: number
    fileName: string
    fileSize: number
    filePath: string
    description?: string | null
  }>
}

// 견적서 정보 타입 (Sheet용)
export interface QuotationInfo {
  id: number
  quotationCode: string | null
  vendorName?: string
  rfqCode?: string
}

interface GetColumnsProps<TData> {
  setRowAction: React.Dispatch<
    React.SetStateAction<DataTableRowAction<TData> | null>
  >;
  unreadMessages?: Record<number, number>; // 읽지 않은 메시지 개수
  onQuotationClick?: (quotationId: number) => void; // 견적 클릭 핸들러
  openQuotationAttachmentsSheet?: (quotationId: number, quotationInfo: QuotationInfo) => void; // 견적서 첨부파일 sheet 열기
  openContactsDialog?: (quotationId: number, vendorName?: string) => void; // 담당자 조회 다이얼로그 열기
}

export function getRfqDetailColumns({
  setRowAction,
  unreadMessages = {},
  onQuotationClick,
  openQuotationAttachmentsSheet,
  openContactsDialog
}: GetColumnsProps<RfqDetailView>): ColumnDef<RfqDetailView>[] {
  return [
    {
      id: "select",
      header: ({ table }) => (
        <Checkbox
          checked={
            table.getIsAllPageRowsSelected() ||
            (table.getIsSomePageRowsSelected() && "indeterminate")
          }
          onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
          aria-label="모두 선택"
        />
      ),
      cell: ({ row }) => {
        const status = row.original.status;
        const isSelectable = status ? !["Accepted", "Rejected"].includes(status) : true;
        
        return (
          <Checkbox
            checked={row.getIsSelected()}
            onCheckedChange={(value) => row.toggleSelected(!!value)}
            disabled={!isSelectable}
            aria-label="행 선택"
            className={!isSelectable ? "opacity-50 cursor-not-allowed" : ""}
          />
        );
      },
      enableSorting: false,
      enableHiding: false,
      size: 40,
    },
    {
      accessorKey: "status",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="견적 상태" />
      ),
      cell: ({ row }) => {
        const status = row.getValue("status") as string;
        // 상태에 따른 배지 색상 설정
        let variant: "default" | "secondary" | "outline" | "destructive" = "outline";
        
        if (status === "Submitted") {
          variant = "default"; // 제출됨 - 기본 색상
        } else if (status === "Accepted") {
          variant = "secondary"; // 승인됨 - 보조 색상
        } else if (status === "Rejected") {
          variant = "destructive"; // 거부됨 - 위험 색상
        }
        
        return (
          <Badge variant={variant}>{status || "Draft"}</Badge>
        );
      },
      meta: {
        excelHeader: "견적 상태"
      },
      enableResizing: true,
      size: 120,
    },
    {
      accessorKey: "vendorCode",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="벤더 코드" />
      ),
      cell: ({ row }) => <div>{row.getValue("vendorCode")}</div>,
      meta: {
        excelHeader: "벤더 코드"
      },
      enableResizing: true,
      size: 120,
    },
    {
      accessorKey: "vendorName",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="벤더명" />
      ),
      cell: ({ row }) => {
        const vendorName = row.getValue("vendorName") as string | null;
        const vendorId = row.original.vendorId;
        
        if (!vendorName) return <div>-</div>;
        
        if (vendorId) {
          return (
            <Button
              variant="link"
              className="p-0 h-auto font-normal text-left justify-start hover:underline"
              onClick={() => {
                window.open(`/ko/evcp/tech-vendors/${vendorId}/info`, '_blank');
              }}
            >
              {vendorName}
            </Button>
          );
        }
        
        return <div>{vendorName}</div>;
      },
      meta: {
        excelHeader: "벤더명"
      },
      enableResizing: true,
      size: 160,
    },
        // [Rev 컬럼 추가]
        {
          id: "rev",
          header: ({ column }) => (
            <DataTableColumnHeaderSimple column={column} title="Rev" />
          ),
          cell: ({ row }) => {
            const version = row.original.quotationVersion ?? 0;
            return <div className="text-center font-mono">{version}</div>;
          },
          meta: {
            excelHeader: "Rev"
          },
          enableResizing: false,
          size: 60,
        },
        // [벤더 구분자 컬럼 추가]
        {
          id: "vendorFlags",
          header: ({ column }) => (
            <DataTableColumnHeaderSimple column={column} title="벤더 유형" />
          ),
          cell: ({ row }) => {
            const vendorFlags = row.original.vendorFlags;
            
            if (!vendorFlags) {
              return <div className="text-muted-foreground">-</div>;
            }
            
            const activeFlags = [];
            
            if (vendorFlags.isCustomerPreferred) {
              activeFlags.push({ key: "isCustomerPreferred", label: "고객(선주) 선호 벤더", variant: "outline" as const });
            }
            if (vendorFlags.isNewDiscovery) {
              activeFlags.push({ key: "isNewDiscovery", label: "신규 발굴 벤더", variant: "outline" as const });
            }
            if (vendorFlags.isProjectApproved) {
              activeFlags.push({ key: "isProjectApproved", label: "Project Approved Vendor", variant: "outline" as const });
            }
            if (vendorFlags.isShiProposal) {
              activeFlags.push({ key: "isShiProposal", label: "SHI Proposal Vendor", variant: "outline" as const });
            }
            
            if (activeFlags.length === 0) {
              return <div className="text-muted-foreground">-</div>;
            }
            
            return (
              <div className="flex flex-wrap gap-1">
                {activeFlags.map((flag) => (
                  <Badge key={flag.key} variant={flag.variant} className="text-xs">
                    {flag.label}
                  </Badge>
                ))}
              </div>
            );
          },
          meta: {
            excelHeader: "벤더 구분자"
          },
          enableResizing: true,
          size: 200,
        },
    {
      accessorKey: "totalPrice",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="견적 금액" />
      ),
      cell: ({ row }) => {
        const value = row.getValue("totalPrice") as string | number | null;
        const currency = row.getValue("currency") as string | null;
        const quotationId = row.original.id;
        
        if (value === null || value === undefined) return "-";
        
        // 숫자로 변환 시도
        const numValue = typeof value === 'string' ? parseFloat(value) : value;
        const displayValue = isNaN(numValue) ? value : numValue.toLocaleString();
        
        // 견적값이 있고 클릭 핸들러가 있는 경우 클릭 가능한 버튼으로 표시
        if (onQuotationClick && quotationId) {
          return (
            <Button
              variant="link"
              className="p-0 h-auto font-medium text-left justify-start hover:underline"
              onClick={() => onQuotationClick(quotationId)}
              title="견적 히스토리 보기"
            >
              {displayValue} {currency}
            </Button>
          );
        }
        
        return (
          <div className="font-medium">
            {displayValue} {currency}
          </div>
        );
      },
      meta: {
        excelHeader: "견적 금액"
      },
      enableResizing: true,
      size: 140,
    },

    {
      accessorKey: "quotationAttachments",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="첨부파일" />
      ),
      cell: ({ row }) => {
        const attachments = row.original.quotationAttachments || [];
        const attachmentCount = attachments.length;

        if (attachmentCount === 0) {
          return <div className="text-muted-foreground">-</div>;
        }

        return (
          <Button
            variant="ghost"
            size="sm"
            className="relative h-8 w-8 p-0 group"
            onClick={() => {
              // 견적서 첨부파일 sheet 열기
              if (openQuotationAttachmentsSheet) {
                const quotation = row.original;
                openQuotationAttachmentsSheet(quotation.id, {
                  id: quotation.id,
                  quotationCode: quotation.quotationCode || null,
                  vendorName: quotation.vendorName || undefined,
                  rfqCode: quotation.rfqCode || undefined,
                });
              }
            }}
            title={
              attachmentCount === 1 
                ? `${attachments[0].fileName} (${(attachments[0].fileSize / 1024 / 1024).toFixed(2)} MB)` 
                : `${attachmentCount}개의 첨부파일:\n${attachments.map(att => att.fileName).join('\n')}`
            }
          >
            <Paperclip className="h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors" />
            {attachmentCount > 0 && (
              <span className="pointer-events-none absolute -top-1 -right-1 inline-flex h-4 min-w-[1rem] items-center justify-center rounded-full bg-primary px-1 text-[0.625rem] font-medium leading-none text-primary-foreground">
                {attachmentCount}
              </span>
            )}
          </Button>
        );
      },
      meta: {
        excelHeader: "첨부파일"
      },
      enableResizing: false,
      size: 80,
    },
    {
      id: "contacts",
      header: "담당자",
      cell: ({ row }) => {
        const quotation = row.original;
        
        const handleClick = () => {
          if (openContactsDialog) {
            openContactsDialog(quotation.id, quotation.vendorName || undefined);
          }
        };

        return (
          <div className="w-20">
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-8 w-8 p-0 group"
                    onClick={handleClick}
                    aria-label="담당자 정보 보기"
                  >
                    <Users className="h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors" />
                    <span className="sr-only">담당자 정보 보기</span>
                  </Button>
                </TooltipTrigger>
                <TooltipContent>
                  <p>RFQ 발송 담당자 보기</p>
                </TooltipContent>
              </Tooltip>
            </TooltipProvider>
          </div>
        );
      },
      meta: {
        excelHeader: "담당자"
      },
      enableResizing: false,
      size: 80,
    },
    {
      accessorKey: "currency",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="통화" />
      ),
      cell: ({ row }) => <div>{row.getValue("currency")}</div>,
      meta: {
        excelHeader: "통화"
      },
      enableResizing: true,
      size: 80,
    },
    {
      accessorKey: "validUntil",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="유효기간" />
      ),
      cell: ({ cell }) => {
        const value = cell.getValue() as Date | null;
        return value ? formatDate(value, "KR") : "-";
      },
      meta: {
        excelHeader: "유효기간"
      },
      enableResizing: true,
      size: 120,
    },
    {
      accessorKey: "submittedAt",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="제출일" />
      ),
      cell: ({ cell }) => {
        const value = cell.getValue() as Date | null;
        return value ? formatDate(value, "KR") : "-";
      },
      meta: {
        excelHeader: "제출일"
      },
      enableResizing: true,
      size: 120,
    },
    {
      accessorKey: "createdByName",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="등록자" />
      ),
      cell: ({ row }) => <div>{row.getValue("createdByName")}</div>,
      meta: {
        excelHeader: "등록자"
      },
      enableResizing: true,
      size: 120,
    },
    {
      accessorKey: "remark",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="비고" />
      ),
      cell: ({ row }) => <div>{row.getValue("remark") || "-"}</div>,
      meta: {
        excelHeader: "비고"
      },
      enableResizing: true,
      size: 200,
    },
    {
      id: "actions",
      header: () => <div className="text-right">동작</div>,
      cell: function Cell({ row }) {
        const vendorId = row.original.vendorId;
        const unreadCount = vendorId ? unreadMessages[vendorId] || 0 : 0;
        const status = row.original.status;
        const isAssigned = status === "Assigned";
        
        return (
          <div className="text-right flex items-center justify-end gap-1">
            {/* 커뮤니케이션 버튼 */}
            <div className="relative">
              <Button
                variant="ghost"
                size="sm"
                className="h-8 w-8 p-0"
                onClick={() => setRowAction({ row, type: "communicate" })}
                title="벤더와 커뮤니케이션"
              >
                <MessageCircle className="h-4 w-4" />
              </Button>
              {unreadCount > 0 && (
                <Badge 
                  variant="destructive" 
                  className="absolute -top-1 -right-1 h-4 w-4 p-0 text-xs flex items-center justify-center"
                >
                  {unreadCount > 9 ? '9+' : unreadCount}
                </Badge>
              )}
            </div>
            
            {/* 컨텍스트 메뉴 */}
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-8 w-8 p-0"
                  title="더 많은 작업"
                >
                  <MoreHorizontal className="h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem
                  onClick={() => setRowAction({ row, type: "delete" })}
                  disabled={!isAssigned}
                  className={!isAssigned ? "opacity-50 cursor-not-allowed" : "text-destructive focus:text-destructive"}
                >
                  <Trash2 className="mr-2 h-4 w-4" />
                  벤더 삭제
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        );
      },
      enableResizing: false,
      size: 120,
    },
  ];
}