summaryrefslogtreecommitdiff
path: root/lib/vendor-investigation/table/investigation-table-columns.tsx
blob: fd76a9a5f340d1631f3020a04807aef7646fb722 (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
"use client"

import * as React from "react"
import { ColumnDef } from "@tanstack/react-table"
import { Checkbox } from "@/components/ui/checkbox"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Ellipsis, Users, Boxes } from "lucide-react"
// import { toast } from "sonner" // If needed
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import { formatDate } from "@/lib/utils" // or your date util

// Example: If you have a type for row actions
import { type DataTableRowAction } from "@/types/table"
import { ContactItem, PossibleItem, vendorInvestigationsColumnsConfig, VendorInvestigationsViewWithContacts } from "@/config/vendorInvestigationsColumnsConfig"

// Props that define how we handle special columns (contacts, items, actions, etc.)
interface GetVendorInvestigationsColumnsProps {
  setRowAction?: React.Dispatch<
    React.SetStateAction<
      DataTableRowAction<VendorInvestigationsViewWithContacts> | null
    >
  >
  openContactsModal?: (investigationId: number, contacts: ContactItem[]) => void
  openItemsDrawer?: (investigationId: number, items: PossibleItem[]) => void
}

// This function returns the array of columns for TanStack Table
export function getColumns({
  setRowAction,
  openContactsModal,
  openItemsDrawer,
}: GetVendorInvestigationsColumnsProps): ColumnDef<
  VendorInvestigationsViewWithContacts
>[] {
  // --------------------------------------------
  // 1) Select (checkbox) column
  // --------------------------------------------
  const selectColumn: ColumnDef<VendorInvestigationsViewWithContacts> = {
    id: "select",
    header: ({ table }) => (
      <Checkbox
        checked={
          table.getIsAllPageRowsSelected() ||
          (table.getIsSomePageRowsSelected() && "indeterminate")
        }
        onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
        aria-label="Select all"
        className="translate-y-0.5"
      />
    ),
    cell: ({ row }) => (
      <Checkbox
        checked={row.getIsSelected()}
        onCheckedChange={(value) => row.toggleSelected(!!value)}
        aria-label="Select row"
        className="translate-y-0.5"
      />
    ),
    size: 40,
    enableSorting: false,
    enableHiding: false,
  }

  // --------------------------------------------
  // 2) Actions column (optional)
  // --------------------------------------------
  const actionsColumn: ColumnDef<VendorInvestigationsViewWithContacts> = {
    id: "actions",
    enableHiding: false,
    cell: ({ row }) => {
      const inv = row.original

      return (
        <Button
          variant="ghost"
          className="flex size-8 p-0 data-[state=open]:bg-muted"
          aria-label="Open menu"
          onClick={() => {
            // e.g. open a dropdown or set your row action
            setRowAction?.({ type: "update", row })
          }}
        >
          <Ellipsis className="size-4" aria-hidden="true" />
        </Button>
      )
    },
    size: 40,
  }

  // --------------------------------------------
  // 3) Contacts column (badge count -> open modal)
  // --------------------------------------------
  const contactsColumn: ColumnDef<VendorInvestigationsViewWithContacts> = {
    id: "contacts",
    header: "Contacts",
    cell: ({ row }) => {
      const { contacts, investigationId } = row.original
      const count = contacts?.length ?? 0

      const handleClick = () => {
        openContactsModal?.(investigationId, contacts)
      }

      return (
        <Button
          variant="ghost"
          size="sm"
          className="relative h-8 w-8 p-0 group"
          onClick={handleClick}
          aria-label={
            count > 0 ? `View ${count} contacts` : "Add contacts"
          }
        >
          <Users className="h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors" />
          {count > 0 && (
            <Badge
              variant="secondary"
              className="pointer-events-none absolute -top-1 -right-1 h-4 min-w-[1rem] p-0 text-[0.625rem] leading-none flex items-center justify-center"
            >
              {count}
            </Badge>
          )}
          <span className="sr-only">
            {count > 0 ? `${count} Contacts` : "Add Contacts"}
          </span>
        </Button>
      )
    },
    enableSorting: false,
    size: 60,
  }

  // --------------------------------------------
  // 4) Possible Items column (badge count -> open drawer)
  // --------------------------------------------
  const possibleItemsColumn: ColumnDef<VendorInvestigationsViewWithContacts> = {
    id: "possibleItems",
    header: "Items",
    cell: ({ row }) => {
      const { possibleItems, investigationId } = row.original
      const count = possibleItems?.length ?? 0

      const handleClick = () => {
        openItemsDrawer?.(investigationId, possibleItems)
      }

      return (
        <Button
          variant="ghost"
          size="sm"
          className="relative h-8 w-8 p-0 group"
          onClick={handleClick}
          aria-label={
            count > 0 ? `View ${count} items` : "Add items"
          }
        >
          <Boxes className="h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors" />
          {count > 0 && (
            <Badge
              variant="secondary"
              className="pointer-events-none absolute -top-1 -right-1 h-4 min-w-[1rem] p-0 text-[0.625rem] leading-none flex items-center justify-center"
            >
              {count}
            </Badge>
          )}
          <span className="sr-only">
            {count > 0 ? `${count} Items` : "Add Items"}
          </span>
        </Button>
      )
    },
    enableSorting: false,
    size: 60,
  }

  // --------------------------------------------
  // 5) Build "grouped" columns from config
  // --------------------------------------------
  const groupMap: Record<string, ColumnDef<VendorInvestigationsViewWithContacts>[]> = {}

  vendorInvestigationsColumnsConfig.forEach((cfg) => {
    const groupName = cfg.group || "_noGroup"

    if (!groupMap[groupName]) {
      groupMap[groupName] = []
    }

    const childCol: ColumnDef<VendorInvestigationsViewWithContacts> = {
      accessorKey: cfg.id,
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title={cfg.label} />
      ),
      meta: {
        excelHeader: cfg.excelHeader,
        group: cfg.group,
        type: cfg.type,
      },
      cell: ({ row, cell }) => {
        const val = cell.getValue()

        // Example: Format date fields
        if (
          cfg.id === "investigationCreatedAt" ||
          cfg.id === "investigationUpdatedAt" ||
          cfg.id === "scheduledStartAt" ||
          cfg.id === "scheduledEndAt" ||
          cfg.id === "completedAt"
        ) {
          const dateVal = val ? new Date(val as string) : null
          return dateVal ? formatDate(dateVal) : ""
        }

        // Example: You could show an icon for "investigationStatus"
        if (cfg.id === "investigationStatus") {
          return <span className="capitalize">{val as string}</span>
        }

        return val ?? ""
      },
    }

    groupMap[groupName].push(childCol)
  })

  // Turn the groupMap into nested columns
  const nestedColumns: ColumnDef<VendorInvestigationsViewWithContacts>[] = []
  for (const [groupName, colDefs] of Object.entries(groupMap)) {
    if (groupName === "_noGroup") {
      nestedColumns.push(...colDefs)
    } else {
      nestedColumns.push({
        id: groupName,
        header: groupName,
        columns: colDefs,
      })
    }
  }

  // --------------------------------------------
  // 6) Return final columns array
  //    (You can reorder these as you wish.)
  // --------------------------------------------
  return [
    selectColumn,
    ...nestedColumns,
    contactsColumn,
    possibleItemsColumn,
    actionsColumn,
  ]
}