summaryrefslogtreecommitdiff
path: root/lib/tbe-last/table/tbe-last-table.tsx
blob: fbb334d04b7cba043fed6ed8f4732766375e08ae (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
// lib/tbe-last/table/tbe-last-table.tsx

"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
import { type DataTableAdvancedFilterField } from "@/types/table"
import { useDataTable } from "@/hooks/use-data-table"
import { DataTable } from "@/components/data-table/data-table"
import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"
import { getColumns } from "./tbe-last-table-columns"
import { TbeLastView } from "@/db/schema"
import { getAllTBELast, getTBESessionDetail, requestTBEForRFQ } from "@/lib/tbe-last/service"
import { Button } from "@/components/ui/button"
import { Download, RefreshCw } from "lucide-react"
import { exportTableToExcel } from "@/lib/export"

// Import Dialogs and Sheets
import { SessionDetailDialog } from "./session-detail-dialog"
import { DocumentsSheet } from "./documents-sheet"
import { PrItemsDialog } from "./pr-items-dialog"
import { EvaluationDialog } from "./evaluation-dialog"
import { toast } from "sonner"

interface TbeLastTableProps {
  promises: Promise<[
    Awaited<ReturnType<typeof getAllTBELast>>,
  ]>
}

export function TbeLastTable({ promises }: TbeLastTableProps) {
  const router = useRouter()
  const [{ data, pageCount }] = React.use(promises)

  console.log(data, "data")

  // Dialog states
  const [sessionDetailOpen, setSessionDetailOpen] = React.useState(false)
  const [documentsOpen, setDocumentsOpen] = React.useState(false)
  const [prItemsOpen, setPrItemsOpen] = React.useState(false)
  const [evaluationOpen, setEvaluationOpen] = React.useState(false)

  const [selectedSessionId, setSelectedSessionId] = React.useState<number | null>(null)
  const [selectedRfqId, setSelectedRfqId] = React.useState<number | null>(null)
  const [selectedSession, setSelectedSession] = React.useState<TbeLastView | null>(null)
  const [sessionDetail, setSessionDetail] = React.useState<any>(null)
  const [isLoadingDetail, setIsLoadingDetail] = React.useState(false)
  // PR Items count overrides per sessionId (sourced from dialog detail)
  const [prItemsCountsBySessionId, setPrItemsCountsBySessionId] = React.useState<Record<number, { total: number, major: number }>>({})

  // Load session detail when needed
  const loadSessionDetail = React.useCallback(async (sessionId: number) => {
    setIsLoadingDetail(true)
    try {
      const detail = await getTBESessionDetail(sessionId)
      setSessionDetail(detail)
      // Update PR items count override for this session
      if (detail?.session?.tbeSessionId) {
        const sid = detail.session.tbeSessionId as number
        const items = Array.isArray(detail?.prItems) ? detail.prItems : []
        const total = items.length
        const major = items.filter((it: any) => it?.majorYn === true).length
        setPrItemsCountsBySessionId(prev => ({ ...prev, [sid]: { total, major } }))
      }
    } catch (error) {
      console.error("Failed to load session detail:", error)
    } finally {
      setIsLoadingDetail(false)
    }
  }, [])

  // Handlers
  const handleOpenSessionDetail = React.useCallback((sessionId: number) => {
    setSelectedSessionId(sessionId)
    setSessionDetailOpen(true)
    loadSessionDetail(sessionId)
  }, [loadSessionDetail])

  const handleOpenDocuments = React.useCallback((sessionId: number) => {
    setSelectedSessionId(sessionId)
    setDocumentsOpen(true)
    loadSessionDetail(sessionId)
  }, [loadSessionDetail])

  const handleOpenPrItems = React.useCallback((sessionId: number) => {
    setSelectedSessionId(sessionId)
    setPrItemsOpen(true)
    loadSessionDetail(sessionId)
  }, [loadSessionDetail])

  const handleOpenEvaluation = React.useCallback((session: TbeLastView) => {
    setSelectedSession(session)
    setEvaluationOpen(true)
    loadSessionDetail(session.rfqId)

  }, [])

  // Refresh 기능 제거됨

  // Table columns
  const columns = React.useMemo(
    () =>
      getColumns({
        onOpenSessionDetail: handleOpenSessionDetail,
        onOpenDocuments: handleOpenDocuments,
        onOpenPrItems: handleOpenPrItems,
        onOpenEvaluation: handleOpenEvaluation,
        getPrCountsOverride: (sessionId: number) => prItemsCountsBySessionId[sessionId]
      }),
    [handleOpenSessionDetail, handleOpenDocuments, handleOpenPrItems, handleOpenEvaluation, prItemsCountsBySessionId]
  )

  // Filter fields
  const filterFields: DataTableAdvancedFilterField<TbeLastView>[] = [
    {
      id: "sessionCode",
      label: "TBE Code",
      type: "text",
    },
    {
      id: "rfqCode",
      label: "RFQ Code",
      type: "text",
    },
    {
      id: "rfqTitle",
      label: "RFQ Title",
      type: "text",
    },
    {
      id: "rfqDueDate",
      label: "Due Date",
      type: "date",
    },
    {
      id: "packageNo",
      label: "Package No",
      type: "text",
    },
    {
      id: "projectCode",
      label: "Project",
      type: "text",
    },
    {
      id: "vendorCode",
      label: "Vendor Code",
      type: "text",
    },
    {
      id: "vendorName",
      label: "Vendor Name",
      type: "text",
    },
    {
      id: "picName",
      label: "구매담당자",
      type: "text",
    },
    {
      id: "EngPicName",
      label: "설계담당자",
      type: "text",
    },
    {
      id: "sessionStatus",
      label: "Status",
      type: "select",
      options: [
        { label: "준비중", value: "준비중" },
        { label: "진행중", value: "진행중" },
        { label: "검토중", value: "검토중" },
        { label: "보류", value: "보류" },
        { label: "완료", value: "완료" },
      ],
    },
    {
      id: "evaluationResult",
      label: "Result",
      type: "select",
      options: [
        { label: "Acceptable", value: "Acceptable" },
        { label: "Conditional", value: "Acceptable with Comment" },
        { label: "Not Acceptable", value: "Not Acceptable" },
        { label: "Pending", value: "" },
      ],
    },
  ]

  // Data table
  const { table } = useDataTable({
    data,
    columns,
    pageCount,
    filterFields,
    enablePinning: true,
    enableAdvancedFilter: true,
    initialState: {
      sorting: [{ id: "createdAt", desc: true }],
      columnPinning: { right: ["documents"] },
    },
    getRowId: (originalRow) => String(originalRow.tbeSessionId),
    shallow: false,
    clearOnDefault: true,
  })

  const handleBulkTBERequest = React.useCallback(async (rfqGroups: Map<string, TbeLastView[]>) => {
    try {
      const promises = Array.from(rfqGroups.entries()).map(async ([rfqCode, sessions]) => {
        // 준비중 상태인 세션만 필터링
        const pendingSessions = sessions.filter(s => s.sessionStatus === "준비중");

        if (pendingSessions.length === 0) {
          toast.info(`RFQ ${rfqCode}: 이미 TBE가 요청되었습니다.`);
          return null;
        }

        const vendors = pendingSessions.map(session => ({
          sessionId: session.tbeSessionId,
          vendorId: session.vendorId, // vendor ID 추가
          vendorCode: session.vendorCode,
          vendorName: session.vendorName,
        }));

        const rfqInfo = {
          rfqId: sessions[0].rfqId, // rfqLastId 추가
          rfqCode: sessions[0].rfqCode,
          rfqTitle: sessions[0].rfqTitle || "",
          rfqDueDate: sessions[0].rfqDueDate,
          projectCode: sessions[0].projectCode || "",
          projectName: sessions[0].projectName || "",
          packageNo: sessions[0].packageNo || "",
          packageName: sessions[0].packageName || "",
          picName: sessions[0].picName || "",
        };

        return requestTBEForRFQ(rfqInfo, vendors);
      });

      const results = await Promise.allSettled(promises);

      const successCount = results.filter(r => r.status === "fulfilled" && r.value?.success).length;
      const failCount = results.filter(r => r.status === "rejected" || (r.status === "fulfilled" && !r.value?.success)).length;

      if (successCount > 0) {
        toast.success(`${successCount}개 RFQ에 대한 TBE 요청이 완료되었습니다.`);
      }

      if (failCount > 0) {
        toast.error(`${failCount}개 RFQ에 대한 TBE 요청이 실패했습니다.`);
      }

      // 테이블 새로고침
      router.refresh();
      table.resetRowSelection();

    } catch (error) {
      console.error("TBE 요청 처리 중 오류:", error);
      toast.error("TBE 요청 처리 중 오류가 발생했습니다.");
    }
  }, [router, table]);


  return (
    <>
      <DataTable table={table}>
        <DataTableAdvancedToolbar
          table={table}
          filterFields={filterFields}
          shallow={false}
        >
          <div className="flex items-center gap-2">

            {table.getFilteredSelectedRowModel().rows.length > 0 && (
              <Button
                variant="default"
                size="sm"
                onClick={() => {
                  const selectedRows = table.getFilteredSelectedRowModel().rows;
                  const rfqGroups = new Map();

                  // RFQ별로 그룹핑
                  selectedRows.forEach(row => {
                    const rfqCode = row.original.rfqCode;
                    if (!rfqGroups.has(rfqCode)) {
                      rfqGroups.set(rfqCode, []);
                    }
                    rfqGroups.get(rfqCode).push(row.original);
                  });

                  handleBulkTBERequest(rfqGroups);
                }}
              >
                선택된 항목 TBE 요청 ({table.getFilteredSelectedRowModel().rows.length})
              </Button>
            )}
            {/* Refresh 버튼 제거됨 */}
            <Button
              variant="outline"
              size="sm"
              onClick={() =>
                exportTableToExcel(table, {
                  filename: "tbe-sessions",
                  excludeColumns: ["select", "actions"],
                  useGroupHeader: true
                })
              }
              className="gap-2"
            >
              <Download className="size-4" />
              <span>Export</span>
            </Button>
          </div>
        </DataTableAdvancedToolbar>
      </DataTable>

      {/* Session Detail Dialog */}
      <SessionDetailDialog
        open={sessionDetailOpen}
        onOpenChange={setSessionDetailOpen}
        sessionDetail={sessionDetail}
        isLoading={isLoadingDetail}
      />

      {/* Documents Sheet */}
      <DocumentsSheet
        open={documentsOpen}
        onOpenChange={setDocumentsOpen}
        sessionDetail={sessionDetail}
        isLoading={isLoadingDetail}
      />

      {/* PR Items Dialog */}
      <PrItemsDialog
        open={prItemsOpen}
        onOpenChange={setPrItemsOpen}
        sessionDetail={sessionDetail}
        isLoading={isLoadingDetail}
      />

      {/* Evaluation Dialog */}
      <EvaluationDialog
        open={evaluationOpen}
        onOpenChange={setEvaluationOpen}
        selectedSession={selectedSession}
        sessionDetail={sessionDetail}

      />
    </>
  )
}