All files / src/sections/PayBuilder/hooks useFormNavigation.ts

77.61% Statements 52/67
53.48% Branches 23/43
63.63% Functions 7/11
77.27% Lines 51/66

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                                        42x     42x               42x 535x 535x 535x 535x 535x 535x 535x 535x 535x 535x 535x         535x 535x         535x   535x   535x   535x 535x   535x 2x       2x     535x 4x 4x     535x   3x 2x     1x   1x                                                 535x       6x   6x 1x     1x                                                   1x                   5x 5x           5x 1x 1x 2x   1x 1x       4x 4x           1x     1x             535x                
import { useNavigate, useLocation, useParams } from "react-router-dom";
import NiceModal from "@ebay/nice-modal-react";
import { GIVE_CONFIRMATION_POP_UP } from "modals/modal_names";
import { showMessage } from "@common/Toast";
import { usePayBuilderForm } from "../provider/PayBuilderFormProvider";
import useCheckFormType from "../components/hooks/useCheckFormType";
import { useAppTheme } from "@theme/v2/Provider";
import { formTypeToUrlMap } from "../utils";
import { useQueryObserver } from "../LaunchStep/hooks/useQueryObserver";
import { QFORM_QUERY_KEY } from "@pages/AcquirerPortal/Enterprises/Modal/constants";
import { useCart } from "../provider/CartContext";
import useOpenCampaignPanel from "./useOpenCampaignPanel";
import { usePayBuilderContext } from "../provider/PayBuilderContext";
import { useGetSeatingRows } from "@hooks/merchant-api/events/useSeatingRows";
import {
  getSeatingPublishBlock,
  SEATING_PUBLISH_BLOCK_MESSAGE,
} from "../seating.helpers";
 
// The Tickets step (id) — where the per-ticket seating error renders, so a blocked save lands there.
const TICKETS_STEP_ID = "variants_creation";
 
// Define required fields per step for each form type
const requiredFieldsByFormType: Record<string, Record<number, string[]>> = {
  sweepstake: {
    0: ["heading", "sweepstakeEndAtDate", "sweepstakeEndAtTime"],
    2: ["singleEntryPrice"], // key here represents step index of those required fields
  },
  // we can add more types if needed in the futur
};
 
export const useFormNavigation = () => {
  const { mutate, methods } = usePayBuilderForm();
  const navigate = useNavigate();
  const location = useLocation();
  const prevPath = location.state?.prevUrl;
  const { formType, isEvent } = useCheckFormType();
  const { palette } = useAppTheme();
  const { editID } = useParams();
  const { remove } = useQueryObserver(QFORM_QUERY_KEY);
  const { clearCart } = useCart();
  const { openCampaignPanel } = useOpenCampaignPanel();
  const { activeStepIndex, goToStep, stepsArray } = usePayBuilderContext();
 
  // PAY Builder 031 (GB-21528) — the persisted seating rows (with ids), used to block a Save Draft
  // that would silently drop an unassigned ticket. Disabled for non-events / before the product
  // exists (mirrors BottomLeftPanelActions' publish guard).
  const seatingProductId = methods.watch("productId");
  const { data: seatingConfig } = useGetSeatingRows(
    seatingProductId,
    Boolean(seatingProductId && isEvent),
  );
 
  const values = methods.watch();
 
  const defaultValues = methods.formState.defaultValues;
  const isDirty =
    methods.formState.isDirty ||
    JSON.stringify(values) !== JSON.stringify(defaultValues);
  const isPublishedForm = methods.getValues().publishedStatus === "public";
  const { isValid } = methods.formState;
 
  const navigateBack = (id?: any) => {
    navigate(prevPath || `/merchant/${formTypeToUrlMap[formType]}`, {
      replace: true,
    });
 
    id && openCampaignPanel(id, isPublishedForm);
  };
 
  const cleanup = (removeQueries = false) => {
    clearCart();
    removeQueries && remove();
  };
 
  const handleConfirmBeforeClose = async () => {
    // no changes, safe to leave
    if (!isDirty) {
      return navigateBack(editID);
    }
 
    await methods.trigger(undefined);
 
    NiceModal.show(GIVE_CONFIRMATION_POP_UP, {
      modalType: "warning-info",
      title: "You have unsaved changes",
      description:
        "Do you want to save changes made to this payment form? If you leave, any unsaved changes will be lost.",
      customSubmitBtnText: "Yes, Save",
      customCancelBtnText: "Leave",
      cancelSx: { color: palette.primitive?.error[100] },
      useDefaultOnClose: true,
      actions: {
        handleSuccess: {
          onClick: () => handleSaveDraftClick({ navigateAfterSave: true }),
          disable: !isValid,
          tooltip: !isValid ? "Complete all required fields to save" : null,
        },
        handleCancel: {
          onClick: () => {
            cleanup(true);
            navigateBack(editID);
          },
        },
      },
    });
  };
 
  const handleSaveDraftClick = async (options?: {
    navigateAfterSave?: boolean;
  }) => {
    // Trigger validation for all required fields
    const isFormValid = await methods.trigger(undefined);
 
    if (!isFormValid) {
      const typeHasSpecialSteps = formType in requiredFieldsByFormType;
 
      // Handle forms that have required fields in multiple steps
      Iif (typeHasSpecialSteps && activeStepIndex === 0) {
        const { errors } = methods.formState;
        const stepFieldConfig = requiredFieldsByFormType[formType];
 
        const firstStepFields = stepFieldConfig?.[0] ?? [];
        const nextStepFields = stepFieldConfig?.[2] ?? [];
 
        // Extract all current errors for the About step
        const aboutErrorKeys = Object.keys(errors.About ?? {});
 
        // Determine if any step 0 fields still have errors
        const hasStep0Errors = aboutErrorKeys.some((key) =>
          firstStepFields.includes(key),
        );
 
        // Check if step 2 fields have errors
        const step2ErrorsExist = nextStepFields.some(
          (field) => errors.Entries && field in errors.Entries,
        );
 
        // Move to step 2 only if step 0 is valid but step 2 has required errors
        if (!hasStep0Errors && step2ErrorsExist) {
          goToStep({ offSet: 2 });
        }
      }
 
      return;
    }
 
    // PAY Builder 031 (GB-21528) — Save Draft runs the full form save, which POSTs a not-yet-assigned
    // ticket to variants/bulk-create; the BE rejects it (ErrTicketNeedsSeatingRow) and the post-save
    // rehydration then wipes the ticket. Block up front — but ONLY the "unassigned-tickets" case
    // (saved rows exist, a ticket has none): the merchant can just assign a row. The "no-rows" case
    // (brand-new event, nothing saved yet) is deliberately NOT blocked — Save Seating also refuses
    // without a productId, so blocking here would dead-end the merchant; mergeUnsavedItems instead
    // preserves the ticket across the rehydration for that case.
    const vals = methods.getValues();
    const seatingBlock = getSeatingPublishBlock(
      isEvent,
      Boolean(vals?.DateLocation?.assignSeating),
      vals?.Items ?? [],
      seatingConfig?.rows ?? [],
    );
    if (seatingBlock === "unassigned-tickets") {
      showMessage("Error", SEATING_PUBLISH_BLOCK_MESSAGE[seatingBlock]);
      const ticketsIndex = stepsArray.findIndex(
        (s: { id: string }) => s.id === TICKETS_STEP_ID,
      );
      Eif (ticketsIndex >= 0) goToStep({ index: ticketsIndex, free: true });
      return;
    }
 
    // Proceed with saving logic if form is valid
    cleanup();
    mutate({
      isSaveDb: true,
      shouldNavigate: false,
      internalNavigation: true,
      isNewDraft: !editID,
      handleSuccessCB() {
        methods.reset(methods.getValues());
 
        // navigate after successful save if requested
        Iif (options?.navigateAfterSave) {
          navigateBack(editID);
        }
      },
    });
  };
 
  return {
    isDirty,
    isValid,
    handleConfirmBeforeClose,
    handleSaveDraftClick,
    isPublishedForm,
  };
};