summaryrefslogtreecommitdiff
path: root/lib/rfq-last/table/rfq-table-toolbar-actions.tsx
blob: 91b2798fbe3ba9ed324cbe65bebe56b5d99a3fd2 (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
"use client";

import * as React from "react";
import { type Table } from "@tanstack/react-table";
import { Download, RefreshCw, Plus, Lock, LockOpen } from "lucide-react";

import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { toast } from "sonner";
import { RfqsLastView } from "@/db/schema";
import { CreateGeneralRfqDialog } from "./create-general-rfq-dialog";
import { sealMultipleRfqs, unsealMultipleRfqs } from "../service";

interface RfqTableToolbarActionsProps {
  table: Table<RfqsLastView>;
  onRefresh?: () => void;
  rfqCategory?: "general" | "itb" | "rfq";
}

export function RfqTableToolbarActions({
  table,
  onRefresh,
  rfqCategory = "itb",
}: RfqTableToolbarActionsProps) {
  const [isExporting, setIsExporting] = React.useState(false);
  const [isSealing, setIsSealing] = React.useState(false);
  const [sealDialogOpen, setSealDialogOpen] = React.useState(false);
  const [sealAction, setSealAction] = React.useState<"seal" | "unseal">("seal");

  const selectedRows = table.getFilteredSelectedRowModel().rows;
  const selectedRfqIds = selectedRows.map(row => row.original.id);
  
  // 선택된 항목들의 밀봉 상태 확인
  const sealedCount = selectedRows.filter(row => row.original.rfqSealedYn).length;
  const unsealedCount = selectedRows.filter(row => !row.original.rfqSealedYn).length;

  const handleSealAction = React.useCallback(async (action: "seal" | "unseal") => {
    setSealAction(action);
    setSealDialogOpen(true);
  }, []);

  const confirmSealAction = React.useCallback(async () => {
    setIsSealing(true);
    try {
      const result = sealAction === "seal" 
        ? await sealMultipleRfqs(selectedRfqIds)
        : await unsealMultipleRfqs(selectedRfqIds);

      if (result.success) {
        toast.success(result.message);
        table.toggleAllRowsSelected(false); // 선택 해제
        onRefresh?.(); // 데이터 새로고침
      } else {
        toast.error(result.error);
      }
    } catch (error) {
      toast.error("작업 중 오류가 발생했습니다.");
    } finally {
      setIsSealing(false);
      setSealDialogOpen(false);
    }
  }, [sealAction, selectedRfqIds, table, onRefresh]);

  const handleExportCSV = React.useCallback(async () => {
    setIsExporting(true);
    try {
      const data = table.getFilteredRowModel().rows.map((row) => {
        const original = row.original;
        return {
          "RFQ 코드": original.rfqCode || "",
          "상태": original.status || "",
          "밀봉여부": original.rfqSealedYn ? "밀봉" : "미밀봉",
          "프로젝트 코드": original.projectCode || "",
          "프로젝트명": original.projectName || "",
          "자재코드": original.itemCode || "",
          "자재명": original.itemName || "",
          "패키지 번호": original.packageNo || "",
          "패키지명": original.packageName || "",
          "구매담당자": original.picUserName || original.picName || "",
          "엔지니어링 담당": original.engPicName || "",
          "발송일": original.rfqSendDate ? new Date(original.rfqSendDate).toLocaleDateString("ko-KR") : "",
          "마감일": original.dueDate ? new Date(original.dueDate).toLocaleDateString("ko-KR") : "",
          "업체수": original.vendorCount || 0,
          "Short List": original.shortListedVendorCount || 0,
          "견적접수": original.quotationReceivedCount || 0,
          "PR Items": original.prItemsCount || 0,
          "주요 Items": original.majorItemsCount || 0,
          "시리즈": original.series || "",
          "견적 유형": original.rfqType || "",
          "견적 제목": original.rfqTitle || "",
          "프로젝트 회사": original.projectCompany || "",
          "프로젝트 사이트": original.projectSite || "",
          "SM 코드": original.smCode || "",
          "PR 번호": original.prNumber || "",
          "PR 발행일": original.prIssueDate ? new Date(original.prIssueDate).toLocaleDateString("ko-KR") : "",
          "생성자": original.createdByUserName || "",
          "생성일": original.createdAt ? new Date(original.createdAt).toLocaleDateString("ko-KR") : "",
          "수정자": original.updatedByUserName || "",
          "수정일": original.updatedAt ? new Date(original.updatedAt).toLocaleDateString("ko-KR") : "",
        };
      });

      const fileName = `RFQ_목록_${new Date().toISOString().split("T")[0]}.csv`;
      exportTableToCSV({ data, filename: fileName });
    } catch (error) {
      console.error("Export failed:", error);
    } finally {
      setIsExporting(false);
    }
  }, [table]);

  const handleExportSelected = React.useCallback(async () => {
    setIsExporting(true);
    try {
      const selectedRows = table.getFilteredSelectedRowModel().rows;
      if (selectedRows.length === 0) {
        alert("선택된 항목이 없습니다.");
        return;
      }

      const data = selectedRows.map((row) => {
        const original = row.original;
        return {
          "RFQ 코드": original.rfqCode || "",
          "상태": original.status || "",
          "밀봉여부": original.rfqSealedYn ? "밀봉" : "미밀봉",
          "프로젝트 코드": original.projectCode || "",
          "프로젝트명": original.projectName || "",
          "자재코드": original.itemCode || "",
          "자재명": original.itemName || "",
          "패키지 번호": original.packageNo || "",
          "패키지명": original.packageName || "",
          "구매담당자": original.picUserName || original.picName || "",
          "엔지니어링 담당": original.engPicName || "",
          "발송일": original.rfqSendDate ? new Date(original.rfqSendDate).toLocaleDateString("ko-KR") : "",
          "마감일": original.dueDate ? new Date(original.dueDate).toLocaleDateString("ko-KR") : "",
          "업체수": original.vendorCount || 0,
          "Short List": original.shortListedVendorCount || 0,
          "견적접수": original.quotationReceivedCount || 0,
        };
      });

      const fileName = `RFQ_선택항목_${new Date().toISOString().split("T")[0]}.csv`;
      exportTableToCSV({ data, filename: fileName });
    } catch (error) {
      console.error("Export failed:", error);
    } finally {
      setIsExporting(false);
    }
  }, [table]);

  return (
    <>
      <div className="flex items-center gap-2">
        {onRefresh && (
          <Button
            variant="outline"
            size="sm"
            onClick={onRefresh}
            className="h-8 px-2 lg:px-3"
          >
            <RefreshCw className="mr-2 h-4 w-4" />
            새로고침
          </Button>
        )}

        {/* 견적 밀봉/해제 버튼 */}
        {selectedRfqIds.length > 0 && (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button
                variant="outline"
                size="sm"
                className="h-8 px-2 lg:px-3"
                disabled={isSealing}
              >
                <Lock className="mr-2 h-4 w-4" />
                견적 밀봉
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem 
                onClick={() => handleSealAction("seal")}
                disabled={unsealedCount === 0}
              >
                <Lock className="mr-2 h-4 w-4" />
                선택 항목 밀봉 ({unsealedCount}개)
              </DropdownMenuItem>
              <DropdownMenuItem 
                onClick={() => handleSealAction("unseal")}
                disabled={sealedCount === 0}
              >
                <LockOpen className="mr-2 h-4 w-4" />
                선택 항목 밀봉 해제 ({sealedCount}개)
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              <div className="px-2 py-1.5 text-xs text-muted-foreground">
                전체 {selectedRfqIds.length}개 선택됨
              </div>
            </DropdownMenuContent>
          </DropdownMenu>
        )}

        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              variant="outline"
              size="sm"
              className="h-8 px-2 lg:px-3"
              disabled={isExporting}
            >
              <Download className="mr-2 h-4 w-4" />
              {isExporting ? "내보내는 중..." : "내보내기"}
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem onClick={handleExportCSV}>
              전체 데이터 내보내기
            </DropdownMenuItem>
            <DropdownMenuItem 
              onClick={handleExportSelected}
              disabled={table.getFilteredSelectedRowModel().rows.length === 0}
            >
              선택한 항목 내보내기 ({table.getFilteredSelectedRowModel().rows.length}개)
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>

        {/* rfqCategory가 'general'일 때만 일반견적 생성 다이얼로그 표시 */}
        {rfqCategory === "general" && (
          <CreateGeneralRfqDialog onSuccess={onRefresh} />
        )}
      </div>

      {/* 밀봉 확인 다이얼로그 */}
      <AlertDialog open={sealDialogOpen} onOpenChange={setSealDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {sealAction === "seal" ? "견적 밀봉 확인" : "견적 밀봉 해제 확인"}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {sealAction === "seal" 
                ? `선택한 ${unsealedCount}개의 견적을 밀봉하시겠습니까? 밀봉된 견적은 업체에서 수정할 수 없습니다.`
                : `선택한 ${sealedCount}개의 견적 밀봉을 해제하시겠습니까? 밀봉이 해제되면 업체에서 견적을 수정할 수 있습니다.`}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isSealing}>취소</AlertDialogCancel>
            <AlertDialogAction 
              onClick={confirmSealAction} 
              disabled={isSealing}
              className={sealAction === "seal" ? "bg-red-600 hover:bg-red-700" : ""}
            >
              {isSealing ? "처리 중..." : "확인"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}

// CSV 내보내기 유틸리티 함수
function exportTableToCSV({ data, filename }: { data: any[]; filename: string }) {
  if (!data || data.length === 0) {
    console.warn("No data to export");
    return;
  }

  const headers = Object.keys(data[0]);
  const csvContent = [
    headers.join(","),
    ...data.map(row => 
      headers.map(header => {
        const value = row[header];
        // 값에 쉼표, 줄바꿈, 따옴표가 있으면 따옴표로 감싸기
        if (typeof value === "string" && (value.includes(",") || value.includes("\n") || value.includes('"'))) {
          return `"${value.replace(/"/g, '""')}"`;
        }
        return value;
      }).join(",")
    )
  ].join("\n");

  const blob = new Blob(["\uFEFF" + csvContent], { type: "text/csv;charset=utf-8;" });
  const link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = filename;
  link.click();
  URL.revokeObjectURL(link.href);
}