summaryrefslogtreecommitdiff
path: root/lib/pq/table/pq-lists-table.tsx
blob: 1be0a1c7d2a0d2661961e97217f00f29395f5da8 (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
"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
import { toast } from "sonner"

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 { createPQListsColumns, type PQList } from "./pq-lists-columns"
import {
  createPQListAction,
  deletePQListsAction,
  copyPQListAction,
  togglePQListsAction,
  updatePqValidToAction,
} from "@/lib/pq/service"
import { CopyPqDialog } from "./copy-pq-list-dialog"
import { AddPqDialog } from "./add-pq-list-dialog"
import { PQListsToolbarActions } from "./pq-lists-toolbar"
import { EditValidToSheet } from "./pq-lists-columns"
import type { DataTableRowAction } from "@/types/table"

interface Project {
  id: number
  name: string
  code: string
}

interface PqListsTableProps {
  promises: Promise<[{ data: PQList[]; pageCount: number }, Project[]]>
}

export function PqListsTable({ promises }: PqListsTableProps) {
  const router = useRouter()
  const [rowAction, setRowAction] = React.useState<DataTableRowAction<PQList> | null>(null)
  const [createDialogOpen, setCreateDialogOpen] = React.useState(false)
  const [copyDialogOpen, setCopyDialogOpen] = React.useState(false)
  const [editValidToSheetOpen, setEditValidToSheetOpen] = React.useState(false)
  const [selectedPqList, setSelectedPqList] = React.useState<PQList | null>(null)
  const [isPending, startTransition] = React.useTransition()

  const [{ data, pageCount }, projects] = React.use(promises)
  // const activePqLists = data.filter((item) => !item.isDeleted)

  const columns = React.useMemo(() => createPQListsColumns({ setRowAction }), [setRowAction])

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

  const handleCreate = async (formData: {
    name: string
    type: "GENERAL" | "PROJECT" | "NON_INSPECTION"
    projectId?: number | null
    validTo?: Date | null
  }) => {
    startTransition(async () => {
      const result = await createPQListAction(formData)
      if (result.success) {
        toast.success("PQ 목록이 생성되었습니다")
        setCreateDialogOpen(false)
        router.refresh()
      } else {
        toast.error(result.error || "PQ 목록 생성 실패")
      }
    })
  }

  const handleToggleActive = async (ids: number[], newIsDeleted: boolean) => {
    startTransition(async () => {
      const result = await togglePQListsAction(ids, newIsDeleted)
      if (result.success) {
        toast.success(newIsDeleted ? "PQ 목록이 비활성화되었습니다" : "PQ 목록이 활성화되었습니다")
        router.refresh()
      } else {
        toast.error("PQ 목록 상태 변경 실패")
      }
    })
  }

  const handleDelete = async (ids: number[]) => {
    startTransition(async () => {
      const result = await deletePQListsAction(ids)
      if (result.success) {
        toast.success("PQ 목록이 삭제되었습니다")
        router.refresh()
      } else {
        toast.error("PQ 목록 삭제 실패")
      }
    })
  }

  const handleCopy = async (copyData: {
    sourcePqListId: number
    targetProjectId: number
    newName?: string
    validTo?: Date | null
  }) => {
    startTransition(async () => {
      const result = await copyPQListAction(copyData)
      if (result.success) {
        toast.success("PQ 목록이 복사되었습니다")
        setCopyDialogOpen(false)
        router.refresh()
      } else {
        toast.error("PQ 목록 복사 실패")
      }
    })
  }

  const handleUpdateValidTo = React.useCallback(async (pqListId: number, newValidTo: Date | null) => {
    startTransition(async () => {
      try {
        const result = await updatePqValidToAction({ pqListId, validTo: newValidTo })
        if (result.success) {
          toast.success(result.message || "유효일이 성공적으로 수정되었습니다")
          setEditValidToSheetOpen(false)
          setSelectedPqList(null)
          router.refresh()
        } else {
          toast.error(`유효일 수정 실패: ${result.error}`)
        }
      } catch (error) {
        console.error("유효일 수정 실패:", error)
        toast.error("유효일 수정 실패")
      }
    })
  }, [])

  React.useEffect(() => {
    if (!rowAction) return
    const pqList = rowAction.row.original
    switch (rowAction.type) {
      case "view":
        router.push(`/evcp/pq-criteria/${pqList.id}`)
        break
      case "delete":
        handleDelete([pqList.id])
        break
      case "editValidTo":
        setSelectedPqList(pqList)
        setEditValidToSheetOpen(true)
        break
    }
    setRowAction(null)
  }, [rowAction])

  return (
    <>
      <DataTable table={table}>
        <DataTableAdvancedToolbar
          table={table}
          filterFields={[]}
          shallow={false}
        >
          <PQListsToolbarActions
            table={table}
            onAddClick={() => setCreateDialogOpen(true)}
            onCopyClick={() => setCopyDialogOpen(true)}
            onToggleActive={(rows, newIsDeleted) =>
              handleToggleActive(rows.map((r) => r.id), newIsDeleted)
            }
          />
        </DataTableAdvancedToolbar>
      </DataTable>

      <AddPqDialog
        open={createDialogOpen}
        onOpenChange={setCreateDialogOpen}
        onSubmit={handleCreate}
        isLoading={isPending}
      />

      <CopyPqDialog
        open={copyDialogOpen}
        onOpenChange={setCopyDialogOpen}
        pqLists={data}
        projects={projects}
        onCopy={handleCopy}
        isLoading={isPending}
      />

      <EditValidToSheet
        pqList={selectedPqList}
        open={editValidToSheetOpen}
        onOpenChange={setEditValidToSheetOpen}
        onUpdate={handleUpdateValidTo}
      />
    </>
  )
}