summaryrefslogtreecommitdiff
path: root/lib/vendor-document-list/plant/upload/table.tsx
blob: 84b040929e12e5e212f5f8de3602b243a19f2b8c (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
// lib/vendor-document-list/plant/upload/table.tsx
"use client"

import * as React from "react"
import type {
  DataTableAdvancedFilterField,
  DataTableFilterField,
  DataTableRowAction,
} 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 "./columns"
import { getStageSubmissions } from "./service"
import { StageSubmissionView } from "@/db/schema"
import { StageSubmissionToolbarActions } from "./toolbar-actions"
import { useRouter, useSearchParams, usePathname } from "next/navigation"
import { ProjectFilter } from "./components/project-filter"
import { SingleUploadDialog } from "./components/single-upload-dialog"
import { HistoryDialog } from "./components/history-dialog"
import { ViewSubmissionDialog } from "./components/view-submission-dialog"
import { toast } from "sonner"

interface StageSubmissionsTableProps {
  promises: Promise<[
    Awaited<ReturnType<typeof getStageSubmissions>>,
    { projects: Array<{ id: number; code: string }> }
  ]>
  selectedProjectId?: number | null
}

export function StageSubmissionsTable({ promises, selectedProjectId }: StageSubmissionsTableProps) {
  const [{ data, pageCount }, { projects }] = React.use(promises)
  const router = useRouter()
  const pathname = usePathname()
  const searchParams = useSearchParams()
  
  const [rowAction, setRowAction] = React.useState<DataTableRowAction<StageSubmissionView> | null>(null)
  
  const columns = React.useMemo(
    () => getColumns({ setRowAction }),
    [setRowAction]
  )
  
  // 프로젝트 필터 핸들러
  const handleProjectChange = (projectId: number | null) => {
    const current = new URLSearchParams(Array.from(searchParams.entries()))
    
    if (projectId) {
      current.set("projectId", projectId.toString())
    } else {
      current.delete("projectId")
    }
    
    // 페이지를 1로 리셋
    current.set("page", "1")
    
    const search = current.toString()
    const query = search ? `?${search}` : ""
    
    router.push(`${pathname}${query}`)
  }

  // Filter fields - 프로젝트 필터 제거
  const filterFields: DataTableFilterField<StageSubmissionView>[] = [
    {
      id: "stageStatus",
      label: "Stage Status",
      options: [
        { label: "Planned", value: "PLANNED" },
        { label: "In Progress", value: "IN_PROGRESS" },
        { label: "Submitted", value: "SUBMITTED" },
        { label: "Approved", value: "APPROVED" },
        { label: "Rejected", value: "REJECTED" },
        { label: "Completed", value: "COMPLETED" },
      ]
    },
    {
      id: "latestSubmissionStatus",
      label: "Submission Status",
      options: [
        { label: "Submitted", value: "SUBMITTED" },
        { label: "Under Review", value: "UNDER_REVIEW" },
        { label: "Draft", value: "DRAFT" },
        { label: "Withdrawn", value: "WITHDRAWN" },
      ]
    },
    {
      id: "requiresSubmission",
      label: "Requires Submission",
      options: [
        { label: "Yes", value: "true" },
        { label: "No", value: "false" },
      ]
    },
    {
      id: "requiresSync",
      label: "Requires Sync",
      options: [
        { label: "Yes", value: "true" },
        { label: "No", value: "false" },
      ]
    },
    {
      id: "isOverdue",
      label: "Overdue",
      options: [
        { label: "Yes", value: "true" },
        { label: "No", value: "false" },
      ]
    }
  ]

  const advancedFilterFields: DataTableAdvancedFilterField<StageSubmissionView>[] = [
    {
      id: "docNumber",
      label: "Doc Number",
      type: "text",
    },
    {
      id: "documentTitle",
      label: "Document Title",
      type: "text",
    },
    {
      id: "stageName",
      label: "Stage Name",
      type: "text",
    },
    {
      id: "stagePlanDate",
      label: "Due Date",
      type: "date",
    },
    {
      id: "daysUntilDue",
      label: "Days Until Due",
      type: "number",
    },
  ]

  const { table } = useDataTable({
    data,
    columns,
    pageCount,
    filterFields,
    enablePinning: true,
    enableAdvancedFilter: true,
    initialState: {
      sorting: [
        { id: "isOverdue", desc: true },
        { id: "daysUntilDue", desc: false }
      ],
      columnPinning: { right: ["actions"] },
    },
    getRowId: (originalRow) => `${originalRow.documentId}-${originalRow.stageId}`,
    shallow: false,
    clearOnDefault: true,
    columnResizeMode: "onEnd",
  })


  React.useEffect(() => {
    if (!rowAction) return;
  
    const { type, row } = rowAction;
  
    if (type === "downloadCover") {
       // 2) 서버에서 생성 후 다운로드 (예: API 호출)
      (async () => {
        try {
          const res = await fetch(`/api/stages/${row.original.stageId}/cover`, { method: "POST" });
          if (!res.ok) throw new Error("failed");
          const { fileUrl } = await res.json(); // 서버 응답: { fileUrl: string }
          window.open(fileUrl, "_blank", "noopener,noreferrer");
        } catch (e) {
          toast.error("커버 페이지 생성에 실패했습니다.");
          console.error(e);
        } finally {
          setRowAction(null);
        }
      })();
    }
  }, [rowAction, setRowAction]);

  return (
    <>
      <DataTable table={table}>
        {/* 프로젝트 필터를 툴바 위에 배치 */}
        <div className="flex items-center justify-between pb-3">
          <ProjectFilter
            projects={projects}
            value={selectedProjectId}
            onValueChange={handleProjectChange}
          />
          <div className="text-sm text-muted-foreground">
            {data.length} record(s) found
          </div>
        </div>
        
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
        >
          <StageSubmissionToolbarActions 
            table={table} 
            rowAction={rowAction}
            setRowAction={setRowAction}
          />
        </DataTableAdvancedToolbar>
      </DataTable>

      {/* Upload Dialog */}
    {rowAction?.type === "upload" && (
      <SingleUploadDialog
        open={true}
        onOpenChange={(open) => !open && setRowAction(null)}
        submission={rowAction.row.original}
        onUploadComplete={() => {
          setRowAction(null)
          // 테이블 새로고침
          window.location.reload()
        }}
      />
    )}

    {/* View Submission Dialog */}
    {rowAction?.type === "view" && (
      <ViewSubmissionDialog
        open={true}
        onOpenChange={(open) => !open && setRowAction(null)}
        submission={rowAction.row.original}
      />
    )}
    
    {/* History Dialog */}
    {rowAction?.type === "history" && (
      <HistoryDialog
        open={true}
        onOpenChange={(open) => !open && setRowAction(null)}
        submission={rowAction.row.original}
      />
    )}
    </>
  )
}