summaryrefslogtreecommitdiff
path: root/lib/vendors/contacts-table/contact-table.tsx
blob: c0e7629299276dcee0d28253efa7b69c590d87c3 (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
"use client"

import * as React from "react"
import type {
  DataTableAdvancedFilterField,
  DataTableFilterField,
  DataTableRowAction,
} from "@/types/table"

import { toSentenceCase } from "@/lib/utils"
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 { useFeatureFlags } from "./feature-flags-provider"
import { getColumns } from "./contact-table-columns"
import { getVendorContacts, deleteVendorContact } from "../service"
import { VendorContact, vendors } from "@/db/schema/vendors"
import { VendorsTableToolbarActions } from "./contact-table-toolbar-actions"
import { EditContactDialog } from "./edit-contact-dialog"
import { toast } from "sonner"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"

interface VendorsTableProps {
  promises: Promise<
    [
      Awaited<ReturnType<typeof getVendorContacts>>,
    ]
  >, 
  vendorId:number
}

export function VendorContactsTable({ promises , vendorId}: VendorsTableProps) {
  const { featureFlags } = useFeatureFlags()

  // Suspense로 받아온 데이터
  const [{ data, pageCount }] = React.use(promises)

  const [rowAction, setRowAction] = React.useState<DataTableRowAction<VendorContact> | null>(null)
  const [editDialogOpen, setEditDialogOpen] = React.useState(false)
  const [selectedContact, setSelectedContact] = React.useState<VendorContact | null>(null)
  const [deleteDialogOpen, setDeleteDialogOpen] = React.useState(false)
  const [isDeleting, setIsDeleting] = React.useState(false)

  // Edit 액션 처리
  React.useEffect(() => {
    if (rowAction?.type === "update") {
      setSelectedContact(rowAction.row.original)
      setEditDialogOpen(true)
      setRowAction(null)
    } else if (rowAction?.type === "delete") {
      setSelectedContact(rowAction.row.original)
      setDeleteDialogOpen(true)
      setRowAction(null)
    }
  }, [rowAction])

  // Delete 액션 처리 함수
  const handleDelete = React.useCallback(async () => {
    if (!selectedContact) return

    setIsDeleting(true)
    try {
      const result = await deleteVendorContact({
        id: selectedContact.id,
        vendorId: vendorId
      })

      if (result.success) {
        toast.success(result.message)
        // 페이지를 새로고침하거나 데이터를 다시 가져오기
        window.location.reload()
      } else {
        toast.error(result.message)
      }
    } catch (error) {
      toast.error("Failed to delete contact")
      console.error("Error deleting contact:", error)
    } finally {
      setIsDeleting(false)
      setDeleteDialogOpen(false)
      setSelectedContact(null)
    }
  }, [selectedContact, vendorId])

  // 데이터 새로고침 함수
  const handleEditSuccess = React.useCallback(() => {
    // 페이지를 새로고침하거나 데이터를 다시 가져오기
    window.location.reload()
  }, [])

  // getColumns() 호출 시, router를 주입
  const columns = React.useMemo(
    () => getColumns({ setRowAction }),
    [setRowAction]
  )

  const filterFields: DataTableFilterField<VendorContact>[] = [
    
  ]

  const advancedFilterFields: DataTableAdvancedFilterField<VendorContact>[] = [
    { id: "contactName", label: "Contact Name", type: "text" },
    { id: "contactPosition", label: "Contact Position", type: "text" },
    { id: "contactEmail", label: "Contact Email", type: "text" },
    { id: "contactPhone", label: "Contact Phone", type: "text" },
    { id: "createdAt", label: "Created at", type: "date" },
    { id: "updatedAt", label: "Updated at", type: "date" },
  ]

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

  return (
    <>
      <DataTable
        table={table}
      >
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
        >
          <VendorsTableToolbarActions table={table} vendorId={vendorId} />
        </DataTableAdvancedToolbar>
      </DataTable>

      <EditContactDialog
        contact={selectedContact}
        open={editDialogOpen}
        onOpenChange={setEditDialogOpen}
        onSuccess={handleEditSuccess}
      />

      {/* Delete 확인 다이얼로그 */}
      {selectedContact && (
        <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>연락처 삭제</DialogTitle>
              <DialogDescription>
                정말로 "{selectedContact.contactName}" 연락처를 삭제하시겠습니까?
                이 작업은 되돌릴 수 없습니다.
              </DialogDescription>
            </DialogHeader>
            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => setDeleteDialogOpen(false)}
                disabled={isDeleting}
              >
                취소
              </Button>
              <Button
                variant="destructive"
                onClick={handleDelete}
                disabled={isDeleting}
              >
                {isDeleting ? "삭제 중..." : "삭제"}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      )}
    </>
  )
}