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 | 12x 384x 384x 384x 384x 12x 384x 384x 384x 384x 384x 384x 384x 384x 384x 384x 384x 384x 9x 384x 384x 384x 384x 384x 384x 384x 384x 384x 384x 384x 384x 384x 384x 384x 384x 384x 60x 384x 384x 384x 384x 384x 384x 384x 38x 38x 384x 74x 384x | import { yupResolver } from "@hookform/resolvers/yup";
import { usePayBuilderForm } from "@sections/PayBuilder/provider/PayBuilderFormProvider";
import { useForm, FieldPath } from "react-hook-form";
import * as Yup from "yup";
import {
addressFields,
FEE_PAYER_OPTIONS,
FIELD_REQUIRED_MESSAGE,
} from "../consts";
import { matchIsValidTel } from "mui-tel-input";
import { isNonValidExpirationDate, isValidCardNumber } from "../helpers";
import { useEffect, useState } from "react";
import { PaymentSuccessInfo } from "@pages/Checkout/components/PaymentSuccess";
import useCheckoutProcess from "./useCheckoutProcess";
import { ICheckoutInputs } from "../types";
import useCheckFormType from "@sections/PayBuilder/components/hooks/useCheckFormType";
import { useSearchParams } from "react-router-dom";
import { NAME_REGEX, getPostalRegexForCountry } from "@validation/regex";
import { getCountryCode } from "@utils/country_dial_codes";
import { useGetFeatureFlagValues } from "FeatureFlags/useGetFeatureFlagValues";
import { useEventParticipantDetails } from "./useEventParticipantDetails";
import { useCart } from "@sections/PayBuilder/provider/CartContext";
import {
buildParticipantSlots,
buildParticipantsSchema,
} from "../participants.helpers";
import { createStreetAddressValidator } from "@validation/address/streetValidator";
import { createCountryValidator } from "@validation/address/countryValidator";
import { createCityValidation } from "@validation/address/cityValidator";
import { VALIDATION_MESSAGES } from "@validation/messages";
import {
CUSTOM_FIELD_REQUIRED_MESSAGE,
MAX_CUSTOM_FIELD_LABEL_LEN,
buildCustomFieldsAnswerDefaults,
getRenderableCustomFields,
} from "../customFields.helpers";
const PARAM_KEYS = ["email"] as const;
function useQueryParams<T extends readonly string[]>(
paramKeys: T,
): { [K in T[number]]: string | null } {
const [searchParams] = useSearchParams();
return paramKeys.reduce((acc, key) => {
(acc as any)[key] = searchParams.get(key) ?? null;
return acc;
}, {} as { [K in T[number]]: string | null });
}
const useCheckoutPreview = (
onPaymentSuccess?: (data: PaymentSuccessInfo) => void,
) => {
const { isFundraiser } = useCheckFormType();
const { methods: checkoutSidepanelMethods, data } = usePayBuilderForm();
const checkoutSidepanelValues = checkoutSidepanelMethods.watch();
const customerCoversFeesDefaultValue =
checkoutSidepanelValues.Checkout.feePayer !== FEE_PAYER_OPTIONS.MERCHANT;
const { isInvoice, isEvent } = useCheckFormType();
const { isPayBuilderCustomFieldsEnabled } = useGetFeatureFlagValues();
// Must stay the same answer Contact renders on, or a required error lands on
// a field the buyer was never shown.
const isContactNameRendered = isEvent;
// Story 2 — the participant rows the buyer is actually shown decide what the
// schema validates. Reading the cart here (rather than only in the section)
// keeps the rule and the rendered set derived from the same source, so a
// required error can never land on a row that isn't on screen.
const { cartItems } = useCart();
const isParticipantDetailsRendered = useEventParticipantDetails();
const collectPerTicket =
!!checkoutSidepanelValues.Checkout.participantDetails?.render;
const isParticipantPhoneRequired =
!!checkoutSidepanelValues.Checkout.participantPhone?.render &&
!!checkoutSidepanelValues.Checkout.participantPhone?.required;
const participantSlotKeys = isParticipantDetailsRendered
? buildParticipantSlots(cartItems).map((slot) => slot.key)
: [];
// PAY-Builder016 — the rendered custom fields (flag on + configured).
const renderableCustomFields = isPayBuilderCustomFieldsEnabled
? getRenderableCustomFields(checkoutSidepanelValues.Checkout.customFields)
: [];
const params = useQueryParams(PARAM_KEYS);
const defaultEmail = decodeURIComponent(params.email || "");
const { render: isPhoneNumberRendered, required: isPhoneNumberRequired } =
checkoutSidepanelValues.Checkout.phoneNumber;
const { render: isDeliveryEnabled } =
checkoutSidepanelValues.Checkout.delivery;
const { render: isBillingEnabled, required: isBillingRequired } =
checkoutSidepanelValues.Checkout.billing;
const [isDeclined, setIsDeclined] = useState(false);
const [isFailed, setIsFailed] = useState(false);
const [declineReason, setDeclineReason] = useState<string | undefined>(
undefined,
);
const donationDetails = checkoutSidepanelValues.Donations
? {
selectedAmount: checkoutSidepanelValues.Donations.selectedAmount,
isAnonymous: checkoutSidepanelValues.Donations.isAnonymous,
}
: { selectedAmount: "", isAnonymous: false };
const entriesDetails = checkoutSidepanelValues.Entries
? {
selectedEntry: checkoutSidepanelValues.Entries.selectedEntry,
isAnonymous: checkoutSidepanelValues.Entries.isAnonymous,
}
: { selectedEntry: "", isAnonymous: false };
const defaultValues = {
name: "",
email: isInvoice ? data?.customer?.email : defaultEmail,
phoneNumber: "",
payment: {
cardNumber: "",
expirationDate: "",
cvv: "",
nameOnCard: "",
},
billingAddress: { ...addressFields, useDeliveryAddress: isDeliveryEnabled },
deliveryAddress: { ...addressFields, phoneNumber: "" },
customerCoversFees: customerCoversFeesDefaultValue,
termsConditions: true,
customFields: buildCustomFieldsAnswerDefaults(renderableCustomFields),
// Story 2 — participant answers are keyed by `${productVariantID}:${unitIndex}`
// and filled in by ParticipantDetails once the cart is known. The switch
// defaults ON (AC054), which is what keeps an untouched event checkout
// sending exactly the payload it sends today.
participants: {},
participantsSameAsContact: true,
sendAllTicketsToEmail: false,
...(isFundraiser && {
recurringInterval: "one_time",
}),
};
const getSchema = (values: ICheckoutInputs) =>
Yup.object().shape({
// Contact Name is required wherever it renders (events, flag on); the BE
// seeds the param required-by-default, so it is never optional.
...(isContactNameRendered && {
name: Yup.string().trim().required(FIELD_REQUIRED_MESSAGE),
}),
email: Yup.string()
.email("Not a valid format")
.required(FIELD_REQUIRED_MESSAGE),
...(isPhoneNumberRendered && {
phoneNumber: Yup.string()
.test(
"is-valid-phone",
"Please enter a valid phone number",
function (value = "") {
/*
Value might be defined with only the prefix but without the rest of the number
We do not have a robust way to validate by prefix
Is literally imposible to find any phone number witch prefix code exceed 6 chars or phone number under 6 chars, includingd, are Caraibean countries the prefix
The longest prefix I can find, are Caraibean countries
*/
if (value.length > 6) {
const phoneNumber = value as string;
return matchIsValidTel(phoneNumber);
}
return true;
},
)
.when({
is: () => {
return isPhoneNumberRequired;
},
then: (schema) =>
schema
.required(FIELD_REQUIRED_MESSAGE)
.test(
"is-valid-phone",
"Please enter a valid phone number",
function (value) {
const phoneNumber = value as string;
return matchIsValidTel(phoneNumber);
},
),
}),
}),
payment: Yup.object().shape({
cardNumber: Yup.string()
.required(FIELD_REQUIRED_MESSAGE)
.when({
is: (exists: string) => !!exists,
then: (schema) =>
schema.test(
"is-valid-card-number",
"Please enter a valid card number",
function (value) {
return isValidCardNumber(value || "");
},
),
}),
expirationDate: Yup.string()
.required(FIELD_REQUIRED_MESSAGE)
.when({
is: (exists: string) => !!exists,
then: (schema) =>
schema
.min(5, "Please enter a valid expiration date")
.test(
"validator-expiration-date",
"Please enter a valid expiration date",
function (value) {
return !isNonValidExpirationDate(value || "");
},
),
}),
cvv: Yup.string()
.required(FIELD_REQUIRED_MESSAGE)
.min(3, "Please enter a valid CVV"),
nameOnCard: Yup.string()
.trim()
.required(FIELD_REQUIRED_MESSAGE)
.matches(NAME_REGEX, VALIDATION_MESSAGES.INVALID_NAME_ENTER),
}),
...(isBillingEnabled && {
billingAddress: Yup.object().shape({
useDeliveryAddress: Yup.boolean(),
country: Yup.string().when("useDeliveryAddress", {
is: true,
then: Yup.string().notRequired(),
otherwise: Yup.string().test(
"country validation",
FIELD_REQUIRED_MESSAGE,
function (value) {
if (isBillingRequired && !value) return false;
return true;
},
),
}),
firstName: Yup.string().when("useDeliveryAddress", {
is: true,
then: Yup.string().notRequired(),
otherwise: Yup.string()
.test(
"firstName validation",
FIELD_REQUIRED_MESSAGE,
function (value) {
if (isBillingRequired && !value) return false;
return true;
},
)
.matches(NAME_REGEX, VALIDATION_MESSAGES.INVALID_NAME_ENTER),
}),
lastName: Yup.string().when("useDeliveryAddress", {
is: true,
then: Yup.string().notRequired(),
otherwise: Yup.string()
.test(
"lastName validation",
FIELD_REQUIRED_MESSAGE,
function (value) {
if (isBillingRequired && !value) return false;
return true;
},
)
.matches(NAME_REGEX, VALIDATION_MESSAGES.INVALID_NAME_ENTER),
}),
address: Yup.string().when("useDeliveryAddress", {
is: true,
then: createStreetAddressValidator({
required: false,
nullable: true,
}),
otherwise: createStreetAddressValidator({
required: isBillingRequired,
nullable: true,
requiredMessage: FIELD_REQUIRED_MESSAGE,
}),
}),
apartment: Yup.string(),
city: Yup.string().when("useDeliveryAddress", {
is: true,
then: Yup.string().notRequired(),
otherwise: Yup.string().test(
"city validation",
FIELD_REQUIRED_MESSAGE,
function (value) {
if (isBillingRequired && !value) return false;
return true;
},
),
}),
province: Yup.string().when("useDeliveryAddress", {
is: true,
then: Yup.string().notRequired(),
otherwise: Yup.string().test(
"province validation",
FIELD_REQUIRED_MESSAGE,
function (value) {
if (isBillingRequired && !value) return false;
return true;
},
),
}),
zipCode: Yup.string().when("useDeliveryAddress", {
is: true,
then: Yup.string().notRequired(),
otherwise: Yup.string()
.test(
"zipCode validation",
FIELD_REQUIRED_MESSAGE,
function (value) {
if (isBillingRequired && !value) return false;
return true;
},
)
.test(
"zipCode format validation",
VALIDATION_MESSAGES.INVALID_ZIP_SHORT,
function (value) {
if (!isBillingRequired && !value) return true;
const isoCode = getCountryCode(this.parent.country);
if (!isoCode) return true;
const regex = getPostalRegexForCountry(isoCode);
return !value || !regex || regex.test(value);
},
),
}),
}),
}),
...(isDeliveryEnabled && {
deliveryAddress: Yup.object().shape({
country: createCountryValidator({ nullable: false }),
firstName: Yup.string()
.required(FIELD_REQUIRED_MESSAGE)
.matches(NAME_REGEX, VALIDATION_MESSAGES.INVALID_NAME_ENTER),
lastName: Yup.string()
.required(FIELD_REQUIRED_MESSAGE)
.matches(NAME_REGEX, VALIDATION_MESSAGES.INVALID_NAME_ENTER),
address: createStreetAddressValidator({
required: true,
requiredMessage: FIELD_REQUIRED_MESSAGE,
}),
apartment: Yup.string(),
city: createCityValidation({
required: true,
customRequiredMessage: FIELD_REQUIRED_MESSAGE,
}),
province: Yup.string().when("country", {
is: (country: string) => country === "United Kingdom",
then: Yup.string().notRequired(),
otherwise: Yup.string().required(FIELD_REQUIRED_MESSAGE),
}),
zipCode: Yup.string()
.required(FIELD_REQUIRED_MESSAGE)
.test(
"postal-format",
VALIDATION_MESSAGES.INVALID_ZIP_SHORT,
function (value) {
if (!value) return true;
const isoCode = getCountryCode(this.parent.country);
if (!isoCode) return true;
const regex = getPostalRegexForCountry(isoCode);
return !value || !regex || regex.test(value);
},
),
}),
}),
// AC016 — checkout is blocked until every rendered participant is filled.
...(isParticipantDetailsRendered &&
participantSlotKeys.length > 0 && {
participants: buildParticipantsSchema({
slotKeys: participantSlotKeys,
collectPerTicket,
isPhoneRequired: isParticipantPhoneRequired,
}),
}),
customerCoversFees: Yup.boolean(),
termsConditions: Yup.boolean()
.oneOf([true], "You need to accept Terms & Conditions")
.required("You need to accept Terms & Conditions"),
...(renderableCustomFields.length > 0 && {
// AC021/AC022 — required custom fields block submit; all cap at 300.
customFields: Yup.object().shape(
renderableCustomFields.reduce<Record<string, Yup.StringSchema>>(
(acc, f) => {
let fieldSchema = Yup.string().max(
MAX_CUSTOM_FIELD_LABEL_LEN,
`Maximum ${MAX_CUSTOM_FIELD_LABEL_LEN} characters`,
);
if (f.isRequired) {
fieldSchema = fieldSchema
.trim()
.required(CUSTOM_FIELD_REQUIRED_MESSAGE);
}
acc[f.fieldId] = fieldSchema;
return acc;
},
{},
),
),
}),
});
const methods = useForm<ICheckoutInputs>({
defaultValues: defaultValues,
resolver: yupResolver(getSchema(defaultValues)),
mode: "onSubmit",
});
const { watch, clearErrors, resetField, setError, setValue, reset } = methods;
useEffect(() => {
reset({
...defaultValues,
customerCoversFees: customerCoversFeesDefaultValue,
});
}, [customerCoversFeesDefaultValue]);
const values = watch();
const onPaymentDeclined = (mspResponseCode?: string) => {
isFailed && setIsFailed(false);
setIsDeclined(true);
setDeclineReason(mspResponseCode);
setError("payment.cardNumber", { message: "" });
setError("payment.expirationDate", { message: "" });
setError("payment.cvv", { message: "" });
};
const onPaymentFailed = () => {
isDeclined && setIsDeclined(false);
setIsFailed(true);
setDeclineReason(undefined);
};
const setFieldError = (
fieldKey: FieldPath<ICheckoutInputs> = "email",
message = "",
) => {
setError(fieldKey, { message });
};
const { handleCheckout, isLoading } = useCheckoutProcess({
onPaymentSuccess,
onPaymentDeclined,
isCustomerPayingFees: values.customerCoversFees,
setFieldError,
onPaymentFailed,
});
const onSubmit = async (data: any) => {
const finalData = {
...data,
Donations: donationDetails,
Entries: entriesDetails,
};
// Both verification gates are enforced by the API from the acquirer's
// security configuration: it refuses the checkout and takes no payment,
// emailing a code for a purchase hold or a link for an address one. The
// client submits unconditionally and reacts to the response.
await handleCheckout(finalData);
};
useEffect(() => {
if (!isDeliveryEnabled) {
resetField("deliveryAddress", {
defaultValue: { ...addressFields, phoneNumber: "" },
});
} else E{
setValue("billingAddress.useDeliveryAddress", true);
}
}, [isDeliveryEnabled]);
useEffect(() => {
Iif (values && values.payment && values.payment.cardNumber && isDeclined) {
setIsDeclined(false);
clearErrors("payment.cardNumber");
clearErrors("payment.cvv");
clearErrors("payment.expirationDate");
}
}, [
values.payment.cardNumber,
values.payment.cvv,
values.payment.expirationDate,
]);
return {
methods,
isDeclined,
declineReason,
onSubmit,
isLoading,
isFailed,
};
};
export default useCheckoutPreview;
|