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 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 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 | 489x 577x 489x 356x 489x 9x 9x 12x 12x 10x 10x 10x 9x 1x 8x 8x 1x 7x 7x 4x 489x 10x 489x 27x 489x 97x 80x 489x 26x 489x 15x 15x 15x 28x 27x 27x 27x 22x 22x 22x 27x 15x 22x 22x 22x 489x 81x 150x 489x 32x 24x 7x 17x 489x 13x 13x 11x 11x 11x 11x 50x 50x 50x 50x 45x 45x 45x 50x 11x 11x 10x 8x 8x 8x 8x 7x 489x 51x 43x 15x 15x 18x 489x 5x 489x 7x 7x 7x 10x 6x 6x 5x 5x 5x 7x 489x 12x 8x 7x 7x 5x 6x 5x 489x 9x 9x 9x 10x 9x 489x 7x 5x 5x 6x 5x 5x 5x 5x 5x 6x 5x 5x 5x 489x 489x 40x 11x 489x 55x 25x 489x 131x 6x 9x 6x 5x 2x 489x 489x 489x 46x 46x 52x 52x 52x 52x 39x 39x 39x 39x 39x | import type { SeatingRow, SeatSelection } from "./types";
// Assigned seating (PAY Builder 031) — shared row/seat identity helpers.
//
// Row labels are free-text ("A", "1", "A1"), so the same row can be entered with
// stray casing/whitespace ("A", "a", "A "). Overlap detection (SeatingConfigEditor)
// and the taken/selected seat keys (SeatPicker) must treat those as the SAME row,
// otherwise overlap checks pass when they shouldn't and a booked seat coming back
// from the BE may not match a rendered seat key (showing it as available).
//
// NOTE: confirm this matches BE row-label normalization on the /seating endpoints.
export const normalizeRowLabel = (label: string | undefined | null): string =>
(label ?? "").trim().toUpperCase();
// Canonical key for a single seat, used for both taken and selected lookups.
export const seatKey = (
rowLabel: string | undefined | null,
seatNumber: number,
): string => `${normalizeRowLabel(rowLabel)}:${seatNumber}`;
// PAY Builder 031 — validate the seating rows before the PUT, mirroring the BE
// (EventSeatingRowsReplaceProcedure.Validate): each row needs a label; seats must
// be >= 1 with lastSeat >= firstSeat; and within the SAME row label, ranges must
// not overlap. The same row label MAY repeat with disjoint ranges (e.g. A 1–5 VIP,
// A 6–10 Standard) — so there is intentionally NO unique-label rule. Catching this
// here gives the merchant a precise message instead of a generic 422 on Save.
export const validateSeatingRows = (rows: SeatingRow[]): string | null => {
const rangesByRow = new Map<string, Array<{ first: number; last: number }>>();
for (const r of rows) {
const label = normalizeRowLabel(r.rowLabel);
if (label === "") return "Each seating row needs a row label.";
const first = Number(r.firstSeat);
const last = Number(r.lastSeat);
if (!(first >= 1)) return "First seat must be at least 1.";
if (!(last >= first))
return "Last seat must be greater than or equal to the first seat.";
const existing = rangesByRow.get(label) ?? [];
// overlap test mirrors the BE: [first,last] ∩ [e.first,e.last] ≠ ∅
if (existing.some((e) => first <= e.last && e.first <= last))
return "Seat ranges within the same row must not overlap.";
existing.push({ first, last });
rangesByRow.set(label, existing);
}
return null;
};
// PAY Builder 031 — shape rows for PUT /seating-rows. Keep `id` so the BE upserts
// in place (preserving ids → ticket seatingRowIDs stay valid); drop the read-only
// `variantIDs`; coerce seat numbers (form inputs are strings). firstSeat/lastSeat
// are merchant-entered (Row / First Seat / Last Seat); validateSeatingRows already
// blocks firstSeat < 1, so the clamp below is defense-in-depth for the BE's
// `firstSeat is:"min:1,required"` and an absent value on a half-typed new row.
export const toSeatingRowsPayload = (rows: SeatingRow[]) =>
rows.map(({ variantIDs, firstSeat, lastSeat, ...r }) => ({
...r,
firstSeat: Math.max(1, Number(firstSeat ?? 1) || 1),
lastSeat: Number(lastSeat),
}));
// PAY Builder 031 — decide whether to seed the Assign Seating toggle from the
// authoritative public GET /products/{id}/seating response.
//
// The merchant product detail GET (GET /merchants/{id}/products/{id}) does NOT return
// assignSeating — it is write-only on the product PATCH and read back only by the
// /seating endpoint. So on edit, generateFormData hydrates the toggle to false, the row
// editor (gated on the toggle) never mounts, AND a later Save re-PATCHes
// assignSeating:false (generatePayload always sends it for events), silently wiping the
// saved flag. The provider seeds the toggle from /seating; this guards that seed so it
// only ever turns the toggle ON, only when the server says seating is on, the form still
// shows it off, and the merchant hasn't toggled it this session (so an intentional
// in-session off is never clobbered). Once the BE returns assignSeating on the product
// GET, generateFormData sets it and this becomes a no-op (formAssignSeating guard).
export const shouldSeedAssignSeating = ({
serverAssignSeating,
formAssignSeating,
isFieldDirty,
}: {
serverAssignSeating: boolean | undefined;
formAssignSeating: boolean;
isFieldDirty: boolean;
}): boolean =>
serverAssignSeating === true && !formAssignSeating && !isFieldDirty;
// PAY Builder 031 — a stable content signature of the server's seating rows. The editor
// re-applies the server rows to its field-array only when this signature changes, so a
// freshly-saved row shows up (the seating-rows query is invalidated on Save → refetch →
// new signature → re-apply) without re-applying identical data on every render and
// without clobbering in-progress edits (the query does not refetch mid-edit). Labels are
// normalized so casing/whitespace alone is not treated as a change.
export const seatingRowsSignature = (
rows: SeatingRow[] | undefined,
): string =>
JSON.stringify(
(rows ?? []).map((r) => [
r.id ?? null,
normalizeRowLabel(r.rowLabel),
Number(r.firstSeat),
Number(r.lastSeat),
r.label ?? "",
]),
);
// PAY Builder 031 — resolve the Assign Seating toggle value when hydrating the builder form.
//
// The merchant product detail GET does NOT return assignSeating (it is write-only on the
// product PATCH and read back only by GET /products/{id}/seating). So hydrating the toggle
// from the product payload defaults it to false, and a post-save product refetch resets it —
// the reported "the toggle turns off after I save". Once the authoritative /seating response
// has loaded we hydrate the toggle from it (in both directions, so turning seating off also
// round-trips). Until /seating loads we return false; the provider's one-shot seed then turns
// the toggle on when the server says it is on, so this is a safe pre-load default (no flicker
// from a premature ON). Non-events never have seating.
export const resolveHydratedAssignSeating = ({
isEvent,
seatingConfigLoaded,
seatingConfigAssignSeating,
}: {
isEvent: boolean;
seatingConfigLoaded: boolean;
seatingConfigAssignSeating: boolean | undefined;
}): boolean =>
isEvent && seatingConfigLoaded ? Boolean(seatingConfigAssignSeating) : false;
// A persisted seating row — has an id, so it is selectable for a ticket.
export type PersistedSeatingRow = SeatingRow & { id: number };
export type SeatingRowGroup = {
rowLabel: string; // display label (original casing of the first range in the group)
ranges: PersistedSeatingRow[]; // ordered by firstSeat
};
// PAY Builder 031 — group a flat seating-row list into per-row-label groups for the
// ticket-modal seat map. Ranges of the same row (e.g. A 1–5 VIP, A 6–10 Standard) render
// together under one row label, separated and labelled. Casing/whitespace variants are the
// same row. Only persisted rows (with an id) are selectable, so unsaved rows are dropped.
export const groupSeatingRowsByLabel = (
rows: SeatingRow[] | undefined,
): SeatingRowGroup[] => {
const order: string[] = []; // normalized labels in first-seen order
const byKey = new Map<string, SeatingRowGroup>();
for (const r of rows ?? []) {
if (r.id == null) continue;
const key = normalizeRowLabel(r.rowLabel);
let group = byKey.get(key);
if (!group) {
group = { rowLabel: r.rowLabel, ranges: [] };
byKey.set(key, group);
order.push(key);
}
group.ranges.push(r as PersistedSeatingRow);
}
return order.map((key) => {
const group = byKey.get(key) as SeatingRowGroup;
group.ranges.sort((a, b) => Number(a.firstSeat) - Number(b.firstSeat));
return group;
});
};
// PAY Builder 031 — the persisted rows a variant (ticket) actually sells, narrowed so the caller
// (SeatPicker) needs no cast for the id. Unsaved rows (no id) are dropped — they aren't
// selectable.
export const getSelectableRows = (
rows: SeatingRow[] | undefined,
variantID: number,
): PersistedSeatingRow[] =>
(rows ?? []).filter(
(r): r is PersistedSeatingRow =>
r.id != null && (r.variantIDs ?? []).includes(variantID),
);
// PAY Builder 031 — reconcile the ticket quantity (the -/+ allowance) when the seat selection
// changes on the checkout modal. The counter follows the selection but only where it should:
// - picking a seat past the current allowance bumps the allowance up to the selected count;
// - removing seats while the selection filled the allowance pulls it down to what's left;
// - filling an open slot under the allowance, or dropping a reserved-but-unfilled slot (one the
// buyer added headroom for via "+"), leaves the allowance unchanged.
// The removal branch keys on how many seats actually went away, not a fixed 1, because a single
// onChange can drop several at once (SeatPicker releases every selected seat that a takenSeats
// refetch just marked taken). Floored at 1 so the counter never shows 0.
export const reconcileSeatQuantity = (
prevSeats: SeatSelection[],
nextSeats: SeatSelection[],
quantity: number,
): number => {
if (nextSeats.length > quantity) return nextSeats.length;
if (nextSeats.length < prevSeats.length && prevSeats.length === quantity) {
return Math.max(1, nextSeats.length);
}
return quantity;
};
// PAY Builder 031 — summarise the rows a ticket sells for its card in the Tickets list,
// e.g. "Row C", "Rows C-D", or "Rows A, C" (Figma "Added rows value in a ticket"). Maps
// the ticket's selected seatingRowIDs to their distinct row labels, in the seating config's
// row order. A run of ADJACENT rows collapses to a compact "Rows first-last"; a selection
// with gaps is listed ("Rows A, C") — never collapsed, since "Rows A-C" would wrongly imply
// the skipped row B is sold. Endpoints follow the config's row order (not selection or raw
// array order), so a reversed/unsorted input can't produce an arbitrary "Rows C-A".
// Row labels are free-text with no numeric ordering, so "adjacent" means an unbroken run
// within the config's distinct-label sequence — not alphabetical/numeric.
// NOTE: assumes seatingRows arrives in the intended seating order (same assumption as the
// sibling groupSeatingRowsByLabel). Returns "" when nothing is selected.
export const formatTicketSeatingRows = (
seatingRowIDs: number[] | undefined,
seatingRows: SeatingRow[] | undefined,
): string => {
const ids = new Set(seatingRowIDs ?? []);
if (ids.size === 0) return "";
// Distinct row labels in first-seen (seating) order, and which positions this ticket sells.
const labelOrder: string[] = []; // original-casing labels, indexed by position
const posOf = new Map<string, number>(); // normalized label -> position in labelOrder
const selected = new Set<number>();
for (const r of seatingRows ?? []) {
Iif (r.id == null) continue;
const key = normalizeRowLabel(r.rowLabel);
let pos = posOf.get(key);
if (pos === undefined) {
pos = labelOrder.length;
posOf.set(key, pos);
labelOrder.push(r.rowLabel);
}
if (ids.has(r.id)) selected.add(pos);
}
const positions = Array.from(selected).sort((a, b) => a - b);
if (positions.length === 0) return "";
if (positions.length === 1) return `Row ${labelOrder[positions[0]]}`;
const first = positions[0];
const last = positions[positions.length - 1];
const isContiguous = last - first + 1 === positions.length;
return isContiguous
? `Rows ${labelOrder[first]}-${labelOrder[last]}`
: `Rows ${positions.map((p) => labelOrder[p]).join(", ")}`;
};
// PAY Builder 031 — the rows a ticket (variant) sells. The variant GET does NOT return
// seatingRowIDs, so on edit they are reconstructed from the seating config's reverse
// mapping: each row lists the variantIDs that sell it. Prefers explicitIds when present so
// this becomes a no-op once the BE returns the variant's seatingRowIDs directly. Without
// this, a saved ticket re-opens with no rows selected (and its card shows no rows).
export const deriveTicketSeatingRowIDs = (
variantId: number | string | undefined | null,
explicitIds: number[] | undefined,
seatingRows: SeatingRow[] | undefined,
): number[] => {
if (explicitIds && explicitIds.length) return explicitIds;
if (variantId == null) return [];
const vid = Number(variantId);
Iif (!Number.isFinite(vid)) return [];
// Reuse the single "rows a variant sells" predicate so selectability lives in one place.
return getSelectableRows(seatingRows, vid).map((r) => r.id);
};
// PAY Builder 031 — enrich each ticket with its true seating-row assignment for the Save
// payload. The variant GET does not return seatingRowIDs, so an existing ticket the merchant
// hasn't re-opened this session carries []. The BE variant-update treats a present empty array
// as "clear all rows" (replaceSeatingRows), so sending [] wipes the ticket->row mapping on every
// save. Deriving each ticket's rows from the seating config's reverse map (row.variantIDs)
// restores the true set; explicit ids (an in-session modal edit) win via deriveTicketSeatingRowIDs,
// so this never overrides a deliberate change. Apply only for assigned-seating events, right
// before formatVariantsToMatchPayload.
export const withDerivedSeatingRowIDs = <
T extends { variantID?: number | string | null; seatingRowIDs?: number[] },
>(
items: T[],
seatingRows: SeatingRow[] | undefined,
): T[] =>
items.map((item) => ({
...item,
seatingRowIDs: deriveTicketSeatingRowIDs(
item.variantID,
item.seatingRowIDs,
seatingRows,
),
}));
// PAY Builder 031 — a seating row belongs to at most ONE ticket. Given the ticket being
// edited and the full ticket list, return the rows already claimed by OTHER tickets, mapped
// to the owning ticket's display name (for the disabled "Assigned to X" label in the seat
// map). A row's owner is derived the same way its card shows its rows (deriveTicketSeatingRowIDs),
// so it covers BOTH an in-session selection held in form state AND a persisted assignment that
// only lives in the config reverse-map (row.variantIDs) — the two ways a row can be taken. The
// edited ticket never blocks its own rows: it is excluded by form id AND, defensively, by
// variantID. This mirrors the BE cross-variant guard (validateVariantSeatingRows exclude-self);
// the BE stays authoritative, this only stops the merchant from picking a taken row.
export const getRowsTakenByOtherTickets = (
current: { id?: string; variantID?: number | string | null },
items: Array<{
id?: string;
variantID?: number | string | null;
title?: string;
seatingRowIDs?: number[];
}>,
seatingRows: SeatingRow[] | undefined,
): Map<number, string> => {
const currentVid =
current.variantID == null ? null : Number(current.variantID);
const taken = new Map<number, string>();
for (const item of items ?? []) {
if (current.id != null && item.id === current.id) continue; // same ticket (form id)
const vid = item.variantID == null ? null : Number(item.variantID);
if (currentVid != null && vid === currentVid) continue; // same ticket (variant)
const name = item.title?.trim() || "another ticket";
for (const rid of deriveTicketSeatingRowIDs(
item.variantID,
item.seatingRowIDs,
seatingRows,
)) {
Eif (!taken.has(rid)) taken.set(rid, name);
}
}
return taken;
};
export type SeatingPublishBlockReason = "no-rows" | "unassigned-tickets";
// PAY Builder 031 — pre-commit check: before publishing/saving an assigned-seating event,
// every ticket must sell at least one seating row. The BE rejects a variant create/update with
// no rows (ErrTicketNeedsSeatingRow) when assignSeating is on, but the FE save fires the product
// PATCH + publish as SEPARATE, un-transacted calls — so a seatless ticket silently half-saves
// (form saved/published while the ticket create is rejected with only a per-request toast). This
// lets the commit be blocked up front with actionable guidance. A ticket's rows are derived the
// same way the ticket card shows them (deriveTicketSeatingRowIDs), so an existing ticket whose
// rows live only in the config reverse-map is NOT falsely flagged. Returns:
// - null → nothing to block (not a seating event, or every ticket has rows)
// - "no-rows" → seating on with tickets, but no saved rows to assign yet
// - "unassigned-tickets" → saved rows exist but ≥1 ticket has none assigned
export const getSeatingPublishBlock = (
isEvent: boolean,
assignSeating: boolean,
items: Array<{ variantID?: number | string | null; seatingRowIDs?: number[] }>,
seatingRows: SeatingRow[] | undefined,
): SeatingPublishBlockReason | null => {
if (!isEvent || !assignSeating) return null;
if (!items || items.length === 0) return null; // no tickets → nothing the BE will reject
const hasSelectableRows = (seatingRows ?? []).some((r) => r.id != null);
if (!hasSelectableRows) return "no-rows";
const anyUnassigned = items.some(
(item) =>
deriveTicketSeatingRowIDs(item.variantID, item.seatingRowIDs, seatingRows)
.length === 0,
);
return anyUnassigned ? "unassigned-tickets" : null;
};
// PAY Builder 031 (GB-21528) — the post-save rehydration rebuilds Items purely from server
// variants (utils.generateFormData / useManagePayFormProvider reset). A brand-new ticket whose
// variant create was rejected by the BE — the classic case being a seatless ticket on an
// assign-seating event (ErrTicketNeedsSeatingRow) — is absent from that server list, so the reset
// silently wipes it (unlike seatingRows, which the reset already preserves). This re-attaches the
// merchant's still-unsaved tickets so a rejected create never erases their work: they stay in the
// form to be assigned to the now-saved rows and re-saved. An item is "unsaved" when it has no
// variantID; it is kept only when the server did NOT return a variant with the same (trimmed)
// title, so a SUCCESSFUL create — which comes back by title while the local copy still lacks a
// variantID at reset time — is not duplicated. bulk-create is atomic (whole batch 200 or 400), so
// title matching cleanly separates "all created" from "all rejected".
export const mergeUnsavedItems = <
T extends { variantID?: number | string | null; title?: string },
>(
serverItems: T[],
localItems: T[] | undefined,
): T[] => {
const serverTitles = new Set(
serverItems.map((i) => (i.title ?? "").trim()),
);
const unsaved = (localItems ?? []).filter(
(i) => !i.variantID && !serverTitles.has((i.title ?? "").trim()),
);
return [...serverItems, ...unsaved];
};
// PAY Builder 031 (GB-21528) — stamp the ids of just-created variants back onto the form's local
// tickets after a successful bulk-create. Without this a created ticket keeps its client-only id
// (no variantID), so the NEXT save re-POSTs it to variants/bulk-create — and on an assign-seating
// event the BE rejects it because the row it wants is already owned by the variant the first save
// created ("A selected seating row is already assigned to another ticket."). Once stamped, the
// next save routes the ticket through variantsToUpdate (PATCH) instead of re-creating it.
//
// bulk-create returns the created variants (with ids + names); each maps to the like-named local
// ticket that still lacks a variantID. Match by trimmed title, FIFO per title so duplicate-named
// tickets get their ids in creation order. Already-persisted tickets (variantID set) are untouched.
export const reconcileCreatedVariantIDs = <
T extends { variantID?: number | string; title?: string },
>(
items: T[],
createdVariants: Array<{ id?: number | string; name?: string }> | undefined,
): T[] => {
if (!createdVariants || createdVariants.length === 0) return items;
const idsByName = new Map<string, Array<number | string>>();
for (const v of createdVariants) {
if (v.id == null) continue;
const name = (v.name ?? "").trim();
const queue = idsByName.get(name) ?? [];
queue.push(v.id);
idsByName.set(name, queue);
}
return items.map((item) => {
if (item.variantID != null) return item;
const queue = idsByName.get((item.title ?? "").trim());
const id = queue?.shift();
return id == null ? item : { ...item, variantID: id };
});
};
export const SEATING_PUBLISH_BLOCK_MESSAGE: Record<
SeatingPublishBlockReason,
string
> = {
"no-rows":
"Add and save your seating layout, then assign rows to each ticket before publishing.",
"unassigned-tickets":
"Assign at least one seating row to every ticket before publishing.",
};
// PAY Builder 031 — the assigned-seating checkout gate. An assigned-seating event may only
// proceed to checkout once every cart ticket has as many chosen seats as its quantity. The
// seat-picking modal (PublicProductItemModal) enforces this per add-to-cart, but an item
// hydrated from a pre-existing server cart (useInitCartItems) — or added before seats were
// picked — carries no `seats` and would otherwise let the buyer check out seatless → BE
// ErrSeatCountMismatch. Both the desktop ticket list (EventTicketList) and the mobile bottom
// sheet (TicketListBottomSheetBody) call this so their page-level checkout button reflects the
// same rule. No-op when seating is off, so non-seating events are unaffected.
export const areSeatsIncomplete = (
assignSeating: boolean,
cartItems: Array<{ seats?: SeatSelection[]; quantity: number }>,
): boolean =>
assignSeating &&
cartItems.some((item) => (item.seats?.length ?? 0) !== item.quantity);
// PAY Builder 031 / GB-21697 — whether a ticket card should render as chosen.
// On an assigned-seating event the card hides the +/- stepper (EventTicketItem), so its
// border is the only "this ticket is in your cart" affordance the buyer has. A cart item
// hydrated from a pre-existing server cart by useInitCartItems carries a quantity but never
// `seats` — OrderItemCartView has no seats field — so keying the highlight on "is there a
// cart item" left a refreshed page showing a chosen ticket the buyer could neither see in
// the seat picker (it opens at 0/N with nothing green) nor click off. Requiring a chosen
// seat keeps the card and the picker telling the same story. Non-seating tickets never
// carry seats, so presence in the cart stays the rule for them.
export const isTicketSelected = (
assignSeating: boolean,
cartItem?: { seats?: SeatSelection[] },
): boolean => {
if (!cartItem) return false;
return assignSeating ? (cartItem.seats?.length ?? 0) > 0 : true;
};
// PAY Builder 031 / GB-21697 — drop cart items a refresh cannot make usable.
// GET /cart restores a quantity but no seats (OrderItemCartView carries no seats field), so
// a seated ticket hydrated from a pre-existing server cart arrives seatless, and in that
// state it is unusable in every direction: the card hides its stepper so there is nothing to
// clear it with, the seat picker opens at 0/N with nothing to deselect, areSeatsIncomplete
// keeps the page Checkout button disabled for as long as it sits in the cart — including
// when the buyer goes on to choose a different ticket entirely — and addToCartHandler
// re-POSTs it seatless on the next add. Hydration therefore skips it and the buyer starts
// that ticket cleanly; the server-side row and its seat hold are wiped by the full-cart
// DELETE that addToCartHandler already awaits before re-POSTing. Non-seating events keep
// every item, since their tickets never carry seats.
export const withoutSeatlessSeatedItems = <
T extends { seats?: SeatSelection[] },
>(
assignSeating: boolean,
items: Record<string, T> | null,
): Record<string, T> | null => {
if (!assignSeating || !items) return items;
const keys = Object.keys(items);
const kept = keys.filter((key) => (items[key].seats?.length ?? 0) > 0);
if (kept.length === keys.length) return items;
return kept.reduce<Record<string, T>>(
(acc, key) => ({ ...acc, [key]: items[key] }),
{},
);
};
export const SEAT_RANGE_OVERLAP_MESSAGE =
"Some seats in this range have already been added to this row. Please choose a different seat range.";
// Shown on a ticket card when assigned seating is on, rows exist, but this ticket has none
// assigned (e.g. the ticket was created before seating was enabled).
export const TICKET_ROWS_REQUIRED_MESSAGE =
"Assigning rows to this ticket is required.";
// PAY Builder 031 — per-row overlap errors for the rows config editor, aligned by index so
// the error renders under the offending row. Flags a range when it overlaps an EARLIER
// range of the same row label (so the first occurrence is clean and the duplicate/overlap
// is flagged). Half-typed rows (no label or last < first) are skipped, not flagged.
export const getSeatingRowOverlapErrors = (
rows: SeatingRow[] | undefined,
): (string | null)[] => {
const rangesByLabel = new Map<string, Array<{ first: number; last: number }>>();
return (rows ?? []).map((r) => {
const label = normalizeRowLabel(r.rowLabel);
const first = Number(r.firstSeat);
const last = Number(r.lastSeat);
if (label === "" || !(first >= 1) || !(last >= first)) return null;
const existing = rangesByLabel.get(label) ?? [];
const overlaps = existing.some((e) => first <= e.last && e.first <= last);
existing.push({ first, last });
rangesByLabel.set(label, existing);
return overlaps ? SEAT_RANGE_OVERLAP_MESSAGE : null;
});
};
|