📦 EqualifyEverything / equalify

📄 UsersTable.tsx · 319 lines
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
319import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  useReactTable,
  getCoreRowModel,
  flexRender,
  ColumnDef,
} from "@tanstack/react-table";
import * as API from "aws-amplify/api";
import { useState, useMemo } from "react";
import { useGlobalStore } from "../utils";
import { SkeletonTable } from "./Skeleton";
import { StyledButton } from "./StyledButton";

const apiClient = API.generateClient();

interface User {
  id: string;
  email: string;
  name: string;
  type: string;
  created_at: string;
}

export const UsersTable = () => {
  const queryClient = useQueryClient();
  const [page, setPage] = useState(0);
  const [pageSize, setPageSize] = useState(50);
  const { setAnnounceMessage } = useGlobalStore();

  // Query to get users
  const { data, isLoading, error } = useQuery({
    queryKey: ["users", page, pageSize],
    queryFn: async () => {
      const response = await apiClient.graphql({
        query: `query($limit: Int!, $offset: Int!) {
          users(
            limit: $limit, 
            offset: $offset, 
            order_by: {created_at: desc}
          ) {
            id
            email
            name
            type
            created_at
          }
          users_aggregate {
            aggregate {
              count
            }
          }
        }`,
        variables: {
          limit: pageSize,
          offset: page * pageSize,
        },
      });
      const data = response as any;
      return {
        users: data.data.users,
        totalCount: data.data.users_aggregate.aggregate.count,
        totalPages: Math.ceil(
          data.data.users_aggregate.aggregate.count / pageSize
        ),
      };
    },
  });

  // Mutation to update user type
  const updateTypeMutation = useMutation({
    mutationFn: async ({ userId, type }: { userId: string; type: string }) => {
      await apiClient.graphql({
        query: `mutation($id: uuid!, $type: String!) {
          update_users_by_pk(pk_columns: {id: $id}, _set: {type: $type}) {
            id
            type
          }
        }`,
        variables: { id: userId, type },
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["users"] });
      setAnnounceMessage("User type updated successfully!", "success");
    },
    onError: (error) => {
      console.error("Failed to update type:", error);
      setAnnounceMessage("Failed to update user type", "error");
    },
  });

  // Mutation to delete user
  const deleteUserMutation = useMutation({
    mutationFn: async (userId: string) => {
      await apiClient.graphql({
        query: `mutation($id: uuid!) {
          delete_users_by_pk(id: $id) {
            id
          }
        }`,
        variables: { id: userId },
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["users"] });
      setAnnounceMessage("User removed.", "success");
    },
  });

  const columns = useMemo<ColumnDef<User>[]>(
    () => [
      {
        accessorKey: "name",
        header: "Name",
        cell: ({ getValue }) => {
          const name = getValue() as string;
          return <span className="text-sm">{name || "N/A"}</span>;
        },
      },
      {
        accessorKey: "email",
        header: "Email",
        cell: ({ getValue }) => {
          const email = getValue() as string;
          return <span className="text-sm">{email}</span>;
        },
      },
      {
        accessorKey: "type",
        header: "Type",
        cell: ({ getValue, row }) => {
          const currentType = getValue() as string;
          const userId = row.original.id;
          return (
            <select
              value={currentType || "user"}
              onChange={(e) =>
                updateTypeMutation.mutate({
                  userId,
                  type: e.target.value,
                })
              }
              className="px-2 py-1 border rounded text-sm"
              aria-label={`Change type for ${row.original.email}`}
            >
              <option value="member">Member</option>
              <option value="admin">Admin</option>
            </select>
          );
        },
      },
      {
        accessorKey: "created_at",
        header: "Created At",
        cell: ({ getValue }) => {
          const date = getValue() as string;
          return (
            <span className="text-sm whitespace-nowrap">
              {new Date(date).toLocaleDateString()}
            </span>
          );
        },
      },
      {
        accessorKey: "id",
        header: "Actions",
        cell: ({ getValue, row }) => {
          const userId = getValue() as string;
          return (
            <StyledButton
              variant="red"
              label={deleteUserMutation.isPending ? "Removing..." : "Remove"}
              onClick={() => {
                if (
                  confirm(
                    `Are you sure you want to remove ${row.original.email}?`
                  )
                ) {
                  deleteUserMutation.mutate(userId);
                }
              }}
              aria-label={`Remove user ${row.original.email}`}
              disabled={deleteUserMutation.isPending}
            />
          );
        },
      },
    ],
    [updateTypeMutation, deleteUserMutation]
  );

  const table = useReactTable({
    data: data?.users || [],
    columns,
    getCoreRowModel: getCoreRowModel(),
    manualPagination: true,
    pageCount: data?.totalPages || 0,
  });

  if (error) {
    return (
      <div className="text-red-600">Error loading users: {String(error)}</div>
    );
  }

  return (
    <div className="mt-8">
      <div className="flex flex-row items-center justify-between mb-4">
        <h2>Users</h2>
      </div>

      {isLoading ? (
        <SkeletonTable columns={5} rows={5} headers={["Name", "Email", "Type", "Created At", "Actions"]} />
      ) : (
        <>
          <div className="table-container">
            <table
              className="w-full border-collapse border border-gray-300"
              aria-label="Users table"
            >
              <thead>
                {table.getHeaderGroups().map((headerGroup) => (
                  <tr key={headerGroup.id} className="bg-gray-100">
                    {headerGroup.headers.map((header) => (
                      <th
                        key={header.id}
                        scope="col"
                        className="border border-gray-300 px-4 py-2 text-left font-semibold"
                      >
                        {header.isPlaceholder
                          ? null
                          : flexRender(
                              header.column.columnDef.header,
                              header.getContext()
                            )}
                      </th>
                    ))}
                  </tr>
                ))}
              </thead>
              <tbody>
                {table.getRowModel().rows.length === 0 ? (
                  <tr>
                    <td
                      colSpan={columns.length}
                      className="border border-gray-300 px-4 py-8 text-center text-gray-500"
                    >
                      No users found
                    </td>
                  </tr>
                ) : (
                  table.getRowModel().rows.map((row, index) => (
                    <tr
                      key={row.id}
                      className={index % 2 === 0 ? "bg-white" : "bg-gray-50"}
                    >
                      {row.getVisibleCells().map((cell) => (
                        <td
                          key={cell.id}
                          className="border border-gray-300 px-4 py-2"
                        >
                          {flexRender(
                            cell.column.columnDef.cell,
                            cell.getContext()
                          )}
                        </td>
                      ))}
                    </tr>
                  ))
                )}
              </tbody>
            </table>

            {/* Pagination Controls */}
            <div
              className="pagination"
              role="navigation"
              aria-label="Pagination"
              
            >
              <div className="pagination-text">
                Showing {data?.users?.length || 0} of {data?.totalCount || 0}{" "}
                users
                {data && ` (Page ${page + 1} of ${data.totalPages})`}
              </div>
              <div className="pagination-buttons">
                <StyledButton
                  label="First"
                  onClick={() => setPage(0)}
                  disabled={page === 0}
                  aria-label="Go to first page"
                />
                <StyledButton
                  label="Previous"
                  onClick={() => setPage((p) => Math.max(0, p - 1))}
                  disabled={page === 0}
                  aria-label="Go to previous page"
                />
                <StyledButton
                  label="Next"
                  onClick={() => setPage((p) => p + 1)}
                  disabled={!data || page >= data.totalPages - 1}
                  aria-label="Go to next page"
                />
                <StyledButton
                  label="Last"
                  onClick={() => data && setPage(data.totalPages - 1)}
                  disabled={!data || page >= data.totalPages - 1}
                  aria-label="Go to last page"
                />
              </div>
            </div>
          </div>
        </>
      )}
    </div>
  );
};