Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 8x 8x 51x 8x 220x 51x 8x 122x 5x 8x 8x 67x 7x 5x 5x 5x 5x 2x 1x 2x 3x 8x 122x 2x 8x 8x 14x 8x 98x 14x 8x 8x 3x 5x 8x 220x 3x 3x 4x 3x 8x 6x | import {
QueryClient,
useMutation,
useQuery,
UseQueryOptions,
} from "react-query";
import { customInstance } from "@services/api";
import {
QKEY_ASSIGNABLE_HOSTS,
QKEY_EVENT_HOSTS,
QKEY_LIST_TEAM_MEMBERS,
} from "@constants/queryKeys";
import { EventHostApiRow } from "@features/Events/EventDetail/host/host.types";
/**
* Host reads for the event page.
*
* Both sections of the Host tab come from the ONE by-product read: the rows
* are this event's assigned members, and `memberStatus` splits them into
* Assigned (`joined`) and Invited (anything else). Invitations are scoped to
* the event on purpose — a host invited to one event must not appear on every
* other event's Host tab, so the merchant-wide member roster is deliberately
* not consulted here.
*/
export type EventHostListResponse = {
data: EventHostApiRow[] | null;
total: number;
};
/**
* The tab renders one un-paginated list, so the read has to ask for the whole
* roster. Left off, the endpoint applies its own `max` of 100 (`lib/web`'s
* `defaultMax`) and truncates `data` silently while `total` keeps the real
* count — the section headings would then quietly under-report the door staff.
* The endpoint puts no ceiling on `max`, and 500 is far above any real event's
* roster.
*/
export const EVENT_HOSTS_MAX = 500;
// customInstance is untyped here (it resolves to `any`), so the response shape
// is pinned on the wrapper's return type instead of a call-site generic.
export const getEventHosts = (
merchantId: number,
productId: string | number,
searchQuery?: string,
): Promise<EventHostListResponse> =>
customInstance({
// Search runs server-side (`q` matches the member's name and email through
// the view's text-search document); default ordering is the endpoint's own
// (assigned_at, then user id).
url: `/merchants/${merchantId}/products/${productId}/members?max=${EVENT_HOSTS_MAX}${
searchQuery ? `&q=${encodeURIComponent(searchQuery)}` : ""
}`,
method: "GET",
});
export const useGetEventHosts = (
merchantId: number,
productId?: string,
searchQuery?: string,
options?: UseQueryOptions<EventHostListResponse>,
) =>
useQuery<EventHostListResponse>(
[QKEY_EVENT_HOSTS, merchantId, productId, searchQuery],
() => getEventHosts(merchantId, productId as string, searchQuery),
{
enabled: Boolean(merchantId && productId),
// Typing re-keys the query per keystroke; keeping the previous rows on
// screen while the next result loads avoids a skeleton flash on each key.
keepPreviousData: true,
...options,
},
);
/**
* Revoke a host: remove the membership outright, taking every event with it
* (assignments cascade off the membership server-side).
*
* This is the same call GiveCash's revoke makes, deliberately: "Revoke" has to
* mean one thing across the two clients, and a merchant reading the word on
* either surface expects the person to stop being a host — not to quietly keep
* access to the merchant's other events.
*/
export const useRevokeHost = (merchantId: number) =>
useMutation(
(memberId: number): Promise<void> =>
customInstance({
url: `/accounts/${merchantId}/members/${memberId}`,
method: "DELETE",
}),
);
export type InviteHostResult = {
/**
* Whether an invitation email actually went out. The API seats an address
* that has already joined some merchant as `joined` right away, with no
* invite row and a "you were added" email instead — so the modal must not
* claim an invitation was sent for those.
*/
invitationSent: boolean;
};
/**
* Invite one email to host this event.
*
* Two calls, because "host" is an account member with an event assignment and
* the API models those separately: create the operator membership (which sends
* the host invite email), then attach this event.
*
* The PATCH replaces the member's whole product set, which is only safe because
* the member is necessarily new here — inviting an address that is already a
* member of this merchant fails the POST with a 409 (ErrMemberExists), so the
* PATCH is never reached for someone who already has assignments to lose. The
* flip side is that an existing host cannot be added to a second event from
* this modal; that needs the roster screen.
*
* The two calls are not one transaction, so the assignment failing has to undo
* the membership: the PATCH rejects an event that has already ended with a 400
* (`ErrProductNotAssignable`), which is deterministic rather than a fluke, and
* without the rollback the merchant is left with a host who was emailed, sits
* on no event, and can never be re-invited because the POST now 409s.
*
* That rollback is scoped to the statuses where the PATCH definitely did not
* apply — see ROLLBACK_STATUSES.
*/
/**
* The PATCH failures the rollback answers: the request was rejected outright, so
* the assignment certainly did not commit and deleting the member is safe.
*
* Deliberately not "any error". A 502/504 (or a dropped connection, which
* carries no status at all) can mean the assignment went through and only the
* response was lost — destroying the membership there would delete a host whose
* invite email has already gone out, and who now has an event.
*/
const ROLLBACK_STATUSES = [400, 404, 422];
export const useInviteEventHost = (merchantId: number, productId?: string) =>
useMutation(async (email: string): Promise<InviteHostResult> => {
const member = await customInstance({
url: `/accounts/${merchantId}/members`,
method: "POST",
data: { email, memberRole: "operator", inviteMember: true },
});
const memberId = member?.user?.accID;
Iif (memberId == null) {
// Hard failure rather than a silent skip: the invitation has gone out, so
// leaving them unassigned would put a host on the roster with no event
// and no signal that the assignment was dropped.
throw new Error("Invite created without a member id.");
}
try {
await customInstance({
url: `/accounts/${merchantId}/members/${memberId}/products`,
method: "PATCH",
data: { productIDs: [Number(productId)] },
});
} catch (error: any) {
// Undo the membership the POST just created, so the address is free to be
// invited again once the cause is fixed. Deleting is safe for the same
// reason the wholesale PATCH is: this member did not exist a moment ago —
// but only where the PATCH is known to have been rejected. A failing
// rollback must not mask why the invite failed, so it is swallowed and the
// original error is what the caller sees.
if (ROLLBACK_STATUSES.includes(error?.response?.status)) {
await customInstance({
url: `/accounts/${merchantId}/members/${memberId}`,
method: "DELETE",
}).catch(() => undefined);
}
throw error;
}
return { invitationSent: member?.memberStatus !== "joined" };
});
/** Re-send a pending host's invitation email. */
export const useResendHostInvite = (merchantId: number) =>
useMutation(
(memberId: number): Promise<void> =>
customInstance({
url: `/accounts/${merchantId}/members/${memberId}/invite`,
method: "POST",
}),
);
/* -------------------------------------------------------------------------- */
/* Assign / unassign an existing host */
/* -------------------------------------------------------------------------- */
/**
* One row of `GET /accounts/{accountID}/members` (`MemberView`) — only the
* fields the Assign Host modal draws. `user` is a nested object on the wire.
*/
export type AccountMemberApiRow = {
roleName: string;
memberStatus: string;
user: {
accID: number;
email: string;
firstName: string;
lastName: string;
imageURL: string;
} | null;
};
export type AccountMemberListResponse = {
data: AccountMemberApiRow[] | null;
total: number;
};
/**
* The modal lists the merchant's whole host bench on one un-paginated
* (virtualized) scroller, so — as with the per-event roster — the read has to
* ask for it. Left off, the endpoint caps at its own `max` of 100 and truncates
* silently. This bounds the read, not the DOM: the list mounts only the rows in
* view.
*
* Deliberately separate from `MEMBER_PRODUCTS_MAX` below even though the two
* currently agree: this one bounds how many hosts the merchant can *see*, and
* lowering it costs a merchant with a long bench nothing but a scroll. The
* other bounds a read whose truncation *deletes* assignments.
*/
export const HOST_BENCH_MAX = 500;
/**
* The merchant's assignable hosts: every `operator` member whose membership is
* live.
*
* `joined` is a PRODUCT decision, not an API constraint. The API would accept
* an assignment for an operator whose invitation is still outstanding — the
* procedure checks the member's role, not their status, which is exactly what
* lets the invite flow attach an event to the member it just created. The
* mockup's empty state rules them out anyway ("The host will be available to
* assign once they accept the invitation and sign in to GiveCash"), because a
* host who has not signed in cannot work the door yet, and this event already
* lists their invitation in the Host tab's Invited section.
*
* Ordering is left to the caller — the endpoint forces no default sort, and the
* modal's own order (this event's hosts first, then alphabetical) is not
* something a single `sort` param can express.
*/
export const getAssignableHosts = (
merchantId: number,
searchQuery?: string,
): Promise<AccountMemberListResponse> =>
customInstance({
// `;` (%3B) is FQL's AND. `q` is the endpoint's own full-text search over
// the member's name and email, the same one the per-event roster uses.
url: `/accounts/${merchantId}/members?max=${HOST_BENCH_MAX}&filter=${encodeURIComponent(
'roleName:"operator"',
)}%3B${encodeURIComponent('memberStatus:"joined"')}${
searchQuery ? `&q=${encodeURIComponent(searchQuery)}` : ""
}`,
method: "GET",
});
export const useGetAssignableHosts = (
merchantId: number,
searchQuery?: string,
options?: UseQueryOptions<AccountMemberListResponse>,
) =>
useQuery<AccountMemberListResponse>(
[QKEY_ASSIGNABLE_HOSTS, merchantId, searchQuery],
() => getAssignableHosts(merchantId, searchQuery),
{
enabled: Boolean(merchantId),
// Typing re-keys the query per keystroke; keeping the previous rows on
// screen avoids a skeleton flash between results.
keepPreviousData: true,
...options,
},
);
/** One row of `GET /accounts/{accountID}/members/{memberID}/products`. */
type MemberProductApiRow = { productID: number };
/**
* The cap on the member's own assignment read.
*
* Not a display concern like `HOST_BENCH_MAX`: whatever this read fails to
* return is absent from the set the PATCH below writes back, so a truncation
* here *unassigns* events. It must stay at or above the number of products a
* single member can hold — never tuned down for the modal's sake.
*/
const MEMBER_PRODUCTS_MAX = 500;
/**
* The events a host currently holds.
*
* Read fresh on every assign/unassign rather than cached: the PATCH below
* replaces the member's WHOLE product set, so a stale set would silently drop
* assignments made elsewhere since the modal opened.
*
* `max` is mandatory here — without it the endpoint caps the list at 100 and
* the PATCH would delete every assignment past that point.
*/
const getMemberProductIDs = async (
merchantId: number,
memberId: number,
): Promise<number[]> => {
const response: { data: MemberProductApiRow[] | null } = await customInstance(
{
url: `/accounts/${merchantId}/members/${memberId}/products?max=${MEMBER_PRODUCTS_MAX}`,
method: "GET",
},
);
return (response?.data ?? []).map((row) => row.productID);
};
export type HostAssignmentVariables = {
memberId: number;
productId: number;
/** True to add this event to the host's set, false to drop it. */
assign: boolean;
};
/**
* Assign one event to an existing host, or take it away.
*
* Read-modify-write, because the API models assignment as the member's whole
* product set: `PATCH .../products` replaces it outright. The read is what
* makes this safe — echoing back the ids the host already holds is what keeps
* their other events (and each grant's original assigner and timestamp, which
* the procedure preserves for ids it sees again).
*
* A grant to a since-deleted event is not echoed back, because the read's view
* drops it; that is the intended outcome — the event is gone.
*/
export const useUpdateHostAssignment = (merchantId: number) =>
useMutation(
async ({
memberId,
productId,
assign,
}: HostAssignmentVariables): Promise<void> => {
const held = await getMemberProductIDs(merchantId, memberId);
const productIDs = assign
? // Guard the duplicate: the handler rejects a set with a repeated id,
// and a double-click can land two assigns before the list refetches.
Array.from(new Set([...held, productId]))
: held.filter((id) => id !== productId);
await customInstance({
url: `/accounts/${merchantId}/members/${memberId}/products`,
method: "PATCH",
data: { productIDs },
});
},
);
/* -------------------------------------------------------------------------- */
/* Cache invalidation */
/* -------------------------------------------------------------------------- */
/**
* Every list a host write lands on.
*
* A host is an account member with an event assignment, so one write is visible
* on three surfaces: the event's Host tab, the Assign Host modal's bench, and
* Settings → Team's per-member event list. The set is non-obvious enough to
* need the explanation, and both callers previously carried their own copy of
* it — it lives here, beside the calls that make it stale, so a fourth surface
* is one edit rather than two that have to agree.
*/
export const invalidateHostRosters = (queryClient: QueryClient) =>
Promise.all([
queryClient.invalidateQueries([QKEY_EVENT_HOSTS]),
queryClient.invalidateQueries([QKEY_ASSIGNABLE_HOSTS]),
queryClient.invalidateQueries(QKEY_LIST_TEAM_MEMBERS),
]);
|