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 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 | 1x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 173x 114x 114x 114x 114x 114x 8x 114x 114x 114x 24x 16x 16x 8x 114x 114x 37x 37x 37x 8x 37x 16x 37x 37x 37x 37x 37x 37x 114x 114x 114x 114x 114x 114x 8x 114x 114x 114x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 114x 114x 4x 114x 4x 4x 114x 37x 25x 25x 25x 25x 25x 25x 114x 114x 114x 114x 29x 29x 29x 114x 8x 114x 4x 4x 4x 4x 4x 4x 114x 114x 114x 114x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 12x 12x 12x 12x 12x 8x 8x 8x 12x 12x 12x 12x 4x 4x 4x 114x 8x 8x 8x 8x 8x 8x 8x 114x 8x 8x 10x 8x 114x 114x 1x 114x 1x 1x 1x 114x 114x 114x 114x 1x 1x 2x 1x 114x 1x 1x 1x 1x 1x 114x 114x 114x 114x 114x 1x 114x 114x 114x 114x 47x 1x 12x 12x 12x 1x 12x 4x 4x 4x 12x 8x 8x 8x 8x 4x 4x 12x 12x 4x 1x 1x 12x 12x 12x 1x | import { useCustomTheme } from "@theme/hooks/useCustomTheme";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
ErrorType_bulk_merchant,
TImportedRow,
TInviteElement,
TInvitesMap,
BulkInviteActions,
} from "../types";
import NiceModal from "@ebay/nice-modal-react";
import { getSelectedKeys, invitesSorter } from "../utils";
import {
GIVE_ADD_INVITE_MODAL,
GIVE_CONFIRMATION_POP_UP,
GIVE_EDIT_INVITE_MODAL,
} from "modals/modal_names";
import useSorting from "@hooks/Reducers/useSorting";
import { useAppDispatch, useAppSelector } from "@redux/hooks";
import {
saveInvitationsDraft,
saveProcessor,
saveProviderId,
selectInvitationsDraft,
} from "@redux/slices/enterprise/merchants";
import { useGetCurrentMerchantId } from "@hooks/common";
import { removeSpecialChars } from "@utils/slug";
import { SLUG_MAX_CHARACTER_LENGTH } from "@constants/constants";
import { checkPortals } from "@utils/routing";
import {
useIsMutating,
useMutation,
useQuery,
useQueryClient,
} from "react-query";
import { customInstance } from "@services/api";
import { showMessage } from "@common/Toast";
import { isEmpty, isNull, uniqBy } from "lodash";
import { MAXIMUM_NUMBER_OF_MERCHANTS_TO_INVITE } from "../constants";
import { Stack } from "@mui/material";
import GiveText from "@shared/Text/GiveText";
import { BellRingingIcon, WarningIcon } from "@phosphor-icons/react";
import {
QKEY_LIST_ACQUIRER_MERCHANTS,
QKEY_LIST_MERCHANT_STATS,
QKEY_LIST_MERCHANTS,
} from "@constants/queryKeys";
import { useRefetchCounters } from "@hooks/acquirer-api/merchants/stats/useGetMerchantCounters";
import { ProcessorValue } from "@features/Merchants/MerchantSidePanel/types";
import { useGetProcessors } from "@hooks/acquirer-api/merchants/useGetProcessors";
import { useGetFeatureFlagValues } from "FeatureFlags/useGetFeatureFlagValues";
import { useAppTheme } from "@theme/v2/Provider";
import { v4 as uuidv4 } from "uuid";
// /accounts/1/background-tasks
type TModifyHandler = (key: string, value: TInviteElement) => void;
type TValuesCount = Record<string, string[]>;
const useBulkInvite = (initialProviderId: number) => {
const { isMerchantProcessorEnabled } = useGetFeatureFlagValues();
const mapRef = useRef<TInvitesMap>(new Map());
// Normalized merchantNames that have just been successfully invited.
// Used to suppress them from the delayed draft-hydration pass (which would
// otherwise restore the stale entries) and from the unmount-persist effect.
const recentlyCompletedNamesRef = useRef<Set<string>>(new Set());
const { handleRefetchCounters } = useRefetchCounters();
const [loading, setLoading] = useState<
"idle" | "isLoading" | "isInviting" | "isSending"
>("idle");
const isLoading = loading === "isLoading";
const isInviting = loading === "isInviting";
const isIdle = loading === "idle";
const {
merchantId,
name: currentUserName,
img: currentUserImg,
} = useGetCurrentMerchantId();
const savedDraft = useAppSelector((state) =>
selectInvitationsDraft(state, merchantId),
);
const {
entries: savedInvitesDraft = [],
providerId: savedProviderId = 0,
processor: savedProcessor = "",
} = savedDraft || {};
const [providerId, setProviderId] = useState(
(savedProviderId != 0 ? savedProviderId : initialProviderId) || 0,
);
const [providerName, setProviderName] = useState<string>("");
const [providerLogo, setProviderLogo] = useState<string>("");
const [invitesList, setInvitesList] = useState(() =>
Array.from(mapRef.current.entries()),
);
const { data: processors, isLoading: processorsLoading } = useGetProcessors(
merchantId,
isMerchantProcessorEnabled,
);
const [processor, setProcessor] = useState<ProcessorValue | "">(
(savedProcessor as ProcessorValue) || "",
);
useEffect(() => {
//the default value needs to be the rs2 processor, which can have different name based on acquirer so we need to set it after data fetch
if (processorsLoading || !processors) return;
// If the processor was restored from draft (or user selected it), don't override it.
if (processor) return;
const rs2 = processors?.find((item) => item.name.includes("rs2"))?.name;
setProcessor(rs2 || "");
}, [processorsLoading, processors, processor]);
const totalSelected = useRef<number>(0);
const {
theEntireList,
allCheckedHaveError,
someCheckedHaveError,
hasSelectedItems,
areAllSelected,
isIndeterminate,
} = useMemo(() => {
const theEntireList = Array.from(mapRef.current.values());
const checkedItems = theEntireList.filter((item: any) => item.checked);
const allCheckedHaveError = checkedItems.every(
(item: any) => item.errorType !== "",
);
const someCheckedHaveError = checkedItems.some(
(item: any) => item.errorType !== "",
);
const hasSelectedItems = theEntireList?.some((item) => item?.checked);
const checkedItemsCount = checkedItems.length;
totalSelected.current = checkedItemsCount;
const areAllSelected =
theEntireList.length > 0 && checkedItemsCount === theEntireList.length;
const isIndeterminate =
checkedItemsCount > 0 && checkedItemsCount < theEntireList.length;
return {
theEntireList,
allCheckedHaveError,
someCheckedHaveError,
hasSelectedItems,
areAllSelected,
isIndeterminate,
};
}, [invitesList]);
const theme = useAppTheme();
const { isEnterprisePortal, isAcquirerPortal } = checkPortals();
const dispatch = useAppDispatch();
const { isMobileView } = useCustomTheme();
const queryClient = useQueryClient();
const sendMutationKey = useMemo(
() => ["bulk-invite-send", merchantId],
[merchantId],
);
const isSending = useIsMutating({ mutationKey: sendMutationKey }) > 0;
const { attribute, order, toggleSorting } = useSorting({
tableName: "merchant-invite",
});
const { refetch, data, isRefetching } = useQuery(
["check-bulk-merchant-invites-background", merchantId],
async () => {
setLoading((prev) => {
Iif (prev === "isInviting") return "isInviting";
return "isLoading";
});
const task = await fetchTasks(merchantId);
Iif (!isEmpty(task) && task?.status === "running") {
showMessage(
"Warning",
"We will notify you when the process is completed",
true,
"Sending in progress",
);
setLoading("isInviting");
return { response: [], taskId: null, isInviting: true }; // Exit early if task is still running
}
setLoading("isLoading");
Iif (task?.readAt) {
mapRef.current = new Map(); // Reset the map when task is read
return { response: [], taskId: null, isInviting: false }; // Exit early if task is already read
}
const getList =
task?.id && (await fetchTaskDetails(merchantId, task?.id));
return { response: getList || [], taskId: task?.id, isInviting: false };
},
{
async onSuccess(res) {
const data = res?.response;
const isInviting = res?.isInviting;
const { Success: successfulMerchants, Failures: failedMerchants } =
data?.result || {};
Iif (!isEmpty(successfulMerchants)) {
const acceptedMerchantsArray = successfulMerchants?.map(
(merchant: any) => merchant?.merchantName,
);
await deleteEntriesByKeys(acceptedMerchantsArray);
}
Iif (!isEmpty(failedMerchants)) {
await mapInit(() => {
failedMerchants?.forEach((payloadObject: any) => {
const email = payloadObject?.ownerEmail;
const newEntry: TInviteElement = {
...payloadObject,
checked: false,
errorType: ErrorType_bulk_merchant.MERCHANT_NAME_EXISTS, //to read from api when ready,
merchantName: payloadObject?.merchantName,
pahEmail: email,
};
const key = generateKey(newEntry.merchantName);
if (mapRef.current.has(key)) {
// Merge with the existing entry in the map
mapRef.current.set(key, {
...mapRef.current.get(key), // Keep the existing properties
...newEntry, // Update with new data
});
} else {
// If no existing entry, set the new entry in the map
mapRef.current.set(key, newEntry);
}
});
const selectedItems = theEntireList.filter((item) => item.checked);
totalSelected.current = selectedItems.length;
});
}
const selectedItems = Array.from(mapRef.current.values()).filter(
(item) => item.checked,
);
totalSelected.current = selectedItems.length;
setLoading(isInviting ? "isInviting" : "idle");
},
onSettled(data, error) {
updateList();
},
onError() {
setLoading("idle");
showMessage(
"Error",
"An error occurred while fetching background tasks ",
);
},
enabled:
Boolean(merchantId) &&
(isEnterprisePortal || (isAcquirerPortal && Boolean(merchantId))) &&
!isSending, // avoid extra polling while the POST is still in-flight
},
);
useQuery(
["mark-as-read", merchantId, data?.response, data?.taskId],
async () => {
return await customInstance({
url: `/accounts/${merchantId}/background-tasks/read`,
method: "PUT",
data: { taskIDs: [data?.taskId] },
});
},
{
enabled:
Boolean(merchantId) && !isEmpty(data?.response) && !!data?.taskId,
},
);
const { mutateAsync } = useMutation((data: any) => {
return customInstance({
url: "/merchants/bulk-check",
method: "POST",
data,
});
});
const reasonToErrorType = (
reason?: string,
): ErrorType_bulk_merchant | "" => {
switch (reason) {
case "name_taken":
return ErrorType_bulk_merchant.MERCHANT_NAME_EXISTS;
case "slug_taken":
return ErrorType_bulk_merchant.SLUG_EXISTS;
default:
return ErrorType_bulk_merchant.MERCHANT_NAME_EXISTS;
}
};
// count items with the same normalized name to check for duplicates.
// Names are compared case-insensitively / whitespace-trimmed because the BE
// treats them that way too — otherwise "Acme" and "acme " would slip past
// the uniqueness check and collide on send.
const valuesCount = useMemo(
() =>
invitesList.reduce((acc: TValuesCount, [key, value]) => {
const keyValue = normalizeName(value.merchantName);
Iif (!keyValue) return acc;
Eif (!acc[keyValue]) {
acc[keyValue] = [];
}
acc[keyValue].push(key);
return acc;
}, {}),
[invitesList],
);
const entryIsUnique = (merchantName: string) =>
!!merchantName && valuesCount[normalizeName(merchantName)]?.length === 1;
const checkIsUnique = useCallback(
(newName: string, originalName?: string) => {
const newNorm = normalizeName(newName);
const originalNorm = originalName ? normalizeName(originalName) : "";
if (originalNorm && newNorm === originalNorm) {
return valuesCount[newNorm]?.length < 2;
} else if (originalNorm) {
const total = valuesCount[newNorm];
return !total || total?.length < 1;
} else {
return !valuesCount[newNorm];
}
},
[valuesCount],
);
const showMaximumError = () =>
showMessage(
"Warning",
`A maximum of ${MAXIMUM_NUMBER_OF_MERCHANTS_TO_INVITE} merchants can be invited each time`,
);
const updateList = useCallback(() => {
const list = Array.from(mapRef.current.entries());
const newList = attribute
? list.sort(invitesSorter(attribute, order))
: list;
setInvitesList(newList);
}, [attribute, order]);
useEffect(() => {
updateList();
}, [attribute, order]);
const mapInit = async (callback: () => void) => {
setLoading("isLoading");
// handle initialization asynchronously
return new Promise((resolve) => {
callback();
updateList();
resolve(undefined);
}).finally(() => setLoading("idle"));
};
const deleteEntriesByKeys = async (keys: string[]) => {
if (!keys.length) return; // Early return if no keys provided
await mapInit(() => {
keys.forEach((name) => {
mapRef.current.delete(generateKey(name));
recentlyCompletedNamesRef.current.add(normalizeName(name));
});
// Update selected items logic if needed
const selectedItems = theEntireList.filter((item) => item.checked);
totalSelected.current = selectedItems.length;
}).then(() => updateList());
};
const clearAllInvites = useCallback(() => {
mapRef.current = new Map();
totalSelected.current = 0;
setInvitesList([]);
dispatch(
saveInvitationsDraft({
merchantId,
entries: [],
}),
);
}, [dispatch, merchantId]);
const resetProviderAndProcessor = useCallback(() => {
// Provider/processor selectors exist only in acquirer portal flow.
if (isEnterprisePortal) return;
// local state
setProviderId(0);
setProviderName("");
setProviderLogo("");
setProcessor("");
// redux draft (so close/reopen is also reset)
dispatch(
saveProviderId({
providerId: 0,
merchantId,
}),
);
dispatch(
saveProcessor({
processor: "" as any,
merchantId,
}),
);
}, [dispatch, isEnterprisePortal, merchantId]);
const importedRowsInit = async (arr: TImportedRow[]) => {
setLoading("isLoading");
let initialEntries = cleanArray(arr)?.slice(
0,
MAXIMUM_NUMBER_OF_MERCHANTS_TO_INVITE,
);
Iif (arr?.length > MAXIMUM_NUMBER_OF_MERCHANTS_TO_INVITE) showMaximumError();
const withAddedLength = theEntireList?.length + initialEntries?.length;
Iif (withAddedLength > MAXIMUM_NUMBER_OF_MERCHANTS_TO_INVITE) {
initialEntries = initialEntries?.slice(
0,
MAXIMUM_NUMBER_OF_MERCHANTS_TO_INVITE - theEntireList?.length,
);
showMaximumError();
}
Iif (isEmpty(arr)) {
setLoading("idle");
return showMessage(
"Error",
"Please use the correct template to upload the list",
);
}
Iif (theEntireList?.length >= MAXIMUM_NUMBER_OF_MERCHANTS_TO_INVITE) {
setLoading("idle");
return;
}
const validatedList = await mutateAsync({ merchants: initialEntries });
await mapInit(() => {
validatedList?.results?.forEach((entry: any) => {
const email = entry?.ownerEmail;
const merchantName = entry?.name;
// Skip row if both are empty
Iif (!email && !merchantName) return;
const getErrorType = () => {
if (!entry?.isValid) return reasonToErrorType(entry?.reason);
Iif (merchantName?.length < 4)
return ErrorType_bulk_merchant.MERCHANT_NAME_TOO_SHORT;
Iif (!email) return ErrorType_bulk_merchant.EMAIL_REQUIRED;
return "";
};
const newEntry: TInviteElement = {
...entry,
checked:
entry?.isValid &&
(merchantName?.length >= 4 || emailPattern.test(email || "")),
errorType: getErrorType(),
merchantName,
pahEmail: email,
};
const key = generateKey(merchantName, email);
// Deduplicate
Eif (!mapRef.current.has(key)) {
mapRef.current.set(key, newEntry);
}
});
totalSelected.current = theEntireList.filter(
(item) => item.checked,
).length;
});
updateList();
setLoading("idle");
};
// Hydrate from draft whenever the draft changes.
// IMPORTANT: this must NOT be [] deps, otherwise it can re-hydrate stale entries
// even after we've cleared the draft on successful send.
useEffect(() => {
let timeout: NodeJS.Timeout | null = null;
Iif (savedInvitesDraft.length > 0) {
setLoading("isLoading");
// delay init to handle animations
timeout = setTimeout(() => {
mapInit(() => {
// Re-key by normalized merchantName so drafts persisted under the
// legacy `name::email` format are migrated, and drop any entry the
// background-task / send onSuccess has already marked as completed
// (otherwise this delayed hydration would restore stale rows that
// were just successfully invited).
const filtered = savedInvitesDraft.filter(
([, v]) =>
!recentlyCompletedNamesRef.current.has(
normalizeName(v.merchantName),
),
);
mapRef.current = new Map(
filtered.map(([, v]) => [generateKey(v.merchantName), v]),
);
totalSelected.current = filtered.reduce((acc, [, value]) => {
if (value.checked) return (acc += 1);
return acc;
}, 0);
});
}, 400);
} else {
// If the draft is cleared (e.g. send succeeded), ensure local state is cleared too.
mapRef.current = new Map();
totalSelected.current = 0;
setInvitesList([]);
}
return () => {
Iif (timeout) clearTimeout(timeout);
};
}, [savedInvitesDraft]);
// Persist current in-memory draft on unmount.
useEffect(() => {
return () => {
// Strip just-completed names so reopen doesn't show them as
// "name_taken" — they were successfully invited, not errored.
const entries = Array.from(mapRef.current.entries()).filter(
([, v]) =>
!recentlyCompletedNamesRef.current.has(
normalizeName(v.merchantName),
),
);
dispatch(
saveInvitationsDraft({
merchantId,
entries,
}),
);
};
}, [dispatch, merchantId]);
const setInvite: TModifyHandler = (key, value) => {
mapRef.current.set(key, value);
updateList();
};
const onAddInvite = () => {
NiceModal.show(GIVE_ADD_INVITE_MODAL, {
onSubmit: async (newEntries: TImportedRow[]) => {
importedRowsInit(newEntries);
},
listItems: theEntireList,
});
};
const confirmRemoval = (cb: VoidFunction, totalItems?: string) => {
const isFromEditModal = !totalItems;
const isMultipleItems = totalItems === "all" || Number(totalItems) > 1;
NiceModal.show(GIVE_CONFIRMATION_POP_UP, {
modalType: "delete",
title: isFromEditModal ? "Delete Invitation" : "Delete Invitations",
description: isFromEditModal
? "Are you sure you want to delete invitation? This action cannot be undone."
: `Are you sure you want to delete ${
totalItems === "all" ? "all" : totalItems
} selected invitation${
isMultipleItems ? "s" : ""
}? This action cannot be undone.`,
actions: {
handleSuccess: {
onClick: cb,
},
},
});
};
const editInvite: TModifyHandler = (key, currentValue) => {
const errorType = (() => {
if (
[
ErrorType_bulk_merchant.MERCHANT_NAME_EXISTS,
ErrorType_bulk_merchant.MERCHANT_NAME_REQUIRED,
ErrorType_bulk_merchant.MERCHANT_NAME_TOO_SHORT,
ErrorType_bulk_merchant.SLUG_EXISTS,
].includes(currentValue?.errorType as ErrorType_bulk_merchant) ||
!currentValue?.merchantName
) {
return "merchantName";
}
if (
[
ErrorType_bulk_merchant.EMAIL_INVALID,
ErrorType_bulk_merchant.EMAIL_REQUIRED,
].includes(currentValue?.errorType as ErrorType_bulk_merchant) ||
!currentValue?.pahEmail
) {
return "email";
}
return null;
})();
NiceModal.show(GIVE_EDIT_INVITE_MODAL, {
merchantName: currentValue.merchantName,
pahEmail: currentValue.pahEmail,
errorType: errorType,
checkIsUnique,
handleDelete: (cb?: VoidFunction) =>
confirmRemoval(() => {
removeInvite(key);
cb?.();
}),
handleSubmit: async (newValue: Partial<TInviteElement>) => {
setLoading("isLoading");
const currentMap = mapRef.current;
const oldKey = key; // key is already the map key (`merchantName::email`)
try {
if (!currentMap.has(oldKey)) {
return;
}
// Retrieve the existing object
const inviteElement = currentMap.get(oldKey);
const slug = removeSpecialChars(
newValue.merchantName || currentValue?.merchantName,
SLUG_MAX_CHARACTER_LENGTH,
);
const validatedList = await mutateAsync({
merchants: [
{
name: newValue?.merchantName || "",
merchantName: newValue?.merchantName,
slug,
email: newValue?.pahEmail,
owner: {
email: newValue?.pahEmail,
},
},
],
});
const item = validatedList?.results?.[0];
if (!item) {
return;
}
const newObject = {
checked:
item?.isValid &&
item?.name?.length >= 4 &&
emailPattern.test(item?.ownerEmail || ""),
errorType: !item?.isValid
? reasonToErrorType(item?.reason)
: item?.name?.length < 4
? ErrorType_bulk_merchant.MERCHANT_NAME_TOO_SHORT
: !item?.ownerEmail
? ErrorType_bulk_merchant.EMAIL_REQUIRED
: "",
merchantName: item?.name,
pahEmail: item?.ownerEmail,
};
const newKey = generateKey(item?.name, item?.ownerEmail);
if (oldKey !== newKey) {
currentMap.delete(oldKey);
}
const updatedElement = { ...inviteElement, ...newObject };
currentMap.set(newKey, updatedElement as any);
updateList();
} catch (error) {
showMessage(
"Error",
"Failed to validate edited invitation. Please try again.",
);
} finally {
setLoading("idle");
}
},
});
};
const toggleSelectItem = useCallback((key: string) => {
const prevItem = mapRef.current.get(key);
if (!prevItem) return;
const newItem = { ...prevItem, checked: !prevItem.checked };
mapRef.current.set(key, newItem);
setInvitesList((prev) =>
prev.map(([k, v]) =>
k === key ? ([k, newItem] as [string, TInviteElement]) : [k, v],
),
);
}, []);
const toggleSelectAll = () => {
Array.from(mapRef.current.keys()).forEach((key) => {
const prevItem = mapRef.current.get(key);
if (prevItem) {
// Errored entries (e.g. duplicate name/slug) must never become checked,
// otherwise "Select all" would resend invalid rows to the BE.
const isErrored = !!prevItem.errorType;
mapRef.current.set(key, {
...prevItem,
checked: isErrored ? false : !areAllSelected,
});
}
});
updateList();
};
const removeInvite = useCallback(
(key: "all" | string | string[]) => {
Iif (key === "all") {
// remove all
mapRef.current = new Map();
} else if (Array.isArray(key)) {
// remove bulk
key.forEach((k) => mapRef.current.delete(k));
} else E{
// remove single item
mapRef.current.delete(key);
}
updateList();
},
[updateList],
);
const deleteSelected = useCallback(() => {
Iif (totalSelected.current === 0) return;
Iif (totalSelected.current === mapRef.current.size) {
removeInvite("all");
} else Iif (totalSelected.current === 1) {
const itemKey = getSelectedKeys(mapRef.current, "single");
!!itemKey && removeInvite(itemKey);
} else {
const itemKeys = getSelectedKeys(mapRef.current, "bulk");
!!itemKeys && itemKeys.length > 0 && removeInvite(itemKeys);
}
}, [removeInvite]);
const { mutate } = useMutation(
async (data: any) => {
const mcc = await customInstance({
url: `merchants/${data?.parentAccID}`,
});
const categoryCodes = mcc?.allowedCategoryCodes?.[0]?.categoryCodes;
const categoryCodeID = categoryCodes?.id;
const newList = data?.merchants
?.filter(
(item: any) => item?.checked && item?.merchantName && item?.pahEmail,
)
?.map((merchant: any) => {
const merchantName_billingDescriptor = merchant.merchantName?.slice(
0,
17,
);
const randomDigits = Math.floor(
1000 + Math.random() * 9000,
).toString();
return {
name: merchant.merchantName,
parentAccID: data?.parentAccID,
...(data?.processorName && { processorName: data.processorName }),
inviteOwner: true,
slug: removeSpecialChars(
merchant.merchantName,
SLUG_MAX_CHARACTER_LENGTH,
),
owner: { email: merchant?.pahEmail },
};
});
return await customInstance({
url: "/merchants/bulk-create-async",
method: "POST",
data: {
...data,
merchants: newList,
},
});
},
{
mutationKey: sendMutationKey,
async onSuccess(data) {
showMessage("Success", "", !isMobileView, "Invitations Sent");
const acceptedMerchantsArray = data?.success?.map(
(merchant: any) => merchant?.merchantName,
);
const rejectedMerchantsArray = data?.failures;
if (
isEmpty(acceptedMerchantsArray) &&
isEmpty(rejectedMerchantsArray)
) {
dispatch(
saveInvitationsDraft({
merchantId,
entries: [],
}),
);
mapRef.current = new Map();
resetProviderAndProcessor();
return setLoading("isInviting");
}
acceptedMerchantsArray &&
(await deleteEntriesByKeys(acceptedMerchantsArray));
// Reset provider/processor on a fully-clean send so the user starts
// fresh next time. We do NOT clear the map here — pre-existing errored
// entries (unchecked, never submitted) must remain visible.
if (isEmpty(rejectedMerchantsArray)) {
resetProviderAndProcessor();
}
await mapInit(() => {
rejectedMerchantsArray?.forEach((payloadObject: any) => {
const email = payloadObject?.ownerEmail;
const isEmailError = payloadObject?.error?.Input?.some(
(input: any) => input?.param === "owner.email",
);
const newEntry: TInviteElement = {
...payloadObject,
checked: false,
errorType: isEmailError
? ErrorType_bulk_merchant.EMAIL_INVALID
: reasonToErrorType(payloadObject?.reason),
merchantName: payloadObject?.merchantName,
pahEmail: email,
};
const key = generateKey(newEntry.merchantName);
if (mapRef.current.has(key)) {
// Merge with the existing entry in the map
mapRef.current.set(key, {
...mapRef.current.get(key), // Keep the existing properties
...newEntry, // Update with new data
});
} else {
// If no existing entry, set the new entry in the map
mapRef.current.set(key, newEntry);
}
});
});
// Persist remaining entries (errored unchecked rows + any new failures)
// so close/reopen of the side panel still shows them.
dispatch(
saveInvitationsDraft({
merchantId,
entries: Array.from(mapRef.current.entries()),
}),
);
queryClient.invalidateQueries(QKEY_LIST_MERCHANT_STATS);
handleRefetchCounters();
queryClient.invalidateQueries(QKEY_LIST_MERCHANTS);
queryClient.invalidateQueries(QKEY_LIST_ACQUIRER_MERCHANTS);
},
onSettled() {
updateList();
// Don't reset state here - handleSendInvitations manages it after showing 100% progress
},
onError() {
setLoading("idle");
showMessage(
"Error",
"",
!isMobileView,
"Failed to send invitations, please try again",
3000,
{ style: { width: "100%" } },
);
},
},
);
const handleSendInvitations = async () => {
// Capture values for request payload before resetting UI state.
const parentAccID = isEnterprisePortal ? merchantId : providerId;
// Reset provider + processor at send start so it persists across modal close/reopen
// even while the request is still pending.
if (!isEnterprisePortal) {
resetProviderAndProcessor();
}
mutate(
{
parentAccID,
merchants: theEntireList,
type: "submerchant",
...(isMerchantProcessorEnabled &&
!isEnterprisePortal && { processorName: processor }),
signupType: isEnterprisePortal
? "enterprise_imported"
: "acquirer_imported",
},
{
onSuccess: () => {
showMessage("Success", "Invitations sent successfully");
// Reset loading state after toast completes
setTimeout(() => {
setLoading("idle");
}, 600);
},
onError: () => {
setLoading("idle");
},
},
);
};
const isProvider = isAcquirerPortal ? !providerId : false;
const actions: BulkInviteActions[] = useMemo(
() => [
{
onSelect: () =>
confirmRemoval(
deleteSelected,
areAllSelected ? "all" : `${totalSelected.current}`,
),
hidden: !hasSelectedItems,
disabled: isInviting || isLoading || isSending,
},
{
onSelect: () => {},
disabled: isInviting || isLoading || isSending,
},
{
onSelect: () => {
NiceModal.show(GIVE_CONFIRMATION_POP_UP, {
modalType: "notification",
title: `Send Invitations`,
description: (
<Stack gap="20px">
<GiveText variant="bodyS" color="secondary">
You are about to send {totalSelected.current} invitations.
Please confirm to continue.
</GiveText>
<Stack
direction="row"
gap="12px"
p="12px"
borderRadius="8px"
alignItems="center"
sx={{
background: someCheckedHaveError
? theme.palette.primitive?.warning?.[10]
: theme.palette.primitive?.transparent["darken-5"],
}}
>
{someCheckedHaveError ? (
<WarningIcon
size={24}
style={{
minWidth: 24,
minHeight: 24,
}}
color={theme.palette.primitive?.warning?.[100]}
/>
) : (
<BellRingingIcon
size={24}
style={{
minWidth: 24,
minHeight: 24,
}}
color={theme.palette?.icon?.["icon-primary"]}
/>
)}
<GiveText
variant="bodyS"
sx={{
color: someCheckedHaveError
? theme.palette.primitive?.warning?.[100]
: theme.palette.text?.primary,
}}
>
{someCheckedHaveError
? "You have invitations with errors, these will not be sent."
: "Sending may take some time. You won't be able to perform another action until it's completed. We will notify you once it's done."}
</GiveText>
</Stack>
</Stack>
),
actions: {
handleSuccess: {
onClick: handleSendInvitations,
},
},
});
},
disabled:
!hasSelectedItems ||
isProvider ||
isInviting ||
allCheckedHaveError ||
isLoading ||
isSending,
tooltipProps: {
show: !hasSelectedItems || isProvider || allCheckedHaveError,
message: isProvider
? "Provider is missing"
: allCheckedHaveError && hasSelectedItems
? "All merchants are invalid. Please check and edit merchant's data."
: "Select the merchants to whom you want to send an invitation",
},
},
],
[
hasSelectedItems,
areAllSelected,
isInviting,
isLoading,
isSending,
isProvider,
allCheckedHaveError,
someCheckedHaveError,
confirmRemoval,
deleteSelected,
handleSendInvitations,
theme,
],
);
const handleSetProviderId = (id: number, name?: string, logo?: string) => {
// Persist current list before changing provider so the draft still has entries
// when the hydration effect runs (otherwise it would see empty entries and clear the list)
dispatch(
saveInvitationsDraft({
merchantId,
entries: Array.from(mapRef.current.entries()),
}),
);
dispatch(
saveProviderId({
providerId: id,
merchantId,
}),
);
setProviderId(id);
if (name) {
setProviderName(name);
}
setProviderLogo(logo || "");
};
const handleSetProcessor = (processor: ProcessorValue) => {
dispatch(
saveProcessor({
processor,
merchantId,
}),
);
setProcessor(processor);
};
const handleCheckInviteDone = () => {
setLoading("isInviting");
refetch();
};
return {
actions,
data: invitesList,
areAllSelected,
isIndeterminate,
isLoading,
isInviting,
isSending,
isIdle,
importedRowsInit,
toggleSelectItem,
toggleSelectAll,
onAddInvite,
editInvite,
entryIsUnique,
processor,
setProcessor: handleSetProcessor,
providerId,
setProviderId: handleSetProviderId,
isRefetching,
sorting: {
attribute,
order,
toggleSorting,
},
handleCheckInviteDone,
processorsLoading,
senderName: isAcquirerPortal ? providerName || "" : currentUserName,
senderLogo: isAcquirerPortal ? providerLogo : currentUserImg,
};
};
export default useBulkInvite;
// Merchant names are globally unique (BE enforces it), so the map key is the
// normalized merchantName. Email is intentionally not part of the key:
// two entries with the same name but different owners are still the same
// merchant for invite/dedup purposes.
const normalizeName = (s?: string) => s?.trim().toLowerCase() || "";
const generateKey = (merchantName?: string, _email?: string) => {
const namePart = normalizeName(merchantName);
Iif (!namePart) return uuidv4(); // only if merchantName is empty
return namePart;
};
const cleanArray = (arr: TImportedRow[]) => {
// Filter out rows where BOTH email and merchantName are empty
const filteredArr = arr.filter((item) => item.merchantName || item.pahEmail);
// Only deduplicate by merchantName if merchantName exists
const deduped: TImportedRow[] = [];
const seenNames = new Set<string>();
filteredArr.forEach((item) => {
// If there's a merchantName, check for duplicates
if (item.merchantName) {
const lowerName = item.merchantName.toLowerCase();
Eif (!seenNames.has(lowerName)) {
seenNames.add(lowerName);
deduped.push(item);
}
} else {
// If no merchantName (only email), always include it
deduped.push(item);
}
});
const initialEntries = deduped.map((item: any) => {
const slug = removeSpecialChars(
item.merchantName,
SLUG_MAX_CHARACTER_LENGTH,
);
return {
...item,
name: item.merchantName,
merchantName: item.merchantName,
slug,
owner: {
email: item?.pahEmail,
},
};
});
return initialEntries;
};
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const fetchTasks = async (providerId: string | number) => {
const { data: allTasks } = await customInstance({
url: `/accounts/${providerId}/background-tasks?filter=%3B(name:%22account_bulk_create_task%22)`,
method: "GET",
});
const response = allTasks
?.filter((item: any) => item.name === "account_bulk_create_task")
?.findLast(
(item: any) => item?.status === "running" || isNull(item?.readAt),
);
return response;
};
const fetchTaskDetails = async (
providerId: string | number,
taskId: string,
) => {
return await customInstance({
url: `/accounts/${providerId}/background-tasks/${taskId}`,
method: "GET",
});
};
|