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 | 505x 289x 289x 289x 1x 1x 1x 1x 1x 1x 1x 1x 1x 289x 505x 505x 4488x 4488x 4488x 4488x 4488x 4488x 4488x 714x 714x 714x 4488x 16x 16x 16x 22x 22x 16x 16x 13x 13x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 17x 17x 17x 2x 2x 19x 29x 13x 13x 13x 13x 19x 19x 17x 2x 13x 11x 13x 3x 16x 16x 4488x 505x 1939x 1939x 1939x 1x 1x 1x 1x 1x 1939x 505x 1222x 1222x 1222x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1222x 505x 45x 45x 45x 45x 45x 45x 1x 1x 1x 1x 45x 45x 45x 505x 1222x 1222x 1x 1222x 505x | import { useIsValidFile } from "@hooks/upload-api/useIsValidFile";
import { useUploadProgress } from "@redux/slices/uploadProgressSlice";
import {
axiosUpload,
confirmAccountFiles,
createAccountFiles,
createImage,
getS3UploadUrl,
getS3UploadUrl2,
} from "@services/api/upload/uploadEndpoints";
import axios from "axios";
import { isEmpty } from "lodash";
import React, { useEffect, useRef, useState } from "react";
import { IFileWithMeta, StatusValue } from "react-dropzone-uploader";
import { QueryKey, useMutation, useQueryClient } from "react-query";
import { getRandomNumber } from "@utils/helpers";
import { isTestEnvironment, fiveMB, tenMB, twentyMB, fiftyMB, MAX_UPLOAD_SIZE, AcceptAllowedImagesTypes } from "@constants/constants";
import { useGetFeatureFlagValues } from "FeatureFlags/useGetFeatureFlagValues";
import { checkPortals } from "@utils/routing";
import pLimit from "p-limit";
type handleUploadProps = {
list: { file: File; id: string | number }[];
attachmentType?: TFileAttachmentType;
};
export enum UPLOAD_STATUSES_ENUM {
failed = "upload_failed",
}
export type HandlePresignedUploadReturnType =
| string[]
| UPLOAD_STATUSES_ENUM.failed;
export const useUploadPresignedDocument = () => {
const [isLoading, setIsLoading] = React.useState(false);
const { setUploadProgress } = useUploadProgress();
const handleUpload = ({
list,
attachmentType = "bank_account",
}: handleUploadProps) => {
const customDocumentList: string[] = [];
setIsLoading(true);
const isConversation = attachmentType === "conversation_message";
return new Promise<HandlePresignedUploadReturnType>(function (resolve) {
Iif (list.length === 0) return resolve([]);
Promise.all(
list.map((document) =>
getS3UploadUrl({
attachmentType,
name: document.file.name,
}),
),
)
.then((res) => {
return Promise.all(
res.map(
(
item: {
URL: string;
presignedURL: string;
},
index,
) => {
const uploadKey = isTestEnvironment
? `${Math.floor(Math.random() * 1000000)}`
: item.presignedURL;
setUploadProgress({
key: uploadKey,
data: {
fileName: list[index].file.name,
size: list[index].file.size,
},
});
const abortController = new AbortController();
const signal = abortController.signal;
setUploadProgress({
key: uploadKey,
data: {
abortController,
},
});
customDocumentList.push(
isConversation ? item.presignedURL : item.URL,
);
return axios
.put(item.presignedURL, list[index].file, {
onUploadProgress: (progressEvent) =>
setUploadProgress({
key: uploadKey,
data: {
progress: progressEvent.total
? Math.floor(
(progressEvent.loaded * 100) /
progressEvent.total,
)
: 0,
},
}),
signal,
})
.then((r) => {
setUploadProgress({
key: uploadKey,
data: {
success: true,
},
});
})
.catch((e) => {
setUploadProgress({
key: uploadKey,
data: {
failed: true,
},
});
throw e;
});
},
),
);
})
.then(() => {
resolve(customDocumentList);
})
.catch(() => {
resolve(UPLOAD_STATUSES_ENUM.failed);
})
.finally(() => {
setIsLoading(false);
});
});
};
return { handleUpload, isLoading };
};
export enum FileAttachmentType {
BankAccount = "bank_account",
LegalPrincipal = "legal_principal",
AccountMember = "account_member",
UnderwritingProfile = "underwriting_profile",
AccountOwner = "account_owner",
AccountOwnerSelfie = "account_owner_selfie",
ConversationMessage = "conversation_message",
UnderwritingMatchReport = "underwriting_match_report",
DisputeEvidence = "dispute_evidence",
BankAccountConfirm = "bank_account_confirm",
}
export type TFileAttachmentType = `${FileAttachmentType}`;
export type UploadProgressParams = {
fileId: string;
progress: number;
identifier?: number | string; // can be id or url
};
export type TUploadFilePayload = {
attachmentType?: TFileAttachmentType;
label?: string;
tag?: string;
list: {
file?: File;
tag?: string;
label?: string;
}[];
merchantId: number;
resourceID: number;
refetcherKey?: QueryKey[];
};
export type TUploadedFile = {
size?: number;
id: number;
isUploaded: true;
url?: string;
};
export type HandleUploadReturnType =
| UPLOAD_STATUSES_ENUM.failed
| TUploadedFile[];
// Global concurrency limiter (shared across all hook instances)
// allow 10 upload at once, to not block users, as well as avoid overloadng memory
const globalUploadLimit = pLimit(10);
export const useUploadFiles = () => {
const [isLoading, setIsLoading] = useState(false);
const { setUploadProgress, deleteUploadProgress } = useUploadProgress();
const { isNewApprovalFlowEnabled } = useGetFeatureFlagValues();
const isTaskIdParam = isNewApprovalFlowEnabled;
const s3ObjectKeysToClean: string[] = [];
const abortControllersRef = useRef<AbortController[]>([]);
useEffect(() => {
return () => {
// cancel all in-progress uploads on unmount / page switch
abortControllersRef.current.forEach((ctrl) => ctrl.abort());
abortControllersRef.current = [];
};
}, []);
const handleUpload = async (
payload: TUploadFilePayload,
challengeSlugParam?: string,
challengeIdParam?: number, //TODO: to be removed fully later
): Promise<any> => {
Iif (isEmpty(payload.list)) return [];
setIsLoading(true);
const customDocumentList = payload.list.map((item) => {
Iif (!item?.file) return null;
return {
attachmentType: payload.attachmentType,
fileName: item?.file?.name,
label: item.label ?? payload.label,
tag: item.tag ?? payload.tag,
resourceID: payload.resourceID,
fileSize: item?.file?.size,
};
});
try {
// Step 1: Create upload entries
const res = await createAccountFiles({
merchantId: payload.merchantId,
challengeSlugParam,
customDocumentList,
challengeIdParam,
isTaskIdParam,
});
Iif (!res?.total || res?.total < 1) return UPLOAD_STATUSES_ENUM.failed;
// Step 2: Prepare upload tasks
const uploadTasks: Array<() => Promise<void>> = res.data.map(
(document: any) =>
globalUploadLimit(async () => {
const s3ObjectKey = isTestEnvironment
? Math.floor(Math.random() * 1000000)
: document.s3ObjectKey;
s3ObjectKeysToClean.push(s3ObjectKey as string);
const originalFile = payload.list.find(
(item) => item?.file?.name === document.fileName,
);
setUploadProgress({
key: s3ObjectKey,
data: {
fileName: originalFile?.file?.name,
size: originalFile?.file?.size,
id: document.id,
accountUpload: true,
accountID: document.accID,
refetcherKey: payload.refetcherKey,
},
});
const abortController = new AbortController();
abortControllersRef.current.push(abortController);
const signal = abortController.signal;
setUploadProgress({
key: s3ObjectKey,
data: { abortController },
});
Iif (!originalFile?.file && !isTestEnvironment) {
setUploadProgress({
key: s3ObjectKey,
data: { failed: true },
});
return; // skip this upload
}
try {
const res = await axios.put(
document.fileURL,
originalFile?.file,
{
onUploadProgress: (progressEvent) => {
setUploadProgress({
key: s3ObjectKey,
data: {
progress: progressEvent.total
? Math.floor(
(progressEvent.loaded * 100) /
progressEvent.total,
)
: 0,
},
});
},
signal,
},
);
setUploadProgress({
key: s3ObjectKey,
data: { success: true, abortController: undefined },
});
return res;
} catch (error) {
setUploadProgress({
key: s3ObjectKey,
data: { failed: true, abortController: undefined },
});
throw error;
} finally {
// Always clean up abort controller
abortControllersRef.current = abortControllersRef.current.filter(
(c) => c !== abortController,
);
}
}),
);
const results = await Promise.allSettled(uploadTasks);
// Step 4: Determine which uploads succeeded
const successfulUploads: TUploadedFile[] = [];
const failedUploads: any[] = [];
res.data.forEach((item: any, index: number) => {
const result = results[index];
if (result.status === "fulfilled") {
successfulUploads.push({
id: item.id,
isUploaded: true,
url: item?.fileURL || "",
size: item?.fileSize,
});
} else {
failedUploads.push({
id: item.id,
url: item?.fileURL || "",
size: item?.fileSize,
});
}
});
if (successfulUploads.length > 0) {
await confirmAccountFiles({
merchantId: payload.merchantId,
confirmedUploadedList: successfulUploads,
});
}
return successfulUploads;
} catch (e) {
return UPLOAD_STATUSES_ENUM.failed;
} finally {
setIsLoading(false);
// Ensure all upload progress items are cleared from Redux state
setTimeout(() => {
s3ObjectKeysToClean.forEach((key) => {
deleteUploadProgress(key);
});
}, 5000); // Delay overall cleanup by 5 seconds to avoid glitchy snackbars
}
};
return { handleUpload, isLoading };
};
export const useUploadImageToS3 = () => {
const { setUploadProgress } = useUploadProgress();
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: async ({
file,
formType,
}: {
file: File;
formType: string;
inValidate?: boolean;
}) => {
let s3Response: any;
let response: any;
let uploadResponse: any;
try {
s3Response = await getS3UploadUrl2({
formType,
});
setUploadProgress({
key: s3Response.key,
data: {
fileName: file.name,
size: file.size,
},
});
const abortController = new AbortController();
const signal = abortController.signal;
setUploadProgress({
key: s3Response.key,
data: {
abortController,
},
});
uploadResponse = await axiosUpload({
file,
s3Response,
setUploadProgress,
signal,
});
const url = `${s3Response.action}/${s3Response.key}`;
response = await createImage({
label: file.name,
url,
});
setUploadProgress({
key: s3Response.key,
data: {
id: response.id,
},
});
setUploadProgress({
key: s3Response.key,
data: {
success: true,
},
});
return {
response,
s3Response,
uploadResponse,
};
} catch (error) {
setUploadProgress({
key: s3Response?.key || `${getRandomNumber(100, 1000000)}`,
data: {
failed: true,
},
});
return null;
}
},
onSuccess(data, variables, context) {
variables?.inValidate &&
queryClient.invalidateQueries("get-all-media-items");
},
});
return mutation;
};
export const useUploadImageToS3WithoutSetting = () => {
const { setUploadProgress } = useUploadProgress();
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: async ({
file,
formType,
}: {
file: File;
formType: string;
}) => {
let s3Response: any;
let url = "";
try {
s3Response = await getS3UploadUrl2({
formType,
});
setUploadProgress({
key: s3Response.key,
data: {
fileName: file.name,
size: file.size,
},
});
const abortController = new AbortController();
const signal = abortController.signal;
setUploadProgress({
key: s3Response.key,
data: {
abortController,
},
});
await axiosUpload({
file,
s3Response,
setUploadProgress,
signal,
});
url = `${s3Response.action}/${s3Response.key}`;
setUploadProgress({
key: s3Response.key,
data: {
success: true,
},
});
return url;
} catch (error) {
setUploadProgress({
key: s3Response?.key || `${getRandomNumber(1000000, 100000000)}`,
data: {
failed: true,
},
});
return null;
}
},
onSuccess: () => {
queryClient.invalidateQueries("get-all-media-items");
},
});
return mutation;
};
export const useDropzoneUpload = () => {
const queryClient = useQueryClient();
const { mutateAsync: directUpload, isLoading } = useUploadImageToS3();
const { isValidFile } = useIsValidFile();
const _handleUpload = async (
file: File,
formType?: string,
actualSize?: number,
) => {
return new Promise(async (resolve, reject) => {
try {
if (
!isValidFile({
file,
allowedTypes: Object.keys(AcceptAllowedImagesTypes),
actualSize,
})
) {
return resolve(null);
}
const responses = await directUpload({
file,
formType: formType || "merchant_image",
});
if (responses) {
await queryClient.invalidateQueries("get-all-media-items");
}
resolve(responses);
} catch (err) {
reject(err); // reject so Promise.allSettled works
}
});
};
const handleUpload = (file: File, formType?: string) =>
globalUploadLimit(() => _handleUpload(file, formType));
const handleDirectUpload = async (
file: File,
formType = "merchant_image",
inValidate = true,
) => {
try {
const responses = await directUpload({
file,
formType: formType,
inValidate,
});
Iif (responses && inValidate) {
queryClient.invalidateQueries("get-all-media-items");
queryClient.invalidateQueries("get-all-media-items-infinite");
}
return responses;
} catch (err) {
console.log(err);
//
}
};
const handleImageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const files = event.target.files;
if (!files || files.length === 0) return;
const uploadTasks = Array.from(files).map((f) => handleUpload(f));
Promise.allSettled(uploadTasks).finally(() => {
event.target.value = "";
});
};
const handleDragDropChange = (
metaFile: IFileWithMeta,
status: StatusValue,
) => {
if (status === "done") handleUpload(metaFile.file);
};
return {
isUploading: isLoading,
handleImageChange,
handleDragDropChange,
handleUpload,
handleDirectUpload,
};
};
export const useUploadSingleImage = () => {
const { mutateAsync, isLoading: isLoadingS3Request } =
useUploadImageToS3WithoutSetting();
const handleUpload = async ({
file,
formType = "customer_avatar",
}: {
file: File;
formType?: string;
}) => {
return await mutateAsync({ formType, file });
};
return { handleUpload, isLoading: isLoadingS3Request };
};
//
export { AcceptAllowedImagesTypes };
export const AcceptAllowedGeneralDocumentsTypes = {
"image/jpeg": [".jpg", ".jpeg"],
"image/jpg": [".jpg"],
"image/png": [".png"],
"image/webp": [".webp"],
"application/pdf": [".pdf"],
"image/heic": [".heic"],
"image/heif": [".heif"],
};
export { fiveMB, tenMB, twentyMB, fiftyMB, MAX_UPLOAD_SIZE };
|