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 | 50x 50x 50x 50x 50x 50x 50x 136x 136x 86x 86x 86x 57x 57x 57x 77x 136x 50x 19x 17x 19x 4x 3x 16x 50x 50x 16x 16x 12x 7x 50x 50x 22x 22x 35x 22x 1x 22x 409x 50x 341x 50x 191x 50x 18x 18x 18x 17x 17x 29x 29x 50x 18x 18x 10x 50x 28x 12x 20x 10x 19x 10x 10x 19x 19x 19x 19x 19x 18x 18x 9x | import * as Yup from "yup";
import type { ICartItem } from "@sections/PayBuilder/provider/CartContext";
import type { ProductItemType } from "@sections/PayBuilder/types";
import { FIELD_REQUIRED_MESSAGE } from "./consts";
/**
* Story 2 — per-ticket Participant Details.
*
* Pure helpers, deliberately free of React and of the cart query, so the two
* behaviours that are easy to get wrong — reconciling what the buyer already
* typed against a changing cart, and producing a payload the BE can trust — are
* testable without rendering anything.
*/
/**
* The order-level participant. Used when ONE participant governs the whole order
* (the merchant left "Require details on each ticket" off and the buyer turned
* "Same as contact details" off).
*
* Kept outside the per-unit key space on purpose: it is not tied to a unit, so
* no cart change should ever discard it.
*/
export const SINGLE_PARTICIPANT_KEY = "all";
/** Copy lives here so the builder helper and the customer banner can't drift. */
export const PARTICIPANT_DETAILS_HELPER =
"The buyer enters participant details for each ticket rather than once for the whole order.";
export const PARTICIPANT_SINGLE_BANNER =
"You only need one participant's info for all the tickets you purchase.";
export const PARTICIPANT_SECTION_TITLE = "Participant Details";
/** Copy is shared so the Contact checkbox and its aria-label cannot drift. */
export const SEND_ALL_TICKETS_LABEL = "Send all tickets to this email";
/** Copy is shared so the switch, its label element and its aria-label cannot drift. */
export const SAME_AS_CONTACT_LABEL = "Same as contact details";
export interface ParticipantValue {
name?: string;
email?: string;
phoneNumber?: string;
}
export type ParticipantValues = Record<string, ParticipantValue>;
export interface ParticipantSlot {
/** `${productVariantID}:${unitIndex}` — see keying note below. */
key: string;
/**
* Resolved from the cart line at build time. Null while the line has no server
* id yet, which makes a complete payload impossible — see buildParticipantsPayload.
*/
orderItemID: number | null;
productVariantID: number;
unitIndex: number;
variantName: string;
/** 1-based across the whole cart — the `Ticket {n}` label the buyer sees. */
ticketNumber: number;
}
/**
* Slots are keyed by VARIANT, not by order item.
*
* useCheckoutHandler recreates the cart when a card is declined ("if the card is
* declined, we need to recreate the cart, otherwise BE will return error"),
* which re-mints every order-item id. Keying on those ids would silently discard
* everything the buyer typed at the exact moment they retry the payment.
*
* The order-item id is still what the BE needs, so it rides along on the slot and
* is resolved at submit.
*/
export const buildParticipantSlots = (
cartItems: ICartItem[] = [],
): ParticipantSlot[] => {
const slots: ParticipantSlot[] = [];
cartItems.forEach((item) => {
const productVariantID = Number(item.productVariantID);
const quantity = Number(item.quantity) || 0;
if (!productVariantID || quantity <= 0) return;
const parsedID = parseInt(String(item.id), 10);
const orderItemID = Number.isNaN(parsedID) ? null : parsedID;
for (let unitIndex = 0; unitIndex < quantity; unitIndex++) {
slots.push({
key: `${productVariantID}:${unitIndex}`,
orderItemID,
productVariantID,
unitIndex,
variantName: item.productVariantName,
ticketNumber: slots.length + 1,
});
}
});
return slots;
};
/**
* POST /cart/checkout persist_participants keys coverage by order-item id
* (givesync-api OrderItemCartView.id). Event tickets in CartContext use
* `id: String(product.id)` — the variant id — because the local cart is keyed
* by variant (EventTicketItem). That integer parses as a real orderItemID, so
* the "no server id yet" null-guard never fires and checkout sends foreign ids.
*
* Checkout already reads the server cart from QKEY_LIST_CART for `items`.
* useInitCartItems cannot supply those ids: it hydrates from useCartItems'
* `[QKEY_LIST_CART]` key, while addToCartHandler writes the string key
* `QKEY_LIST_CART`. Submit therefore takes ids from that same cache.
*
* Slot keys stay `${productVariantID}:${unitIndex}` so form values still match.
*/
export const resolveParticipantSlots = ({
cartItems,
serverItems = [],
}: {
cartItems?: ICartItem[];
serverItems?: Array<{
id?: number | string;
productVariantID?: number | string;
productVariantName?: string;
quantity?: number;
}>;
}): ParticipantSlot[] => {
const fromServer = buildParticipantSlots(
serverItems.map((item) => ({
id: String(item.id ?? ""),
productVariantID: Number(item.productVariantID) || 0,
productVariantName: item.productVariantName ?? "",
quantity: Number(item.quantity) || 0,
productVariantPrice: 0,
unitPrice: 0,
productVariantImageURL: "",
recurringIntervalName: null,
})),
);
if (
fromServer.length > 0 &&
fromServer.every((slot) => slot.orderItemID !== null)
) {
return fromServer;
}
return buildParticipantSlots(cartItems);
};
/**
* Preview-only key space. Distinct prefix so a preview slot can never collide
* with a real `${productVariantID}:${unitIndex}` key, and so anything that leaks
* into form state is obvious on sight.
*/
export const PREVIEW_SLOT_PREFIX = "preview";
/**
* Slots for the BUILDER PREVIEW, which has no cart.
*
* The preview renders the customer checkout while the merchant configures it, so
* nothing has been purchased and buildParticipantSlots returns [] — which made
* the whole section invisible in the pane whose job is to show it. Mockup
* 7409:188886 shows one row per ticket, so seed one row per enabled ticket
* variant, falling back to a single row for an event with no tickets yet.
*
* Preview-only: these carry no orderItemID and must never reach a payload —
* buildParticipantsPayload is fed from buildParticipantSlots, never from here.
*/
export const buildPreviewParticipantSlots = (
items: ProductItemType[] = [],
): ParticipantSlot[] => {
const visible = items.filter((item) => item?.display !== false);
if (visible.length === 0) {
return [
{
key: `${PREVIEW_SLOT_PREFIX}:0`,
orderItemID: null,
productVariantID: 0,
unitIndex: 0,
variantName: "",
ticketNumber: 1,
},
];
}
return visible.map((item, index) => ({
key: `${PREVIEW_SLOT_PREFIX}:${index}`,
orderItemID: null,
productVariantID: Number(item.variantID ?? item.id) || 0,
unitIndex: index,
variantName: item.title ?? "",
ticketNumber: index + 1,
}));
};
const EMPTY_PARTICIPANT: ParticipantValue = {
name: "",
email: "",
phoneNumber: "",
};
/**
* AC017 — reconcile what the buyer already typed against the current cart.
*
* This is a key-set diff rather than index surgery: keys whose unit no longer
* exists disappear, new units start empty, and every surviving key keeps its
* value untouched. Preserving the buyer's input is the default behaviour of the
* data structure, not something the caller has to remember to do.
*/
export const reconcileParticipants = (
values: ParticipantValues = {},
slots: ParticipantSlot[] = [],
): ParticipantValues => {
const next: ParticipantValues = {};
slots.forEach(({ key }) => {
next[key] = values[key] ?? { ...EMPTY_PARTICIPANT };
});
if (values[SINGLE_PARTICIPANT_KEY]) {
next[SINGLE_PARTICIPANT_KEY] = values[SINGLE_PARTICIPANT_KEY];
}
return next;
};
const hasText = (value?: string) => !!String(value ?? "").trim();
/** Nothing to copy until Contact carries both a name and an email. */
export const isContactComplete = (
contactName?: string,
contactEmail?: string,
) => hasText(contactName) && hasText(contactEmail);
interface SameAsContactParams {
/** Raw `participantsSameAsContact`; undefined is the AC054 ON default. */
sameAsContact?: boolean;
contactName?: string;
contactEmail?: string;
}
/**
* The single reading of "the buyer is the participant" — the switch, the schema
* and the payload all key on this, so none of them can drift out of the others.
*/
export const isSameAsContactActive = ({
sameAsContact,
contactName,
contactEmail,
}: SameAsContactParams) =>
sameAsContact !== false && isContactComplete(contactName, contactEmail);
interface BuildParticipantsSchemaParams {
/** Keys of the rows actually on screen — the only ones we may require. */
slotKeys: string[];
collectPerTicket: boolean;
isPhoneRequired: boolean;
}
/**
* AC016 — block checkout until every rendered participant is filled.
*
* Lazy because the answer depends on a sibling field the buyer controls ("Same
* as contact details"), which is not known when the schema is built. Reading it
* from `options.parent` at validation time keeps one schema correct in both
* modes, instead of rebuilding the whole form schema whenever that switch moves.
*/
export const buildParticipantsSchema = ({
slotKeys,
collectPerTicket,
isPhoneRequired,
}: BuildParticipantsSchemaParams) =>
Yup.lazy((_value, options) => {
const isSameAsContact = isSameAsContactActive({
sameAsContact: options?.parent?.participantsSameAsContact,
contactName: options?.parent?.name,
contactEmail: options?.parent?.email,
});
// The buyer is the participant: their Contact fields are already validated,
// so there is nothing extra to require here.
if (!collectPerTicket && isSameAsContact) return Yup.mixed().notRequired();
const keys = collectPerTicket ? slotKeys : [SINGLE_PARTICIPANT_KEY];
// "Send all tickets to this email" writes into these visible fields rather
// than hiding them, so the plain required rules below already cover it.
return Yup.object().shape(
keys.reduce<Record<string, Yup.AnyObjectSchema>>((acc, key) => {
acc[key] = Yup.object().shape({
name: Yup.string().trim().required(FIELD_REQUIRED_MESSAGE),
email: Yup.string()
.trim()
.email("Not a valid format")
.required(FIELD_REQUIRED_MESSAGE),
...(isPhoneRequired && {
phoneNumber: Yup.string().trim().required(FIELD_REQUIRED_MESSAGE),
}),
});
return acc;
}, {}),
);
});
export interface ParticipantPayloadEntry {
orderItemID: number;
unitIndex: number;
firstName: string;
lastName: string;
email: string;
phoneNumber?: string;
}
/**
* The BE stores the participant name as separate parts and never splits a
* composite itself (only the caller knows which word is which), so the single
* Full Name field is split here: last word → lastName, the rest → firstName —
* the same convention useCheckout applies to nameOnCard. A lone word becomes
* the first name, since the BE requires firstName and lastName is optional.
*/
export const splitParticipantName = (
name: string,
): { firstName: string; lastName: string } => {
const words = name.trim().split(/\s+/).filter(Boolean);
if (words.length <= 1) return { firstName: words[0] ?? "", lastName: "" };
return {
firstName: words.slice(0, -1).join(" "),
lastName: words[words.length - 1],
};
};
interface BuildParticipantsPayloadParams {
slots: ParticipantSlot[];
values: ParticipantValues;
/** useEventParticipantDetails() — true on event form types. */
isEnabled: boolean;
/** The merchant's "Require details on each ticket" toggle. */
collectPerTicket: boolean;
/** The buyer's "Same as contact details" switch (order-level mode only). */
sameAsContact: boolean;
/** The merchant enabled the participant Phone Number row. */
includePhone: boolean;
}
/**
* Produces the `participants` array for POST /cart/checkout.
*
* The BE may rely on: one entry per purchased unit or no entries at all; a
* 0-based unitIndex within each orderItemID; phoneNumber present only when it
* carries a value. An empty result means the caller omits the key entirely, so
* every checkout that does not collect participants keeps today's payload.
*
* A single governing participant is EXPANDED to one entry per unit rather than
* sent once with an "apply to all" flag — that leaves the BE one rule to
* implement instead of two, and no mode to mis-detect.
*/
export const buildParticipantsPayload = ({
slots,
values,
isEnabled,
collectPerTicket,
sameAsContact,
includePhone,
}: BuildParticipantsPayloadParams): ParticipantPayloadEntry[] => {
if (!isEnabled || slots.length === 0) return [];
// The buyer is the participant: their name and email already ride `user`, so
// repeating them here would be noise the BE has to interpret.
if (!collectPerTicket && sameAsContact) return [];
// Without every order-item id we cannot produce full coverage, and a partial
// array would have the BE issue some tickets to a participant and the rest to
// the buyer with nothing to show that happened.
if (slots.some((slot) => slot.orderItemID === null)) return [];
// "Send all tickets to this email" needs no branch: it writes the contact
// email into `values`, so form state already holds what the buyer sees.
const valueFor = (slot: ParticipantSlot): ParticipantValue | undefined =>
collectPerTicket ? values[slot.key] : values[SINGLE_PARTICIPANT_KEY];
const entries: ParticipantPayloadEntry[] = [];
for (const slot of slots) {
const value = valueFor(slot);
const name = value?.name?.trim() ?? "";
const email = value?.email?.trim() ?? "";
const phoneNumber = value?.phoneNumber?.trim() ?? "";
if (!name || !email) return [];
const { firstName, lastName } = splitParticipantName(name);
entries.push({
orderItemID: slot.orderItemID as number,
unitIndex: slot.unitIndex,
firstName,
lastName,
email,
...(includePhone && phoneNumber ? { phoneNumber } : {}),
});
}
return entries;
};
|