📦 EqualifyEverything / equalify

📄 InvitesTable.tsx · 303 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
303import styles from "./InvitesTable.module.css";
import { 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 Invite {
  id: string;
  email: string;
  created_at: string;
}

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

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

  // Mutation to create invite
  const createInviteMutation = useMutation({
    mutationFn: async (email: string) => {
      // Call the backend API to send invite
      const response = await (
        await API.post({
          apiName: "auth",
          path: "/inviteUser",
          options: {
            body: { email },
          },
        }).response
      ).body.json();
      if (response?.status === "error") {
        console.error("Failed to create invite:", response?.message);
        window.alert(`Failed to send invite: ${response?.message}`);
        setAnnounceMessage(`Failed to send invite: ${response?.message}`, "error");
      } else if (response?.status === "success") {
        queryClient.invalidateQueries({ queryKey: ["invites"] });
        setNewEmail("");
        setAnnounceMessage("Invite sent successfully!", "success");
      }
    },
  });

  // Mutation to delete invite
  const deleteInviteMutation = useMutation({
    mutationFn: async (inviteId: string) => {
      await apiClient.graphql({
        query: `mutation($id: uuid!) {
          delete_invites_by_pk(id: $id) {
            id
          }
        }`,
        variables: { id: inviteId },
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["invites"] });
      setAnnounceMessage("Invite deleted", "success");
    },
  });

  const columns = useMemo<ColumnDef<Invite>[]>(
    () => [
      {
        accessorKey: "email",
        header: "Email",
        cell: ({ getValue }) => {
          const email = getValue() as string;
          return <span className="text-sm">{email}</span>;
        },
      },
      {
        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 }) => {
          const inviteId = getValue() as string;
          return (
            <StyledButton
              variant="red"
              label={deleteInviteMutation.isPending ? "Deleting..." : "Delete"}
              onClick={() => deleteInviteMutation.mutate(inviteId)}
              aria-label={`Delete invite`}
              disabled={deleteInviteMutation.isPending}
            />
          );
        },
      },
    ],
    [deleteInviteMutation]
  );

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

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (newEmail.trim()) {
      createInviteMutation.mutate(newEmail.trim());
    }
  };

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

  return (
    <div className={styles.InvitesTable}>
      <div className="flex flex-row items-center justify-between mb-4">
        <h2>Invites</h2>
        <form onSubmit={handleSubmit} className="flex items-center gap-2">
          <input
            type="email"
            value={newEmail}
            onChange={(e) => setNewEmail(e.target.value)}
            placeholder="Email address"
            required
            aria-label="Email address for invite"
          />
          <StyledButton
            variant="green"
            label={createInviteMutation.isPending ? "Sending..." : "Invite"}
            onClick={() => {}}
            type="submit"
            inline
            disabled={createInviteMutation.isPending}
          />
        </form>
      </div>

      {isLoading ? (
        <SkeletonTable columns={3} rows={3} headers={["Email", "Created At", "Actions"]} />
      ) : (
        <>
          <div className="table-container">
            <table
              className="w-full border-collapse border border-gray-300"
              aria-label="Invites 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 invites 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="text">
                Showing {data?.invites?.length || 0} of {data?.totalCount || 0}{" "}
                invites
                {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>
  );
};