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 | 13x 238x 238x 238x 238x 238x 238x 238x 238x 238x 238x 238x 238x 238x 238x 238x 238x 26x 238x 26x 238x 3x 3x 238x 238x 238x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 238x 238x | import React from "react";
import { showMessage } from "@common/Toast";
import { useModal } from "@ebay/nice-modal-react";
import { yupResolver } from "@hookform/resolvers/yup";
import {
createBusinessOwner,
patchBusinessOwner,
} from "@services/api/business-owners";
import { useEffect, useRef } from "react";
import { useUploadPresignedDocument } from "@hooks/upload-api/uploadHooks";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import { uniqueId, pick } from "lodash";
import { SubmitHandler, useForm } from "react-hook-form";
import { useMutation, useQueryClient } from "react-query";
import {
LocalFileMeta,
TBusinessOwner,
TMerchantDocument,
} from "../data.types";
import { BusinessUnionTypes } from "@common/BusinessProfileInputs/BusinessTypeSelect";
import {
defaultBOFormValues,
generateDefaultValues,
} from "../helpers/businessOwners";
import { TFormInputs } from "@components/ProfilePage/BusinessProfileSetupNew/types";
import { payloadBuilder } from "@components/ProfilePage/BusinessProfileSetupNew/helpers/onSubmitPayloadBuilder";
import {
QKEY_BUSINESS_PROFILE_BY_ID,
QKEY_LIST_BUSINESS_OWNERS,
} from "@constants/queryKeys";
import { MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS } from "@features/Merchants/MerchantSidePanel/constants";
import { useGetFeatureFlagValues } from "FeatureFlags/useGetFeatureFlagValues";
import { useDeleteAccountFile } from "@hooks/upload-api/useDeleteAccountFile";
import { VALIDATION_MESSAGES } from "@validation/messages";
import {
getBusinessOwnerSchema,
createFilesSchema,
} from "@validation/businessOwner";
import useManagePepData from "../modals/hooks/useManagePepData";
type Props = {
merchantId: number;
totalOwnerships: number;
data?: TBusinessOwner;
legalEntityID?: number;
onClose?: (data: TBusinessOwner) => void;
primaryAccountHolder?: Partial<TBusinessOwner>;
isIndividualSoleProprietorship?: boolean;
businessType: BusinessUnionTypes;
idFile?: TMerchantDocument & { meta?: LocalFileMeta };
};
export const useCreateMerchantBusinessOwnerV2 = ({
merchantId,
legalEntityID,
data: businessOwner,
totalOwnerships,
onClose,
primaryAccountHolder,
isIndividualSoleProprietorship,
businessType,
idFile,
}: Props) => {
const { isDesktopView } = useCustomThemeV2();
const {
handleUpload: handleUploadPresignedDocument,
isLoading: uploadLoading,
} = useUploadPresignedDocument();
const modal = useModal();
const open = modal.visible;
const queryClient = useQueryClient();
const defaultValues: any = businessOwner
? generateDefaultValues(businessOwner)
: defaultBOFormValues;
const { mutateAsync: handleDeleteFile } = useDeleteAccountFile();
const { data: pepData, isLoading: pepLoading } = useManagePepData({
selectedOwner: businessOwner as TBusinessOwner & { name: string },
merchantId: merchantId,
legalEntityID: legalEntityID,
});
const idImageUrlRef = useRef<string | undefined>("");
const { isMerchantOnboardingModalEnabled } = useGetFeatureFlagValues();
let baseSchema = getBusinessOwnerSchema({
businessType,
isMerchantOnboardingModalEnabled,
isAddressRequired: false,
useNewSchema: isMerchantOnboardingModalEnabled,
generalMessageError: VALIDATION_MESSAGES.REQUIRED,
});
// on creation mode, when legal entity id is undefined, we are not allowing creation without files
Iif (legalEntityID === undefined) {
baseSchema = baseSchema.concat(createFilesSchema());
}
const methods = useForm<TFormInputs>({
mode: "onChange",
reValidateMode: "onChange",
resolver: yupResolver(baseSchema, {
context: {
currentIdImageUrl: idImageUrlRef.current,
},
}),
defaultValues,
});
const {
reset,
setValue,
formState: { dirtyFields },
} = methods;
const handleCancel = () => modal.remove();
useEffect(() => {
Iif (
primaryAccountHolder &&
!businessOwner &&
isIndividualSoleProprietorship
) {
Object.entries(primaryAccountHolder).forEach(([key, value]) => {
setValue(
key as keyof TFormInputs,
value as TFormInputs[keyof TFormInputs],
{
shouldDirty: true,
},
);
});
}
}, []);
useEffect(() => {
idImageUrlRef.current = methods?.watch("idImageUrl") ?? "";
}, [methods?.watch("idImageUrl")]);
const handleChangeAddress = (e: React.ChangeEvent<HTMLInputElement>) => {
setValue("useBusinessAddress", e.target.checked, { shouldDirty: true });
setValue("address.country", "US", { shouldDirty: true });
};
const createBusinessOwnerMutation = useMutation(
({ leID, data }: { leID: number; data: any }) => {
return businessOwner?.id
? patchBusinessOwner(leID, businessOwner.id, data, merchantId)
: createBusinessOwner(leID, data, merchantId);
},
{
onError: (error: unknown) => {
const defaultMessage = "An error occured. Please try again";
const errorObj = (error as any)?.response?.data;
const apiError = errorObj?.input?.length
? errorObj?.input[0]?.message
: errorObj?.message;
showMessage("Error", apiError || defaultMessage);
},
onSettled: (_d, _e, variables) => {
queryClient.invalidateQueries([
MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET_LEGAL_ENTITY,
merchantId,
variables.leID,
]);
queryClient.invalidateQueries(QKEY_LIST_BUSINESS_OWNERS);
queryClient.invalidateQueries("pep-checks-history");
queryClient.invalidateQueries([
MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET_OFAC,
merchantId,
]);
queryClient.invalidateQueries(["get-bo-files", merchantId]);
queryClient.invalidateQueries([
QKEY_BUSINESS_PROFILE_BY_ID,
variables.leID,
]);
queryClient.invalidateQueries([
MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.PENDING_TASKS_LIST,
merchantId,
]);
modal.remove();
},
},
);
const isConfirmMatch = businessOwner?.pepStatusName === "confirmed_match";
const onSubmit: SubmitHandler<TFormInputs> = async (data) => {
// Address is already in canonical format from the form (address.line1, etc.)
// No transformation needed - data can be used directly
const computedOwnership =
+(data?.ownership || 0) +
totalOwnerships -
+(businessOwner?.ownership || 0);
if (computedOwnership > 100) {
showMessage("Info", "Ownership sum cannot exceed 100%");
return;
}
const firstFile = data.files?.allFiles?.[0] as any;
// if file doesnt have meta field, that means the file is from BE, so no upload required
const isLocalFile = !!data?.files?.allFiles[0]?.meta;
//the flow for adding BO on merchant/provider create
// Check if the file URL has changed from the original
const originalFileUrl = isLocalFile
? idFile?.meta?.previewUrl
: idFile?.fileURL;
const currentFileUrl = firstFile?.meta?.previewUrl;
const hasFileChanged = originalFileUrl !== currentFileUrl;
let newUploadedFileUrl = "";
if (isLocalFile && hasFileChanged) {
const presignedUploadRes = await handleUploadPresignedDocument({
list: data.files?.allFiles,
attachmentType: "legal_principal",
});
Iif (Array.isArray(presignedUploadRes))
newUploadedFileUrl = presignedUploadRes[0];
} else Eif (!isLocalFile && firstFile?.meta?.previewUrl) {
if (firstFile.file) {
const presignedImage = await handleUploadPresignedDocument({
list: [
{
file: firstFile.file,
id: firstFile.id,
},
],
attachmentType: "legal_principal",
});
newUploadedFileUrl = presignedImage[0];
}
}
Eif (
onClose &&
isLocalFile &&
!businessOwner?.createdAt &&
data?.files?.allFiles?.length > 0 &&
(data?.files?.allFiles[0]?.meta?.previewUrl !=
businessOwner?.files?.allFiles[0]?.meta?.previewUrl ||
!legalEntityID) // on edit we still need to save data and close modal
) {
const ownerData = {
...data,
citizenship: data.citizenship || "US",
countryOfResidence: data.countryOfResidence || "US",
id: businessOwner?.id || uniqueId(),
...(!businessOwner?.createdAt &&
newUploadedFileUrl && {
idImageUrl: newUploadedFileUrl,
}),
} as TBusinessOwner;
onClose(ownerData as TBusinessOwner);
reset(businessOwner?.id ? ownerData : (defaultValues as any));
modal.remove();
Eif (!newUploadedFileUrl && hasFileChanged)
showMessage("Error", "Document upload failed.", isDesktopView);
return;
}
if (!legalEntityID) return;
const payloadOnConrfimedMatch = {
ownershipPercentage: data.ownership ? +data.ownership : null,
};
const payload = isConfirmMatch
? payloadOnConrfimedMatch
: payloadBuilder(
data,
dirtyFields,
defaultValues,
isMerchantOnboardingModalEnabled,
true,
);
const isFileDeleted = Boolean(idFile?.id) && !data?.files?.allFiles[0];
await createBusinessOwnerMutation.mutateAsync({
leID: legalEntityID,
data: {
...payload,
//the image change is handled separately based on multiple checks
...(newUploadedFileUrl && {
idImageURL: newUploadedFileUrl,
}),
...(!newUploadedFileUrl &&
isFileDeleted &&
idFile?.accID &&
idFile?.id && {
idImageUrl: "",
}),
},
});
if (isFileDeleted && idFile?.accID && idFile?.id) {
await handleDeleteFile(
{ id: idFile?.accID, fileID: idFile?.id },
{
onSuccess: () => {
queryClient.invalidateQueries(["get-bo-files", merchantId]);
},
},
);
}
};
const latestPepCheck =
pepData && pepData.length > 0
? pepData.reduce((latest: any, current: any) =>
current.date > latest.date ? current : latest,
)
: null;
return {
open,
methods,
handleCancel,
onSubmit,
isLoading: createBusinessOwnerMutation.isLoading || uploadLoading,
handleChangeAddress,
latestPepCheck,
pepLoading,
};
};
|