All files / src/sections/PayBuilder/provider useManagePayFormProvider.ts

53.5% Statements 145/271
32.77% Branches 98/299
69.76% Functions 30/43
52.54% Lines 134/255

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 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164                                                                                                                                                            46x   46x 22x   22x                       46x 738x   201x           537x         738x 738x 738x 738x 738x     738x 738x 738x           738x 738x 738x 738x 60x     738x           738x             738x   738x     738x 91x 91x 91x   91x                   738x 738x   738x 738x 738x 738x     738x   738x     738x 738x             738x                   738x   738x         738x   738x     738x           738x   738x         738x   738x 104x 22x                                                                                     22x 3x         22x       22x               22x 22x                 738x 82x 22x                             738x   738x 60x     60x       738x                                       738x                                   2x 2x   2x     2x     2x 2x 2x 2x 2x                                                                                                                                                                                                                                                                                                                                                                                                         2x                                                                                                                                                                                                                                                                                                                                                                               2x     2x         738x                       10x               10x 8x           2x         2x                   738x     738x   738x   738x                                               738x                                                                         46x 374x             4x         4x                       188x 139x 139x     159x 110x 110x 110x 110x       46x             4x         4x                   4x 4x                 46x   169x   68x                   46x       278x                                                                                                 46x           46x 46x   46x                                                         46x 201x                           278x   148x     130x               278x             5x 5x   5x   3x           3x                 278x             2x 2x   2x                                           2x             2x               46x                          
import { useForm } from "react-hook-form";
import { showMessage } from "@common/Toast";
import NiceModal from "@ebay/nice-modal-react";
import { yupResolver } from "@hookform/resolvers/yup";
import { useGetCurrentMerchantId } from "@hooks/common";
import { useGetPaymentFormInfos } from "@hooks/payment-forms/useListPaymentForms";
import { QFORM_QUERY_KEY } from "@pages/AcquirerPortal/Enterprises/Modal/constants";
import { useAppSelector } from "@redux/hooks";
import { selectPaymentFormID } from "@redux/slices/products";
import { customInstance } from "@services/api";
import {
  capitalizeFirstLetter,
  getSettledPromise,
  rgbaToHex,
} from "@utils/index";
import { CAMPAIGN_DETAILS_MODAL } from "modals/modal_names";
import { useEffect, useMemo, useState } from "react";
import { useMutation, useQueryClient } from "react-query";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import * as Yup from "yup";
import { INTERNATIONAL_ZIP_REGEX, TIME_12HR_FORMAT_REGEX } from "@validation/regex";
import { VALIDATION_MESSAGES } from "@validation/messages";
import { PaymentRecurringType, PendingActionType } from "../types";
import {
  combineDateAndTime,
  convertProductToCartItem,
  formatVariantsToMatchPayload,
  FormDataType,
  formTypeToUrlMap,
  generateFormData,
  generatePayloadForCheckout,
  generatePayloadForProduct,
  getInitialFormData,
  getTextColorsBasedOnBackground,
  isAheadOfCurrentTime,
} from "../utils";
import { usePayBuilderContext } from "./PayBuilderContext";
import { Variant } from "./provider.type";
import { ICartItem, useCart, useInitCartItems } from "./CartContext";
import { useIsEnabled } from "../components/hooks/useHelpers";
import { isEmpty } from "lodash";
import useCheckFormType from "../components/hooks/useCheckFormType";
import {
  QKEY_GET_CAMPAGIN_STATS,
  QKEY_GET_PRODUCT_TYPES,
  QKEY_LIST_PAYMENT_FORMS,
  QKEY_SEATING_ROWS,
} from "@constants/queryKeys";
import { CampaignMapperValues } from "features/Minibuilders/PaymentFormMinibuilder/useCreateCampaignFn";
import { mapTypeToQueryKey } from "@services/api/products/queryFactory";
import { useIsPreviewMode } from "./useIsPreviewMode";
import { FormType } from "../utils";
import { useGetCustomerById } from "@services/api/customer";
import useOpenCampaignPanel from "../hooks/useOpenCampaignPanel";
import { createStreetAddressValidator } from "@validation/address/streetValidator";
import { buildZipSchema } from "@validation/address/zipValidator";
import { createStateValidator } from "@validation/address/stateValidator";
import { createCityValidation } from "@validation/address/cityValidator";
import { createCountryValidator } from "@validation/address/countryValidator";
import {
  mergeUnsavedItems,
  reconcileCreatedVariantIDs,
  resolveHydratedAssignSeating,
  shouldSeedAssignSeating,
  toSeatingRowsPayload,
  validateSeatingRows,
  withDerivedSeatingRowIDs,
} from "../seating.helpers";
import { SeatingRow } from "../types";
import { usePublicSeating } from "@hooks/payment-forms/usePublicSeating";
import { useGetFeatureFlagValues } from "FeatureFlags/useGetFeatureFlagValues";
import { useEventParticipantDetails } from "../Checkout/hooks/useEventParticipantDetails";
import {
  CUSTOM_FIELD_LABEL_REQUIRED,
  hasEmptyEnabledCustomFieldLabel,
  shouldForkPublishedFormOnSave,
} from "../Checkout/customFields.helpers";
 
const REQUIRED_FIELD_TEXT = VALIDATION_MESSAGES.REQUIRED;
 
const getStartIndex = (stop?: string) => {
  switch (stop) {
    case "launch":
      return 4;
    case "checkout_configuration":
      return 3;
    case "style_configuration":
      return 2;
    case "variants_creation":
      return 1;
    default:
      return 0;
  }
};
 
const schemaBuilder = (type: CampaignMapperValues, isEdit: boolean) => {
  switch (type) {
    case "event":
      return schema.concat(eventSchema(isEdit));
    case "sweepstake":
      return schema.concat(sweepstakeSchema);
    case "invoice":
      return invoiceSchema;
    default:
      return schema;
  }
};
 
export default function useManagePayFormProvider() {
  const { id, editID } = useParams();
  const location = useLocation();
  const prevPath = location.state?.prevUrl;
  const peekedFormId = useAppSelector(selectPaymentFormID);
  const duplicateInvoiceId = location?.state?.duplicateInvoiceId;
 
  const editFormId =
    id || location.state?.id || peekedFormId || editID || duplicateInvoiceId;
  const isEdit = !!editFormId;
  const queryClient = useQueryClient();
  const {
    formType,
    isInvoice,
    isEvent,
    isLoading: isCheckoutLoading,
  } = useCheckFormType();
  const { isPreviewMode } = useIsPreviewMode();
  const productTableQueryKey = mapTypeToQueryKey[formType];
  const defaultValues = useMemo(
    () => getInitialFormData(formType, isPreviewMode),
    [formType, isPreviewMode],
  );
  const methods = useForm<FormDataType>({
    reValidateMode: "onChange",
    resolver: yupResolver(schemaBuilder(formType, isEdit)),
    defaultValues,
  });
 
  const { watch, trigger, formState, setValue, reset } = methods;
 
  const {
    endsAt: eventsEndsAt,
    endsAtTime: eventsEndsAtTime,
    includeTime: eventsIncludeTime,
    startsAt: eventsStartsAt,
  } = watch("DateLocation");
 
  const sweepstakeTimeError = formState?.errors?.About?.sweepstakeEndAtTime;
 
  //this useEffect is added to validate fields onMounth. (for ex.: when we edit events to validate, and check if the ends date is in the past)
  useEffect(() => {
    if (eventsStartsAt) trigger("DateLocation.startsAt");
    Iif (eventsEndsAt) trigger("DateLocation.endsAt");
    Iif (eventsIncludeTime && eventsEndsAtTime)
      trigger("DateLocation.endsAtTime");
    Iif (sweepstakeTimeError) trigger("About.sweepstakeEndAtDate");
  }, [
    eventsStartsAt,
    eventsEndsAt,
    eventsEndsAtTime,
    eventsIncludeTime,
    sweepstakeTimeError,
    trigger,
  ]);
 
  const { addItemsToCart } = useCart();
  const { merchantId } = useGetCurrentMerchantId();
 
  const { isLastStep } = usePayBuilderContext();
  const navigate = useNavigate();
  const { openCampaignPanel } = useOpenCampaignPanel();
  const { setLastStepCompleted, lastStepCompleted } = usePayBuilderContext();
 
  const [checkoutBottomSheetVisible, setCheckoutBottomSheetVisible] =
    useState(false);
 
  const { isPayBuilderCustomFieldsEnabled } = useGetFeatureFlagValues();
  // same answer the three render surfaces use, so the save can never write a
  // config the checkout does not render (or vice versa)
  const isContactNameEnabled = isEvent;
  const isParticipantDetailsEnabled = useEventParticipantDetails();
 
  // PAY-Builder016 (AC017/AC018) — set once a structural custom-field edit is
  // confirmed on a *published* form. The eventual Save reads this to fork a new
  // draft (saveAsNewDraft) instead of patching the live form. Lives here (not in
  // the section) so it survives step navigation and no per-edit save fires.
  const [customFieldsNeedNewDraft, setCustomFieldsNeedNewDraft] =
    useState(false);
 
  /* TODO: we should remove all the instances of calling this hook in another files.
  in some cases id should be 
  */
 
  const {
    data,
    isLoading: isPaymentFormInfosLoading,
    isFetched,
  } = useGetPaymentFormInfos(editFormId);
 
  const { data: customer } = useGetCustomerById(
    methods.watch("About.customerId") || 0,
  );
 
  // Check if the current route matches either `/:id` or `/:id/checkout` to enable get cart request
  const isEnabled = useIsEnabled();
 
  const defaultRecurringIntervalName = data?.defaultRecurringIntervalName;
 
  const [isFormDataFilledWithApiData, setIsFormDataFilledWithApiData] =
    useState(editFormId ? false : true);
 
  // PAY Builder 031 — the authoritative Assign Seating state lives on the public /seating
  // response (the merchant product GET omits assignSeating). Declared above the hydration
  // call so the reset below can seed the toggle from it instead of defaulting to false, and
  // so cart hydration knows whether a seatless item is a seated ticket (GB-21697).
  const { data: seatingConfig } = usePublicSeating(editFormId, isEdit && isEvent);
 
  useInitCartItems(
    Boolean(isEnabled && data?.variants?.length && !isInvoice),
    data?.variants,
    Boolean(seatingConfig?.assignSeating),
  );
  const initPrice = location?.state?.initPrice;
 
  useEffect(() => {
    if (isFetched) {
      const formData = generateFormData(
        {
          ...data,
          // For duplicate invoices we shouldn't keep the same publish status as original one
          publishedStatus: duplicateInvoiceId
            ? undefined
            : data?.publishedStatus,
          // PAY Builder 031 — the product GET omits assignSeating, so hydrate the toggle from
          // the authoritative /seating response. Without this, this reset (which also re-runs
          // on the post-save product refetch) resets the toggle to false → the reported
          // "toggle turns off after save". Falls back to false until /seating loads; the seed
          // effect below then turns it on when the server says on.
          assignSeating: resolveHydratedAssignSeating({
            isEvent,
            seatingConfigLoaded: seatingConfig !== undefined,
            seatingConfigAssignSeating: seatingConfig?.assignSeating,
          }),
          // PAY Builder 031 — preserve the current seating rows across this reset. The product
          // GET omits seatingRows, so generateFormData would set them to []; on the post-save
          // product refetch that reset WIPES the just-saved rows out of the editor and they
          // vanish — the config editor only re-applies server rows when the /seating-rows query
          // signature CHANGES, and after a save the server already matches its last-applied
          // signature, so it never re-applies. Keeping the current form rows lets the editor
          // keep showing them; the /seating-rows query stays the source of truth and reconciles
          // on its next real change. On first load the form is empty, so this is a no-op there.
          ...(isEvent
            ? {
                seatingRows:
                  methods.getValues("DateLocation.seatingRows") ?? [],
              }
            : {}),
        } as any,
        { selectedAmount: initPrice },
        isPreviewMode,
        duplicateInvoiceId,
      );
      // PAY Builder 031 (GB-21528) — this reset rebuilds Items from server variants only, so a
      // brand-new ticket whose variant create the BE rejected (a seatless ticket on an
      // assign-seating event) would be silently wiped. Re-attach the merchant's still-unsaved
      // tickets (mergeUnsavedItems drops any that the successful save now returns by title, so no
      // duplicates) so a rejected create never erases their work — they stay to be assigned and
      // re-saved. Events only: the seating reject is event-specific, and this keeps invoice/cart
      // hydration below untouched.
      if (isEvent) {
        formData.Items = mergeUnsavedItems(
          formData.Items ?? [],
          methods.getValues("Items"),
        );
      }
      reset(formData);
      /* If the first item has in_stock 0, this means that this form is either paid or reserved.
       * In this case we shouldn't create cart manually.
       */
      Iif (isInvoice && formData.Items?.[0]?.in_stock !== 0) {
        const cartObject: { [id: number | string]: ICartItem } = {};
        formData.Items?.forEach((item) => {
          const id = item.id;
          cartObject[id] = convertProductToCartItem(item);
        });
        addItemsToCart(cartObject);
      }
      setLastStepCompleted?.(getStartIndex(formData.stopStep));
      setIsFormDataFilledWithApiData(true);
    }
  }, [isPaymentFormInfosLoading, isFetched, initPrice]);
 
  // PAY Builder 031 — the hydration reset above now seeds the toggle from the authoritative
  // /seating response (seatingConfig, declared before that effect). This seed remains as a
  // belt-and-suspenders for the case where /seating resolves AFTER the reset has already run
  // with it undefined (initial open): it turns the toggle ON when the server says on and never
  // clobbers an in-session toggle (dirty).
  useEffect(() => {
    if (!isFormDataFilledWithApiData) return;
    Iif (
      shouldSeedAssignSeating({
        serverAssignSeating: seatingConfig?.assignSeating,
        formAssignSeating: Boolean(
          methods.getValues("DateLocation.assignSeating"),
        ),
        isFieldDirty: methods.getFieldState("DateLocation.assignSeating")
          .isDirty,
      })
    ) {
      setValue("DateLocation.assignSeating", true);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [seatingConfig, isFormDataFilledWithApiData]);
 
  const selectedCountry = methods.watch("DateLocation.locationAddress.country");
  //to reset the state if country is changed
  useEffect(() => {
    const { isDirty } = methods.getFieldState(
      "DateLocation.locationAddress.country",
    );
    Iif (!!selectedCountry && isDirty)
      setValue("DateLocation.locationAddress.state", "");
  }, [selectedCountry]);
 
  const createBaseVariant = (formType: string) => {
    const baseVariant = {
      amount: null,
      description: "",
      display: false,
      id: "1",
      in_stock: null,
      paymentType: "once" as PaymentRecurringType,
      thumbnail: "",
      title: "Any Amount",
      allowCustomPrice: true,
    };
    //TODO: update more attr
    if (formType === FormType.SWEEPSTAKE) {
      return { ...baseVariant, bundle: 1 };
    }
 
    return baseVariant;
  };
 
  const { mutate, isLoading } = useMutation(
    async ({
      cb,
      publish,
      shouldNavigate = true,
      internalNavigation = false,
      isNewDraft = false,
      saveAsNewDraft = false,
    }: {
      cb?: () => void;
      publish?: boolean;
      shouldNavigate?: boolean;
      internalNavigation?: boolean;
      isNewDraft?: boolean;
      // PAY-Builder016 (AC018) — force a full create of a brand-new draft copy
      // (product/checkout/variants/seating) and leave the source form untouched.
      saveAsNewDraft?: boolean;
    }) => {
      const values = methods.watch();
      const cachedId = (queryClient.getQueryData(QFORM_QUERY_KEY) as any)
        ?.product?.id;
      const cachedCheckooutId = (
        queryClient.getQueryData(QFORM_QUERY_KEY) as any
      )?.checkout?.value?.id;
      const productId = location.state?.id || cachedId;
      // A "duplicate" save always creates (never patches) — the invoice-duplicate
      // flow and the PAY-Builder016 duplicate-on-published-edit share this.
      const isDuplicate = !!duplicateInvoiceId || saveAsNewDraft;
      const isPatch = !!productId && !isDuplicate;
      const dbFormType = formType === "product" ? "standard" : formType;
      try {
        const productResponse = await customInstance({
          url: isPatch
            ? `/merchants/${merchantId}/products/${productId}`
            : `/merchants/${merchantId}/products`,
          method: isPatch ? "PATCH" : "POST",
          data: generatePayloadForProduct(
            { ...values, stopStep: lastStepCompleted },
            getInitialFormData(dbFormType),
            dbFormType,
            defaultRecurringIntervalName, // This props is for making the fundraisers donation backwards compatible with the old form
            isParticipantDetailsEnabled, // Story 2 — omit the keys entirely for non-events
          ),
        });
 
        const dbProductId = productResponse?.id || productId;
 
        // PAY Builder 031 — the variant GET omits seatingRowIDs, so an existing ticket the
        // merchant hasn't re-opened this session carries []. Sending [] makes the BE clear the
        // ticket->row mapping (replaceSeatingRows treats a present empty array as authoritative),
        // wiping assigned seating on every save. Derive each ticket's true rows from the seating
        // config (which carries variantIDs) so untouched tickets round-trip their assignment;
        // explicit in-session edits win (deriveTicketSeatingRowIDs). Read the config from the
        // query cache — freshest, and its key is invalidated on Save.
        const seatingConfigRows =
          (
            queryClient.getQueryData([QKEY_SEATING_ROWS, dbProductId]) as
              | { rows?: SeatingRow[] }
              | undefined
          )?.rows ?? [];
        const withSeats = <
          T extends { variantID?: number | string | null; seatingRowIDs?: number[] },
        >(
          items: T[] | undefined,
        ): T[] =>
          isEvent && !!values?.DateLocation?.assignSeating
            ? withDerivedSeatingRowIDs(items ?? [], seatingConfigRows)
            : items ?? [];
 
        // For a duplicate all the variants need to be created, not updated or deleted
        const variantsToUpdate = isDuplicate
          ? []
          : formatVariantsToMatchPayload(
              withSeats(values?.Items?.filter((item) => item.variantID)),
            );
 
        const variantsToCreate = formatVariantsToMatchPayload(
          formType === FormType.FUNDRAISERS || formType === FormType.SWEEPSTAKE
            ? [createBaseVariant(formType)]
            : withSeats(
                values?.Items?.filter((item) =>
                  isDuplicate ? true : !item.variantID,
                ),
              ),
        );
        const variantsToDelete = isDuplicate
          ? []
          : values.variantsToDeleteIDS;
 
        // PAY Builder 031 — persist seating rows with the normal Save. Keep row ids
        // (toSeatingRowsPayload) so the BE upserts in place and ticket seatingRowIDs
        // stay valid. Validate client-side first; on error toast and skip the PUT.
        const seatingRows = (values?.DateLocation?.seatingRows ||
          []) as SeatingRow[];
        const seatingError =
          isEvent && values?.DateLocation?.assignSeating && dbProductId
            ? validateSeatingRows(seatingRows)
            : null;
        if (seatingError) showMessage("Error", seatingError);
        const doSaveSeating =
          isEvent &&
          !!values?.DateLocation?.assignSeating &&
          !!dbProductId &&
          !seatingError;
 
        const variantsURL = `/merchants/${merchantId}/products/${dbProductId}/variants`;
        const checkoutId =
          data?.checkout?.customCheckoutForm?.id || cachedCheckooutId;
        const isCheckoutPost = !checkoutId || isDuplicate;
        const checkoutUrl = isCheckoutPost
          ? `/merchants/${merchantId}/products/${dbProductId}/checkout-forms`
          : `/merchants/${merchantId}/products/${dbProductId}/checkout-forms/${checkoutId}`;
        const nexRequests = [
          variantsToUpdate.length > 0
            ? customInstance({
                url: variantsURL,
                data: variantsToUpdate,
                method: "PATCH",
              })
            : Promise.resolve(null),
          variantsToCreate.length > 0
            ? customInstance({
                url: `/merchants/${merchantId}/products/${dbProductId}/variants/bulk-create`,
                data: { variants: variantsToCreate },
                method: "POST",
              })
            : Promise.resolve(null),
          variantsToDelete.length > 0
            ? customInstance({
                url: variantsURL,
                data: { variantIDs: variantsToDelete },
                method: "DELETE",
              })
            : Promise.resolve(null),
          dbProductId
            ? customInstance({
                url: checkoutUrl,
                method: isCheckoutPost ? "POST" : "PATCH",
                data: generatePayloadForCheckout(
                  values,
                  dbFormType,
                  isPayBuilderCustomFieldsEnabled,
                  isContactNameEnabled,
                ),
              })
            : Promise.resolve(null),
          doSaveSeating
            ? customInstance({
                url: `/merchants/${merchantId}/products/${dbProductId}/seating-rows`,
                method: "PUT",
                data: { rows: toSeatingRowsPayload(seatingRows) },
              })
            : Promise.resolve(null),
        ];
 
        const [updateRes, createRes, deleteRes, checkoutRes, seatingRes] =
          await Promise.allSettled(nexRequests);
 
        /**
         * Publish request needs to be sent after all the above requests are done with Promise.allSettled, because if for example,
         * publish request finishes before bulk-create request, for invoices user will recieve email without items.
         */
 
        const [publishedRes] = await Promise.allSettled([
          publish && dbProductId
            ? customInstance({
                url: `/merchants/${merchantId}/products/${dbProductId}/publish-status`,
                data: {
                  publishedStatus: "public",
                },
                method: "PATCH",
              })
            : Promise.resolve(null),
        ]);
 
        const updatedVariants: Variant[] =
          getSettledPromise(updateRes)?.succeeded || [];
        const createdVariants: Variant[] =
          getSettledPromise(createRes)?.data || [];
 
        // when either of the above request fails in totality
        const publishedProduct = getSettledPromise(publishedRes);
 
        const failedResponses = {
          update:
            updateRes.status === "rejected"
              ? updateRes.reason?.response?.data?.message
              : null,
          create:
            createRes.status === "rejected"
              ? createRes.reason?.response?.data?.message
              : null,
          delete:
            deleteRes.status === "rejected"
              ? deleteRes.reason?.response?.data?.message
              : null,
          publish:
            publishedRes?.status === "rejected"
              ? publishedRes?.reason?.response?.data?.message
              : null,
          checkout:
            checkoutRes?.status === "rejected"
              ? checkoutRes?.reason?.response?.data?.message ||
                "Checkout request failed."
              : null,
          seating:
            seatingRes?.status === "rejected"
              ? seatingRes?.reason?.response?.data?.message ||
                "Seating request failed."
              : null,
        };
        const variants = [...createdVariants, ...updatedVariants];
 
        const product =
          (publishedRes as any)?.value && publishedRes?.status === "fulfilled"
            ? publishedProduct
            : productResponse;
 
        return {
          product: product,
          checkout: checkoutRes,
          failedResponses,
          variants,
          createdVariants,
          publishedProduct,
          dbProductId,
        };
      } catch (error) {
        throw new Error("Product request failed");
      }
    },
    {
      onSuccess(data, variables) {
        const { product, failedResponses, publishedProduct, dbProductId } =
          data || {};
 
        queryClient.setQueryData([QFORM_QUERY_KEY], data);
        if (product?.id) setValue("productId", product?.id);
 
        // PAY-Builder016 — the pending-fork intent is consumed by this save
        // (a fork lands on a fresh unpublished draft anyway). Clear it so a
        // later edit-and-save doesn't fork again unintentionally.
        setCustomFieldsNeedNewDraft(false);
 
        // PAY Builder 031 (GB-21528) — stamp the just-created variants' ids back onto the form's
        // tickets. Without this a created ticket keeps its client-only id (no variantID), so the
        // next save re-POSTs it to bulk-create; on a seating event the BE then rejects it because
        // the row is already owned by the variant this save created ("...already assigned to
        // another ticket"). Set before the caller's success cb runs its reset(getValues()), so the
        // stamped ids are captured and the ticket routes through variantsToUpdate (PATCH) next time.
        if (isEvent && (data?.createdVariants?.length ?? 0) > 0) {
          setValue(
            "Items",
            reconcileCreatedVariantIDs(
              methods.getValues("Items") ?? [],
              data?.createdVariants,
            ),
          );
        }
 
        if (dbProductId)
          queryClient.invalidateQueries([
            "get-payment-form-checkout",
            dbProductId,
          ]);
 
        // PAY Builder 031 — refresh the seating rows so the editor re-hydrates with the
        // just-saved rows. Without this the [QKEY_SEATING_ROWS, productId] cache stays stale
        // and a newly added row never appears after Save (SeatingConfigEditor re-applies
        // server rows by content signature, which only changes once this refetches).
        if (dbProductId) {
          queryClient.invalidateQueries([QKEY_SEATING_ROWS, dbProductId]);
          // PAY Builder 031 — refresh the authoritative seating state so the toggle hydration
          // (and its seed) reflect the just-saved assignSeating, especially a first-time enable
          // whose /seating was cached false/empty. Prefix match sidesteps the string/number id
          // variance between the /seating query key (editFormId) and dbProductId.
          queryClient.invalidateQueries(["public-seating"]);
        }
 
        queryClient.invalidateQueries(QKEY_LIST_PAYMENT_FORMS);
        queryClient.refetchQueries(QKEY_GET_CAMPAGIN_STATS);
        queryClient.refetchQueries({
          queryKey: [QKEY_GET_PRODUCT_TYPES, merchantId],
          exact: true,
        });
 
        queryClient.invalidateQueries(productTableQueryKey);
 
        if (failedResponses) {
          Object.entries(failedResponses).forEach(([key, message]) => {
            if (message) {
              showMessage("Error", message);
            }
          });
        }
        NiceModal.hide(CAMPAIGN_DETAILS_MODAL);
 
        // Re-populate cart after successful save if we're staying on the page (internalNavigation)
        // This is needed because clearCart() is called before save, and we need to restore the cart
        if (variables?.internalNavigation && isInvoice) {
          const currentValues = methods.getValues();
          if (
            currentValues.Items?.length > 0 &&
            currentValues.Items[0]?.in_stock !== 0
          ) {
            const cartObject: { [id: number | string]: ICartItem } = {};
            currentValues.Items.forEach((item) => {
              const id = item.id;
              cartObject[id] = convertProductToCartItem(item);
            });
            addItemsToCart(cartObject);
          }
        }
 
        // PAY-Builder016 (AC018) — a duplicate save lands the merchant in the new
        // draft copy; the source (published) form was never patched, so it stays
        // live and unchanged. Skip the default list/campaign navigation below.
        if (variables?.saveAsNewDraft && dbProductId) {
          showMessage(
            "Success",
            "Saved as a new draft. Your published form is unchanged.",
          );
          navigate(`/pay_product_builder/${dbProductId}`, {
            state: { id: dbProductId },
            replace: true,
          });
          return;
        }
 
        // append newly created draft ID to URL so a page refresh can restore the correct draft data.
        if (variables?.isNewDraft && dbProductId) {
          const pathname = location.pathname.endsWith("/")
            ? location.pathname.slice(0, -1)
            : location.pathname;
 
          navigate(
            {
              pathname: `${pathname}/${dbProductId}`,
              search: location.search,
            },
            {
              replace: true,
            },
          );
        }
        if (variables?.shouldNavigate !== false) {
          navigate(`/merchant/${formTypeToUrlMap[formType]}`);
          queryClient.removeQueries({ queryKey: QFORM_QUERY_KEY });
        } else {
          const paymentDetailsQueryKeys = [
            ["find-product-payment-by-id", dbProductId],
            ["get-payment-form-by-id", dbProductId],
            ["get-payment-form-checkout", dbProductId],
            ["get-payment-form-variants", dbProductId],
          ];
 
          paymentDetailsQueryKeys.forEach((key) =>
            queryClient.invalidateQueries(key),
          );
 
          !variables?.internalNavigation &&
            navigate(
              isEmpty(publishedProduct)
                ? { pathname: location.pathname, search: location.search }
                : {
                    pathname:
                      prevPath || `/merchant/${formTypeToUrlMap[formType]}`,
                  },
              {
                state: {
                  id: product?.id,
                },
                replace: true,
              },
            );
        }
        !isEmpty(publishedProduct) && openCampaignPanel(product?.id, true);
        variables?.cb?.();
 
        const paymentName =
          product.typeName === "standard"
            ? "Product"
            : capitalizeFirstLetter(product.typeName);
        // if (
        //   isADBEnabled &&
        //   location.pathname === "/pay_product_builder" &&
        //   product?.publishedStatus !== "draft"
        // ) {
        // NiceModal.show(
        //   getCampaignModal(formType, isADBEnabled, true)
        //     ?.success,
        //   {
        //     data: {
        //       ...product,
        //       about: {
        //         title: product.name,
        //         description: product.description,
        //       },
        //       style: {
        //         image: {
        //           URL: product.imageURL,
        //         },
        //       },
        //       campaign: product.typeName,
        //     },
        //     productId: product?.id,
        //   },
        // );
        // } else {
        // }
      },
      onError(error, variables, context) {
        showMessage("Error", "error creating the products");
      },
      onSettled(data, error, variables, context) {
        variables?.cb?.();
      },
    },
  );
 
  const handleSubmit = (data: {
    handleSuccessCB?: () => void;
    isSaveDb?: boolean;
    publish?: boolean;
    shouldNavigate?: boolean;
    internalNavigation?: boolean;
    isNewDraft?: boolean;
    saveAsNewDraft?: boolean;
  }) => {
    // PAY-Builder016 (AC005) — the BE rejects a blank custom-field label
    // (ErrInvalidCustomFieldLabel); block the commit before it goes out. The
    // offending row already shows its inline "Field can't be empty." error.
    Iif (
      isPayBuilderCustomFieldsEnabled &&
      hasEmptyEnabledCustomFieldLabel(methods.getValues("Checkout.customFields"))
    ) {
      showMessage("Error", CUSTOM_FIELD_LABEL_REQUIRED);
      return;
    }
 
    if (!isLastStep && !data?.isSaveDb && !data?.saveAsNewDraft)
      return data.handleSuccessCB && data.handleSuccessCB();
 
    // PAY-Builder016 (AC018) — a published form whose custom fields were
    // structurally edited this session is saved as a new draft copy, not
    // patched in place. Decided at the save chokepoint so structural edits
    // never fire their own (racy, duplicating) network save.
    const forkPublishedForm = shouldForkPublishedFormOnSave({
      isPublished: methods.watch("publishedStatus") === "public",
      customFieldsNeedNewDraft,
    });
 
    mutate({
      cb: data?.handleSuccessCB,
      publish: data?.publish,
      shouldNavigate: data?.shouldNavigate,
      internalNavigation: data?.internalNavigation,
      isNewDraft: data?.isNewDraft,
      saveAsNewDraft: data?.saveAsNewDraft || forkPublishedForm,
    });
  };
 
  const { luminance } = getTextColorsBasedOnBackground(
    rgbaToHex(methods.watch().Style.background, true).toUpperCase(),
  );
  const inputColor = luminance < 0.5 ? "#4D4D4C66" : "#FFFFFF80";
  const paymentSectionBackground =
    luminance < 0.5 ? "rgba(255,255,255,0.06)" : "rgba(255,255,255,0.15)";
 
  const checkoutInputStyles = {
    ".MuiInputBase-root": {
      backgroundColor: `${inputColor} !important`,
    },
    ".MuiInputBase-root.Mui-disabled": {
      backgroundColor: `${inputColor} !important`,
    },
    ".MuiInputBase-root.Mui-error": {
      boxShadow: "none !important",
    },
    ".MuiInputBase-root.Mui-focused": {
      backgroundColor: `${inputColor} !important`,
      backgroundImage: "none !important",
      boxShadow: `
          inset 0 0 0 -2px ${inputColor},
          inset 0 0 0 2px #4F86D5,
          inset 0 0 0 2px #61C7E8
    `,
    },
    "& .MuiInputBase-input:-webkit-autofill": {
      boxShadow: "none",
    },
  };
 
  return {
    data,
    methods,
    mutate: handleSubmit,
    merchantId,
    isLoading,
    isFetched,
    isPaymentFormInfosLoading,
    queryClient,
    isFormDataFilledWithApiData,
    customer,
    parsedValues: {
      accentColor: rgbaToHex(methods.watch().Style.accent, true),
      background: rgbaToHex(methods.watch().Style.background, true),
      itemsLayout: methods.watch().Style.itemLayout,
      heading: methods.watch().About.heading,
      description: methods.watch().About.description,
      selectedImage: methods.watch().About.selectedImage,
      selectedVideoURL: methods.watch().About.selectedVideoURL,
      assetPosition: methods.watch().About.assetPosition,
      items: methods.watch().Items,
      logo: methods.watch().Style.logo,
      checkoutContent: methods.watch().Style.checkoutContent,
      inputColor,
      paymentSectionBackground,
      checkoutInputStyles,
    },
    checkoutBottomSheetVisible,
    setCheckoutBottomSheetVisible,
    isCheckoutLoading,
    // PAY-Builder016 — structural custom-field edits on a published form mark
    // this so the next Save forks a new draft (AC018).
    customFieldsNeedNewDraft,
    setCustomFieldsNeedNewDraft,
  };
}
 
export const startsAtValidationSchema = (isEdit = false) =>
  Yup.mixed()
    .nullable()
    .when("timeActiveTab", {
      is: "range",
      then: Yup.mixed()
        .required(REQUIRED_FIELD_TEXT)
        .test("is-valid-date", "Provide a valid date", (value) => {
          Eif (!value) return false;
          const date = new Date(value);
          return date instanceof Date && !isNaN(date.getTime());
        })
        .test("is-not-in-past", "The date cannot be in the past", (value) => {
          Eif (isEdit) return true;
 
          if (!value) return false;
          const inputDate = new Date(value);
          const today = new Date();
          today.setHours(0, 0, 0, 0);
          return inputDate >= today;
        }),
      otherwise: Yup.mixed()
        .nullable()
        .required(REQUIRED_FIELD_TEXT)
        .test("is-valid-date", "Provide a valid date", (value) => {
          if (!value) return false;
          const date = new Date(value);
          return date instanceof Date && !isNaN(date.getTime());
        })
        .test("is-not-in-past", "The date cannot be in the past", (value) => {
          if (!value) return false;
          const inputDate = new Date(value);
          const today = new Date();
          today.setHours(0, 0, 0, 0);
          return inputDate >= today;
        }),
    });
 
export const endsAtValidationSchema = Yup.mixed()
  .nullable()
  .when("timeActiveTab", {
    is: "range",
    then: Yup.mixed()
      .required(REQUIRED_FIELD_TEXT)
      .test("is-valid-date", "Provide a valid date", (value) => {
        Eif (!value) return false;
        const date = new Date(value);
        return date instanceof Date && !isNaN(date.getTime());
      })
      .test("is-not-in-past", "The date cannot be in the past", (value) => {
        Eif (!value) return false;
        const inputDate = new Date(value);
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        return inputDate >= today;
      })
      .test(
        "is-after-start",
        "End date must be after or equal to the start date",
        function (value) {
          const { startsAt } = this.parent || {};
          Eif (!value || !startsAt) return true;
          const startDate = new Date(startsAt);
          const endDate = new Date(value);
          return endDate >= startDate;
        },
      ),
    otherwise: Yup.mixed().nullable(),
  });
 
export const locationURLValidationSchema = Yup.string()
  .transform((value, originalValue) => {
    if (!originalValue) return "";
 
    return "https://" + originalValue;
  })
  .when("locationPosition", {
    is: "online",
    then: Yup.string()
      .required("Location URL is required")
      .url("Please enter a valid URL"),
    otherwise: Yup.string().nullable(),
  });
 
export const locationAddressSchema = Yup.object().when(
  ["locationPosition", "isManualAddress"],
  {
    is: (locationPosition: string, isManualAddress: boolean) =>
      locationPosition === "onsite" && isManualAddress === true,
    then: Yup.object().shape({
      line1: createStreetAddressValidator({
        requiredMessage: VALIDATION_MESSAGES.LINE1_REQUIRED,
      }),
      line2: createStreetAddressValidator({ required: false, nullable: true }),
      city: createCityValidation({
        required: true,
        customRequiredMessage: VALIDATION_MESSAGES.CITY_REQUIRED,
      }),
      state: createStateValidator({
        required: true,
        requiredMessage: VALIDATION_MESSAGES.STATE_REQUIRED,
      }),
      zip: buildZipSchema({
        required: true,
        countryField: "country",
        nonUSValidator: () =>
          Yup.string().matches(
            INTERNATIONAL_ZIP_REGEX,
            VALIDATION_MESSAGES.INVALID_POSTAL_CODE_SHORT,
          ),
        message: VALIDATION_MESSAGES.INVALID_ZIP_SHORT,
        allowNull: false,
      }),
 
      country: createCountryValidator({
        required: true,
        message: VALIDATION_MESSAGES.COUNTRY_REQUIRED,
      }),
    }),
    otherwise: Yup.object()
      .nullable()
      .shape({
        line1: createStreetAddressValidator({
          required: false,
          nullable: true,
        }),
        line2: createStreetAddressValidator({
          required: false,
          nullable: true,
        }),
        city: createCityValidation({ nullable: true }),
        state: createStateValidator({ nullable: true }),
        zip: buildZipSchema({ allowNull: true }),
        country: createCountryValidator({ nullable: true }),
      }),
  },
);
const schema = Yup.object().shape({
  About: Yup.object().shape({
    heading: Yup.string().required(REQUIRED_FIELD_TEXT),
  }),
});
 
export const MAX_QNT_ALLOWED = 2147483647;
export const MAX_QNT_ALLOWED_ERROR_MESSAGE = `Entered number exceeds the acceptable range`;
 
const sweepstakeSchema = Yup.object().shape({
  About: Yup.object().shape({
    sweepstakeEndAtDate: startsAtValidationSchema(),
    sweepstakeEndAtTime: Yup.string()
      .required(REQUIRED_FIELD_TEXT)
      .test("is-valid-time", "Provide a valid time", (value, { parent }) => {
        const timeRegex = TIME_12HR_FORMAT_REGEX;
        if (parent["sweepstakeEndAtDate"] && value) {
          return (
            timeRegex.test(value) &&
            isAheadOfCurrentTime(parent["sweepstakeEndAtDate"], value)
          );
        }
        return timeRegex.test(value ?? "");
      }),
  }),
  Entries: Yup.object().shape({
    singleEntryPrice: Yup.string()
      .required(REQUIRED_FIELD_TEXT)
      .test(
        "is-valid-price",
        VALIDATION_MESSAGES.PROVIDE_VALID_VALUE,
        (value) => {
          return true;
        },
      ),
  }),
});
 
export const eventSchema = (isEdit: boolean) =>
  Yup.object().shape({
    DateLocation: Yup.object().shape({
      locationPosition: Yup.string().oneOf(
        ["online", "onsite"],
        "Invalid location position",
      ),
      isManualAddress: Yup.boolean(),
      startsAt: startsAtValidationSchema(isEdit),
      endsAt: endsAtValidationSchema,
      locationURL: locationURLValidationSchema,
      locationShortAddress: Yup.string().when(
        ["locationPosition", "isManualAddress"],
        {
          is: (locationPosition: string, isManualAddress: boolean) =>
            locationPosition === "onsite" && isManualAddress === false,
          then: (schema) =>
            schema
              .nullable() // accept null for type check
              .required(REQUIRED_FIELD_TEXT),
          otherwise: (schema) => schema.nullable(),
        },
      ),
      locationAddress: locationAddressSchema,
      startsAtTime: Yup.mixed()
        .nullable()
        .when(["timeActiveTab", "includeTime"], {
          is: (timeActiveTab: string, includeTime: boolean) =>
            includeTime === true,
          then: Yup.string()
            .required(REQUIRED_FIELD_TEXT)
            .test(
              "is-valid-time",
              "Provide a valid time",
              (value, { parent }) => {
                const { timeActiveTab } = parent || {};
                const timeRegex = TIME_12HR_FORMAT_REGEX;
 
                if (isEdit && timeActiveTab === "range") return true;
 
                Iif (parent["startsAt"] && value) {
                  return (
                    timeRegex.test(value) &&
                    isAheadOfCurrentTime(parent["startsAt"], value)
                  );
                }
                return timeRegex.test(value ?? "");
              },
            ),
          otherwise: Yup.mixed().nullable(),
        }),
      endsAtTime: Yup.mixed()
        .nullable()
        .when(["timeActiveTab", "includeTime"], {
          is: (timeActiveTab: string, includeTime: boolean) =>
            timeActiveTab === "range" && includeTime === true,
          then: Yup.string()
            .required(REQUIRED_FIELD_TEXT)
            .test(
              "is-valid-time",
              "Provide a valid time",
              (value, { parent }) => {
                const timeRegex = TIME_12HR_FORMAT_REGEX;
                const isValidValue = timeRegex.test(value ?? "");
 
                Iif (
                  parent["startsAt"] &&
                  parent["startsAtTime"] &&
                  parent["endsAt"] &&
                  value
                ) {
                  const startsDateValue = combineDateAndTime(
                    parent["startsAt"],
                    parent["startsAtTime"],
                  );
                  const endsDateValue = combineDateAndTime(
                    parent["endsAt"],
                    value,
                  );
                  const isAheadOfStartDate = endsDateValue > startsDateValue;
                  return (
                    isValidValue &&
                    isAheadOfCurrentTime(parent["endsAt"], value) &&
                    isAheadOfStartDate
                  );
                }
 
                Iif (parent["endsAt"] && value) {
                  return (
                    isValidValue &&
                    isAheadOfCurrentTime(parent["endsAt"], value)
                  );
                }
 
                return isValidValue;
              },
            ),
          otherwise: Yup.mixed().nullable(),
        }),
    }),
  });
 
const invoiceSchema = Yup.object().shape({
  About: Yup.object().shape({
    customerId: Yup.mixed()
      .nullable()
      .required(REQUIRED_FIELD_TEXT)
      .test(
        "not-empty",
        REQUIRED_FIELD_TEXT,
        (value) => value !== "" && value !== null,
      ),
  }),
  Items: Yup.array().of(Yup.object()).min(1, "Item is required"),
});