All files / src/sections/PayBuilder/items AddProductItemModal.tsx

53.01% Statements 44/83
49.74% Branches 96/193
45.83% Functions 11/24
56.41% Lines 44/78

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                                                                                      45x 45x                                                                                     45x                       29x 29x   29x   29x 29x               29x                                               29x   29x           29x               13x 13x 13x 13x         44x                                               11x             29x                     29x   29x 29x 29x   29x 9x     29x                   29x         29x                                                                                                     29x 29x     29x       29x   9x     9x       9x     29x         29x                     29x                                                                                                                                                                                                                                                                                                                                                                                                                                 1x                     29x   29x                                         3x                                                                             377x   230x                                                    
import { WithTooltipWrapper } from "@common/Menu/NewDropdownMenu";
import useNiceModal from "@common/Modal/ModalFactory/hooks/useNiceModal";
import { showMessage } from "@common/Toast";
import RESOURCE_BASE, {
  OPERATIONS,
  UPLOAD_DENY_MESSAGE,
} from "@constants/permissions";
import NiceModal from "@ebay/nice-modal-react";
import { yupResolver } from "@hookform/resolvers/yup";
import { Grid, Stack } from "@mui/material";
import { TrashIcon } from "@phosphor-icons/react";
import GiveButton from "@shared/Button/GiveButton";
import HFGiveCustomAmount from "@shared/HFInputs/HFGiveCustomAmount/HFGiveCustomAmount";
import { HFGiveInput } from "@shared/HFInputs/HFGiveInput/HFGiveInput";
import HFGiveIntegerInput from "@shared/HFInputs/HFGiveInput/HFGiveIntegerInput";
import HFGiveSelect from "@shared/HFInputs/HFGiveSelect/HFGiveSelect";
import GiveBaseModal from "@shared/modals/GiveBaseModal";
import GiveMotionWrapper from "@shared/Motion/GiveMotionWrapper";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import {
  composePermission,
  useAccessControl,
} from "features/Permissions/AccessControl";
import { uniqueId } from "lodash";
import { useEffect, useMemo, useState } from "react";
import { FormProvider, SubmitHandler, useForm } from "react-hook-form";
import * as Yup from "yup";
import { VALIDATION_MESSAGES } from "@validation/messages";
import { PaymentRecurringType, ProductItemType, SeatingRow } from "../types";
import ImageBox from "../components/ImageBox";
import { MediaItem } from "../provider/provider.type";
import GiveCheckbox from "@shared/GiveCheckbox/GiveCheckbox";
import GiveText from "@shared/Text/GiveText";
import { getItemName, parseNumber } from "@sections/PayBuilder/helpers";
import GiveSwitch from "@shared/Switch/GiveSwitch";
import GiveTooltip from "@shared/Tooltip/GiveTooltip";
import { CANNOT_EXCEED_MAX_AMOUNT } from "@constants/stringConstants";
import { MAX_ALLOWED_AMOUNT } from "@constants/constants";
import { CampaignMapperValues } from "@features/Minibuilders/PaymentFormMinibuilder/useCreateCampaignFn";
import { paymentTypeSuffixes, recurringOptions } from "../constants";
import SeatingRowsField from "./SeatingRowsField";
import { deriveTicketSeatingRowIDs } from "../seating.helpers";
 
const AMOUNT_ERROR_MESSAGE = "Must be above 1 USD";
const MAX_SIGNUP_FEE = 25000;
 
type FormInputs = {
  thumbnail: string;
  amount: string | null;
  title: string;
  in_stock?: number | null;
  display?: boolean;
  description: string | null;
  paymentType: string;
  signupFee?: string | null;
  featureList?: string;
  signupFeeCheckbox?: boolean;
  hideInventory?: boolean;
  hideSoldOut?: boolean;
  seatingRowIDs?: number[];
};
 
type FormTypes = {
  isEvent: boolean;
  isMembership: boolean;
  formType: CampaignMapperValues;
  isProduct: boolean;
  isInvoice: boolean;
};
 
type Props = {
  item?: ProductItemType;
  hasUniqueTitle?: (title: string, id?: string) => boolean;
  onClose?: (item?: ProductItemType) => void;
  handleDelete: (item: ProductItemType) => void;
  totalItemsAmount?: number;
  formTypes?: FormTypes;
  assignSeating?: boolean; // AC006: event has assigned seating on
  seatingRows?: SeatingRow[]; // AC006: saved rows (with ids) selectable for this ticket
  // rowID → owning ticket name for rows already assigned to OTHER tickets (rendered
  // disabled in the seat map) — one seating row belongs to at most one ticket.
  takenRows?: Map<number, string>;
};
 
// Moved to ../constants.ts to break circular dependencies
export { paymentTypeSuffixes } from "../constants";
 
const AddProductItemModal = NiceModal.create(
  ({
    item,
    hasUniqueTitle,
    onClose,
    handleDelete,
    totalItemsAmount = 0,
    formTypes,
    assignSeating = false,
    seatingRows = [],
    takenRows,
  }: Props) => {
    const { open, onClose: hideModal } = useNiceModal();
    const [isLoading, setIsLoading] = useState<boolean>(false);
 
    const { isMobileView } = useCustomThemeV2();
    const { isEvent, isMembership, formType, isProduct, isInvoice } =
      formTypes || {};
    const isUpdateAllowed = useAccessControl({
      resource: composePermission(
        RESOURCE_BASE.MERCHANT,
        RESOURCE_BASE.PRODUCT,
        RESOURCE_BASE.AMOUNT,
      ),
      operation: OPERATIONS.UPDATE,
    });
    const defaultValues = {
      thumbnail: item?.thumbnail || "",
      amount: item?.amount || null,
      in_stock: item?.in_stock ?? (isInvoice ? 1 : null),
      title: item?.title || "",
      description: item?.description?.replaceAll("<br>", "\n") || "",
      paymentType: item?.paymentType || (isMembership ? "monthly" : "once"),
      ...(isMembership && {
        featureList: item?.featureList || "• ",
      }),
      signupFee: item?.signupFee || "",
      signupFeeCheckbox: item?.signupFeeCheckbox || false,
      hideInventory: item?.hideInventory ?? false,
      hideSoldOut: item?.hideSoldOut ?? false,
      // The variant GET doesn't return seatingRowIDs, so reconstruct them from the seating
      // config's reverse mapping (rows[].variantIDs) — else a saved ticket re-opens with no
      // rows selected. Falls back to explicit ids if the BE ever returns them.
      seatingRowIDs: deriveTicketSeatingRowIDs(
        item?.variantID,
        item?.seatingRowIDs,
        seatingRows,
      ),
    };
 
    const canEdit = (!!item && isUpdateAllowed) || !item;
 
    const isAddImageAllowed = useAccessControl({
      resource: RESOURCE_BASE.MEDIA_ITEM,
      operation: OPERATIONS.CREATE,
      withPortal: true,
    });
 
    const schema = Yup.object().shape({
      title: Yup.string()
        .trim()
        .max(100, "Name can not contain more than 100 characters")
        .required(VALIDATION_MESSAGES.REQUIRED),
      amount: Yup.string()
        .required(AMOUNT_ERROR_MESSAGE)
        .test(AMOUNT_ERROR_MESSAGE, (value) => {
          Iif (!value) return false;
          const valueToNumber = parseFloat(value);
          Iif (Number.isNaN(valueToNumber)) return false;
          return valueToNumber >= 1;
        }),
      in_stock: Yup.number()
        .nullable()
        .transform((value, originalValue) => {
          return originalValue === "" ? undefined : value;
        })
        .max(2147483647, "Entered number exceeds the acceptable range"),
      display: Yup.boolean(),
      hideInventory: Yup.boolean(),
      thumbnail: Yup.mixed<File | string>(),
      description: Yup.string().nullable(),
      signupFeeCheckbox: Yup.boolean(),
      signupFee: Yup.string().when("signupFeeCheckbox", {
        is: true,
        then: Yup.string()
          .required(AMOUNT_ERROR_MESSAGE)
          .test("isValidAmount", AMOUNT_ERROR_MESSAGE, (value) => {
            if (!value) return false;
            const valueToNumber = parseFloat(value);
            if (Number.isNaN(valueToNumber)) return false;
            return valueToNumber >= 1;
          }),
        otherwise: Yup.string().nullable(),
      }),
      // AC007: when the event uses assigned seating, a ticket must sell at least one row.
      // Only enforce once rows actually exist — otherwise a brand-new event (rows saved
      // separately, after the ticket) deadlocks: you couldn't save the first ticket.
      seatingRowIDs:
        isEvent && assignSeating && seatingRows.some((r) => r.id != null)
          ? Yup.array()
              .of(Yup.number())
              .min(1, "Select at least one seating row for this ticket.")
          : Yup.array().of(Yup.number()).nullable(),
    });
 
    const methods = useForm<FormInputs>({
      mode: "onChange",
      resolver: yupResolver(schema),
      defaultValues,
    });
    const {
      setValue,
      formState: { dirtyFields, isValid },
      watch,
      reset,
      trigger,
    } = methods;
 
    const signupFeeCheckbox = watch("signupFeeCheckbox");
    const hideInventory = watch("hideInventory");
    const hideSoldOut = watch("hideSoldOut");
 
    useEffect(() => {
      reset(defaultValues);
    }, [item, isMembership]);
 
    const handleSignupFeeCheckboxChange = (
      e: React.ChangeEvent<HTMLInputElement>,
    ) => {
      const isChecked = e.target.checked;
      setValue("signupFeeCheckbox", isChecked, { shouldDirty: true });
      if (!isChecked) {
        trigger("signupFee");
      }
    };
 
    const onCancel = () => {
      reset(defaultValues);
      hideModal();
    };
 
    const onSubmit: SubmitHandler<FormInputs> = async (data) => {
      if (hasUniqueTitle && !hasUniqueTitle(data.title, item?.id)) {
        showMessage("Error", "An element with the same name already exists");
        return;
      }
      setIsLoading(true);
 
      const amount: ProductItemType = {
        id: item ? item.id : uniqueId(),
        title: dirtyFields.title || !item ? data.title : item.title,
        amount: dirtyFields.amount || !item ? data.amount : item.amount,
        description:
          dirtyFields.description || !item
            ? data.description?.replaceAll("<br>", "\n") ?? ""
            : item.description,
        thumbnail:
          dirtyFields.thumbnail || !item ? data?.thumbnail : item?.thumbnail,
        in_stock: data?.in_stock ?? (isInvoice ? 1 : null),
        hideInventory: data?.hideInventory,
        hideSoldOut: data?.hideSoldOut,
        paymentType: data?.paymentType as PaymentRecurringType,
        signupFee: signupFeeCheckbox
          ? dirtyFields.signupFee || !item
            ? data.signupFee
            : item.signupFee
          : "",
        signupFeeCheckbox:
          dirtyFields.signupFeeCheckbox || !item
            ? data?.signupFeeCheckbox
            : item?.signupFeeCheckbox,
        // Empty dots should be removed
        ...(isMembership && {
          featureList: (data.featureList || "")
            .split("\n")
            .filter((item) => item.trim().length > 1)
            .join("\n"),
        }),
        ...(isEvent && {
          seatingRowIDs: data.seatingRowIDs ?? [],
        }),
        ...(!item && {
          display: true,
        }),
      };
      setIsLoading(false);
      hideModal();
      reset(defaultValues);
 
      if (onClose) onClose(amount);
    };
 
    const getCurrencyLabel = (type: string): string => {
      return `USD ${isInvoice ? "" : paymentTypeSuffixes[type]}`;
    };
 
    const filteredRecurringOptions = isMembership
      ? recurringOptions.filter((option) => option.value !== "once")
      : recurringOptions;
 
    const isInvoiceItemExceeded = useMemo(() => {
      const amount =
        typeof watch("amount") === "string" ? watch("amount") : "0";
 
      const summaryAmount =
        totalItemsAmount -
        parseNumber(item?.amount || "0") * +(item?.in_stock || 1) +
        parseNumber(amount || "0") * +(watch("in_stock") || 1);
 
      return isInvoice && summaryAmount > MAX_ALLOWED_AMOUNT;
    }, [isInvoice, totalItemsAmount, item, watch("amount"), watch("in_stock")]);
 
    const handleSelect = (item?: MediaItem) => {
      setValue("thumbnail", item?.URL || "", { shouldDirty: true });
    };
 
    const StockInput = (
      <HFGiveIntegerInput
        label={isInvoice ? "Quantity" : "Stock (Optional)"}
        name="in_stock"
        placeholder="Stock"
        disabled={!canEdit}
        {...(isInvoice ? { min: 1 } : {})}
        max={Number.MAX_SAFE_INTEGER}
        hidePlaceholder
      />
    );
 
    const nodesList = [
      {
        node: (
          <WithTooltipWrapper
            hasTooltip={!isAddImageAllowed}
            tooltipProps={{
              show: !isAddImageAllowed,
              message: UPLOAD_DENY_MESSAGE,
            }}
          >
            <>
              <ImageBox
                imageUrl={methods.watch("thumbnail")}
                handleSelect={handleSelect}
              />
            </>
          </WithTooltipWrapper>
        ),
        hidden: isInvoice,
      },
      {
        node: (
          <HFGiveInput
            label="Name"
            name="title"
            placeholder="Name"
            maxLength={100}
            disabled={!canEdit}
          />
        ),
      },
      {
        node: (
          <HFGiveCustomAmount
            name="amount"
            label="Price"
            placeholder="Price"
            currency={getCurrencyLabel(methods.watch("paymentType"))}
            disabled={!canEdit}
            onHandleBlur={
              dirtyFields.amount ? () => trigger("amount") : undefined
            }
          />
        ),
        xs: isMobileView ? 12 : isMembership || isProduct ? 6 : 12,
        ...(isInvoice && {
          xs: isMobileView ? 6 : 4,
        }),
      },
      {
        node: StockInput,
        xs: isMobileView ? 6 : 4,
        hidden: !isInvoice,
      },
      {
        node: (
          <HFGiveSelect
            label={isMembership ? "Recurring" : "One Time or Recurring"}
            placeholder={isMembership ? "Recurring" : "One Time or Recurring"}
            name="paymentType"
            options={filteredRecurringOptions}
            useContextualMenu
            contextualMenuProps={
              !isMobileView
                ? {
                    color: "tertiary",
                    texture: "blurred",
                    menuWidth: 278,
                  }
                : {}
            }
            disabled={!canEdit}
          />
        ),
        xs: isMobileView ? 12 : isMembership || isProduct ? 6 : 12,
        ...(isInvoice && {
          xs: isMobileView ? 12 : 4,
        }),
        hidden: isEvent,
      },
      {
        node: (
          <Stack direction="row" alignItems="center" gap="12px">
            <GiveCheckbox
              name="signupFeeCheckbox"
              checked={signupFeeCheckbox}
              size="medium"
              disabled={!canEdit}
              onChange={handleSignupFeeCheckboxChange}
            />
            <GiveText variant="bodyS">Add Signup Fee</GiveText>
          </Stack>
        ),
        hidden: !isMembership,
      },
      {
        node: (
          <HFGiveCustomAmount
            name="signupFee"
            label="Signup Fee"
            placeholder="Signup Fee"
            currency="usd"
            disabled={!canEdit}
            hidePlaceholder
            max={MAX_SIGNUP_FEE}
            onHandleBlur={
              dirtyFields.signupFee ? () => trigger("signupFee") : undefined
            }
          />
        ),
        animate: false,
        hidden: !isMembership || !signupFeeCheckbox,
      },
      {
        node: (
          <HFGiveInput
            label="Description (Optional)"
            name="description"
            placeholder="Description"
            multiline
            rows={8}
            disabled={!canEdit}
            displayCounter
            hidePlaceholder
          />
        ),
        hidden: isInvoice,
      },
      {
        node: StockInput,
        hidden: isMembership || isInvoice,
      },
      {
        node: (
          <Stack direction="row" spacing={2}>
            <GiveSwitch
              aria-label="display item"
              checked={!hideInventory}
              onChange={() => {
                setValue("hideInventory", !hideInventory, {
                  shouldDirty: true,
                });
              }}
            />
            <GiveText variant="bodyS">Display stock to the customer</GiveText>
          </Stack>
        ),
        hidden: isMembership || isInvoice,
      },
      {
        node: (
          <Stack direction="row" spacing={2}>
            <GiveSwitch
              aria-label="display item"
              checked={!hideSoldOut}
              onChange={() => {
                setValue("hideSoldOut", !hideSoldOut, {
                  shouldDirty: true,
                });
              }}
            />
            <GiveText variant="bodyS">
              Display Sold Out if no inventory
            </GiveText>
          </Stack>
        ),
        hidden: isMembership || isInvoice,
      },
      {
        node: (
          <HFGiveInput
            name="featureList"
            label="Feature List (Optional)"
            multiline
            rows={8}
            sx={{
              "& .MuiInputBase-input": {
                lineHeight: "20px !important", // Adjust line height
              },
            }}
            onKeyUp={(e) => {
              if (e.key === "Enter") {
                const lines = watch("featureList")?.split("\n") || [];
 
                const bulletified = lines.map((line: string) => {
                  // If line doesn't start with '• ', prepend it
                  if (!line.trim().startsWith("•")) {
                    return `• ${line}`;
                  }
                  // Otherwise, leave it as-is
                  return line;
                });
 
                const newValue = bulletified.join("\n");
                setValue("featureList", newValue);
              }
            }}
          />
        ),
        hidden: !isMembership,
      },
      {
        node: (
          <SeatingRowsField
            seatingRows={seatingRows}
            value={(watch("seatingRowIDs") || []) as number[]}
            canEdit={canEdit}
            takenRows={takenRows}
            onChange={(ids) =>
              setValue("seatingRowIDs", ids, {
                shouldValidate: true,
                shouldDirty: true,
              })
            }
          />
        ),
        hidden: !(isEvent && assignSeating),
      },
    ];
 
    const title = `${item ? "Edit" : "Add"} ${getItemName(formType)}`;
 
    return (
      <GiveBaseModal
        open={open}
        title={title}
        width="640px"
        height="95%"
        onClose={onCancel}
        customDialogStyle={{
          zIndex: 1201,
          "& .MuiDialogActions-root .MuiButton-root": {
            width: "unset",
          },
        }}
        footerLeftContent={
          item && handleDelete ? (
            <GiveButton
              label="Delete"
              variant="ghost"
              color="destructive"
              size="large"
              startIcon={<TrashIcon size={18} />}
              onClick={() => handleDelete(item)}
            />
          ) : null
        }
        buttons={
          <Stack gap="12px" flexDirection="row">
            <GiveButton
              onClick={onCancel}
              label="Cancel"
              variant="ghost"
              size="large"
            />
            <GiveTooltip
              title={CANNOT_EXCEED_MAX_AMOUNT}
              placement="top"
              disableHoverListener={!isInvoiceItemExceeded}
            >
              <GiveButton
                label={item ? "Save Changes" : "Add"}
                variant="filled"
                size="large"
                disabled={isLoading || !isValid || isInvoiceItemExceeded}
                form="create-product-item"
                onClick={methods.handleSubmit(onSubmit)}
                sx={{ whiteSpace: "nowrap" }}
              />
            </GiveTooltip>
          </Stack>
        }
      >
        <FormProvider {...methods}>
          <Grid
            container
            component="form"
            spacing={3}
            id="create-product-item"
            onSubmit={methods.handleSubmit(onSubmit)}
          >
            {nodesList
              .filter((item) => !item.hidden)
              .map(({ node, xs, hidden, animate = true }, index) => (
                <Grid
                  item
                  xs={xs || 12}
                  key={index}
                  sx={{ ...(hidden && { display: "none" }) }}
                >
                  {animate ? (
                    <GiveMotionWrapper delay={50 * (index + 1)}>
                      {node}
                    </GiveMotionWrapper>
                  ) : (
                    node
                  )}
                </Grid>
              ))}
          </Grid>
        </FormProvider>
      </GiveBaseModal>
    );
  },
);
 
// Moved to ../constants.ts to break circular dependencies
export { recurringOptions } from "../constants";
 
export default AddProductItemModal;