-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathgroups.ts
More file actions
448 lines (400 loc) · 11.4 KB
/
Copy pathgroups.ts
File metadata and controls
448 lines (400 loc) · 11.4 KB
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
import type { QueryClient, UseQueryOptions } from "react-query";
import { API } from "#/api/api";
import { isApiError } from "#/api/errors";
import type {
CreateGroupRequest,
Group,
GroupAIBudget,
GroupMembersAISpend,
GroupMembersResponse,
GroupRequest,
OrganizationGroupsAISpend,
PaginatedGroupsRequest,
PaginatedGroupsResponse,
PatchGroupRequest,
UsersRequest,
} from "#/api/typesGenerated";
import type { UsePaginatedQueryOptions } from "#/hooks/usePaginatedQuery";
import { prepareQuery } from "#/utils/filters";
type GroupSortOrder = "asc" | "desc";
export const groupsQueryKey = ["groups"];
/** @public */
export const groups = () => {
return {
queryKey: groupsQueryKey,
queryFn: () => API.getGroups(),
} satisfies UseQueryOptions<Group[]>;
};
const getGroupsByOrganizationQueryKey = (organization: string) => [
"organization",
organization,
"groups",
];
export const groupsByOrganization = (organization: string) => {
return {
queryKey: getGroupsByOrganizationQueryKey(organization),
queryFn: () => API.getGroupsByOrganization(organization),
} satisfies UseQueryOptions<Group[]>;
};
const getOrganizationGroupsAISpendQueryKey = (
organization: string,
groupIds: readonly string[],
) => [
...getGroupsByOrganizationQueryKey(organization),
"aiSpend",
[...groupIds].sort(),
];
export const organizationGroupsAISpend = (
organization: string,
groupIds: readonly string[],
) => {
return {
queryKey: getOrganizationGroupsAISpendQueryKey(organization, groupIds),
queryFn: () => API.getOrganizationGroupsAISpend(organization, groupIds),
} satisfies UseQueryOptions<OrganizationGroupsAISpend>;
};
export const getGroupMembersAISpendQueryKey = (
groupId: string,
userIds: readonly string[],
) => ["group", groupId, "members", "aiSpend", [...userIds].sort()];
const isGroupMembersAISpendQueryKey = (
queryKey: readonly unknown[],
userId: string,
): boolean =>
queryKey[0] === "group" &&
queryKey[2] === "members" &&
queryKey[3] === "aiSpend" &&
Array.isArray(queryKey[4]) &&
queryKey[4].includes(userId);
export const invalidateGroupMembersAISpend = (
queryClient: QueryClient,
userId: string,
) =>
queryClient.invalidateQueries({
queryKey: ["group"],
predicate: (query) => isGroupMembersAISpendQueryKey(query.queryKey, userId),
});
export const groupMembersAISpend = (
groupId: string,
userIds: readonly string[],
) => {
return {
queryKey: getGroupMembersAISpendQueryKey(groupId, userIds),
queryFn: () => API.getGroupMembersAISpend(groupId, userIds),
} satisfies UseQueryOptions<GroupMembersAISpend>;
};
const getPaginatedGroupsByOrganizationQueryKey = (
organization: string,
req?: PaginatedGroupsRequest,
) => {
// Nested under the org groups key so create/patch/delete invalidations,
// which target ["organization", org, "groups"], also cover this list.
const base = [...getGroupsByOrganizationQueryKey(organization), "paginated"];
return req ? [...base, req] : base;
};
export function paginatedGroupsByOrganization(
organization: string,
searchParams: URLSearchParams,
): UsePaginatedQueryOptions<PaginatedGroupsResponse, PaginatedGroupsRequest> {
return {
searchParams,
queryPayload: ({ limit, offset }) => {
return {
limit,
offset,
q: prepareQuery(searchParams.get("filter") ?? ""),
};
},
queryKey: ({ payload }) =>
getPaginatedGroupsByOrganizationQueryKey(organization, payload),
queryFn: ({ payload }) =>
API.getOrganizationPaginatedGroups(organization, payload),
};
}
const getRootGroupQueryKey = (organization: string, groupName: string) => [
"organization",
organization,
"group",
groupName,
];
export const getGroupByIdQueryKey = (groupId: string, req: GroupRequest) => [
"group",
groupId,
req,
];
export const groupById = (
groupId: string,
req: GroupRequest,
): UseQueryOptions<Group> => {
return {
queryKey: getGroupByIdQueryKey(groupId, req),
queryFn: ({ signal }) => API.getGroupById(groupId, req, signal),
};
};
export const getGroupQueryKey = (
organization: string,
groupName: string,
req: GroupRequest,
) => {
const base = getRootGroupQueryKey(organization, groupName);
return [...base, req];
};
export const group = (
organization: string,
groupName: string,
req: GroupRequest,
): UseQueryOptions<Group> => {
return {
queryKey: getGroupQueryKey(organization, groupName, req),
queryFn: ({ signal }) => API.getGroup(organization, groupName, req, signal),
};
};
export const getGroupMembersQueryKey = (
organization: string,
groupName: string,
req?: UsersRequest,
) => {
const base = [...getRootGroupQueryKey(organization, groupName), "members"];
return req ? [...base, req] : base;
};
export function groupMembers(
organization: string,
groupName: string,
searchParams: URLSearchParams,
): UsePaginatedQueryOptions<GroupMembersResponse, UsersRequest> {
return {
searchParams,
queryPayload: ({ limit, offset }) => {
return {
limit,
offset,
q: prepareQuery(searchParams.get("filter") ?? ""),
};
},
queryKey: ({ payload }) =>
getGroupMembersQueryKey(organization, groupName, payload),
queryFn: ({ payload, signal }) =>
API.getGroupMembers(organization, groupName, payload, signal),
};
}
export const getGroupMemberAvatarsQueryKey = (
organization: string,
groupName: string,
limit: number,
) => [...getGroupMembersQueryKey(organization, groupName), "avatars", limit];
/** Number of member avatars previewed per group row in list views. */
export const GROUP_MEMBER_AVATAR_LIMIT = 5;
/**
* A capped page of a group's members for avatar previews in list views. The
* paginated groups endpoint no longer returns rosters, so rows fetch a small
* preview lazily. Nests under the group members key so membership mutations
* invalidate it.
*/
export const groupMemberAvatars = (
organization: string,
groupName: string,
limit: number,
): UseQueryOptions<GroupMembersResponse> => {
return {
queryKey: getGroupMemberAvatarsQueryKey(organization, groupName, limit),
queryFn: ({ signal }) =>
API.getGroupMembers(organization, groupName, { limit }, signal),
};
};
export type GroupsByUserId = Readonly<Map<string, readonly Group[]>>;
export function groupsByUserId() {
return {
...groups(),
select: selectGroupsByUserId,
} satisfies UseQueryOptions<Group[], unknown, GroupsByUserId>;
}
export function groupsByUserIdInOrganization(organization: string) {
return {
...groupsByOrganization(organization),
select: selectGroupsByUserId,
} satisfies UseQueryOptions<Group[], unknown, GroupsByUserId>;
}
function selectGroupsByUserId(groups: Group[]): GroupsByUserId {
// Sorting here means that nothing has to be sorted for the individual
// user arrays later
const sorted = sortGroupsByName(groups, "asc");
const userIdMapper = new Map<string, Group[]>();
for (const group of sorted) {
for (const user of group.members) {
let groupsForUser = userIdMapper.get(user.id);
if (groupsForUser === undefined) {
groupsForUser = [];
userIdMapper.set(user.id, groupsForUser);
}
groupsForUser.push(group);
}
}
return userIdMapper as GroupsByUserId;
}
export const getGroupsForUserQueryKey = (
userId: string,
organizationId?: string,
) => [
...groupsQueryKey,
"user",
userId,
...(organizationId ? ["organization", organizationId] : []),
];
export function groupsForUser(userId: string, organizationId?: string) {
return {
queryKey: getGroupsForUserQueryKey(userId, organizationId),
queryFn: () => API.getGroups({ userId, organization: organizationId }),
} as const satisfies UseQueryOptions<Group[]>;
}
export const groupPermissionsKey = (groupId: string) => [
"group",
groupId,
"permissions",
];
export const groupPermissions = (groupId: string) => {
return {
queryKey: groupPermissionsKey(groupId),
queryFn: () =>
API.checkAuthorization({
checks: {
canUpdateGroup: {
object: {
resource_type: "group",
resource_id: groupId,
},
action: "update",
},
},
}),
};
};
export const createGroup = (queryClient: QueryClient, organization: string) => {
return {
mutationFn: (request: CreateGroupRequest) =>
API.createGroup(organization, request),
onSuccess: async () => {
await queryClient.invalidateQueries({
queryKey: groupsQueryKey,
});
await queryClient.invalidateQueries({
queryKey: getGroupsByOrganizationQueryKey(organization),
});
},
};
};
export const patchGroup = (queryClient: QueryClient, organization: string) => {
return {
mutationFn: ({
groupId,
...request
}: PatchGroupRequest & { groupId: string }) =>
API.patchGroup(groupId, request),
onSuccess: async (updatedGroup: Group) =>
invalidateGroup(queryClient, organization, updatedGroup.name),
};
};
export const deleteGroup = (queryClient: QueryClient, organization: string) => {
return {
mutationFn: ({ groupId }: { groupId: string; groupName: string }) =>
API.deleteGroup(groupId),
onSuccess: async (
_: unknown,
{ groupName }: { groupId: string; groupName: string },
) => invalidateGroup(queryClient, organization, groupName),
};
};
export const addMembers = (queryClient: QueryClient, organization: string) => {
return {
mutationFn: ({
groupId,
userIds,
}: {
groupId: string;
userIds: string[];
}) => API.addMembers(groupId, userIds),
onSuccess: async (updatedGroup: Group) =>
invalidateGroup(queryClient, organization, updatedGroup.name),
};
};
export const removeMember = (
queryClient: QueryClient,
organization: string,
) => {
return {
mutationFn: ({ groupId, userId }: { groupId: string; userId: string }) =>
API.removeMember(groupId, userId),
onSuccess: async (updatedGroup: Group) =>
invalidateGroup(queryClient, organization, updatedGroup.name),
};
};
const getGroupAIBudgetQueryKey = (groupId: string) => [
"group",
groupId,
"aiBudget",
];
/** Budget query; resolves to null when none is set (the GET 404s). */
export const groupAIBudget = (
groupId: string,
): UseQueryOptions<GroupAIBudget | null> => {
return {
queryKey: getGroupAIBudgetQueryKey(groupId),
queryFn: async () => {
try {
return await API.getGroupAIBudget(groupId);
} catch (error) {
if (isApiError(error) && error.response.status === 404) {
return null;
}
throw error;
}
},
};
};
/* Upserts the budget for a value, or deletes it (uncapped) when given null. */
export const saveGroupAIBudget = (
queryClient: QueryClient,
groupId: string,
) => {
return {
mutationFn: async (spendLimitMicros: number | null) => {
if (spendLimitMicros === null) {
await API.deleteGroupAIBudget(groupId);
} else {
await API.upsertGroupAIBudget(groupId, {
spend_limit_micros: spendLimitMicros,
});
}
},
onSuccess: async () =>
queryClient.invalidateQueries({
queryKey: getGroupAIBudgetQueryKey(groupId),
}),
};
};
const invalidateGroup = (
queryClient: QueryClient,
organization: string,
groupName: string,
) =>
Promise.all([
queryClient.invalidateQueries({ queryKey: groupsQueryKey }),
queryClient.invalidateQueries({
queryKey: getGroupsByOrganizationQueryKey(organization),
}),
queryClient.invalidateQueries({
queryKey: getRootGroupQueryKey(organization, groupName),
}),
]);
function sortGroupsByName<T extends Group>(
groups: readonly T[],
order: GroupSortOrder,
) {
return [...groups].sort((g1, g2) => {
const key = g1.display_name && g2.display_name ? "display_name" : "name";
const direction = order === "asc" ? 1 : -1;
if (g1[key] === g2[key]) {
return 0;
}
return (g1[key] < g2[key] ? -1 : 1) * direction;
});
}