@erpsquad/common 1.8.93 → 1.8.95
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api-client/api.hrms/api/index.esm.js +1 -12
- package/dist/api-client/api.hrms/api/index.esm.js.map +1 -1
- package/dist/api-client/api.hrms/api/index.js +1 -1
- package/dist/api-client/api.hrms/api/index.js.map +1 -1
- package/dist/api-client/api.inventory/api/index.esm.js +95 -30
- package/dist/api-client/api.inventory/api/index.esm.js.map +1 -1
- package/dist/api-client/api.inventory/api/index.js +1 -1
- package/dist/api-client/api.inventory/api/index.js.map +1 -1
- package/dist/api-client/api.inventory/api-types.d.ts +930 -425
- package/dist/api-client/api.inventory/api.d.ts +14 -10
- package/dist/api-client/api.rbac/api/index.esm2.js +218 -0
- package/dist/api-client/api.rbac/api/index.esm2.js.map +1 -1
- package/dist/api-client/api.rbac/api/index2.js +1 -1
- package/dist/api-client/api.rbac/api/index2.js.map +1 -1
- package/dist/components/action-bar/action-bar/index.esm.js +1 -1
- package/dist/components/action-bar/action-bar/index.esm.js.map +1 -1
- package/dist/components/action-bar/action-bar/index.js +5 -5
- package/dist/components/action-bar/action-bar/index.js.map +1 -1
- package/dist/components/filter/filter/index.esm.js +1 -1
- package/dist/components/filter/filter/index.esm.js.map +1 -1
- package/dist/components/filter/filter/index.js +7 -7
- package/dist/components/filter/filter/index.js.map +1 -1
- package/dist/components/header/redux/actionCreator/index.esm.js +1 -1
- package/dist/components/header/redux/actionCreator/index.esm.js.map +1 -1
- package/dist/components/header/redux/actionCreator/index.js +1 -1
- package/dist/components/header/redux/actionCreator/index.js.map +1 -1
- package/dist/components/inventory-reports-title-bar/redux/actionCreator/index.esm.js +1 -1
- package/dist/components/inventory-reports-title-bar/redux/actionCreator/index.esm.js.map +1 -1
- package/dist/components/inventory-reports-title-bar/redux/actionCreator/index.js +1 -1
- package/dist/components/inventory-reports-title-bar/redux/actionCreator/index.js.map +1 -1
- package/dist/components/reports-title-bar/redux/actionCreator/index.esm.js +1 -1
- package/dist/components/reports-title-bar/redux/actionCreator/index.esm.js.map +1 -1
- package/dist/components/reports-title-bar/redux/actionCreator/index.js +1 -1
- package/dist/components/reports-title-bar/redux/actionCreator/index.js.map +1 -1
- package/dist/components/share-modal/redux/actionCreator/index.esm.js +1 -1
- package/dist/components/share-modal/redux/actionCreator/index.esm.js.map +1 -1
- package/dist/components/share-modal/redux/actionCreator/index.js +1 -1
- package/dist/components/share-modal/redux/actionCreator/index.js.map +1 -1
- package/dist/components/upload/upload/index.esm.js +2 -2
- package/dist/components/upload/upload/index.esm.js.map +1 -1
- package/dist/components/upload/upload/index.js +11 -11
- package/dist/components/upload/upload/index.js.map +1 -1
- package/dist/contexts/AuthContext/index.esm.js +1 -1
- package/dist/contexts/AuthContext/index.esm.js.map +1 -1
- package/dist/contexts/AuthContext/index.js +1 -1
- package/dist/contexts/AuthContext/index.js.map +1 -1
- package/dist/contexts/languageContext/index.esm.js +1 -1
- package/dist/contexts/languageContext/index.esm.js.map +1 -1
- package/dist/contexts/languageContext/index.js +1 -1
- package/dist/contexts/languageContext/index.js.map +1 -1
- package/dist/src/api-client/api.inventory/api.d.ts +14 -10
- package/dist/src/utils/api.d.ts +18 -8
- package/dist/style.css +65 -65
- package/dist/utils/api/index.esm.js +39 -18
- package/dist/utils/api/index.esm.js.map +1 -1
- package/dist/utils/api/index.js +1 -1
- package/dist/utils/api/index.js.map +1 -1
- package/dist/utils/api.d.ts +18 -8
- package/dist/utils/common/index.esm.js +6 -6
- package/dist/utils/common/index.esm.js.map +1 -1
- package/dist/utils/common/index.js +1 -1
- package/dist/utils/common/index.js.map +1 -1
- package/dist/views/form-builder/redux/actionCreator/index.esm.js +1 -1
- package/dist/views/form-builder/redux/actionCreator/index.esm.js.map +1 -1
- package/dist/views/form-builder/redux/actionCreator/index.js +1 -1
- package/dist/views/form-builder/redux/actionCreator/index.js.map +1 -1
- package/dist/views/template-editor/components/EditorSidebar/index.esm.js +1 -1
- package/dist/views/template-editor/components/EditorSidebar/index.esm.js.map +1 -1
- package/dist/views/template-editor/components/EditorSidebar/index.js +1 -1
- package/dist/views/template-editor/components/EditorSidebar/index.js.map +1 -1
- package/dist/views/template-editor/templates/index.esm.js +1 -1
- package/dist/views/template-editor/templates/index.esm.js.map +1 -1
- package/dist/views/template-editor/templates/index.js +1 -1
- package/dist/views/template-editor/templates/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../../src/components/upload/upload.tsx"],"sourcesContent":["import { useEffect, useRef, useState } from \"react\";\n\nimport CloseIcon from \"@mui/icons-material/Close\";\nimport Typography from \"../typography/typography\";\nimport Box from \"@mui/material/Box\";\nimport LinearProgress from \"@mui/material/LinearProgress\";\nimport \"./upload.scss\";\nimport { useDropzone } from \"react-dropzone\";\nimport Toast from '../toast/toast';\nimport {\n CircularProgress,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Divider,\n IconButton,\n} from \"@mui/material\";\nimport RemoveIcon from \"@mui/icons-material/Remove\";\nimport { Add } from \"@mui/icons-material\";\nimport Button from \"../button/button\";\nimport Checkbox from \"../checkbox/checkbox\";\nimport Avatar from \"../avatar/avatar\";\nimport images from \"../../assets/images\";\nimport Chip from \"../chip/chip\";\nimport { auth } from \"../../constants/auth\";\nimport { KeyboardArrowDown, KeyboardArrowUp, Clear } from \"@mui/icons-material\";\nimport FileConfirmationDialog from \"./file-confirmation\"\n\n\ninterface UploadProps {\n open: boolean;\n title: string;\n multiple?: boolean;\n accept?: string;\n onClose: () => void;\n onConfirm: () => void;\n onSubmit: (files: any[]) => void;\n existingDriveData?: any;\n fileUploaded?: (value: boolean) => void | undefined;\n type: any\n\n\n}\ninterface CustomNavigator extends Navigator {\n connection?: {\n downlink?: number;\n };\n}\nconst formatBytes = (bytes: number, decimals = 2) => {\n if (bytes === 0) return \"0 Bytes\";\n const k = 1024;\n const dm = decimals < 0 ? 0 : decimals;\n const sizes = [\"Bytes\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\"];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + \" \" + sizes[i];\n};\n\nconst Upload = (props: UploadProps) => {\n const {\n open,\n title,\n onClose,\n onConfirm,\n accept = \"*\",\n onSubmit,\n multiple = true,\n existingDriveData,\n fileUploaded , \n type\n \n } = props;\n\n const [files, setFiles] = useState<\n {\n file: File;\n isPrivate: boolean;\n checkboxDisabled: boolean;\n status: string;\n uploadProgress: number;\n fileSize: number;\n fileName: string;\n fileType: string;\n location: string;\n message: string;\n }[]\n >([]);\n\n interface IToast {\n type: 'normal' | 'alert';\n message: string;\n }\n const [isUploading, setIsUploading] = useState(false);\n const [isCollapsed, setIsCollapsed] = useState(false);\n const [isDialogMinimized, setIsDialogMinimized] = useState(false);\n const [isDragOver, setIsDragOver] = useState(false);\n const [abortController, setAbortController] = useState(new AbortController());\n const authToken = localStorage.getItem(auth.storageTokenKeyName);\n const [allDriveData, setAllDriveData] = useState();\n const [isConfirmDialogOpen, setIsConfirmDialogOpen] = useState(false);\n const [selectedFileTitle, setSelectedFileTitle] = useState();\n const [toast, setToast] = useState<IToast | null>(null);\n\n const { getRootProps, getInputProps, isDragActive } = useDropzone({\n onDropAccepted: (newFiles) => {\n setFiles([\n ...files,\n ...newFiles.map((file) => ({\n file,\n isPrivate: false,\n checkboxDisabled: false,\n status: \"pending\",\n uploadProgress: 0,\n fileSize: file.size,\n fileName: file.name,\n fileType: file.type,\n location: \"\",\n message: \"\",\n })),\n ]);\n setIsDragOver(false);\n },\n onDragEnter: () => {\n setIsDragOver(true);\n },\n onDragLeave: () => {\n setIsDragOver(false);\n },\n noClick: true,\n noKeyboard: true,\n multiple: multiple,\n accept: accept ? convertAcceptObject(accept) : accept,\n });\n\n const fileInputRef = useRef<HTMLInputElement>(null);\n\n useEffect(() => {\n const driveTitles = existingDriveData?.map(item => item['title'])\n setAllDriveData(driveTitles);\n }, [existingDriveData]);\n\n useEffect(() => {\n const handleBeforeUnload = (event: any) => {\n if (isUploading) {\n const message =\n \"Are you sure you want to leave? Your uploads are not complete.\";\n event.returnValue = message; // Standard for most browsers\n return message; // For some older browsers\n }\n };\n if (fileInputRef.current) {\n fileInputRef.current.multiple = multiple;\n }\n\n window.addEventListener(\"beforeunload\", handleBeforeUnload);\n\n return () => {\n // Clean up the event listener when the component unmounts\n window.removeEventListener(\"beforeunload\", handleBeforeUnload);\n };\n }, [isUploading, multiple]);\n\n const getInternetSpeed = () => {\n const customNavigator = navigator as CustomNavigator;\n if (\"connection\" in customNavigator && customNavigator.connection) {\n return customNavigator.connection.downlink;\n } else {\n return null;\n }\n };\n\n function convertAcceptObject(types: string) {\n const accepts = types.split(\",\").map((item) => item.trim());\n const acceptObject = accepts.reduce((acc: any, type: string) => {\n acc[type] = [];\n return acc;\n }, {});\n return acceptObject;\n }\n\n const renderFileIcon = (file: any) => {\n const fileType = file?.type.split(\"/\")[0];\n switch (fileType) {\n case \"image\":\n return (\n <div\n className={\n isDialogMinimized ? \"document-icon-sm\" : \"document-icon-lg\"\n }\n style={{ backgroundColor: \"#FFEBEB\" }}\n >\n <Avatar size={20} src={images.upload.documentPDF}></Avatar>\n </div>\n );\n case \"application\":\n return (\n <div\n className={\n isDialogMinimized ? \"document-icon-sm\" : \"document-icon-lg\"\n }\n style={{ backgroundColor: \"#FFEBEB\" }}\n >\n <Avatar size={20} src={images.upload.documentPDF}></Avatar>\n </div>\n );\n case \"text\":\n return (\n <div\n className={\n isDialogMinimized ? \"document-icon-sm\" : \"document-icon-lg\"\n }\n style={{ backgroundColor: \"#EBF9F2\" }}\n >\n <Avatar size={20} src={images.upload.docFile}></Avatar>\n </div>\n );\n default:\n return (\n <div\n className={\n isDialogMinimized ? \"document-icon-sm\" : \"document-icon-lg\"\n }\n style={{ backgroundColor: \"#EBF9F2\" }}\n >\n <Avatar size={20} src={images.upload.docFile}></Avatar>\n </div>\n );\n }\n };\n\n const BASE_URL = `${import.meta.env.VITE_BACKEND_BASE_URL}/document/v1/file-upload/`;\n\n const handleConfirm = async () => {\n setIsUploading(true);\n // Create a new AbortController for each confirmation\n const controller = new AbortController();\n setAbortController(controller);\n \n const filteredFiles = files.filter((file : any) => file.status !== \"canceled\").length;\n for (let i = 0; i < files.length; i++) {\n if (files[i].uploadProgress === 100 || files[i].status !== \"pending\") {\n continue;\n }\n\n const file = files[i];\n \n const fileSize = file?.fileSize;\n try {\n if (fileSize > 10 * 1024 * 1024) {\n const uploadResponse = await handleMultipartUpload(file, i, controller);\n if (uploadResponse) {\n setTimeout(()=>{fileUploaded(true) } , 1000);\n }\n } else {\n await handleRegularUpload(file, i, controller, filteredFiles);\n }\n } catch (error: any) {\n setFiles((prevFiles) => {\n const updatedFiles = [...prevFiles];\n updatedFiles[i] = {\n ...updatedFiles[i],\n status: \"failed\",\n message: error.message || \"Internal Server Error\",\n };\n return updatedFiles;\n });\n } finally {\n setIsUploading(false);\n }\n }\n };\n\n\n \n\n let tempCount = 0;\n const handleRegularUpload = async (\n file: any,\n index: number,\n controller: any,\n fileCount : number\n ) => {\n try {\n const format = ['docx', 'doc', 'csv', 'pdf', 'xls', 'xlsx', 'vnd.ms-excel', 'excel', 'txt'];\n const mimeType = file?.mimeType || file?.fileType || '';\n\t\t\tconst isValid = format.some(f => mimeType.includes(f));\n \n if (isValid && file?.fileSize && file?.fileSize >= 5242880) {\n return setToast({\n type: 'alert',\n message: 'File size must be within 5 MB!'\n });\n }\n const preSignedUrlsResponse = await fetch(\n `${BASE_URL}?key=${file?.fileName}&partCount=1&mimeType=${file?.fileType}&is_private=${!file?.isPrivate}`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n \"file-size\": file?.fileSize,\n \"x-token\": authToken,\n },\n signal: controller.signal\n },\n );\n const preSignedUrlsData = await preSignedUrlsResponse.json();\n if (preSignedUrlsData?.status_code == 400) {\n // alert(preSignedUrlsData?.message);\n setToast({\n type: 'alert',\n message: preSignedUrlsData?.message\n });\n return;\n }\n const preSignedUrl = preSignedUrlsData.data?.preSignedData?.presignedUrl;\n const location = preSignedUrlsData.data?.preSignedData?.location;\n const partParams = {\n Body: file?.file.slice(0, file?.fileSize),\n url: preSignedUrl,\n };\n const contentLength = file.fileSize;\n // const maxChunkSize = 1024 * 1024 * 1024; // 10 MB maximum chunk size\n // const chunkSize = Math.min(contentLength * 0.1, maxChunkSize);\n const chunkSize = 1024 * 1024 * 1024 * 1024 // 1MB chunk size\n let bytesUploaded = 0;\n\n while (bytesUploaded < contentLength) {\n const start = bytesUploaded;\n const end = Math.min(bytesUploaded + chunkSize, contentLength);\n\n // Send chunk of the file\n await fetch(partParams.url, {\n method: \"PUT\",\n body: file.file.slice(start, end),\n headers: {\n \"Content-Type\": \"application/octet-stream\",\n },\n });\n\n // Update progress\n bytesUploaded = end;\n const progress = Math.round((bytesUploaded / contentLength) * 100);\n\n setFiles((prevFiles) => {\n const updatedFiles = [...prevFiles];\n updatedFiles[index] = {\n ...updatedFiles[index],\n checkboxDisabled: true,\n status: \"uploading\",\n uploadProgress: progress,\n };\n return updatedFiles;\n });\n }\n \n setFiles((prevFiles) => {\n const updatedFiles = [...prevFiles];\n updatedFiles[index] = {\n ...updatedFiles[index],\n status: \"completed\",\n location ,\n message: \"Uploaded Successfully\",\n };\n tempCount = tempCount + 1;\n \n if(fileCount == tempCount){\n onSubmit(updatedFiles);\n tempCount = 0;\n \n }\n return updatedFiles;\n });\n } catch (error: any) {\n setFiles((prevFiles) => {\n const updatedFiles = [...prevFiles];\n updatedFiles[index] = {\n ...updatedFiles[index],\n status: \"failed\",\n message: error.message || \"Internal Server Error\",\n };\n return updatedFiles;\n });\n }\n \n };\n\n const handleMultipartUpload = async (\n file: any,\n index: number,\n controller: any,\n ) => {\n\n try {\n const partSize =\n (getInternetSpeed() || 10) * 1024 * 1024 < 5 * 1024 * 1024\n ? 5 * 1024 * 1024\n : (getInternetSpeed() || 10) * 1024 * 1024;\n const parts = Math.ceil(file?.fileSize / partSize);\n const preSignedUrlsResponse = await fetch(\n `${BASE_URL}?key=${file?.fileName}&partCount=${parts}&mimeType=${file?.fileType}&is_private=${!file?.isPrivate}`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n \"file-size\": file?.fileSize,\n \"x-token\": authToken,\n },\n signal: controller.signal,\n },\n );\n const preSignedUrlsData = await preSignedUrlsResponse.json();\n\n if (preSignedUrlsData && preSignedUrlsData?.status_code && preSignedUrlsData?.status_code == 400) {\n setToast({ message: preSignedUrlsData?.message || \"Internal Server Error\", type: \"error\" });\n return null;\n }\n\n const preSignedUrls = preSignedUrlsData.data.preSignedData?.preSignedUrls;\n if (preSignedUrls.length > 0) { \n const uploadId =\n preSignedUrls[0].presignedUrl.match(/uploadId=([^&]+)/)[1];\n for (let i = 0; i < preSignedUrls.length; i++) {\n const partNum = preSignedUrls[i].partNumber;\n const preSignedUrl = preSignedUrls[i].presignedUrl;\n const start = (partNum - 1) * partSize;\n const end = Math.min(start + partSize, file?.fileSize);\n const partParams = {\n Body: file?.file?.slice(start, end),\n url: preSignedUrl,\n };\n await fetch(partParams.url, {\n method: \"PUT\",\n body: partParams.Body,\n headers: {\n \"Content-Type\": \"application/octet-stream\",\n },\n });\n const progress = Math.round(((i + 1) * 100) / parts);\n setFiles((prevFiles) => {\n const updatedFiles = [...prevFiles];\n updatedFiles[index] = {\n ...updatedFiles[index],\n checkboxDisabled: true,\n status: \"uploading\",\n uploadProgress: progress,\n };\n return updatedFiles;\n });\n }\n const markCompleteResponse = await fetch(`${BASE_URL}mark-complete`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-token\": authToken,\n },\n body: JSON.stringify({\n fileName: file?.fileName,\n uploadId: uploadId,\n }),\n });\n const markCompleteData = await markCompleteResponse.json();\n const location = markCompleteData?.data?.location;\n setFiles((prevFiles) => {\n const updatedFiles = [...prevFiles];\n updatedFiles[index] = {\n ...updatedFiles[index],\n status: \"completed\",\n location: location,\n message: \"Uploaded Successfully\",\n };\n \n onSubmit(updatedFiles);\n return updatedFiles;\n });\n } else {\n setFiles((prevFiles) => {\n const updatedFiles = [...prevFiles];\n updatedFiles[index] = {\n ...updatedFiles[index],\n status: \"failed\",\n message: \"Did not get pre-signed URLs\",\n };\n return updatedFiles;\n });\n }\n } catch (error: any) {\n setFiles((prevFiles) => {\n const updatedFiles = [...prevFiles];\n updatedFiles[index] = {\n ...updatedFiles[index],\n status: \"failed\",\n message: error.message || \"Internal Server Error\",\n };\n return updatedFiles;\n });\n }\n };\n\n const handleChipClick = () => {\n if (fileInputRef.current) {\n // If multiple is true, set input for multiple files\n if (props.multiple) {\n fileInputRef.current.setAttribute(\"multiple\", \"true\");\n } else {\n // If multiple is false, set input for a single file\n fileInputRef.current.removeAttribute(\"multiple\");\n }\n fileInputRef.current.click();\n }\n };\n\n //checking if the file already exists or not in the drive \n const handleFileChange = (e: any) => {\n \n const selectedFiles = e.target.files;\n \n const fileTitles = Array.from(selectedFiles).map(file => {\n const fileName = file.name;\n const nameWithoutExtension = fileName.substring(0, fileName.lastIndexOf('.')) || fileName;\n return nameWithoutExtension;\n })[0];\n\n setSelectedFileTitle(fileTitles);\n\n setIsConfirmDialogOpen(allDriveData?.includes(fileTitles));\n const newFiles = Array.from(selectedFiles).map((file: any) => ({\n file,\n isPrivate: false,\n checkboxDisabled: false,\n status: \"pending\",\n uploadProgress: 0,\n fileSize: file?.size,\n fileName: file?.name,\n fileType: file?.type,\n location: \"\",\n message: \"\",\n }));\n setFiles((prevFiles: any) => [...prevFiles, ...newFiles]);\n setIsUploading(false);\n \n\n };\n\n const removeFile = (indexToRemove: number) => {\n \n setFiles((prevFiles) =>\n prevFiles.map((file, index) =>\n index === indexToRemove ? { ...file, status: \"canceled\" } : file,\n ),\n );\n\n };\n\n\n\n const toggleIsPrivate = (index: number) => {\n setFiles((prevFiles) =>\n prevFiles.map((item, i) =>\n i === index ? { ...item, isPrivate: !item.isPrivate } : item,\n ),\n );\n };\n\n const toggleCollapse = () => {\n setIsCollapsed((prevIsCollapsed) => !prevIsCollapsed);\n };\n\n const handleMinimizeClick = () => {\n setIsDialogMinimized(!isDialogMinimized);\n isDialogMinimized ? onConfirm() : onClose();\n };\n\n const handleDialogClose = () => {\n if (files.length > 0) {\n if (\n confirm(\n \"Your uploads are not complete. Would you like to cancel all ongoing uploads?\",\n )\n ) {\n // Abort the ongoing requests when the dialog is closed\n abortController.abort();\n if (abortController?.signal?.aborted) {\n onClose();\n }\n setFiles([]);\n }\n } else {\n onClose();\n }\n };\n useEffect(() => {\n open && setFiles([]);\n }, [open]);\n\n const onCloseConfirmPopup = () => {\n setIsConfirmDialogOpen(false);\n }\n\n const onReplace = async () => {\n const baseUrl = `${import.meta.env.VITE_BACKEND_BASE_URL}`;\n const fileId = existingDriveData?.filter(file => file.title === selectedFileTitle)[0].id;\n const headers = {\n \"Content-type\": \"application/json; charset=utf-8\",\n };\n const authToken = localStorage.getItem(auth.storageTokenKeyName) || '';\n headers[\"x-token\"] = authToken;\n await fetch(`${baseUrl}/document/v1/drive/${fileId}`, {\n method: \"DELETE\",\n headers,\n });\n\n onCloseConfirmPopup();\n }\n\n const onKeepBoth = () => {\n onCloseConfirmPopup();\n }\n return (\n <>\n <Dialog open={open} onClose={onClose} className=\"upload\">\n <DialogTitle className=\"upload--head\">\n <Box className=\"upload--title\">\n <Typography\n type=\"s3\"\n ml={1}\n weight=\"medium\"\n color=\"theme.secondary.1000\"\n >\n {title}\n </Typography>\n </Box>\n <div>\n <IconButton disableRipple onClick={handleMinimizeClick}>\n <RemoveIcon />\n </IconButton>\n <IconButton disableRipple onClick={handleDialogClose}>\n <CloseIcon />\n </IconButton>\n </div>\n </DialogTitle>\n <Divider />\n <DialogContent className=\"upload--content\">\n {files.length === 0 ? (\n <div\n className={`upload--fileContent ${isDragActive ? \"drag-active\" : \"\"\n }`}\n >\n <div {...getRootProps()} className=\"drop-view\">\n {!isDragOver ? (\n <>\n <input {...getInputProps()} ref={fileInputRef} />\n <p className=\"upload--text\">\n Drag and Drop files here or upload from\n </p>\n\n <div className=\"device-wrap\">\n <div className=\"select-button\" onClick={handleChipClick}>\n <img src={images.upload.monitor} />\n <Typography type=\"s5\">My Device</Typography>\n <input\n type=\"file\"\n {...getInputProps({ multiple: true })}\n ref={fileInputRef}\n style={{ display: \"none\" }}\n onChange={async () => {\n // handleFileChange(e) ; \n handleConfirm();\n }}\n accept={accept}\n />\n </div>\n <div className=\"select-button\" onClick={handleChipClick}>\n <img src={images.upload.camera} />\n <Typography type=\"s5\">Camera</Typography>\n <input\n type=\"file\"\n {...getInputProps({ multiple: true })}\n ref={fileInputRef}\n style={{ display: \"none\" }}\n onChange={handleFileChange}\n accept={accept}\n />\n </div>\n </div>\n </>\n ) : (\n <div className=\"after-drop\">\n <img src={images.upload.documentUpload} />\n <Typography type=\"s3\">\n Drag & Drop your files here\n </Typography>\n </div>\n )}\n </div>\n </div>\n ) : (\n <div className=\"main-container\">\n <div className=\"body-section\">\n <div className=\"document-section\">\n <div className=\"document-body\">\n {files.map((file: any, index: number) => (\n <div className=\"upload-list\" key={index}>\n <div className=\"document-cover\" key={file?.file?.name}>\n <div className=\"document-name\">\n {renderFileIcon(file?.file)}\n <div className=\"document-title\">\n <div className=\"document-box\">\n <div className=\"document-desc\">\n {file?.file?.name}\n </div>\n <div className=\"document-size\">\n {formatBytes(file?.file?.size)}\n <span\n className={\n file?.status === \"completed\" &&\n file?.message.length > 0\n ? \"success-file\"\n : \"fail-file\"\n }\n >\n {file?.message}\n </span>\n </div>\n </div>\n </div>\n </div>\n <div className=\"document-choices\">\n {file?.status !== \"canceled\" ? (\n <>\n <div className=\"checkbox\">\n <Checkbox\n checked={file?.isPrivate || type == 'public'}\n onChange={() => toggleIsPrivate(index)}\n disabled={file?.checkboxDisabled || type == 'public'}\n />\n <div className=\"checkbox-text\">Public</div>\n </div>\n <div\n className=\"delete-icon\"\n onClick={() => removeFile(index)}\n >\n <Avatar\n size={24}\n src={images.upload.trash}\n ></Avatar>\n </div>\n </>\n ) : (\n <Typography type=\"s4\" className=\"canceled-text\">\n Upload Canceled\n </Typography>\n )}\n </div>\n </div>\n <div className=\"document-progress\">\n {file?.uploadProgress > 0 && (\n <LinearProgress\n color=\"success\"\n variant=\"determinate\"\n value={file?.uploadProgress}\n />\n )}\n </div>\n </div>\n ))}\n </div>\n </div>\n {multiple && (\n <>\n <Chip\n className=\"add-file\"\n variant=\"outlined\"\n type=\"normal\"\n label={\"Add File\"}\n icon={<Add />}\n onClick={handleChipClick}\n />\n <input\n type=\"file\"\n {...getInputProps({ multiple: true })}\n ref={fileInputRef}\n style={{ display: \"none\" }}\n onChange={handleFileChange}\n accept={accept}\n />\n </>\n )}\n </div>\n </div>\n )}\n </DialogContent>\n <Divider />\n <DialogActions className=\"upload--actions\">\n <Button variant=\"text\" onClick={handleDialogClose}>\n Cancel\n </Button>\n <Button\n color=\"secondary\"\n onClick={handleConfirm}\n disabled={!files.length || isUploading}\n >\n Upload\n </Button>\n </DialogActions>\n </Dialog>\n {isDialogMinimized && (\n <div className=\"bottom-corner-box\">\n <div className=\"top-section\">\n <div className=\"top-text\">\n Uploading {files.length} Item{files.length !== 1 ? \"s\" : \"\"}\n </div>\n <div className=\"top-options\">\n <div className=\"btn\" onClick={handleMinimizeClick}>\n <RemoveIcon />\n </div>\n <div className=\"btn\" onClick={toggleCollapse}>\n <div className=\"arrow-btn\">\n {isCollapsed ? <KeyboardArrowUp /> : <KeyboardArrowDown />}\n </div>\n </div>\n <div className=\"btn\" onClick={handleDialogClose}>\n <Clear />\n </div>\n </div>\n </div>\n <div className=\"box-list\">\n {!isCollapsed &&\n files.map((file: any, index: number) => (\n <div className=\"bottom-section\">\n <div className=\"doc-icon\">{renderFileIcon(file?.file)}</div>\n <div className=\"file-detail\">\n <div className=\"file-name\">\n <div className=\"file-text\">\n {file?.file?.name}\n {index}\n </div>\n </div>\n <div className=\"file-status\">\n {file?.status !== \"canceled\" ? (\n <>\n {file.uploadProgress === 0 && (\n <div className=\"avatar-container\">\n <Avatar\n size={20}\n className=\"avatar\"\n src={images.upload.empty}\n ></Avatar>\n <Avatar\n size={20}\n onClick={() => removeFile(index)}\n src={images.upload.close}\n className=\"close-icon\"\n ></Avatar>\n </div>\n )}\n {file?.uploadProgress > 0 &&\n file?.uploadProgress < 100 && (\n <CircularProgress\n color=\"success\"\n variant=\"determinate\"\n value={file?.uploadProgress}\n />\n )}\n {file?.uploadProgress === 100 && (\n <div className=\"avatar-container\">\n <Avatar\n size={20}\n className=\"avatar\"\n src={images.upload.tick}\n ></Avatar>\n <Avatar\n size={20}\n src={images.upload.folder}\n className=\"close-icon\"\n ></Avatar>\n </div>\n )}\n </>\n ) : (\n <Typography type=\"s4\" className=\"canceled-text\">\n Upload Canceled\n </Typography>\n )}\n </div>\n </div>\n </div>\n ))}\n </div>\n </div>\n )}\n {isConfirmDialogOpen && <FileConfirmationDialog title={selectedFileTitle} open={isConfirmDialogOpen} onClose={onCloseConfirmPopup} onReplace={onReplace} onKeepBoth={onKeepBoth} isFile = {true} />}\n\n <Toast\n open={Boolean(toast)}\n type={toast?.type}\n message={toast?.message}\n handleClose={() => setToast(null)}\n anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}\n />\n </>\n );\n};\n\nexport { Upload };\nexport default Upload;\n"],"names":["formatBytes","bytes","decimals","dm","i","Math","floor","log","parseFloat","pow","toFixed","Upload","props","open","title","onClose","onConfirm","accept","onSubmit","multiple","existingDriveData","fileUploaded","type","files","setFiles","useState","isUploading","setIsUploading","isCollapsed","setIsCollapsed","isDialogMinimized","setIsDialogMinimized","isDragOver","setIsDragOver","abortController","setAbortController","AbortController","authToken","localStorage","getItem","auth","storageTokenKeyName","allDriveData","setAllDriveData","isConfirmDialogOpen","setIsConfirmDialogOpen","selectedFileTitle","setSelectedFileTitle","toast","setToast","getRootProps","getInputProps","isDragActive","useDropzone","onDropAccepted","newFiles","map","file","isPrivate","checkboxDisabled","status","uploadProgress","fileSize","size","fileName","name","fileType","location","message","onDragEnter","onDragLeave","noClick","noKeyboard","types","split","item","trim","reduce","acc","fileInputRef","useRef","useEffect","driveTitles","handleBeforeUnload","event","returnValue","current","window","addEventListener","removeEventListener","getInternetSpeed","customNavigator","navigator","connection","downlink","renderFileIcon","jsx","className","style","backgroundColor","children","Avatar","src","images","upload","documentPDF","docFile","BASE_URL","handleConfirm","async","controller","filteredFiles","filter","length","handleMultipartUpload","setTimeout","handleRegularUpload","error","prevFiles","updatedFiles","tempCount","index","fileCount","format","mimeType","some","includes","f","preSignedUrlsResponse","fetch","headers","signal","preSignedUrlsData","json","status_code","preSignedUrl","_b","_a","data","preSignedData","presignedUrl","_d","_c","partParams","Body","slice","url","contentLength","chunkSize","bytesUploaded","start","end","min","method","body","progress","round","partSize","parts","ceil","preSignedUrls","uploadId","match","partNum","partNumber","markCompleteResponse","JSON","stringify","markCompleteData","handleChipClick","setAttribute","removeAttribute","click","handleFileChange","e","selectedFiles","target","fileTitles","Array","from","substring","lastIndexOf","removeFile","indexToRemove","handleMinimizeClick","handleDialogClose","confirm","abort","aborted","onCloseConfirmPopup","jsxs","Fragment","Dialog","DialogTitle","Box","Typography","ml","weight","color","IconButton","disableRipple","onClick","RemoveIcon","CloseIcon","Divider","DialogContent","documentUpload","ref","monitor","display","onChange","camera","Checkbox","checked","toggleIsPrivate","disabled","trash","LinearProgress","variant","value","Chip","label","icon","Add","DialogActions","Button","prevIsCollapsed","KeyboardArrowUp","KeyboardArrowDown","Clear","empty","close","CircularProgress","tick","folder","FileConfirmationDialog","onReplace","fileId","id","onKeepBoth","isFile","Toast","Boolean","handleClose","anchorOrigin","horizontal","vertical"],"mappings":"6tDAiDA,MAAMA,EAAc,CAACC,EAAeC,EAAW,KAC7C,GAAc,IAAVD,EAAa,MAAO,UACxB,MACME,EAAKD,EAAW,EAAI,EAAIA,EAExBE,EAAIC,KAAKC,MAAMD,KAAKE,IAAIN,GAASI,KAAKE,IAHlC,OAIV,OAAOC,YAAYP,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,sBAAwB,GACpEyF,EAAQ,WAAa7F,QACf4F,MAAM,2CAAgC4G,IAAU,CACpDpF,OAAQ,SACRvB,YAGF2D,MAuR2JkD,WApR1I,KACjBlD,MAmRoLmD,QAAU;eAE5LhJ,EAAAA,IAACiJ,EAAAA,MAAA,CACGpO,KAAMqO,QAAQlM,IACd1B,KAAM0B,MAAAA,QAAAA,EAAAA,GAAO1B,KACb8C,QAASpB,MAAAA,QAAAA,EAAAA,GAAOoB,QAChB+K,YAAa,IAAMlM,GAAS,MAC5BmM,aAAc,CAAEC,WAAY,QAASC,SAAU"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../src/components/upload/upload.tsx"],"sourcesContent":["import { useEffect, useRef, useState } from \"react\";\n\nimport CloseIcon from \"@mui/icons-material/Close\";\nimport Typography from \"../typography/typography\";\nimport Box from \"@mui/material/Box\";\nimport LinearProgress from \"@mui/material/LinearProgress\";\nimport \"./upload.scss\";\nimport { useDropzone } from \"react-dropzone\";\nimport Toast from '../toast/toast';\nimport {\n CircularProgress,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Divider,\n IconButton,\n} from \"@mui/material\";\nimport RemoveIcon from \"@mui/icons-material/Remove\";\nimport { Add } from \"@mui/icons-material\";\nimport Button from \"../button/button\";\nimport Checkbox from \"../checkbox/checkbox\";\nimport Avatar from \"../avatar/avatar\";\nimport images from \"../../assets/images\";\nimport Chip from \"../chip/chip\";\nimport { auth } from \"../../constants/auth\";\nimport { KeyboardArrowDown, KeyboardArrowUp, Clear } from \"@mui/icons-material\";\nimport FileConfirmationDialog from \"./file-confirmation\"\n\n\ninterface UploadProps {\n open: boolean;\n title: string;\n multiple?: boolean;\n accept?: string;\n onClose: () => void;\n onConfirm: () => void;\n onSubmit: (files: any[]) => void;\n existingDriveData?: any;\n fileUploaded?: (value: boolean) => void | undefined;\n type: any\n\n\n}\ninterface CustomNavigator extends Navigator {\n connection?: {\n downlink?: number;\n };\n}\nconst formatBytes = (bytes: number, decimals = 2) => {\n if (bytes === 0) return \"0 Bytes\";\n const k = 1024;\n const dm = decimals < 0 ? 0 : decimals;\n const sizes = [\"Bytes\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\"];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + \" \" + sizes[i];\n};\n\nconst Upload = (props: UploadProps) => {\n const {\n open,\n title,\n onClose,\n onConfirm,\n accept = \"*\",\n onSubmit,\n multiple = true,\n existingDriveData,\n fileUploaded , \n type\n \n } = props;\n\n const [files, setFiles] = useState<\n {\n file: File;\n isPrivate: boolean;\n checkboxDisabled: boolean;\n status: string;\n uploadProgress: number;\n fileSize: number;\n fileName: string;\n fileType: string;\n location: string;\n message: string;\n }[]\n >([]);\n\n interface IToast {\n type: 'normal' | 'alert';\n message: string;\n }\n const [isUploading, setIsUploading] = useState(false);\n const [isCollapsed, setIsCollapsed] = useState(false);\n const [isDialogMinimized, setIsDialogMinimized] = useState(false);\n const [isDragOver, setIsDragOver] = useState(false);\n const [abortController, setAbortController] = useState(new AbortController());\n const authToken = localStorage.getItem(auth.storageTokenKeyName);\n const [allDriveData, setAllDriveData] = useState();\n const [isConfirmDialogOpen, setIsConfirmDialogOpen] = useState(false);\n const [selectedFileTitle, setSelectedFileTitle] = useState();\n const [toast, setToast] = useState<IToast | null>(null);\n\n const { getRootProps, getInputProps, isDragActive } = useDropzone({\n onDropAccepted: (newFiles) => {\n setFiles([\n ...files,\n ...newFiles.map((file) => ({\n file,\n isPrivate: false,\n checkboxDisabled: false,\n status: \"pending\",\n uploadProgress: 0,\n fileSize: file.size,\n fileName: file.name,\n fileType: file.type,\n location: \"\",\n message: \"\",\n })),\n ]);\n setIsDragOver(false);\n },\n onDragEnter: () => {\n setIsDragOver(true);\n },\n onDragLeave: () => {\n setIsDragOver(false);\n },\n noClick: true,\n noKeyboard: true,\n multiple: multiple,\n accept: accept ? convertAcceptObject(accept) : accept,\n });\n\n const fileInputRef = useRef<HTMLInputElement>(null);\n\n useEffect(() => {\n const driveTitles = existingDriveData?.map(item => item['title'])\n setAllDriveData(driveTitles);\n }, [existingDriveData]);\n\n useEffect(() => {\n const handleBeforeUnload = (event: any) => {\n if (isUploading) {\n const message =\n \"Are you sure you want to leave? Your uploads are not complete.\";\n event.returnValue = message; // Standard for most browsers\n return message; // For some older browsers\n }\n };\n if (fileInputRef.current) {\n fileInputRef.current.multiple = multiple;\n }\n\n window.addEventListener(\"beforeunload\", handleBeforeUnload);\n\n return () => {\n // Clean up the event listener when the component unmounts\n window.removeEventListener(\"beforeunload\", handleBeforeUnload);\n };\n }, [isUploading, multiple]);\n\n const getInternetSpeed = () => {\n const customNavigator = navigator as CustomNavigator;\n if (\"connection\" in customNavigator && customNavigator.connection) {\n return customNavigator.connection.downlink;\n } else {\n return null;\n }\n };\n\n function convertAcceptObject(types: string) {\n const accepts = types.split(\",\").map((item) => item.trim());\n const acceptObject = accepts.reduce((acc: any, type: string) => {\n acc[type] = [];\n return acc;\n }, {});\n return acceptObject;\n }\n\n const renderFileIcon = (file: any) => {\n const fileType = file?.type.split(\"/\")[0];\n switch (fileType) {\n case \"image\":\n return (\n <div\n className={\n isDialogMinimized ? \"document-icon-sm\" : \"document-icon-lg\"\n }\n style={{ backgroundColor: \"#FFEBEB\" }}\n >\n <Avatar size={20} src={images.upload.documentPDF}></Avatar>\n </div>\n );\n case \"application\":\n return (\n <div\n className={\n isDialogMinimized ? \"document-icon-sm\" : \"document-icon-lg\"\n }\n style={{ backgroundColor: \"#FFEBEB\" }}\n >\n <Avatar size={20} src={images.upload.documentPDF}></Avatar>\n </div>\n );\n case \"text\":\n return (\n <div\n className={\n isDialogMinimized ? \"document-icon-sm\" : \"document-icon-lg\"\n }\n style={{ backgroundColor: \"#EBF9F2\" }}\n >\n <Avatar size={20} src={images.upload.docFile}></Avatar>\n </div>\n );\n default:\n return (\n <div\n className={\n isDialogMinimized ? \"document-icon-sm\" : \"document-icon-lg\"\n }\n style={{ backgroundColor: \"#EBF9F2\" }}\n >\n <Avatar size={20} src={images.upload.docFile}></Avatar>\n </div>\n );\n }\n };\n\n const BASE_URL = `${import.meta.env.VITE_BACKEND_BASE_URL}/document/v1/file-upload/`;\n\n const handleConfirm = async () => {\n setIsUploading(true);\n // Create a new AbortController for each confirmation\n const controller = new AbortController();\n setAbortController(controller);\n \n const filteredFiles = files.filter((file : any) => file.status !== \"canceled\").length;\n for (let i = 0; i < files.length; i++) {\n if (files[i].uploadProgress === 100 || files[i].status !== \"pending\") {\n continue;\n }\n\n const file = files[i];\n \n const fileSize = file?.fileSize;\n try {\n if (fileSize > 10 * 1024 * 1024) {\n const uploadResponse = await handleMultipartUpload(file, i, controller);\n if (uploadResponse) {\n setTimeout(()=>{fileUploaded(true) } , 1000);\n }\n } else {\n await handleRegularUpload(file, i, controller, filteredFiles);\n }\n } catch (error: any) {\n setFiles((prevFiles) => {\n const updatedFiles = [...prevFiles];\n updatedFiles[i] = {\n ...updatedFiles[i],\n status: \"failed\",\n message: error.message || \"Internal Server Error\",\n };\n return updatedFiles;\n });\n } finally {\n setIsUploading(false);\n }\n }\n };\n\n\n \n\n let tempCount = 0;\n const handleRegularUpload = async (\n file: any,\n index: number,\n controller: any,\n fileCount : number\n ) => {\n try {\n const format = ['docx', 'doc', 'csv', 'pdf', 'xls', 'xlsx', 'vnd.ms-excel', 'excel', 'txt'];\n const mimeType = file?.mimeType || file?.fileType || '';\n\t\t\tconst isValid = format.some(f => mimeType.includes(f));\n \n if (isValid && file?.fileSize && file?.fileSize >= 5242880) {\n return setToast({\n type: 'alert',\n message: 'File size must be within 5 MB!'\n });\n }\n const preSignedUrlsResponse = await fetch(\n `${BASE_URL}?key=${file?.fileName}&partCount=1&mimeType=${file?.fileType}&is_private=${!file?.isPrivate}`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n \"file-size\": file?.fileSize,\n \"x-token\": authToken,\n },\n signal: controller.signal\n },\n );\n const preSignedUrlsData = await preSignedUrlsResponse.json();\n if (preSignedUrlsData?.status_code == 400) {\n // alert(preSignedUrlsData?.message);\n setToast({\n type: 'alert',\n message: preSignedUrlsData?.message\n });\n return;\n }\n const preSignedUrl = preSignedUrlsData.data?.preSignedData?.presignedUrl;\n const location = preSignedUrlsData.data?.preSignedData?.location;\n const partParams = {\n Body: file?.file.slice(0, file?.fileSize),\n url: preSignedUrl,\n };\n const contentLength = file.fileSize;\n // const maxChunkSize = 1024 * 1024 * 1024; // 10 MB maximum chunk size\n // const chunkSize = Math.min(contentLength * 0.1, maxChunkSize);\n const chunkSize = 1024 * 1024 * 1024 * 1024 // 1MB chunk size\n let bytesUploaded = 0;\n\n while (bytesUploaded < contentLength) {\n const start = bytesUploaded;\n const end = Math.min(bytesUploaded + chunkSize, contentLength);\n\n // Send chunk of the file\n await fetch(partParams.url, {\n method: \"PUT\",\n body: file.file.slice(start, end),\n headers: {\n \"Content-Type\": \"application/octet-stream\",\n },\n });\n\n // Update progress\n bytesUploaded = end;\n const progress = Math.round((bytesUploaded / contentLength) * 100);\n\n setFiles((prevFiles) => {\n const updatedFiles = [...prevFiles];\n updatedFiles[index] = {\n ...updatedFiles[index],\n checkboxDisabled: true,\n status: \"uploading\",\n uploadProgress: progress,\n };\n return updatedFiles;\n });\n }\n \n setFiles((prevFiles) => {\n const updatedFiles = [...prevFiles];\n updatedFiles[index] = {\n ...updatedFiles[index],\n status: \"completed\",\n location ,\n message: \"Uploaded Successfully\",\n };\n tempCount = tempCount + 1;\n \n if(fileCount == tempCount){\n onSubmit(updatedFiles);\n tempCount = 0;\n \n }\n return updatedFiles;\n });\n } catch (error: any) {\n setFiles((prevFiles) => {\n const updatedFiles = [...prevFiles];\n updatedFiles[index] = {\n ...updatedFiles[index],\n status: \"failed\",\n message: error.message || \"Internal Server Error\",\n };\n return updatedFiles;\n });\n }\n \n };\n\n const handleMultipartUpload = async (\n file: any,\n index: number,\n controller: any,\n ) => {\n\n try {\n const partSize =\n (getInternetSpeed() || 10) * 1024 * 1024 < 5 * 1024 * 1024\n ? 5 * 1024 * 1024\n : (getInternetSpeed() || 10) * 1024 * 1024;\n const parts = Math.ceil(file?.fileSize / partSize);\n const preSignedUrlsResponse = await fetch(\n `${BASE_URL}?key=${file?.fileName}&partCount=${parts}&mimeType=${file?.fileType}&is_private=${!file?.isPrivate}`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n \"file-size\": file?.fileSize,\n \"x-token\": authToken,\n },\n signal: controller.signal,\n },\n );\n const preSignedUrlsData = await preSignedUrlsResponse.json();\n\n if (preSignedUrlsData && preSignedUrlsData?.status_code && preSignedUrlsData?.status_code == 400) {\n setToast({ message: preSignedUrlsData?.message || \"Internal Server Error\", type: \"error\" });\n return null;\n }\n\n const preSignedUrls = preSignedUrlsData.data.preSignedData?.preSignedUrls;\n if (preSignedUrls.length > 0) { \n const uploadId =\n preSignedUrls[0].presignedUrl.match(/uploadId=([^&]+)/)[1];\n for (let i = 0; i < preSignedUrls.length; i++) {\n const partNum = preSignedUrls[i].partNumber;\n const preSignedUrl = preSignedUrls[i].presignedUrl;\n const start = (partNum - 1) * partSize;\n const end = Math.min(start + partSize, file?.fileSize);\n const partParams = {\n Body: file?.file?.slice(start, end),\n url: preSignedUrl,\n };\n await fetch(partParams.url, {\n method: \"PUT\",\n body: partParams.Body,\n headers: {\n \"Content-Type\": \"application/octet-stream\",\n },\n });\n const progress = Math.round(((i + 1) * 100) / parts);\n setFiles((prevFiles) => {\n const updatedFiles = [...prevFiles];\n updatedFiles[index] = {\n ...updatedFiles[index],\n checkboxDisabled: true,\n status: \"uploading\",\n uploadProgress: progress,\n };\n return updatedFiles;\n });\n }\n const markCompleteResponse = await fetch(`${BASE_URL}mark-complete`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-token\": authToken,\n },\n body: JSON.stringify({\n fileName: file?.fileName,\n uploadId: uploadId,\n }),\n });\n const markCompleteData = await markCompleteResponse.json();\n const location = markCompleteData?.data?.location;\n setFiles((prevFiles) => {\n const updatedFiles = [...prevFiles];\n updatedFiles[index] = {\n ...updatedFiles[index],\n status: \"completed\",\n location: location,\n message: \"Uploaded Successfully\",\n };\n \n onSubmit(updatedFiles);\n return updatedFiles;\n });\n } else {\n setFiles((prevFiles) => {\n const updatedFiles = [...prevFiles];\n updatedFiles[index] = {\n ...updatedFiles[index],\n status: \"failed\",\n message: \"Did not get pre-signed URLs\",\n };\n return updatedFiles;\n });\n }\n } catch (error: any) {\n setFiles((prevFiles) => {\n const updatedFiles = [...prevFiles];\n updatedFiles[index] = {\n ...updatedFiles[index],\n status: \"failed\",\n message: error.message || \"Internal Server Error\",\n };\n return updatedFiles;\n });\n }\n };\n\n const handleChipClick = () => {\n if (fileInputRef.current) {\n // If multiple is true, set input for multiple files\n if (props.multiple) {\n fileInputRef.current.setAttribute(\"multiple\", \"true\");\n } else {\n // If multiple is false, set input for a single file\n fileInputRef.current.removeAttribute(\"multiple\");\n }\n fileInputRef.current.click();\n }\n };\n\n //checking if the file already exists or not in the drive \n const handleFileChange = (e: any) => {\n \n const selectedFiles = e.target.files;\n \n const fileTitles = Array.from(selectedFiles).map(file => {\n const fileName = file.name;\n const nameWithoutExtension = fileName.substring(0, fileName.lastIndexOf('.')) || fileName;\n return nameWithoutExtension;\n })[0];\n\n setSelectedFileTitle(fileTitles);\n\n setIsConfirmDialogOpen(allDriveData?.includes(fileTitles));\n const newFiles = Array.from(selectedFiles).map((file: any) => ({\n file,\n isPrivate: false,\n checkboxDisabled: false,\n status: \"pending\",\n uploadProgress: 0,\n fileSize: file?.size,\n fileName: file?.name,\n fileType: file?.type,\n location: \"\",\n message: \"\",\n }));\n setFiles((prevFiles: any) => [...prevFiles, ...newFiles]);\n setIsUploading(false);\n \n\n };\n\n const removeFile = (indexToRemove: number) => {\n \n setFiles((prevFiles) =>\n prevFiles.map((file, index) =>\n index === indexToRemove ? { ...file, status: \"canceled\" } : file,\n ),\n );\n\n };\n\n\n\n const toggleIsPrivate = (index: number) => {\n setFiles((prevFiles) =>\n prevFiles.map((item, i) =>\n i === index ? { ...item, isPrivate: !item.isPrivate } : item,\n ),\n );\n };\n\n const toggleCollapse = () => {\n setIsCollapsed((prevIsCollapsed) => !prevIsCollapsed);\n };\n\n const handleMinimizeClick = () => {\n setIsDialogMinimized(!isDialogMinimized);\n isDialogMinimized ? onConfirm() : onClose();\n };\n\n const handleDialogClose = () => {\n if (files.length > 0) {\n if (\n confirm(\n \"Your uploads are not complete. Would you like to cancel all ongoing uploads?\",\n )\n ) {\n // Abort the ongoing requests when the dialog is closed\n abortController.abort();\n if (abortController?.signal?.aborted) {\n onClose();\n }\n setFiles([]);\n }\n } else {\n onClose();\n }\n };\n useEffect(() => {\n open && setFiles([]);\n }, [open]);\n\n const onCloseConfirmPopup = () => {\n setIsConfirmDialogOpen(false);\n }\n\n const onReplace = async () => {\n const baseUrl = `${import.meta.env.VITE_BACKEND_BASE_URL}`;\n const fileId = existingDriveData?.filter(file => file.title === selectedFileTitle)[0].id;\n const headers = {\n \"Content-type\": \"application/json; charset=utf-8\",\n };\n const authToken = localStorage.getItem(auth.storageTokenKeyName) || '';\n headers[\"x-token\"] = authToken;\n await fetch(`${baseUrl}/document/v1/drive/${fileId}`, {\n method: \"DELETE\",\n headers,\n });\n\n onCloseConfirmPopup();\n }\n\n const onKeepBoth = () => {\n onCloseConfirmPopup();\n }\n return (\n <>\n <Dialog open={open} onClose={onClose} className=\"upload\">\n <DialogTitle className=\"upload--head\">\n <Box className=\"upload--title\">\n <Typography\n type=\"s3\"\n ml={1}\n weight=\"medium\"\n color=\"theme.secondary.1000\"\n >\n {title}\n </Typography>\n </Box>\n <div>\n <IconButton disableRipple onClick={handleMinimizeClick}>\n <RemoveIcon />\n </IconButton>\n <IconButton disableRipple onClick={handleDialogClose}>\n <CloseIcon />\n </IconButton>\n </div>\n </DialogTitle>\n <Divider />\n <DialogContent className=\"upload--content\">\n {files.length === 0 ? (\n <div\n className={`upload--fileContent ${isDragActive ? \"drag-active\" : \"\"\n }`}\n >\n <div {...getRootProps()} className=\"drop-view\">\n {!isDragOver ? (\n <>\n <input {...getInputProps()} ref={fileInputRef} />\n <p className=\"upload--text\">\n Drag and Drop files here or upload from\n </p>\n\n <div className=\"device-wrap\">\n <div className=\"select-button\" onClick={handleChipClick}>\n <img src={images.upload.monitor} />\n <Typography type=\"s5\">My Device</Typography>\n <input\n type=\"file\"\n {...getInputProps({ multiple: true })}\n ref={fileInputRef}\n style={{ display: \"none\" }}\n onChange={async () => {\n // handleFileChange(e) ; \n handleConfirm();\n }}\n accept={accept}\n />\n </div>\n <div className=\"select-button\" onClick={handleChipClick}>\n <img src={images.upload.camera} />\n <Typography type=\"s5\">Camera</Typography>\n <input\n type=\"file\"\n {...getInputProps({ multiple: true })}\n ref={fileInputRef}\n style={{ display: \"none\" }}\n onChange={handleFileChange}\n accept={accept}\n />\n </div>\n </div>\n </>\n ) : (\n <div className=\"after-drop\">\n <img src={images.upload.documentUpload} />\n <Typography type=\"s3\">\n Drag & Drop your files here\n </Typography>\n </div>\n )}\n </div>\n </div>\n ) : (\n <div className=\"main-container\">\n <div className=\"body-section\">\n <div className=\"document-section\">\n <div className=\"document-body\">\n {files.map((file: any, index: number) => (\n <div className=\"upload-list\" key={index}>\n <div className=\"document-cover\" key={file?.file?.name}>\n <div className=\"document-name\">\n {renderFileIcon(file?.file)}\n <div className=\"document-title\">\n <div className=\"document-box\">\n <div className=\"document-desc\">\n {file?.file?.name}\n </div>\n <div className=\"document-size\">\n {formatBytes(file?.file?.size)}\n <span\n className={\n file?.status === \"completed\" &&\n file?.message.length > 0\n ? \"success-file\"\n : \"fail-file\"\n }\n >\n {file?.message}\n </span>\n </div>\n </div>\n </div>\n </div>\n <div className=\"document-choices\">\n {file?.status !== \"canceled\" ? (\n <>\n <div className=\"checkbox\">\n <Checkbox\n checked={file?.isPrivate || type == 'public'}\n onChange={() => toggleIsPrivate(index)}\n disabled={file?.checkboxDisabled || type == 'public'}\n />\n <div className=\"checkbox-text\">Public</div>\n </div>\n <div\n className=\"delete-icon\"\n onClick={() => removeFile(index)}\n >\n <Avatar\n size={24}\n src={images.upload.trash}\n ></Avatar>\n </div>\n </>\n ) : (\n <Typography type=\"s4\" className=\"canceled-text\">\n Upload Canceled\n </Typography>\n )}\n </div>\n </div>\n <div className=\"document-progress\">\n {file?.uploadProgress > 0 && (\n <LinearProgress\n color=\"success\"\n variant=\"determinate\"\n value={file?.uploadProgress}\n />\n )}\n </div>\n </div>\n ))}\n </div>\n </div>\n {multiple && (\n <>\n <Chip\n className=\"add-file\"\n variant=\"outlined\"\n type=\"normal\"\n label={\"Add File\"}\n icon={<Add />}\n onClick={handleChipClick}\n />\n <input\n type=\"file\"\n {...getInputProps({ multiple: true })}\n ref={fileInputRef}\n style={{ display: \"none\" }}\n onChange={handleFileChange}\n accept={accept}\n />\n </>\n )}\n </div>\n </div>\n )}\n </DialogContent>\n <Divider />\n <DialogActions className=\"upload--actions\">\n <Button variant=\"text\" onClick={handleDialogClose}>\n Cancel\n </Button>\n <Button\n color=\"secondary\"\n onClick={handleConfirm}\n disabled={!files.length || isUploading}\n >\n Upload\n </Button>\n </DialogActions>\n </Dialog>\n {isDialogMinimized && (\n <div className=\"bottom-corner-box\">\n <div className=\"top-section\">\n <div className=\"top-text\">\n Uploading {files.length} Item{files.length !== 1 ? \"s\" : \"\"}\n </div>\n <div className=\"top-options\">\n <div className=\"btn\" onClick={handleMinimizeClick}>\n <RemoveIcon />\n </div>\n <div className=\"btn\" onClick={toggleCollapse}>\n <div className=\"arrow-btn\">\n {isCollapsed ? <KeyboardArrowUp /> : <KeyboardArrowDown />}\n </div>\n </div>\n <div className=\"btn\" onClick={handleDialogClose}>\n <Clear />\n </div>\n </div>\n </div>\n <div className=\"box-list\">\n {!isCollapsed &&\n files.map((file: any, index: number) => (\n <div className=\"bottom-section\">\n <div className=\"doc-icon\">{renderFileIcon(file?.file)}</div>\n <div className=\"file-detail\">\n <div className=\"file-name\">\n <div className=\"file-text\">\n {file?.file?.name}\n {index}\n </div>\n </div>\n <div className=\"file-status\">\n {file?.status !== \"canceled\" ? (\n <>\n {file.uploadProgress === 0 && (\n <div className=\"avatar-container\">\n <Avatar\n size={20}\n className=\"avatar\"\n src={images.upload.empty}\n ></Avatar>\n <Avatar\n size={20}\n onClick={() => removeFile(index)}\n src={images.upload.close}\n className=\"close-icon\"\n ></Avatar>\n </div>\n )}\n {file?.uploadProgress > 0 &&\n file?.uploadProgress < 100 && (\n <CircularProgress\n color=\"success\"\n variant=\"determinate\"\n value={file?.uploadProgress}\n />\n )}\n {file?.uploadProgress === 100 && (\n <div className=\"avatar-container\">\n <Avatar\n size={20}\n className=\"avatar\"\n src={images.upload.tick}\n ></Avatar>\n <Avatar\n size={20}\n src={images.upload.folder}\n className=\"close-icon\"\n ></Avatar>\n </div>\n )}\n </>\n ) : (\n <Typography type=\"s4\" className=\"canceled-text\">\n Upload Canceled\n </Typography>\n )}\n </div>\n </div>\n </div>\n ))}\n </div>\n </div>\n )}\n {isConfirmDialogOpen && <FileConfirmationDialog title={selectedFileTitle} open={isConfirmDialogOpen} onClose={onCloseConfirmPopup} onReplace={onReplace} onKeepBoth={onKeepBoth} isFile = {true} />}\n\n <Toast\n open={Boolean(toast)}\n type={toast?.type}\n message={toast?.message}\n handleClose={() => setToast(null)}\n anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}\n />\n </>\n );\n};\n\nexport { Upload };\nexport default Upload;\n"],"names":["formatBytes","bytes","decimals","dm","i","Math","floor","log","parseFloat","pow","toFixed","Upload","props","open","title","onClose","onConfirm","accept","onSubmit","multiple","existingDriveData","fileUploaded","type","files","setFiles","useState","isUploading","setIsUploading","isCollapsed","setIsCollapsed","isDialogMinimized","setIsDialogMinimized","isDragOver","setIsDragOver","abortController","setAbortController","AbortController","authToken","localStorage","getItem","auth","storageTokenKeyName","allDriveData","setAllDriveData","isConfirmDialogOpen","setIsConfirmDialogOpen","selectedFileTitle","setSelectedFileTitle","toast","setToast","getRootProps","getInputProps","isDragActive","useDropzone","onDropAccepted","newFiles","map","file","isPrivate","checkboxDisabled","status","uploadProgress","fileSize","size","fileName","name","fileType","location","message","onDragEnter","onDragLeave","noClick","noKeyboard","types","split","item","trim","reduce","acc","fileInputRef","useRef","useEffect","driveTitles","handleBeforeUnload","event","returnValue","current","window","addEventListener","removeEventListener","getInternetSpeed","customNavigator","navigator","connection","downlink","renderFileIcon","jsx","className","style","backgroundColor","children","Avatar","src","images","upload","documentPDF","docFile","BASE_URL","handleConfirm","async","controller","filteredFiles","filter","length","handleMultipartUpload","setTimeout","handleRegularUpload","error","prevFiles","updatedFiles","tempCount","index","fileCount","format","mimeType","some","includes","f","preSignedUrlsResponse","fetch","headers","signal","preSignedUrlsData","json","status_code","preSignedUrl","_b","_a","data","preSignedData","presignedUrl","_d","_c","partParams","Body","slice","url","contentLength","chunkSize","bytesUploaded","start","end","min","method","body","progress","round","partSize","parts","ceil","preSignedUrls","uploadId","match","partNum","partNumber","markCompleteResponse","JSON","stringify","markCompleteData","handleChipClick","setAttribute","removeAttribute","click","handleFileChange","e","selectedFiles","target","fileTitles","Array","from","substring","lastIndexOf","removeFile","indexToRemove","handleMinimizeClick","handleDialogClose","confirm","abort","aborted","onCloseConfirmPopup","jsxs","Fragment","Dialog","DialogTitle","Box","Typography","ml","weight","color","IconButton","disableRipple","onClick","RemoveIcon","CloseIcon","Divider","DialogContent","documentUpload","ref","monitor","display","onChange","camera","Checkbox","checked","toggleIsPrivate","disabled","trash","LinearProgress","variant","value","Chip","label","icon","Add","DialogActions","Button","prevIsCollapsed","KeyboardArrowUp","KeyboardArrowDown","Clear","empty","close","CircularProgress","tick","folder","FileConfirmationDialog","onReplace","fileId","id","onKeepBoth","isFile","Toast","Boolean","handleClose","anchorOrigin","horizontal","vertical"],"mappings":"6tDAiDA,MAAMA,EAAc,CAACC,EAAeC,EAAW,KAC7C,GAAc,IAAVD,EAAa,MAAO,UACxB,MACME,EAAKD,EAAW,EAAI,EAAIA,EAExBE,EA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M,GAChF5G,EAAU,CACd,eAAgB,mCAEZ7F,EAAYC,aAAaC,QAAQC,EAAAA,KAAKC,sBAAwB,GACpEyF,EAAQ,WAAa7F,QACf4F,MAAM,gDAAgC4G,IAAU,CACpDpF,OAAQ,SACRvB,YAGF2D,MAuR2JkD,WApR1I,KACjBlD,MAmRoLmD,QAAU;eAE5LhJ,EAAAA,IAACiJ,EAAAA,MAAA,CACGpO,KAAMqO,QAAQlM,IACd1B,KAAM0B,MAAAA,QAAAA,EAAAA,GAAO1B,KACb8C,QAASpB,MAAAA,QAAAA,EAAAA,GAAOoB,QAChB+K,YAAa,IAAMlM,GAAS,MAC5BmM,aAAc,CAAEC,WAAY,QAASC,SAAU"}
|
|
@@ -29,7 +29,7 @@ const defaultProvider = {
|
|
|
29
29
|
changeUserPassword: () => Promise.resolve()
|
|
30
30
|
};
|
|
31
31
|
const AuthContext = createContext(defaultProvider);
|
|
32
|
-
setBaseUrl(`${"
|
|
32
|
+
setBaseUrl(`${"https://apidev.erpforce.co"}/rbac`);
|
|
33
33
|
const AuthProvider = ({ children }) => {
|
|
34
34
|
const [user, setUser] = useState(defaultProvider.user);
|
|
35
35
|
const [authToken, setAuthToken] = useState("");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.esm.js","sources":["../../../src/contexts/AuthContext.tsx"],"sourcesContent":["import React, { createContext, useEffect, useRef, useState } from 'react';\nimport {\n\tpostV1AuthChangePassword,\n\tpostV1AuthForgotPassword,\n\tpostV1AuthChangeUserPassword,\n\t// getV1UserId,\n\tpostV1AuthLogin,\n\tpostV1AuthResetPassword,\n\tsetBaseUrl,\n\tpostV1AuthChangeUserPasswordByAdmin\n} from '../api-client/api.rbac/api';\nimport { auth } from '../constants/auth';\nimport { /* useLocation, */ useNavigate } from 'react-router-dom';\nimport { Pathname } from '../constants/pathnames/pathname'; // Removed - should be passed as props or configured by consuming app\nimport { getToken } from '../utils/common';\nimport { enqueueSnackbar } from 'notistack';\nimport { Socket, io } from 'socket.io-client';\nimport { generateRouteWithId } from '../utils/route-utils';\nimport {\n\tPathnameAccounting,\n\tPathnameGenerator\n} from '../constants/pathnames/pathname.accounting';\n\nimport {\n\tPathnameInventory,\n\tPathnameGenerator as PathnameGeneratorInventory\n} from '../constants/pathnames/pathname.inventory';\n\nimport {\n\tPathnameManufacturing,\n\tPathnameGenerator as PathnameGeneratorManufacuring\n} from '../constants/pathnames/pathname.manufacturing';\n\nimport {\n\tPathnamePurchase,\n\tPathnameGenerator as PathnameGeneratorPurchase\n} from '../constants/pathnames/pathname.procurement';\n\nimport {\n\tPathnameCrm,\n\tPathnameGenerator as PathnameGeneratorCrm\n} from '../constants/pathnames/pathname.crm';\n\nimport {\n\tPathnameRental,\n\tPathnameGenerator as PathnameGeneratorRental\n} from '../constants/pathnames/pathname.rental';\n\nimport { ROUTES as RENTALROUTES } from '../constants/pathnames/pathname.rental';\n\nimport CustomSnackbar from '../components/custom-snackbar/custom-snackbar.tsx';\nexport interface LoginFormValues {\n\temail: string;\n\tpassword: string;\n}\n\nexport interface resetFormValues {\n\temail: string;\n}\n\nexport interface resetPasswordValues {\n\ttoken: string;\n}\n\nexport interface changePasswordValues {\n\tpassword: string;\n}\n\nexport interface changeUserPasswordValues {\n\tpassword: string;\n}\n\ninterface ERPApiUser {\n\tid: string | number;\n\tfirst_name: string;\n\tlast_name: string;\n\tmiddle_name: string;\n\tcountry_code: string;\n\temail: string;\n\tcreated_by: any;\n\tupdated_by: any;\n\tcreated_at: string;\n\tupdated_at: string;\n\trole_id: string;\n\tdepartment_id: number;\n\tis_deleted: number;\n\tdeleted_at: string | null;\n\tdeleted_by: any;\n\ttoken: string;\n\tprofile_image: string;\n\tcurrency_data?: {\n\t\tid: number;\n\t\tsymbol: string;\n\t\tcurrency_name: string;\n\t\tnumber_format:string;\n\t\tposition: string | null;\n\t\tfraction_unit: string | null\n\t};\n\taccessCompanies?: any[]\n}\ninterface ERPUser extends Omit<ERPApiUser, 'token'> {\n\tfull_name: string;\n\tcompany_id: string;\n}\n\ninterface DefaultProviderProps {\n\tuser: ERPUser | null;\n\tloading: boolean;\n\tauthToken: string;\n\tsetUser: React.Dispatch<React.SetStateAction<ERPUser | null>>;\n\tsetLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\tlogin: (\n\t\tparams: LoginFormValues,\n\t\tcallback: (err: string) => void\n\t) => Promise<void>;\n\tlogout: () => Promise<void>;\n\tforgotPassword: (\n\t\tparams: resetFormValues,\n\t\tcallback: (err: string) => void\n\t) => Promise<void>;\n\tresetPassword: (\n\t\tparams: resetPasswordValues,\n\t\tcallback: (err: string) => void\n\t) => Promise<void>;\n\tchangePassword: (\n\t\tparams: changePasswordValues,\n\t\tcallback: (err: string) => void\n\t) => Promise<void>;\n\tchangeUserPassword: (\n\t\tparams: changeUserPasswordValues,\n\t\tcallback: (err: string) => void\n\t) => Promise<void>;\n}\n\nconst defaultProvider: DefaultProviderProps = {\n\tuser: null,\n\tloading: true,\n\tauthToken: '',\n\tsetUser: () => null,\n\tsetLoading: () => Boolean,\n\tlogin: () => Promise.resolve(),\n\tlogout: () => Promise.resolve(),\n\tforgotPassword: () => Promise.resolve(),\n\tresetPassword: () => Promise.resolve(),\n\tchangePassword: () => Promise.resolve(),\n\tchangeUserPassword: () => Promise.resolve()\n};\n\nconst AuthContext = createContext(defaultProvider);\n\ninterface AuthProviderProps {\n\tchildren: React.ReactNode;\n}\n\nsetBaseUrl(`${import.meta.env.VITE_BACKEND_BASE_URL}/rbac`);\n\nconst AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {\n\t// ** States\n\tconst [user, setUser] = useState(defaultProvider.user);\n\tconst [authToken, setAuthToken] = useState<string>('');\n\tconst [loading, setLoading] = useState(defaultProvider.loading);\n\tconst socketRef = useRef<Socket | null>(null);\n\n\t// ** Hooks\n\tconst navigate = useNavigate();\n\t// const location = useLocation();\n\tconst isJsonParse = (string?: string | null) => {\n\t\tif (!string) return false;\n\n\t\ttry {\n\t\t\treturn JSON.parse(string);\n\t\t} catch (error) {\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tconst getNotificationUrl = (data: any) => {\n\t\tconst { moduleName = '', moduleId = '', notificationData = {} } = data;\n\t\tconst key = moduleName.toLowerCase();\n\n\t\tconst routeMap: Record<string, () => string> = {\n\t\t\t'sales invoice': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_SALES_INVOICES), moduleId.toString()),\n\n\t\t\t'asset transfers': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_ASSET_TRANSFER), moduleId.toString()),\n\n\t\t\t'budgets': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_BUDGET), moduleId.toString()),\n\n\t\t\t'cash expense': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_CASH_EXPENSE), moduleId.toString()),\n\n\t\t\t'credit notes': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_CREDIT_NOTE), moduleId.toString()),\n\n\t\t\t'debit notes': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_DEBIT_NOTE), moduleId.toString()),\n\n\t\t\t'expense reimbursement': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_EXPENSE_REIMBURSEMENT), moduleId.toString()),\n\n\t\t\t'journal entries': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_JOURNAL_ENTRY), moduleId.toString()),\n\n\t\t\t'payment entries': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_PAYMENT_ENTRY), moduleId.toString()),\n\n\t\t\t'purchase invoice': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_PURCHASE_INVOICE), moduleId.toString()),\n\n\t\t\t'stock transfer': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorInventory(PathnameInventory.VIEW_STOCK_TRANSFER), moduleId.toString()),\n\n\t\t\t'bills of materials': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorManufacuring(PathnameManufacturing.VIEW_BILL_OF_MATERIAL), moduleId.toString()),\n\n\t\t\t'purchase agreement': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorPurchase(PathnamePurchase.VIEW_PURCHASE_AGREEMENT), moduleId.toString()),\n\n\t\t\t'purchase orders': () =>\n\t\t\tgenerateRouteWithId(notificationData?.data?.is_rental == 1 ? RENTALROUTES.VIEW : PathnameGeneratorPurchase(PathnamePurchase.VIEW_PURCHASE_ORDER) , moduleId.toString()),\n\n\t\t\t'purchase request': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorPurchase(PathnamePurchase.VIEW_PURCHASE_ORDER), moduleId.toString()),\n\n\t\t\t'vra': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorPurchase(PathnamePurchase.VIEW_VENDOR_RETURNS), moduleId.toString()),\n\n\t\t\t'sl customer returns': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorCrm(PathnameCrm.VIEW_CUSTOMER_RETURNS), moduleId.toString()),\n\n\t\t\t'sales order': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorCrm(PathnameCrm.VIEW_SALES_ORDER), moduleId.toString()),\n\n\t\t\t'rental order': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorRental(PathnameRental.VIEW_RENTAL_ORDER), moduleId.toString()),\n\n\t\t\t'replacement order': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorRental(PathnameRental.VIEW_RENTAL_ORDER), moduleId.toString()),\n\n\t\t\t'rental agreement': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorRental(PathnameRental.VIEW_AGREEMENT), moduleId.toString()),\n\n\t\t\t'cross hire order': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorRental(PathnameRental.VIEW_CROSS_HIRE_ORDER), moduleId.toString()),\n\n\t\t\t'cross hire request': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorRental(PathnameRental.VIEW_CROSS_HIRE_REQUEST), moduleId.toString()),\n\t\t};\n\n\t\treturn routeMap[key]?.() || '/dashboard';\n\t};\n\n\n\t// const initAuth = async () => {\n\t// \tconst storedToken = window.localStorage.getItem(auth.storageTokenKeyName);\n\t// \tconst storedUser: ERPUser =\n\t// \t\tisJsonParse(window.localStorage.getItem(auth.storageUserKeyName)) || null;\n\t// \tif (storedToken && storedUser) {\n\t// \t\ttry {\n\t// \t\t\tconst userData = await getV1UserId({\n\t// \t\t\t\t'x-token': storedToken,\n\t// \t\t\t\tid: String(storedUser.id)\n\t// \t\t\t});\n\t// \t\t} catch (error) {\n\t// \t\t}\n\t// \t} else {\n\t// \t\tsetLoading(false);\n\t// \t}\n\t// \tif (storedToken && storedUser) {\n\t// \t\tsetUser(storedUser);\n\t// setLoading(false);\n\t// \t} else {\n\t// \t\thandleLogout();\n\t// setLoading(false);\n\t// \t}\n\t// };\n\n\t// useEffect(() => {\n\t// setLoading(true)\n\t// \tinitAuth();\n\t// \tconst storedToken = window.localStorage.getItem(auth.storageTokenKeyName);\n\t// \tif (!storedToken) {\n\t// \t\tsetUser(null);\n\t// \t} else {\n\t// \t\tsetLoading(false);\n\t// \t}\n\t// \teslint-disable-next-line react-hooks/exhaustive-deps\n\t// }, [location.pathname]);\n\n\t// useEffect(() => {\n\t// \tsetLoading(true);\n\t// \tinitAuth();\n\t// \tconst storedToken = window.localStorage.getItem(auth.storageTokenKeyName);\n\t// \tif (!storedToken) {\n\t// \t\tsetLoading(false);\n\t// \t\tnavigate(Pathname.LOGIN);\n\t// \t}\n\t// \t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t// }, []);\n\n\tuseEffect(() => {\n\t\tsetLoading(true);\n\t\t// initAuth()\n\t\tconst storedToken = window.localStorage.getItem(auth.storageTokenKeyName);\n\t\tconst storedUser =\n\t\t\tisJsonParse(window.localStorage.getItem(auth.storageUserKeyName)) ?? null;\n\t\tconst publicRoutes = [Pathname.LOGIN, Pathname.FORGOT_PASSWORD, Pathname.RESET_PASSWORD, Pathname.CHANGE_PASSWORD];\n\t\tconst currentPath = window.location.pathname;\n\t\tif (!storedToken && !storedUser) {\n\t\t\tif (!publicRoutes.includes(currentPath)) {\n\t\t\t\tnavigate(Pathname.LOGIN);\n\t\t\t}\n\t\t\tsetLoading(false);\n\t\t} else {\n\t\t\tsetUser(storedUser);\n\t\t\tsetAuthToken(storedToken || '');\n\t\t\tsetLoading(false);\n\t\t}\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, []);\n\n\tuseEffect(() => {\n\t\tif (!authToken) {\n\t\t\tif (socketRef.current) {\n\t\t\t\tsocketRef.current?.disconnect();\n\t\t\t\tsocketRef.current = null\n\t\t\t}\n\t\t\tconsole.warn(\"No auth token found, not connecting to socket.\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst socket = io(import.meta.env.VITE_SOCKET_BASE_URL, {\n\t\t\ttransports: [\"websocket\"],\n\t\t\tauth: { token: authToken },\n\t\t\tpath: \"/socket.io/\",\n\t\t\t\n\t\t});\n\t\tsocketRef.current = socket;\n\n\t\tsocket.on(\"connect\", () => {\n\t\t\tconsole.log(\"Socket connected:\", socket.id);\n\t\t\tsocket.onAny((event, ...args) => {\n\t\t\t\tconsole.log(`Received event: ${event}`, args);\n\t\t\t});\n\t\t});\n\t\t\n\t\t// socket event handler\n\t\tsocket.on('notification', (data) => {\n\t\tconst { message, notificationData } = data || {};\n\t\tlet notificationContent: React.ReactNode = message;\n\t\tconst url = getNotificationUrl(data);\n\n\t\tif (notificationData) {\n\t\t\tconst { notification_type } = notificationData;\n\n\t\t\tswitch (notification_type) {\n\t\t\t\tcase 'addApprovers': {\n\t\t\t\t\t\n\t\t\t\t\tnotificationContent = message;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcase 'change_approval_status': {\n\t\t\t\t\tnotificationContent = message;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tdefault: {\n\t\t\t\t\tnotificationContent = message;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tenqueueSnackbar(String(message), {\n\t\t\tvariant: 'default',\n\t\t\tanchorOrigin: { vertical: 'top', horizontal: 'center' },\n\t\t\tautoHideDuration: 5000,\n\t\t\tcontent: (key) => (\n\t\t\t<CustomSnackbar snackbarKey={key} message={notificationContent} data={notificationData} variant=\"default\" linkUrl={url}/>\n\t\t\t),\n\t\t});\n\t\t});\n\n\n\t\tsocket.on(\"sales_invoice_viewed\", (data) => {\n\t\t\tconsole.log(\"Invoice viewed:\", data.invoiceId, \"by user:\", data.userId);\n\t\t});\n\n\t\tsocket.on(\"error\", (errMsg) => {\n\t\t\tenqueueSnackbar(`Socket error: ${errMsg}`, { variant: \"error\" });\n\t\t\tconsole.error(\"Socket error:\", errMsg);\n\t\t});\n\n\t\t// Clean up on unmount\n\t\treturn () => {\n\t\t\tif (socketRef.current) {\n\t\t\t\tsocketRef.current.disconnect();\n\t\t\t\tsocketRef.current = null\n\t\t\t}\n\t\t};\n\t}, [authToken]);\n\n\tconst handleLogin = async (\n\t\tparams: LoginFormValues,\n\t\tcallback: (err: string) => void\n\t) => {\n\t\tsetLoading(true);\n\t\tconst storedToken = window.localStorage.getItem(auth.storageTokenKeyName);\n\t\tif (storedToken && user) {\n\t\t\treturn navigate(Pathname.DASHBOARD);\n\t\t}\n\n\t\ttry {\n\t\t\tconst loginUser = await postV1AuthLogin({ ...params, ...getToken() });\n\t\t\tif (loginUser.success) {\n\t\t\t\tconst data: ERPApiUser | null = loginUser?.data?.login || null;\n\t\t\t\tif (data) {\n\t\t\t\t\twindow.localStorage.setItem(auth.storageTokenKeyName, data.token);\n\t\t\t\t\tconst userData: ERPUser = {\n\t\t\t\t\t\t...data,\n\t\t\t\t\t\tfull_name: `${data.first_name} ${data.last_name}`\n\t\t\t\t\t};\n\t\t\t\t\twindow.localStorage.setItem(\n\t\t\t\t\t\tauth.storageUserKeyName,\n\t\t\t\t\t\tJSON.stringify(userData)\n\t\t\t\t\t);\n\t\t\t\t\tsetUser(userData);\n\t\t\t\t\tsetAuthToken(data.token);\n\t\t\t\t\tnavigate(Pathname.DASHBOARD);\n\t\t\t\t\tsetLoading(false);\n\t\t\t\t\tdelete data.token;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t}\n\n\t\t\tcallback(message);\n\t\t}\n\t};\n\n\tconst handleLogout = async () => {\n\t\twindow.localStorage.removeItem(auth.storageTokenKeyName);\n\t\twindow.localStorage.removeItem(auth.storageUserKeyName);\n\t\twindow.localStorage.removeItem(auth.storageAccessKeyName);\n\t\tsetUser(null);\n\t\tsetAuthToken('');\n\t\tnavigate(Pathname.LOGIN);\n\t};\n\n\tconst handleForgotPassword = async (params: resetFormValues,\n\t\tcallback: (type: boolean, err: string) => void) => {\n\t\ttry {\n\t\t\tawait postV1AuthForgotPassword({ ...params, ...getToken() });\n\t\t\tcallback(true, \"Reset Link sent to your email\");\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t}\n\n\t\t\tcallback(false, message);\n\t\t}\n\t};\n\n\tconst handleResetPassword = async (params: resetPasswordValues,\n\t\tcallback: (err: string) => void) => {\n\t\ttry {\n\t\t\tconst response = await postV1AuthResetPassword({ ...params, ...getToken() });\n\t\t\tcallback(response);\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tconsole.log(\"Error \", error)\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t\tcallback(message);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst handleChangePassword = async (params: resetPasswordValues,\n\t\tcallback: (err: string) => void) => {\n\t\ttry {\n\t\t\tawait postV1AuthChangePassword({ ...params, ...getToken() });\n\t\t\tcallback(null);\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tconsole.log(\"Error \", error)\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t\tcallback(message);\n\t\t\t}\n\t\t}\n\t\tcallback(\"reset\");\n\t}\n\n\tconst handleChangeUserPassword = async (params: resetPasswordValues,\n\t\tcallback: (err: string, resType: boolean) => void) => {\n\t\ttry {\n\t\t\tawait postV1AuthChangeUserPassword({ ...params, ...getToken() });\n\t\t\tcallback('Password Changed Successfully', true);\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t\tcallback(message, false);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst handleChangeUserPasswordByAdmin = async (params: changePasswordValues,\n\t\tcallback: (err: string, resType: boolean) => void) => {\n\t\ttry {\n\t\t\tawait postV1AuthChangeUserPasswordByAdmin({ ...params, ...getToken() });\n\t\t\tcallback('Password Changed Successfully', true);\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t\tcallback(message, false);\n\t\t\t}\n\t\t}\n\t}\n\n\n\tconst values = {\n\t\tuser,\n\t\tauthToken,\n\t\tloading,\n\t\tsetUser,\n\t\tsetLoading,\n\t\tlogin: handleLogin,\n\t\tlogout: handleLogout,\n\t\tforgotPassword: handleForgotPassword,\n\t\tresetPassword: handleResetPassword,\n\t\tchangePassword: handleChangePassword,\n\t\tchangeUserPassword: handleChangeUserPassword,\n\t\tchangeUserPasswordByAdmin: handleChangeUserPasswordByAdmin\n\t};\n\n\treturn <AuthContext.Provider value={values}>{children}</AuthContext.Provider>;\n};\n\nexport { AuthContext, AuthProvider };\n"],"names":["PathnameGenerator","PathnameGeneratorInventory","PathnameGeneratorManufacuring","PathnameGeneratorPurchase","_a","RENTALROUTES","PathnameGeneratorCrm","PathnameGeneratorRental"],"mappings":";;;;;;;;;;;;;;;;;AAsIA,MAAM,kBAAwC;AAAA,EAC7C,MAAM;AAAA,EACN,SAAS;AAAA,EACT,WAAW;AAAA,EACX,SAAS,MAAM;AAAA,EACf,YAAY,MAAM;AAAA,EAClB,OAAO,MAAM,QAAQ,QAAA;AAAA,EACrB,QAAQ,MAAM,QAAQ,QAAA;AAAA,EACtB,gBAAgB,MAAM,QAAQ,QAAA;AAAA,EAC9B,eAAe,MAAM,QAAQ,QAAA;AAAA,EAC7B,gBAAgB,MAAM,QAAQ,QAAA;AAAA,EAC9B,oBAAoB,MAAM,QAAQ,QAAA;AACnC;AAEA,MAAM,cAAc,cAAc,eAAe;AAMjD,WAAW,GAAG,uBAAqC,OAAO;AAE1D,MAAM,eAA4C,CAAC,EAAE,eAAe;AAEnE,QAAM,CAAC,MAAM,OAAO,IAAI,SAAS,gBAAgB,IAAI;AACrD,QAAM,CAAC,WAAW,YAAY,IAAI,SAAiB,EAAE;AACrD,QAAM,CAAC,SAAS,UAAU,IAAI,SAAS,gBAAgB,OAAO;AAC9D,QAAM,YAAY,OAAsB,IAAI;AAG5C,QAAM,WAAW,YAAA;AAEjB,QAAM,cAAc,CAAC,WAA2B;AAC/C,QAAI,CAAC,OAAQ,QAAO;AAEpB,QAAI;AACH,aAAO,KAAK,MAAM,MAAM;AAAA,IACzB,SAAS,OAAO;AACf,aAAO;AAAA,IACR;AAAA,EACD;AAEA,QAAM,qBAAqB,CAAC,SAAc;;AACzC,UAAM,EAAE,aAAa,IAAI,WAAW,IAAI,mBAAmB,CAAA,MAAO;AAClE,UAAM,MAAM,WAAW,YAAA;AAEvB,UAAM,WAAyC;AAAA,MAC9C,iBAAiB,MACjB,oBAAoBA,oBAAkB,mBAAmB,mBAAmB,GAAG,SAAS,UA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G,QAAQ,GAAG,SAAA,GAAY;AAC/D,eAAS,iCAAiC,IAAI;AAAA,IAC/C,SAAS,OAAO;AACf,UAAI,UAAkB;AACtB,UAAI,iBAAiB,OAAO;AAC3B,kBAAU,YAAY,MAAM,OAAO,EAAE,WAAW,MAAM;AACtD,iBAAS,SAAS,KAAK;AAAA,MACxB;AAAA,IACD;AAAA,EACD;AAEA,QAAM,kCAAkC,OAAO,QAC9C,aAAsD;AACtD,QAAI;AACH,YAAM,oCAAoC,EAAE,GAAG,QAAQ,GAAG,SAAA,GAAY;AACtE,eAAS,iCAAiC,IAAI;AAAA,IAC/C,SAAS,OAAO;AACf,UAAI,UAAkB;AACtB,UAAI,iBAAiB,OAAO;AAC3B,kBAAU,YAAY,MAAM,OAAO,EAAE,WAAW,MAAM;AACtD,iBAAS,SAAS,KAAK;AAAA,MACxB;AAAA,IACD;AAAA,EACD;AAGA,QAAM,SAAS;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,gBAAgB;AAAA,IAChB,eAAe;AAAA,IACf,gBAAgB;AAAA,IAChB,oBAAoB;AAAA,IACpB,2BAA2B;AAAA,EAAA;AAG5B,6BAAQ,YAAY,UAAZ,EAAqB,OAAO,QAAS,UAAS;AACvD;"}
|
|
1
|
+
{"version":3,"file":"index.esm.js","sources":["../../../src/contexts/AuthContext.tsx"],"sourcesContent":["import React, { createContext, useEffect, useRef, useState } from 'react';\nimport {\n\tpostV1AuthChangePassword,\n\tpostV1AuthForgotPassword,\n\tpostV1AuthChangeUserPassword,\n\t// getV1UserId,\n\tpostV1AuthLogin,\n\tpostV1AuthResetPassword,\n\tsetBaseUrl,\n\tpostV1AuthChangeUserPasswordByAdmin\n} from '../api-client/api.rbac/api';\nimport { auth } from '../constants/auth';\nimport { /* useLocation, */ useNavigate } from 'react-router-dom';\nimport { Pathname } from '../constants/pathnames/pathname'; // Removed - should be passed as props or configured by consuming app\nimport { getToken } from '../utils/common';\nimport { enqueueSnackbar } from 'notistack';\nimport { Socket, io } from 'socket.io-client';\nimport { generateRouteWithId } from '../utils/route-utils';\nimport {\n\tPathnameAccounting,\n\tPathnameGenerator\n} from '../constants/pathnames/pathname.accounting';\n\nimport {\n\tPathnameInventory,\n\tPathnameGenerator as PathnameGeneratorInventory\n} from '../constants/pathnames/pathname.inventory';\n\nimport {\n\tPathnameManufacturing,\n\tPathnameGenerator as PathnameGeneratorManufacuring\n} from '../constants/pathnames/pathname.manufacturing';\n\nimport {\n\tPathnamePurchase,\n\tPathnameGenerator as PathnameGeneratorPurchase\n} from '../constants/pathnames/pathname.procurement';\n\nimport {\n\tPathnameCrm,\n\tPathnameGenerator as PathnameGeneratorCrm\n} from '../constants/pathnames/pathname.crm';\n\nimport {\n\tPathnameRental,\n\tPathnameGenerator as PathnameGeneratorRental\n} from '../constants/pathnames/pathname.rental';\n\nimport { ROUTES as RENTALROUTES } from '../constants/pathnames/pathname.rental';\n\nimport CustomSnackbar from '../components/custom-snackbar/custom-snackbar.tsx';\nexport interface LoginFormValues {\n\temail: string;\n\tpassword: string;\n}\n\nexport interface resetFormValues {\n\temail: string;\n}\n\nexport interface resetPasswordValues {\n\ttoken: string;\n}\n\nexport interface changePasswordValues {\n\tpassword: string;\n}\n\nexport interface changeUserPasswordValues {\n\tpassword: string;\n}\n\ninterface ERPApiUser {\n\tid: string | number;\n\tfirst_name: string;\n\tlast_name: string;\n\tmiddle_name: string;\n\tcountry_code: string;\n\temail: string;\n\tcreated_by: any;\n\tupdated_by: any;\n\tcreated_at: string;\n\tupdated_at: string;\n\trole_id: string;\n\tdepartment_id: number;\n\tis_deleted: number;\n\tdeleted_at: string | null;\n\tdeleted_by: any;\n\ttoken: string;\n\tprofile_image: string;\n\tcurrency_data?: {\n\t\tid: number;\n\t\tsymbol: string;\n\t\tcurrency_name: string;\n\t\tnumber_format:string;\n\t\tposition: string | null;\n\t\tfraction_unit: string | null\n\t};\n\taccessCompanies?: any[]\n}\ninterface ERPUser extends Omit<ERPApiUser, 'token'> {\n\tfull_name: string;\n\tcompany_id: string;\n}\n\ninterface DefaultProviderProps {\n\tuser: ERPUser | null;\n\tloading: boolean;\n\tauthToken: string;\n\tsetUser: React.Dispatch<React.SetStateAction<ERPUser | null>>;\n\tsetLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\tlogin: (\n\t\tparams: LoginFormValues,\n\t\tcallback: (err: string) => void\n\t) => Promise<void>;\n\tlogout: () => Promise<void>;\n\tforgotPassword: (\n\t\tparams: resetFormValues,\n\t\tcallback: (err: string) => void\n\t) => Promise<void>;\n\tresetPassword: (\n\t\tparams: resetPasswordValues,\n\t\tcallback: (err: string) => void\n\t) => Promise<void>;\n\tchangePassword: (\n\t\tparams: changePasswordValues,\n\t\tcallback: (err: string) => void\n\t) => Promise<void>;\n\tchangeUserPassword: (\n\t\tparams: changeUserPasswordValues,\n\t\tcallback: (err: string) => void\n\t) => Promise<void>;\n}\n\nconst defaultProvider: DefaultProviderProps = {\n\tuser: null,\n\tloading: true,\n\tauthToken: '',\n\tsetUser: () => null,\n\tsetLoading: () => Boolean,\n\tlogin: () => Promise.resolve(),\n\tlogout: () => Promise.resolve(),\n\tforgotPassword: () => Promise.resolve(),\n\tresetPassword: () => Promise.resolve(),\n\tchangePassword: () => Promise.resolve(),\n\tchangeUserPassword: () => Promise.resolve()\n};\n\nconst AuthContext = createContext(defaultProvider);\n\ninterface AuthProviderProps {\n\tchildren: React.ReactNode;\n}\n\nsetBaseUrl(`${import.meta.env.VITE_BACKEND_BASE_URL}/rbac`);\n\nconst AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {\n\t// ** States\n\tconst [user, setUser] = useState(defaultProvider.user);\n\tconst [authToken, setAuthToken] = useState<string>('');\n\tconst [loading, setLoading] = useState(defaultProvider.loading);\n\tconst socketRef = useRef<Socket | null>(null);\n\n\t// ** Hooks\n\tconst navigate = useNavigate();\n\t// const location = useLocation();\n\tconst isJsonParse = (string?: string | null) => {\n\t\tif (!string) return false;\n\n\t\ttry {\n\t\t\treturn JSON.parse(string);\n\t\t} catch (error) {\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tconst getNotificationUrl = (data: any) => {\n\t\tconst { moduleName = '', moduleId = '', notificationData = {} } = data;\n\t\tconst key = moduleName.toLowerCase();\n\n\t\tconst routeMap: Record<string, () => string> = {\n\t\t\t'sales invoice': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_SALES_INVOICES), moduleId.toString()),\n\n\t\t\t'asset transfers': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_ASSET_TRANSFER), moduleId.toString()),\n\n\t\t\t'budgets': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_BUDGET), moduleId.toString()),\n\n\t\t\t'cash expense': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_CASH_EXPENSE), moduleId.toString()),\n\n\t\t\t'credit notes': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_CREDIT_NOTE), moduleId.toString()),\n\n\t\t\t'debit notes': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_DEBIT_NOTE), moduleId.toString()),\n\n\t\t\t'expense reimbursement': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_EXPENSE_REIMBURSEMENT), moduleId.toString()),\n\n\t\t\t'journal entries': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_JOURNAL_ENTRY), moduleId.toString()),\n\n\t\t\t'payment entries': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_PAYMENT_ENTRY), moduleId.toString()),\n\n\t\t\t'purchase invoice': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_PURCHASE_INVOICE), moduleId.toString()),\n\n\t\t\t'stock transfer': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorInventory(PathnameInventory.VIEW_STOCK_TRANSFER), moduleId.toString()),\n\n\t\t\t'bills of materials': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorManufacuring(PathnameManufacturing.VIEW_BILL_OF_MATERIAL), moduleId.toString()),\n\n\t\t\t'purchase agreement': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorPurchase(PathnamePurchase.VIEW_PURCHASE_AGREEMENT), moduleId.toString()),\n\n\t\t\t'purchase orders': () =>\n\t\t\tgenerateRouteWithId(notificationData?.data?.is_rental == 1 ? RENTALROUTES.VIEW : PathnameGeneratorPurchase(PathnamePurchase.VIEW_PURCHASE_ORDER) , moduleId.toString()),\n\n\t\t\t'purchase request': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorPurchase(PathnamePurchase.VIEW_PURCHASE_ORDER), moduleId.toString()),\n\n\t\t\t'vra': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorPurchase(PathnamePurchase.VIEW_VENDOR_RETURNS), moduleId.toString()),\n\n\t\t\t'sl customer returns': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorCrm(PathnameCrm.VIEW_CUSTOMER_RETURNS), moduleId.toString()),\n\n\t\t\t'sales order': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorCrm(PathnameCrm.VIEW_SALES_ORDER), moduleId.toString()),\n\n\t\t\t'rental order': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorRental(PathnameRental.VIEW_RENTAL_ORDER), moduleId.toString()),\n\n\t\t\t'replacement order': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorRental(PathnameRental.VIEW_RENTAL_ORDER), moduleId.toString()),\n\n\t\t\t'rental agreement': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorRental(PathnameRental.VIEW_AGREEMENT), moduleId.toString()),\n\n\t\t\t'cross hire order': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorRental(PathnameRental.VIEW_CROSS_HIRE_ORDER), moduleId.toString()),\n\n\t\t\t'cross hire request': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorRental(PathnameRental.VIEW_CROSS_HIRE_REQUEST), moduleId.toString()),\n\t\t};\n\n\t\treturn routeMap[key]?.() || '/dashboard';\n\t};\n\n\n\t// const initAuth = async () => {\n\t// \tconst storedToken = window.localStorage.getItem(auth.storageTokenKeyName);\n\t// \tconst storedUser: ERPUser =\n\t// \t\tisJsonParse(window.localStorage.getItem(auth.storageUserKeyName)) || null;\n\t// \tif (storedToken && storedUser) {\n\t// \t\ttry {\n\t// \t\t\tconst userData = await getV1UserId({\n\t// \t\t\t\t'x-token': storedToken,\n\t// \t\t\t\tid: String(storedUser.id)\n\t// \t\t\t});\n\t// \t\t} catch (error) {\n\t// \t\t}\n\t// \t} else {\n\t// \t\tsetLoading(false);\n\t// \t}\n\t// \tif (storedToken && storedUser) {\n\t// \t\tsetUser(storedUser);\n\t// setLoading(false);\n\t// \t} else {\n\t// \t\thandleLogout();\n\t// setLoading(false);\n\t// \t}\n\t// };\n\n\t// useEffect(() => {\n\t// setLoading(true)\n\t// \tinitAuth();\n\t// \tconst storedToken = window.localStorage.getItem(auth.storageTokenKeyName);\n\t// \tif (!storedToken) {\n\t// \t\tsetUser(null);\n\t// \t} else {\n\t// \t\tsetLoading(false);\n\t// \t}\n\t// \teslint-disable-next-line react-hooks/exhaustive-deps\n\t// }, [location.pathname]);\n\n\t// useEffect(() => {\n\t// \tsetLoading(true);\n\t// \tinitAuth();\n\t// \tconst storedToken = window.localStorage.getItem(auth.storageTokenKeyName);\n\t// \tif (!storedToken) {\n\t// \t\tsetLoading(false);\n\t// \t\tnavigate(Pathname.LOGIN);\n\t// \t}\n\t// \t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t// }, []);\n\n\tuseEffect(() => {\n\t\tsetLoading(true);\n\t\t// initAuth()\n\t\tconst storedToken = window.localStorage.getItem(auth.storageTokenKeyName);\n\t\tconst storedUser =\n\t\t\tisJsonParse(window.localStorage.getItem(auth.storageUserKeyName)) ?? null;\n\t\tconst publicRoutes = [Pathname.LOGIN, Pathname.FORGOT_PASSWORD, Pathname.RESET_PASSWORD, Pathname.CHANGE_PASSWORD];\n\t\tconst currentPath = window.location.pathname;\n\t\tif (!storedToken && !storedUser) {\n\t\t\tif (!publicRoutes.includes(currentPath)) {\n\t\t\t\tnavigate(Pathname.LOGIN);\n\t\t\t}\n\t\t\tsetLoading(false);\n\t\t} else {\n\t\t\tsetUser(storedUser);\n\t\t\tsetAuthToken(storedToken || '');\n\t\t\tsetLoading(false);\n\t\t}\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, []);\n\n\tuseEffect(() => {\n\t\tif (!authToken) {\n\t\t\tif (socketRef.current) {\n\t\t\t\tsocketRef.current?.disconnect();\n\t\t\t\tsocketRef.current = null\n\t\t\t}\n\t\t\tconsole.warn(\"No auth token found, not connecting to socket.\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst socket = io(import.meta.env.VITE_SOCKET_BASE_URL, {\n\t\t\ttransports: [\"websocket\"],\n\t\t\tauth: { token: authToken },\n\t\t\tpath: \"/socket.io/\",\n\t\t\t\n\t\t});\n\t\tsocketRef.current = socket;\n\n\t\tsocket.on(\"connect\", () => {\n\t\t\tconsole.log(\"Socket connected:\", socket.id);\n\t\t\tsocket.onAny((event, ...args) => {\n\t\t\t\tconsole.log(`Received event: ${event}`, args);\n\t\t\t});\n\t\t});\n\t\t\n\t\t// socket event handler\n\t\tsocket.on('notification', (data) => {\n\t\tconst { message, notificationData } = data || {};\n\t\tlet notificationContent: React.ReactNode = message;\n\t\tconst url = getNotificationUrl(data);\n\n\t\tif (notificationData) {\n\t\t\tconst { notification_type } = notificationData;\n\n\t\t\tswitch (notification_type) {\n\t\t\t\tcase 'addApprovers': {\n\t\t\t\t\t\n\t\t\t\t\tnotificationContent = message;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcase 'change_approval_status': {\n\t\t\t\t\tnotificationContent = message;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tdefault: {\n\t\t\t\t\tnotificationContent = message;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tenqueueSnackbar(String(message), {\n\t\t\tvariant: 'default',\n\t\t\tanchorOrigin: { vertical: 'top', horizontal: 'center' },\n\t\t\tautoHideDuration: 5000,\n\t\t\tcontent: (key) => (\n\t\t\t<CustomSnackbar snackbarKey={key} message={notificationContent} data={notificationData} variant=\"default\" linkUrl={url}/>\n\t\t\t),\n\t\t});\n\t\t});\n\n\n\t\tsocket.on(\"sales_invoice_viewed\", (data) => {\n\t\t\tconsole.log(\"Invoice viewed:\", data.invoiceId, \"by user:\", data.userId);\n\t\t});\n\n\t\tsocket.on(\"error\", (errMsg) => {\n\t\t\tenqueueSnackbar(`Socket error: ${errMsg}`, { variant: \"error\" });\n\t\t\tconsole.error(\"Socket error:\", errMsg);\n\t\t});\n\n\t\t// Clean up on unmount\n\t\treturn () => {\n\t\t\tif (socketRef.current) {\n\t\t\t\tsocketRef.current.disconnect();\n\t\t\t\tsocketRef.current = null\n\t\t\t}\n\t\t};\n\t}, [authToken]);\n\n\tconst handleLogin = async (\n\t\tparams: LoginFormValues,\n\t\tcallback: (err: string) => void\n\t) => {\n\t\tsetLoading(true);\n\t\tconst storedToken = window.localStorage.getItem(auth.storageTokenKeyName);\n\t\tif (storedToken && user) {\n\t\t\treturn navigate(Pathname.DASHBOARD);\n\t\t}\n\n\t\ttry {\n\t\t\tconst loginUser = await postV1AuthLogin({ ...params, ...getToken() });\n\t\t\tif (loginUser.success) {\n\t\t\t\tconst data: ERPApiUser | null = loginUser?.data?.login || null;\n\t\t\t\tif (data) {\n\t\t\t\t\twindow.localStorage.setItem(auth.storageTokenKeyName, data.token);\n\t\t\t\t\tconst userData: ERPUser = {\n\t\t\t\t\t\t...data,\n\t\t\t\t\t\tfull_name: `${data.first_name} ${data.last_name}`\n\t\t\t\t\t};\n\t\t\t\t\twindow.localStorage.setItem(\n\t\t\t\t\t\tauth.storageUserKeyName,\n\t\t\t\t\t\tJSON.stringify(userData)\n\t\t\t\t\t);\n\t\t\t\t\tsetUser(userData);\n\t\t\t\t\tsetAuthToken(data.token);\n\t\t\t\t\tnavigate(Pathname.DASHBOARD);\n\t\t\t\t\tsetLoading(false);\n\t\t\t\t\tdelete data.token;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t}\n\n\t\t\tcallback(message);\n\t\t}\n\t};\n\n\tconst handleLogout = async () => {\n\t\twindow.localStorage.removeItem(auth.storageTokenKeyName);\n\t\twindow.localStorage.removeItem(auth.storageUserKeyName);\n\t\twindow.localStorage.removeItem(auth.storageAccessKeyName);\n\t\tsetUser(null);\n\t\tsetAuthToken('');\n\t\tnavigate(Pathname.LOGIN);\n\t};\n\n\tconst handleForgotPassword = async (params: resetFormValues,\n\t\tcallback: (type: boolean, err: string) => void) => {\n\t\ttry {\n\t\t\tawait postV1AuthForgotPassword({ ...params, ...getToken() });\n\t\t\tcallback(true, \"Reset Link sent to your email\");\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t}\n\n\t\t\tcallback(false, message);\n\t\t}\n\t};\n\n\tconst handleResetPassword = async (params: resetPasswordValues,\n\t\tcallback: (err: string) => void) => {\n\t\ttry {\n\t\t\tconst response = await postV1AuthResetPassword({ ...params, ...getToken() });\n\t\t\tcallback(response);\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tconsole.log(\"Error \", error)\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t\tcallback(message);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst handleChangePassword = async (params: resetPasswordValues,\n\t\tcallback: (err: string) => void) => {\n\t\ttry {\n\t\t\tawait postV1AuthChangePassword({ ...params, ...getToken() });\n\t\t\tcallback(null);\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tconsole.log(\"Error \", error)\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t\tcallback(message);\n\t\t\t}\n\t\t}\n\t\tcallback(\"reset\");\n\t}\n\n\tconst handleChangeUserPassword = async (params: resetPasswordValues,\n\t\tcallback: (err: string, resType: boolean) => void) => {\n\t\ttry {\n\t\t\tawait postV1AuthChangeUserPassword({ ...params, ...getToken() });\n\t\t\tcallback('Password Changed Successfully', true);\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t\tcallback(message, false);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst handleChangeUserPasswordByAdmin = async (params: changePasswordValues,\n\t\tcallback: (err: string, resType: boolean) => void) => {\n\t\ttry {\n\t\t\tawait postV1AuthChangeUserPasswordByAdmin({ ...params, ...getToken() });\n\t\t\tcallback('Password Changed Successfully', true);\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t\tcallback(message, false);\n\t\t\t}\n\t\t}\n\t}\n\n\n\tconst values = {\n\t\tuser,\n\t\tauthToken,\n\t\tloading,\n\t\tsetUser,\n\t\tsetLoading,\n\t\tlogin: handleLogin,\n\t\tlogout: handleLogout,\n\t\tforgotPassword: handleForgotPassword,\n\t\tresetPassword: handleResetPassword,\n\t\tchangePassword: handleChangePassword,\n\t\tchangeUserPassword: handleChangeUserPassword,\n\t\tchangeUserPasswordByAdmin: handleChangeUserPasswordByAdmin\n\t};\n\n\treturn <AuthContext.Provider value={values}>{children}</AuthContext.Provider>;\n};\n\nexport { AuthContext, AuthProvider };\n"],"names":["PathnameGenerator","PathnameGeneratorInventory","PathnameGeneratorManufacuring","PathnameGeneratorPurchase","_a","RENTALROUTES","PathnameGeneratorCrm","PathnameGeneratorRental"],"mappings":";;;;;;;;;;;;;;;;;AAsIA,MAAM,kBAAwC;AAAA,EAC7C,MAAM;AAAA,EACN,SAAS;AAAA,EACT,WAAW;AAAA,EACX,SAAS,MAAM;AAAA,EACf,YAAY,MAAM;AAAA,EAClB,OAAO,MAAM,QAAQ,QAAA;AAAA,EACrB,QAAQ,MAAM,QAAQ,QAAA;AAAA,EACtB,gBAAgB,MAAM,QAAQ,QAAA;AAAA,EAC9B,eAAe,MAAM,QAAQ,QAAA;AAAA,EAC7B,gBAAgB,MAAM,QAAQ,QAAA;AAAA,EAC9B,oBAAoB,MAAM,QAAQ,QAAA;AACnC;AAEA,MAAM,cAAc,cAAc,eAAe;AAMjD,WAAW,GAAG,4BAAqC,OAAO;AAE1D,MAAM,eAA4C,CAAC,EAAE,eAAe;AAEnE,QAAM,CAAC,MAAM,OAAO,IAAI,SAAS,gBAAgB,IAAI;AACrD,QAAM,CAAC,WAAW,YAAY,IAAI,SAAiB,EAAE;AACrD,QAAM,CAAC,SAAS,UAAU,IAAI,SAAS,gBAAgB,OAAO;AAC9D,QAAM,YAAY,OAAsB,IAAI;AAG5C,QAAM,WAAW,YAAA;AAEjB,QAAM,cAAc,CAAC,WAA2B;AAC/C,QAAI,CAAC,OAAQ,QAAO;AAEpB,QAAI;AACH,aAAO,KAAK,MAAM,MAAM;AAAA,IACzB,SAAS,OAAO;AACf,aAAO;AAAA,IACR;AAAA,EACD;AAEA,QAAM,qBAAqB,CAAC,SAAc;;AACzC,UAAM,EAAE,aAAa,IAAI,WAAW,IAAI,mBAAmB,CAAA,MAAO;AAClE,UAAM,MAAM,WAAW,YAAA;AAEvB,UAAM,WAAyC;AAAA,MAC9C,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2B,OAAO,QACvC,aAAsD;AACtD,QAAI;AACH,YAAM,6BAA6B,EAAE,GAAG,QAAQ,GAAG,SAAA,GAAY;AAC/D,eAAS,iCAAiC,IAAI;AAAA,IAC/C,SAAS,OAAO;AACf,UAAI,UAAkB;AACtB,UAAI,iBAAiB,OAAO;AAC3B,kBAAU,YAAY,MAAM,OAAO,EAAE,WAAW,MAAM;AACtD,iBAAS,SAAS,KAAK;AAAA,MACxB;AAAA,IACD;AAAA,EACD;AAEA,QAAM,kCAAkC,OAAO,QAC9C,aAAsD;AACtD,QAAI;AACH,YAAM,oCAAoC,EAAE,GAAG,QAAQ,GAAG,SAAA,GAAY;AACtE,eAAS,iCAAiC,IAAI;AAAA,IAC/C,SAAS,OAAO;AACf,UAAI,UAAkB;AACtB,UAAI,iBAAiB,OAAO;AAC3B,kBAAU,YAAY,MAAM,OAAO,EAAE,WAAW,MAAM;AACtD,iBAAS,SAAS,KAAK;AAAA,MACxB;AAAA,IACD;AAAA,EACD;AAGA,QAAM,SAAS;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,gBAAgB;AAAA,IAChB,eAAe;AAAA,IACf,gBAAgB;AAAA,IAChB,oBAAoB;AAAA,IACpB,2BAA2B;AAAA,EAAA;AAG5B,6BAAQ,YAAY,UAAZ,EAAqB,OAAO,QAAS,UAAS;AACvD;"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),t=require("react"),a=require("../../api-client/api.rbac/api/index.js"),n=require("../../constants/auth/index.js"),r=require("react-router-dom"),o=require("../../constants/pathnames/pathname/index.js"),s=require("../../utils/common/index.js"),i=require("../../node_modules/notistack/notistack.esm/index.js"),c=require("socket.io-client"),u=require("../../utils/route-utils/index.js"),h=require("../../constants/pathnames/pathname.accounting/index.js"),m=require("../../constants/pathnames/pathname.inventory/index.js"),g=require("../../constants/pathnames/pathname.manufacturing/index.js"),l=require("../../constants/pathnames/pathname.procurement/index.js"),d=require("../../constants/pathnames/pathname.crm/index.js"),P=require("../../constants/pathnames/pathname.rental/index.js"),E=require("../../components/custom-snackbar/custom-snackbar/index.js");const S={user:null,loading:!0,authToken:"",setUser:()=>null,setLoading:()=>Boolean,login:()=>Promise.resolve(),logout:()=>Promise.resolve(),forgotPassword:()=>Promise.resolve(),resetPassword:()=>Promise.resolve(),changePassword:()=>Promise.resolve(),changeUserPassword:()=>Promise.resolve()},R=t.createContext(S);a.setBaseUrl("
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),t=require("react"),a=require("../../api-client/api.rbac/api/index.js"),n=require("../../constants/auth/index.js"),r=require("react-router-dom"),o=require("../../constants/pathnames/pathname/index.js"),s=require("../../utils/common/index.js"),i=require("../../node_modules/notistack/notistack.esm/index.js"),c=require("socket.io-client"),u=require("../../utils/route-utils/index.js"),h=require("../../constants/pathnames/pathname.accounting/index.js"),m=require("../../constants/pathnames/pathname.inventory/index.js"),g=require("../../constants/pathnames/pathname.manufacturing/index.js"),l=require("../../constants/pathnames/pathname.procurement/index.js"),d=require("../../constants/pathnames/pathname.crm/index.js"),P=require("../../constants/pathnames/pathname.rental/index.js"),E=require("../../components/custom-snackbar/custom-snackbar/index.js");const S={user:null,loading:!0,authToken:"",setUser:()=>null,setLoading:()=>Boolean,login:()=>Promise.resolve(),logout:()=>Promise.resolve(),forgotPassword:()=>Promise.resolve(),resetPassword:()=>Promise.resolve(),changePassword:()=>Promise.resolve(),changeUserPassword:()=>Promise.resolve()},R=t.createContext(S);a.setBaseUrl("https://apidev.erpforce.co/rbac"),exports.AuthContext=R,exports.AuthProvider=({children:I})=>{const[_,w]=t.useState(S.user),[W,p]=t.useState(""),[A,f]=t.useState(S.loading),v=t.useRef(null),T=r.useNavigate(),N=e=>{if(!e)return!1;try{return JSON.parse(e)}catch(t){return!1}};t.useEffect(()=>{f(!0);const e=window.localStorage.getItem(n.auth.storageTokenKeyName),t=N(window.localStorage.getItem(n.auth.storageUserKeyName))??null,a=[o.Pathname.LOGIN,o.Pathname.FORGOT_PASSWORD,o.Pathname.RESET_PASSWORD,o.Pathname.CHANGE_PASSWORD],r=window.location.pathname;e||t?(w(t),p(e||""),f(!1)):(a.includes(r)||T(o.Pathname.LOGIN),f(!1))},[]),t.useEffect(()=>{var t;if(!W)return void(v.current&&(null==(t=v.current)||t.disconnect(),v.current=null));const a=c.io("https://apidev.erpforce.co",{transports:["websocket"],auth:{token:W},path:"/socket.io/"});return v.current=a,a.on("connect",()=>{a.onAny((e,...t)=>{})}),a.on("notification",t=>{const{message:a,notificationData:n}=t||{};let r=a;const o=(e=>{var t;const{moduleName:a="",moduleId:n="",notificationData:r={}}=e,o={"sales invoice":()=>u.generateRouteWithId(h.PathnameGenerator(h.PathnameAccounting.VIEW_SALES_INVOICES),n.toString()),"asset transfers":()=>u.generateRouteWithId(h.PathnameGenerator(h.PathnameAccounting.VIEW_ASSET_TRANSFER),n.toString()),budgets:()=>u.generateRouteWithId(h.PathnameGenerator(h.PathnameAccounting.VIEW_BUDGET),n.toString()),"cash expense":()=>u.generateRouteWithId(h.PathnameGenerator(h.PathnameAccounting.VIEW_CASH_EXPENSE),n.toString()),"credit notes":()=>u.generateRouteWithId(h.PathnameGenerator(h.PathnameAccounting.VIEW_CREDIT_NOTE),n.toString()),"debit notes":()=>u.generateRouteWithId(h.PathnameGenerator(h.PathnameAccounting.VIEW_DEBIT_NOTE),n.toString()),"expense reimbursement":()=>u.generateRouteWithId(h.PathnameGenerator(h.PathnameAccounting.VIEW_EXPENSE_REIMBURSEMENT),n.toString()),"journal entries":()=>u.generateRouteWithId(h.PathnameGenerator(h.PathnameAccounting.VIEW_JOURNAL_ENTRY),n.toString()),"payment entries":()=>u.generateRouteWithId(h.PathnameGenerator(h.PathnameAccounting.VIEW_PAYMENT_ENTRY),n.toString()),"purchase invoice":()=>u.generateRouteWithId(h.PathnameGenerator(h.PathnameAccounting.VIEW_PURCHASE_INVOICE),n.toString()),"stock transfer":()=>u.generateRouteWithId(m.PathnameGenerator(m.PathnameInventory.VIEW_STOCK_TRANSFER),n.toString()),"bills of materials":()=>u.generateRouteWithId(g.PathnameGenerator(g.PathnameManufacturing.VIEW_BILL_OF_MATERIAL),n.toString()),"purchase agreement":()=>u.generateRouteWithId(l.PathnameGenerator(l.PathnamePurchase.VIEW_PURCHASE_AGREEMENT),n.toString()),"purchase orders":()=>{var e;return u.generateRouteWithId(1==(null==(e=null==r?void 0:r.data)?void 0:e.is_rental)?P.ROUTES.VIEW:l.PathnameGenerator(l.PathnamePurchase.VIEW_PURCHASE_ORDER),n.toString())},"purchase request":()=>u.generateRouteWithId(l.PathnameGenerator(l.PathnamePurchase.VIEW_PURCHASE_ORDER),n.toString()),vra:()=>u.generateRouteWithId(l.PathnameGenerator(l.PathnamePurchase.VIEW_VENDOR_RETURNS),n.toString()),"sl customer returns":()=>u.generateRouteWithId(d.PathnameGenerator(d.PathnameCrm.VIEW_CUSTOMER_RETURNS),n.toString()),"sales order":()=>u.generateRouteWithId(d.PathnameGenerator(d.PathnameCrm.VIEW_SALES_ORDER),n.toString()),"rental order":()=>u.generateRouteWithId(P.PathnameGenerator(P.PathnameRental.VIEW_RENTAL_ORDER),n.toString()),"replacement order":()=>u.generateRouteWithId(P.PathnameGenerator(P.PathnameRental.VIEW_RENTAL_ORDER),n.toString()),"rental agreement":()=>u.generateRouteWithId(P.PathnameGenerator(P.PathnameRental.VIEW_AGREEMENT),n.toString()),"cross hire order":()=>u.generateRouteWithId(P.PathnameGenerator(P.PathnameRental.VIEW_CROSS_HIRE_ORDER),n.toString()),"cross hire request":()=>u.generateRouteWithId(P.PathnameGenerator(P.PathnameRental.VIEW_CROSS_HIRE_REQUEST),n.toString())};return(null==(t=o[a.toLowerCase()])?void 0:t.call(o))||"/dashboard"})(t);if(n){const{notification_type:e}=n;r=a}i.enqueueSnackbar(String(a),{variant:"default",anchorOrigin:{vertical:"top",horizontal:"center"},autoHideDuration:5e3,content:t=>/* @__PURE__ */e.jsx(E.CustomSnackbar,{snackbarKey:t,message:r,data:n,variant:"default",linkUrl:o})})}),a.on("sales_invoice_viewed",e=>{}),a.on("error",e=>{i.enqueueSnackbar(`Socket error: ${e}`,{variant:"error"})}),()=>{v.current&&(v.current.disconnect(),v.current=null)}},[W]);const y={user:_,authToken:W,loading:A,setUser:w,setLoading:f,login:async(e,t)=>{var r;if(f(!0),window.localStorage.getItem(n.auth.storageTokenKeyName)&&_)return T(o.Pathname.DASHBOARD);try{const t=await a.postV1AuthLogin({...e,...s.getToken()});if(t.success){const e=(null==(r=null==t?void 0:t.data)?void 0:r.login)||null;if(e){window.localStorage.setItem(n.auth.storageTokenKeyName,e.token);const t={...e,full_name:`${e.first_name} ${e.last_name}`};window.localStorage.setItem(n.auth.storageUserKeyName,JSON.stringify(t)),w(t),p(e.token),T(o.Pathname.DASHBOARD),f(!1),delete e.token}}}catch(i){let e="Something went wrong";i instanceof Error&&(e=N(i.message).message||i.message),t(e)}},logout:async()=>{window.localStorage.removeItem(n.auth.storageTokenKeyName),window.localStorage.removeItem(n.auth.storageUserKeyName),window.localStorage.removeItem(n.auth.storageAccessKeyName),w(null),p(""),T(o.Pathname.LOGIN)},forgotPassword:async(e,t)=>{try{await a.postV1AuthForgotPassword({...e,...s.getToken()}),t(!0,"Reset Link sent to your email")}catch(n){let e="Something went wrong";n instanceof Error&&(e=N(n.message).message||n.message),t(!1,e)}},resetPassword:async(e,t)=>{try{t(await a.postV1AuthResetPassword({...e,...s.getToken()}))}catch(n){let e="Something went wrong";n instanceof Error&&(e=N(n.message).message||n.message,t(e))}},changePassword:async(e,t)=>{try{await a.postV1AuthChangePassword({...e,...s.getToken()}),t(null)}catch(n){let e="Something went wrong";n instanceof Error&&(e=N(n.message).message||n.message,t(e))}t("reset")},changeUserPassword:async(e,t)=>{try{await a.postV1AuthChangeUserPassword({...e,...s.getToken()}),t("Password Changed Successfully",!0)}catch(n){let e="Something went wrong";n instanceof Error&&(e=N(n.message).message||n.message,t(e,!1))}},changeUserPasswordByAdmin:async(e,t)=>{try{await a.postV1AuthChangeUserPasswordByAdmin({...e,...s.getToken()}),t("Password Changed Successfully",!0)}catch(n){let e="Something went wrong";n instanceof Error&&(e=N(n.message).message||n.message,t(e,!1))}}};/* @__PURE__ */
|
|
2
2
|
return e.jsx(R.Provider,{value:y,children:I})};
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../src/contexts/AuthContext.tsx"],"sourcesContent":["import React, { createContext, useEffect, useRef, useState } from 'react';\nimport {\n\tpostV1AuthChangePassword,\n\tpostV1AuthForgotPassword,\n\tpostV1AuthChangeUserPassword,\n\t// getV1UserId,\n\tpostV1AuthLogin,\n\tpostV1AuthResetPassword,\n\tsetBaseUrl,\n\tpostV1AuthChangeUserPasswordByAdmin\n} from '../api-client/api.rbac/api';\nimport { auth } from '../constants/auth';\nimport { /* useLocation, */ useNavigate } from 'react-router-dom';\nimport { Pathname } from '../constants/pathnames/pathname'; // Removed - should be passed as props or configured by consuming app\nimport { getToken } from '../utils/common';\nimport { enqueueSnackbar } from 'notistack';\nimport { Socket, io } from 'socket.io-client';\nimport { generateRouteWithId } from '../utils/route-utils';\nimport {\n\tPathnameAccounting,\n\tPathnameGenerator\n} from '../constants/pathnames/pathname.accounting';\n\nimport {\n\tPathnameInventory,\n\tPathnameGenerator as PathnameGeneratorInventory\n} from '../constants/pathnames/pathname.inventory';\n\nimport {\n\tPathnameManufacturing,\n\tPathnameGenerator as PathnameGeneratorManufacuring\n} from '../constants/pathnames/pathname.manufacturing';\n\nimport {\n\tPathnamePurchase,\n\tPathnameGenerator as PathnameGeneratorPurchase\n} from '../constants/pathnames/pathname.procurement';\n\nimport {\n\tPathnameCrm,\n\tPathnameGenerator as PathnameGeneratorCrm\n} from '../constants/pathnames/pathname.crm';\n\nimport {\n\tPathnameRental,\n\tPathnameGenerator as PathnameGeneratorRental\n} from '../constants/pathnames/pathname.rental';\n\nimport { ROUTES as RENTALROUTES } from '../constants/pathnames/pathname.rental';\n\nimport CustomSnackbar from '../components/custom-snackbar/custom-snackbar.tsx';\nexport interface LoginFormValues {\n\temail: string;\n\tpassword: string;\n}\n\nexport interface resetFormValues {\n\temail: string;\n}\n\nexport interface resetPasswordValues {\n\ttoken: string;\n}\n\nexport interface changePasswordValues {\n\tpassword: string;\n}\n\nexport interface changeUserPasswordValues {\n\tpassword: string;\n}\n\ninterface ERPApiUser {\n\tid: string | number;\n\tfirst_name: string;\n\tlast_name: string;\n\tmiddle_name: string;\n\tcountry_code: string;\n\temail: string;\n\tcreated_by: any;\n\tupdated_by: any;\n\tcreated_at: string;\n\tupdated_at: string;\n\trole_id: string;\n\tdepartment_id: number;\n\tis_deleted: number;\n\tdeleted_at: string | null;\n\tdeleted_by: any;\n\ttoken: string;\n\tprofile_image: string;\n\tcurrency_data?: {\n\t\tid: number;\n\t\tsymbol: string;\n\t\tcurrency_name: string;\n\t\tnumber_format:string;\n\t\tposition: string | null;\n\t\tfraction_unit: string | null\n\t};\n\taccessCompanies?: any[]\n}\ninterface ERPUser extends Omit<ERPApiUser, 'token'> {\n\tfull_name: string;\n\tcompany_id: string;\n}\n\ninterface DefaultProviderProps {\n\tuser: ERPUser | null;\n\tloading: boolean;\n\tauthToken: string;\n\tsetUser: React.Dispatch<React.SetStateAction<ERPUser | null>>;\n\tsetLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\tlogin: (\n\t\tparams: LoginFormValues,\n\t\tcallback: (err: string) => void\n\t) => Promise<void>;\n\tlogout: () => Promise<void>;\n\tforgotPassword: (\n\t\tparams: resetFormValues,\n\t\tcallback: (err: string) => void\n\t) => Promise<void>;\n\tresetPassword: (\n\t\tparams: resetPasswordValues,\n\t\tcallback: (err: string) => void\n\t) => Promise<void>;\n\tchangePassword: (\n\t\tparams: changePasswordValues,\n\t\tcallback: (err: string) => void\n\t) => Promise<void>;\n\tchangeUserPassword: (\n\t\tparams: changeUserPasswordValues,\n\t\tcallback: (err: string) => void\n\t) => Promise<void>;\n}\n\nconst defaultProvider: DefaultProviderProps = {\n\tuser: null,\n\tloading: true,\n\tauthToken: '',\n\tsetUser: () => null,\n\tsetLoading: () => Boolean,\n\tlogin: () => Promise.resolve(),\n\tlogout: () => Promise.resolve(),\n\tforgotPassword: () => Promise.resolve(),\n\tresetPassword: () => Promise.resolve(),\n\tchangePassword: () => Promise.resolve(),\n\tchangeUserPassword: () => Promise.resolve()\n};\n\nconst AuthContext = createContext(defaultProvider);\n\ninterface AuthProviderProps {\n\tchildren: React.ReactNode;\n}\n\nsetBaseUrl(`${import.meta.env.VITE_BACKEND_BASE_URL}/rbac`);\n\nconst AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {\n\t// ** States\n\tconst [user, setUser] = useState(defaultProvider.user);\n\tconst [authToken, setAuthToken] = useState<string>('');\n\tconst [loading, setLoading] = useState(defaultProvider.loading);\n\tconst socketRef = useRef<Socket | null>(null);\n\n\t// ** Hooks\n\tconst navigate = useNavigate();\n\t// const location = useLocation();\n\tconst isJsonParse = (string?: string | null) => {\n\t\tif (!string) return false;\n\n\t\ttry {\n\t\t\treturn JSON.parse(string);\n\t\t} catch (error) {\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tconst getNotificationUrl = (data: any) => {\n\t\tconst { moduleName = '', moduleId = '', notificationData = {} } = data;\n\t\tconst key = moduleName.toLowerCase();\n\n\t\tconst routeMap: Record<string, () => string> = {\n\t\t\t'sales invoice': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_SALES_INVOICES), moduleId.toString()),\n\n\t\t\t'asset transfers': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_ASSET_TRANSFER), moduleId.toString()),\n\n\t\t\t'budgets': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_BUDGET), moduleId.toString()),\n\n\t\t\t'cash expense': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_CASH_EXPENSE), moduleId.toString()),\n\n\t\t\t'credit notes': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_CREDIT_NOTE), moduleId.toString()),\n\n\t\t\t'debit notes': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_DEBIT_NOTE), moduleId.toString()),\n\n\t\t\t'expense reimbursement': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_EXPENSE_REIMBURSEMENT), moduleId.toString()),\n\n\t\t\t'journal entries': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_JOURNAL_ENTRY), moduleId.toString()),\n\n\t\t\t'payment entries': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_PAYMENT_ENTRY), moduleId.toString()),\n\n\t\t\t'purchase invoice': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_PURCHASE_INVOICE), moduleId.toString()),\n\n\t\t\t'stock transfer': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorInventory(PathnameInventory.VIEW_STOCK_TRANSFER), moduleId.toString()),\n\n\t\t\t'bills of materials': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorManufacuring(PathnameManufacturing.VIEW_BILL_OF_MATERIAL), moduleId.toString()),\n\n\t\t\t'purchase agreement': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorPurchase(PathnamePurchase.VIEW_PURCHASE_AGREEMENT), moduleId.toString()),\n\n\t\t\t'purchase orders': () =>\n\t\t\tgenerateRouteWithId(notificationData?.data?.is_rental == 1 ? RENTALROUTES.VIEW : PathnameGeneratorPurchase(PathnamePurchase.VIEW_PURCHASE_ORDER) , moduleId.toString()),\n\n\t\t\t'purchase request': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorPurchase(PathnamePurchase.VIEW_PURCHASE_ORDER), moduleId.toString()),\n\n\t\t\t'vra': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorPurchase(PathnamePurchase.VIEW_VENDOR_RETURNS), moduleId.toString()),\n\n\t\t\t'sl customer returns': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorCrm(PathnameCrm.VIEW_CUSTOMER_RETURNS), moduleId.toString()),\n\n\t\t\t'sales order': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorCrm(PathnameCrm.VIEW_SALES_ORDER), moduleId.toString()),\n\n\t\t\t'rental order': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorRental(PathnameRental.VIEW_RENTAL_ORDER), moduleId.toString()),\n\n\t\t\t'replacement order': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorRental(PathnameRental.VIEW_RENTAL_ORDER), moduleId.toString()),\n\n\t\t\t'rental agreement': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorRental(PathnameRental.VIEW_AGREEMENT), moduleId.toString()),\n\n\t\t\t'cross hire order': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorRental(PathnameRental.VIEW_CROSS_HIRE_ORDER), moduleId.toString()),\n\n\t\t\t'cross hire request': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorRental(PathnameRental.VIEW_CROSS_HIRE_REQUEST), moduleId.toString()),\n\t\t};\n\n\t\treturn routeMap[key]?.() || '/dashboard';\n\t};\n\n\n\t// const initAuth = async () => {\n\t// \tconst storedToken = window.localStorage.getItem(auth.storageTokenKeyName);\n\t// \tconst storedUser: ERPUser =\n\t// \t\tisJsonParse(window.localStorage.getItem(auth.storageUserKeyName)) || null;\n\t// \tif (storedToken && storedUser) {\n\t// \t\ttry {\n\t// \t\t\tconst userData = await getV1UserId({\n\t// \t\t\t\t'x-token': storedToken,\n\t// \t\t\t\tid: String(storedUser.id)\n\t// \t\t\t});\n\t// \t\t} catch (error) {\n\t// \t\t}\n\t// \t} else {\n\t// \t\tsetLoading(false);\n\t// \t}\n\t// \tif (storedToken && storedUser) {\n\t// \t\tsetUser(storedUser);\n\t// setLoading(false);\n\t// \t} else {\n\t// \t\thandleLogout();\n\t// setLoading(false);\n\t// \t}\n\t// };\n\n\t// useEffect(() => {\n\t// setLoading(true)\n\t// \tinitAuth();\n\t// \tconst storedToken = window.localStorage.getItem(auth.storageTokenKeyName);\n\t// \tif (!storedToken) {\n\t// \t\tsetUser(null);\n\t// \t} else {\n\t// \t\tsetLoading(false);\n\t// \t}\n\t// \teslint-disable-next-line react-hooks/exhaustive-deps\n\t// }, [location.pathname]);\n\n\t// useEffect(() => {\n\t// \tsetLoading(true);\n\t// \tinitAuth();\n\t// \tconst storedToken = window.localStorage.getItem(auth.storageTokenKeyName);\n\t// \tif (!storedToken) {\n\t// \t\tsetLoading(false);\n\t// \t\tnavigate(Pathname.LOGIN);\n\t// \t}\n\t// \t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t// }, []);\n\n\tuseEffect(() => {\n\t\tsetLoading(true);\n\t\t// initAuth()\n\t\tconst storedToken = window.localStorage.getItem(auth.storageTokenKeyName);\n\t\tconst storedUser =\n\t\t\tisJsonParse(window.localStorage.getItem(auth.storageUserKeyName)) ?? null;\n\t\tconst publicRoutes = [Pathname.LOGIN, Pathname.FORGOT_PASSWORD, Pathname.RESET_PASSWORD, Pathname.CHANGE_PASSWORD];\n\t\tconst currentPath = window.location.pathname;\n\t\tif (!storedToken && !storedUser) {\n\t\t\tif (!publicRoutes.includes(currentPath)) {\n\t\t\t\tnavigate(Pathname.LOGIN);\n\t\t\t}\n\t\t\tsetLoading(false);\n\t\t} else {\n\t\t\tsetUser(storedUser);\n\t\t\tsetAuthToken(storedToken || '');\n\t\t\tsetLoading(false);\n\t\t}\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, []);\n\n\tuseEffect(() => {\n\t\tif (!authToken) {\n\t\t\tif (socketRef.current) {\n\t\t\t\tsocketRef.current?.disconnect();\n\t\t\t\tsocketRef.current = null\n\t\t\t}\n\t\t\tconsole.warn(\"No auth token found, not connecting to socket.\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst socket = io(import.meta.env.VITE_SOCKET_BASE_URL, {\n\t\t\ttransports: [\"websocket\"],\n\t\t\tauth: { token: authToken },\n\t\t\tpath: \"/socket.io/\",\n\t\t\t\n\t\t});\n\t\tsocketRef.current = socket;\n\n\t\tsocket.on(\"connect\", () => {\n\t\t\tconsole.log(\"Socket connected:\", socket.id);\n\t\t\tsocket.onAny((event, ...args) => {\n\t\t\t\tconsole.log(`Received event: ${event}`, args);\n\t\t\t});\n\t\t});\n\t\t\n\t\t// socket event handler\n\t\tsocket.on('notification', (data) => {\n\t\tconst { message, notificationData } = data || {};\n\t\tlet notificationContent: React.ReactNode = message;\n\t\tconst url = getNotificationUrl(data);\n\n\t\tif (notificationData) {\n\t\t\tconst { notification_type } = notificationData;\n\n\t\t\tswitch (notification_type) {\n\t\t\t\tcase 'addApprovers': {\n\t\t\t\t\t\n\t\t\t\t\tnotificationContent = message;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcase 'change_approval_status': {\n\t\t\t\t\tnotificationContent = message;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tdefault: {\n\t\t\t\t\tnotificationContent = message;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tenqueueSnackbar(String(message), {\n\t\t\tvariant: 'default',\n\t\t\tanchorOrigin: { vertical: 'top', horizontal: 'center' },\n\t\t\tautoHideDuration: 5000,\n\t\t\tcontent: (key) => (\n\t\t\t<CustomSnackbar snackbarKey={key} message={notificationContent} data={notificationData} variant=\"default\" linkUrl={url}/>\n\t\t\t),\n\t\t});\n\t\t});\n\n\n\t\tsocket.on(\"sales_invoice_viewed\", (data) => {\n\t\t\tconsole.log(\"Invoice viewed:\", data.invoiceId, \"by user:\", data.userId);\n\t\t});\n\n\t\tsocket.on(\"error\", (errMsg) => {\n\t\t\tenqueueSnackbar(`Socket error: ${errMsg}`, { variant: \"error\" });\n\t\t\tconsole.error(\"Socket error:\", errMsg);\n\t\t});\n\n\t\t// Clean up on unmount\n\t\treturn () => {\n\t\t\tif (socketRef.current) {\n\t\t\t\tsocketRef.current.disconnect();\n\t\t\t\tsocketRef.current = null\n\t\t\t}\n\t\t};\n\t}, [authToken]);\n\n\tconst handleLogin = async (\n\t\tparams: LoginFormValues,\n\t\tcallback: (err: string) => void\n\t) => {\n\t\tsetLoading(true);\n\t\tconst storedToken = window.localStorage.getItem(auth.storageTokenKeyName);\n\t\tif (storedToken && user) {\n\t\t\treturn navigate(Pathname.DASHBOARD);\n\t\t}\n\n\t\ttry {\n\t\t\tconst loginUser = await postV1AuthLogin({ ...params, ...getToken() });\n\t\t\tif (loginUser.success) {\n\t\t\t\tconst data: ERPApiUser | null = loginUser?.data?.login || null;\n\t\t\t\tif (data) {\n\t\t\t\t\twindow.localStorage.setItem(auth.storageTokenKeyName, data.token);\n\t\t\t\t\tconst userData: ERPUser = {\n\t\t\t\t\t\t...data,\n\t\t\t\t\t\tfull_name: `${data.first_name} ${data.last_name}`\n\t\t\t\t\t};\n\t\t\t\t\twindow.localStorage.setItem(\n\t\t\t\t\t\tauth.storageUserKeyName,\n\t\t\t\t\t\tJSON.stringify(userData)\n\t\t\t\t\t);\n\t\t\t\t\tsetUser(userData);\n\t\t\t\t\tsetAuthToken(data.token);\n\t\t\t\t\tnavigate(Pathname.DASHBOARD);\n\t\t\t\t\tsetLoading(false);\n\t\t\t\t\tdelete data.token;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t}\n\n\t\t\tcallback(message);\n\t\t}\n\t};\n\n\tconst handleLogout = async () => {\n\t\twindow.localStorage.removeItem(auth.storageTokenKeyName);\n\t\twindow.localStorage.removeItem(auth.storageUserKeyName);\n\t\twindow.localStorage.removeItem(auth.storageAccessKeyName);\n\t\tsetUser(null);\n\t\tsetAuthToken('');\n\t\tnavigate(Pathname.LOGIN);\n\t};\n\n\tconst handleForgotPassword = async (params: resetFormValues,\n\t\tcallback: (type: boolean, err: string) => void) => {\n\t\ttry {\n\t\t\tawait postV1AuthForgotPassword({ ...params, ...getToken() });\n\t\t\tcallback(true, \"Reset Link sent to your email\");\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t}\n\n\t\t\tcallback(false, message);\n\t\t}\n\t};\n\n\tconst handleResetPassword = async (params: resetPasswordValues,\n\t\tcallback: (err: string) => void) => {\n\t\ttry {\n\t\t\tconst response = await postV1AuthResetPassword({ ...params, ...getToken() });\n\t\t\tcallback(response);\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tconsole.log(\"Error \", error)\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t\tcallback(message);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst handleChangePassword = async (params: resetPasswordValues,\n\t\tcallback: (err: string) => void) => {\n\t\ttry {\n\t\t\tawait postV1AuthChangePassword({ ...params, ...getToken() });\n\t\t\tcallback(null);\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tconsole.log(\"Error \", error)\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t\tcallback(message);\n\t\t\t}\n\t\t}\n\t\tcallback(\"reset\");\n\t}\n\n\tconst handleChangeUserPassword = async (params: resetPasswordValues,\n\t\tcallback: (err: string, resType: boolean) => void) => {\n\t\ttry {\n\t\t\tawait postV1AuthChangeUserPassword({ ...params, ...getToken() });\n\t\t\tcallback('Password Changed Successfully', true);\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t\tcallback(message, false);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst handleChangeUserPasswordByAdmin = async (params: changePasswordValues,\n\t\tcallback: (err: string, resType: boolean) => void) => {\n\t\ttry {\n\t\t\tawait postV1AuthChangeUserPasswordByAdmin({ ...params, ...getToken() });\n\t\t\tcallback('Password Changed Successfully', true);\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t\tcallback(message, false);\n\t\t\t}\n\t\t}\n\t}\n\n\n\tconst values = {\n\t\tuser,\n\t\tauthToken,\n\t\tloading,\n\t\tsetUser,\n\t\tsetLoading,\n\t\tlogin: handleLogin,\n\t\tlogout: handleLogout,\n\t\tforgotPassword: handleForgotPassword,\n\t\tresetPassword: handleResetPassword,\n\t\tchangePassword: handleChangePassword,\n\t\tchangeUserPassword: handleChangeUserPassword,\n\t\tchangeUserPasswordByAdmin: handleChangeUserPasswordByAdmin\n\t};\n\n\treturn <AuthContext.Provider value={values}>{children}</AuthContext.Provider>;\n};\n\nexport { AuthContext, AuthProvider };\n"],"names":["defaultProvider","user","loading","authToken","setUser","setLoading","Boolean","login","Promise","resolve","logout","forgotPassword","resetPassword","changePassword","changeUserPassword","AuthContext","createContext","setBaseUrl","children","useState","setAuthToken","socketRef","useRef","navigate","useNavigate","isJsonParse","string","JSON","parse","error","useEffect","storedToken","window","localStorage","getItem","auth","storageTokenKeyName","storedUser","storageUserKeyName","publicRoutes","Pathname","LOGIN","FORGOT_PASSWORD","RESET_PASSWORD","CHANGE_PASSWORD","currentPath","location","pathname","includes","current","_a","disconnect","socket","io","transports","token","path","on","onAny","event","args","data","message","notificationData","notificationContent","url","moduleName","moduleId","routeMap","generateRouteWithId","PathnameGenerator","PathnameAccounting","VIEW_SALES_INVOICES","toString","VIEW_ASSET_TRANSFER","budgets","VIEW_BUDGET","VIEW_CASH_EXPENSE","VIEW_CREDIT_NOTE","VIEW_DEBIT_NOTE","VIEW_EXPENSE_REIMBURSEMENT","VIEW_JOURNAL_ENTRY","VIEW_PAYMENT_ENTRY","VIEW_PURCHASE_INVOICE","PathnameGeneratorInventory","PathnameInventory","VIEW_STOCK_TRANSFER","PathnameGeneratorManufacuring","PathnameManufacturing","VIEW_BILL_OF_MATERIAL","PathnameGeneratorPurchase","PathnamePurchase","VIEW_PURCHASE_AGREEMENT","is_rental","RENTALROUTES","VIEW","VIEW_PURCHASE_ORDER","vra","VIEW_VENDOR_RETURNS","PathnameGeneratorCrm","PathnameCrm","VIEW_CUSTOMER_RETURNS","VIEW_SALES_ORDER","PathnameGeneratorRental","PathnameRental","VIEW_RENTAL_ORDER","VIEW_AGREEMENT","VIEW_CROSS_HIRE_ORDER","VIEW_CROSS_HIRE_REQUEST","toLowerCase","call","getNotificationUrl","notification_type","enqueueSnackbar","String","variant","anchorOrigin","vertical","horizontal","autoHideDuration","content","key","jsx","CustomSnackbar","snackbarKey","linkUrl","errMsg","values","async","params","callback","DASHBOARD","loginUser","postV1AuthLogin","getToken","success","setItem","userData","full_name","first_name","last_name","stringify","Error","removeItem","storageAccessKeyName","postV1AuthForgotPassword","postV1AuthResetPassword","postV1AuthChangePassword","postV1AuthChangeUserPassword","changeUserPasswordByAdmin","postV1AuthChangeUserPasswordByAdmin","Provider","value"],"mappings":"67BAsIA,MAAMA,EAAwC,CAC7CC,KAAM,KACNC,SAAS,EACTC,UAAW,GACXC,QAAS,IAAM,KACfC,WAAY,IAAMC,QAClBC,MAAO,IAAMC,QAAQC,UACrBC,OAAQ,IAAMF,QAAQC,UACtBE,eAAgB,IAAMH,QAAQC,UAC9BG,cAAe,IAAMJ,QAAQC,UAC7BI,eAAgB,IAAML,QAAQC,UAC9BK,mBAAoB,IAAMN,QAAQC,WAG7BM,EAAcC,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EAAMiC,SAASA,SAAWjC,EAAMiC,QACtDoE,EAASpE,GAAS,GAEpB;AAmBD,aAAQ/C,EAAYwI,SAAZ,CAAqBC,MAAOzB,EAAS7G"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../src/contexts/AuthContext.tsx"],"sourcesContent":["import React, { createContext, useEffect, useRef, useState } from 'react';\nimport {\n\tpostV1AuthChangePassword,\n\tpostV1AuthForgotPassword,\n\tpostV1AuthChangeUserPassword,\n\t// getV1UserId,\n\tpostV1AuthLogin,\n\tpostV1AuthResetPassword,\n\tsetBaseUrl,\n\tpostV1AuthChangeUserPasswordByAdmin\n} from '../api-client/api.rbac/api';\nimport { auth } from '../constants/auth';\nimport { /* useLocation, */ useNavigate } from 'react-router-dom';\nimport { Pathname } from '../constants/pathnames/pathname'; // Removed - should be passed as props or configured by consuming app\nimport { getToken } from '../utils/common';\nimport { enqueueSnackbar } from 'notistack';\nimport { Socket, io } from 'socket.io-client';\nimport { generateRouteWithId } from '../utils/route-utils';\nimport {\n\tPathnameAccounting,\n\tPathnameGenerator\n} from '../constants/pathnames/pathname.accounting';\n\nimport {\n\tPathnameInventory,\n\tPathnameGenerator as PathnameGeneratorInventory\n} from '../constants/pathnames/pathname.inventory';\n\nimport {\n\tPathnameManufacturing,\n\tPathnameGenerator as PathnameGeneratorManufacuring\n} from '../constants/pathnames/pathname.manufacturing';\n\nimport {\n\tPathnamePurchase,\n\tPathnameGenerator as PathnameGeneratorPurchase\n} from '../constants/pathnames/pathname.procurement';\n\nimport {\n\tPathnameCrm,\n\tPathnameGenerator as PathnameGeneratorCrm\n} from '../constants/pathnames/pathname.crm';\n\nimport {\n\tPathnameRental,\n\tPathnameGenerator as PathnameGeneratorRental\n} from '../constants/pathnames/pathname.rental';\n\nimport { ROUTES as RENTALROUTES } from '../constants/pathnames/pathname.rental';\n\nimport CustomSnackbar from '../components/custom-snackbar/custom-snackbar.tsx';\nexport interface LoginFormValues {\n\temail: string;\n\tpassword: string;\n}\n\nexport interface resetFormValues {\n\temail: string;\n}\n\nexport interface resetPasswordValues {\n\ttoken: string;\n}\n\nexport interface changePasswordValues {\n\tpassword: string;\n}\n\nexport interface changeUserPasswordValues {\n\tpassword: string;\n}\n\ninterface ERPApiUser {\n\tid: string | number;\n\tfirst_name: string;\n\tlast_name: string;\n\tmiddle_name: string;\n\tcountry_code: string;\n\temail: string;\n\tcreated_by: any;\n\tupdated_by: any;\n\tcreated_at: string;\n\tupdated_at: string;\n\trole_id: string;\n\tdepartment_id: number;\n\tis_deleted: number;\n\tdeleted_at: string | null;\n\tdeleted_by: any;\n\ttoken: string;\n\tprofile_image: string;\n\tcurrency_data?: {\n\t\tid: number;\n\t\tsymbol: string;\n\t\tcurrency_name: string;\n\t\tnumber_format:string;\n\t\tposition: string | null;\n\t\tfraction_unit: string | null\n\t};\n\taccessCompanies?: any[]\n}\ninterface ERPUser extends Omit<ERPApiUser, 'token'> {\n\tfull_name: string;\n\tcompany_id: string;\n}\n\ninterface DefaultProviderProps {\n\tuser: ERPUser | null;\n\tloading: boolean;\n\tauthToken: string;\n\tsetUser: React.Dispatch<React.SetStateAction<ERPUser | null>>;\n\tsetLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\tlogin: (\n\t\tparams: LoginFormValues,\n\t\tcallback: (err: string) => void\n\t) => Promise<void>;\n\tlogout: () => Promise<void>;\n\tforgotPassword: (\n\t\tparams: resetFormValues,\n\t\tcallback: (err: string) => void\n\t) => Promise<void>;\n\tresetPassword: (\n\t\tparams: resetPasswordValues,\n\t\tcallback: (err: string) => void\n\t) => Promise<void>;\n\tchangePassword: (\n\t\tparams: changePasswordValues,\n\t\tcallback: (err: string) => void\n\t) => Promise<void>;\n\tchangeUserPassword: (\n\t\tparams: changeUserPasswordValues,\n\t\tcallback: (err: string) => void\n\t) => Promise<void>;\n}\n\nconst defaultProvider: DefaultProviderProps = {\n\tuser: null,\n\tloading: true,\n\tauthToken: '',\n\tsetUser: () => null,\n\tsetLoading: () => Boolean,\n\tlogin: () => Promise.resolve(),\n\tlogout: () => Promise.resolve(),\n\tforgotPassword: () => Promise.resolve(),\n\tresetPassword: () => Promise.resolve(),\n\tchangePassword: () => Promise.resolve(),\n\tchangeUserPassword: () => Promise.resolve()\n};\n\nconst AuthContext = createContext(defaultProvider);\n\ninterface AuthProviderProps {\n\tchildren: React.ReactNode;\n}\n\nsetBaseUrl(`${import.meta.env.VITE_BACKEND_BASE_URL}/rbac`);\n\nconst AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {\n\t// ** States\n\tconst [user, setUser] = useState(defaultProvider.user);\n\tconst [authToken, setAuthToken] = useState<string>('');\n\tconst [loading, setLoading] = useState(defaultProvider.loading);\n\tconst socketRef = useRef<Socket | null>(null);\n\n\t// ** Hooks\n\tconst navigate = useNavigate();\n\t// const location = useLocation();\n\tconst isJsonParse = (string?: string | null) => {\n\t\tif (!string) return false;\n\n\t\ttry {\n\t\t\treturn JSON.parse(string);\n\t\t} catch (error) {\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tconst getNotificationUrl = (data: any) => {\n\t\tconst { moduleName = '', moduleId = '', notificationData = {} } = data;\n\t\tconst key = moduleName.toLowerCase();\n\n\t\tconst routeMap: Record<string, () => string> = {\n\t\t\t'sales invoice': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_SALES_INVOICES), moduleId.toString()),\n\n\t\t\t'asset transfers': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_ASSET_TRANSFER), moduleId.toString()),\n\n\t\t\t'budgets': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_BUDGET), moduleId.toString()),\n\n\t\t\t'cash expense': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_CASH_EXPENSE), moduleId.toString()),\n\n\t\t\t'credit notes': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_CREDIT_NOTE), moduleId.toString()),\n\n\t\t\t'debit notes': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_DEBIT_NOTE), moduleId.toString()),\n\n\t\t\t'expense reimbursement': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_EXPENSE_REIMBURSEMENT), moduleId.toString()),\n\n\t\t\t'journal entries': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_JOURNAL_ENTRY), moduleId.toString()),\n\n\t\t\t'payment entries': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_PAYMENT_ENTRY), moduleId.toString()),\n\n\t\t\t'purchase invoice': () =>\n\t\t\tgenerateRouteWithId(PathnameGenerator(PathnameAccounting.VIEW_PURCHASE_INVOICE), moduleId.toString()),\n\n\t\t\t'stock transfer': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorInventory(PathnameInventory.VIEW_STOCK_TRANSFER), moduleId.toString()),\n\n\t\t\t'bills of materials': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorManufacuring(PathnameManufacturing.VIEW_BILL_OF_MATERIAL), moduleId.toString()),\n\n\t\t\t'purchase agreement': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorPurchase(PathnamePurchase.VIEW_PURCHASE_AGREEMENT), moduleId.toString()),\n\n\t\t\t'purchase orders': () =>\n\t\t\tgenerateRouteWithId(notificationData?.data?.is_rental == 1 ? RENTALROUTES.VIEW : PathnameGeneratorPurchase(PathnamePurchase.VIEW_PURCHASE_ORDER) , moduleId.toString()),\n\n\t\t\t'purchase request': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorPurchase(PathnamePurchase.VIEW_PURCHASE_ORDER), moduleId.toString()),\n\n\t\t\t'vra': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorPurchase(PathnamePurchase.VIEW_VENDOR_RETURNS), moduleId.toString()),\n\n\t\t\t'sl customer returns': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorCrm(PathnameCrm.VIEW_CUSTOMER_RETURNS), moduleId.toString()),\n\n\t\t\t'sales order': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorCrm(PathnameCrm.VIEW_SALES_ORDER), moduleId.toString()),\n\n\t\t\t'rental order': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorRental(PathnameRental.VIEW_RENTAL_ORDER), moduleId.toString()),\n\n\t\t\t'replacement order': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorRental(PathnameRental.VIEW_RENTAL_ORDER), moduleId.toString()),\n\n\t\t\t'rental agreement': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorRental(PathnameRental.VIEW_AGREEMENT), moduleId.toString()),\n\n\t\t\t'cross hire order': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorRental(PathnameRental.VIEW_CROSS_HIRE_ORDER), moduleId.toString()),\n\n\t\t\t'cross hire request': () =>\n\t\t\tgenerateRouteWithId(PathnameGeneratorRental(PathnameRental.VIEW_CROSS_HIRE_REQUEST), moduleId.toString()),\n\t\t};\n\n\t\treturn routeMap[key]?.() || '/dashboard';\n\t};\n\n\n\t// const initAuth = async () => {\n\t// \tconst storedToken = window.localStorage.getItem(auth.storageTokenKeyName);\n\t// \tconst storedUser: ERPUser =\n\t// \t\tisJsonParse(window.localStorage.getItem(auth.storageUserKeyName)) || null;\n\t// \tif (storedToken && storedUser) {\n\t// \t\ttry {\n\t// \t\t\tconst userData = await getV1UserId({\n\t// \t\t\t\t'x-token': storedToken,\n\t// \t\t\t\tid: String(storedUser.id)\n\t// \t\t\t});\n\t// \t\t} catch (error) {\n\t// \t\t}\n\t// \t} else {\n\t// \t\tsetLoading(false);\n\t// \t}\n\t// \tif (storedToken && storedUser) {\n\t// \t\tsetUser(storedUser);\n\t// setLoading(false);\n\t// \t} else {\n\t// \t\thandleLogout();\n\t// setLoading(false);\n\t// \t}\n\t// };\n\n\t// useEffect(() => {\n\t// setLoading(true)\n\t// \tinitAuth();\n\t// \tconst storedToken = window.localStorage.getItem(auth.storageTokenKeyName);\n\t// \tif (!storedToken) {\n\t// \t\tsetUser(null);\n\t// \t} else {\n\t// \t\tsetLoading(false);\n\t// \t}\n\t// \teslint-disable-next-line react-hooks/exhaustive-deps\n\t// }, [location.pathname]);\n\n\t// useEffect(() => {\n\t// \tsetLoading(true);\n\t// \tinitAuth();\n\t// \tconst storedToken = window.localStorage.getItem(auth.storageTokenKeyName);\n\t// \tif (!storedToken) {\n\t// \t\tsetLoading(false);\n\t// \t\tnavigate(Pathname.LOGIN);\n\t// \t}\n\t// \t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t// }, []);\n\n\tuseEffect(() => {\n\t\tsetLoading(true);\n\t\t// initAuth()\n\t\tconst storedToken = window.localStorage.getItem(auth.storageTokenKeyName);\n\t\tconst storedUser =\n\t\t\tisJsonParse(window.localStorage.getItem(auth.storageUserKeyName)) ?? null;\n\t\tconst publicRoutes = [Pathname.LOGIN, Pathname.FORGOT_PASSWORD, Pathname.RESET_PASSWORD, Pathname.CHANGE_PASSWORD];\n\t\tconst currentPath = window.location.pathname;\n\t\tif (!storedToken && !storedUser) {\n\t\t\tif (!publicRoutes.includes(currentPath)) {\n\t\t\t\tnavigate(Pathname.LOGIN);\n\t\t\t}\n\t\t\tsetLoading(false);\n\t\t} else {\n\t\t\tsetUser(storedUser);\n\t\t\tsetAuthToken(storedToken || '');\n\t\t\tsetLoading(false);\n\t\t}\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, []);\n\n\tuseEffect(() => {\n\t\tif (!authToken) {\n\t\t\tif (socketRef.current) {\n\t\t\t\tsocketRef.current?.disconnect();\n\t\t\t\tsocketRef.current = null\n\t\t\t}\n\t\t\tconsole.warn(\"No auth token found, not connecting to socket.\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst socket = io(import.meta.env.VITE_SOCKET_BASE_URL, {\n\t\t\ttransports: [\"websocket\"],\n\t\t\tauth: { token: authToken },\n\t\t\tpath: \"/socket.io/\",\n\t\t\t\n\t\t});\n\t\tsocketRef.current = socket;\n\n\t\tsocket.on(\"connect\", () => {\n\t\t\tconsole.log(\"Socket connected:\", socket.id);\n\t\t\tsocket.onAny((event, ...args) => {\n\t\t\t\tconsole.log(`Received event: ${event}`, args);\n\t\t\t});\n\t\t});\n\t\t\n\t\t// socket event handler\n\t\tsocket.on('notification', (data) => {\n\t\tconst { message, notificationData } = data || {};\n\t\tlet notificationContent: React.ReactNode = message;\n\t\tconst url = getNotificationUrl(data);\n\n\t\tif (notificationData) {\n\t\t\tconst { notification_type } = notificationData;\n\n\t\t\tswitch (notification_type) {\n\t\t\t\tcase 'addApprovers': {\n\t\t\t\t\t\n\t\t\t\t\tnotificationContent = message;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcase 'change_approval_status': {\n\t\t\t\t\tnotificationContent = message;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tdefault: {\n\t\t\t\t\tnotificationContent = message;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tenqueueSnackbar(String(message), {\n\t\t\tvariant: 'default',\n\t\t\tanchorOrigin: { vertical: 'top', horizontal: 'center' },\n\t\t\tautoHideDuration: 5000,\n\t\t\tcontent: (key) => (\n\t\t\t<CustomSnackbar snackbarKey={key} message={notificationContent} data={notificationData} variant=\"default\" linkUrl={url}/>\n\t\t\t),\n\t\t});\n\t\t});\n\n\n\t\tsocket.on(\"sales_invoice_viewed\", (data) => {\n\t\t\tconsole.log(\"Invoice viewed:\", data.invoiceId, \"by user:\", data.userId);\n\t\t});\n\n\t\tsocket.on(\"error\", (errMsg) => {\n\t\t\tenqueueSnackbar(`Socket error: ${errMsg}`, { variant: \"error\" });\n\t\t\tconsole.error(\"Socket error:\", errMsg);\n\t\t});\n\n\t\t// Clean up on unmount\n\t\treturn () => {\n\t\t\tif (socketRef.current) {\n\t\t\t\tsocketRef.current.disconnect();\n\t\t\t\tsocketRef.current = null\n\t\t\t}\n\t\t};\n\t}, [authToken]);\n\n\tconst handleLogin = async (\n\t\tparams: LoginFormValues,\n\t\tcallback: (err: string) => void\n\t) => {\n\t\tsetLoading(true);\n\t\tconst storedToken = window.localStorage.getItem(auth.storageTokenKeyName);\n\t\tif (storedToken && user) {\n\t\t\treturn navigate(Pathname.DASHBOARD);\n\t\t}\n\n\t\ttry {\n\t\t\tconst loginUser = await postV1AuthLogin({ ...params, ...getToken() });\n\t\t\tif (loginUser.success) {\n\t\t\t\tconst data: ERPApiUser | null = loginUser?.data?.login || null;\n\t\t\t\tif (data) {\n\t\t\t\t\twindow.localStorage.setItem(auth.storageTokenKeyName, data.token);\n\t\t\t\t\tconst userData: ERPUser = {\n\t\t\t\t\t\t...data,\n\t\t\t\t\t\tfull_name: `${data.first_name} ${data.last_name}`\n\t\t\t\t\t};\n\t\t\t\t\twindow.localStorage.setItem(\n\t\t\t\t\t\tauth.storageUserKeyName,\n\t\t\t\t\t\tJSON.stringify(userData)\n\t\t\t\t\t);\n\t\t\t\t\tsetUser(userData);\n\t\t\t\t\tsetAuthToken(data.token);\n\t\t\t\t\tnavigate(Pathname.DASHBOARD);\n\t\t\t\t\tsetLoading(false);\n\t\t\t\t\tdelete data.token;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t}\n\n\t\t\tcallback(message);\n\t\t}\n\t};\n\n\tconst handleLogout = async () => {\n\t\twindow.localStorage.removeItem(auth.storageTokenKeyName);\n\t\twindow.localStorage.removeItem(auth.storageUserKeyName);\n\t\twindow.localStorage.removeItem(auth.storageAccessKeyName);\n\t\tsetUser(null);\n\t\tsetAuthToken('');\n\t\tnavigate(Pathname.LOGIN);\n\t};\n\n\tconst handleForgotPassword = async (params: resetFormValues,\n\t\tcallback: (type: boolean, err: string) => void) => {\n\t\ttry {\n\t\t\tawait postV1AuthForgotPassword({ ...params, ...getToken() });\n\t\t\tcallback(true, \"Reset Link sent to your email\");\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t}\n\n\t\t\tcallback(false, message);\n\t\t}\n\t};\n\n\tconst handleResetPassword = async (params: resetPasswordValues,\n\t\tcallback: (err: string) => void) => {\n\t\ttry {\n\t\t\tconst response = await postV1AuthResetPassword({ ...params, ...getToken() });\n\t\t\tcallback(response);\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tconsole.log(\"Error \", error)\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t\tcallback(message);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst handleChangePassword = async (params: resetPasswordValues,\n\t\tcallback: (err: string) => void) => {\n\t\ttry {\n\t\t\tawait postV1AuthChangePassword({ ...params, ...getToken() });\n\t\t\tcallback(null);\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tconsole.log(\"Error \", error)\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t\tcallback(message);\n\t\t\t}\n\t\t}\n\t\tcallback(\"reset\");\n\t}\n\n\tconst handleChangeUserPassword = async (params: resetPasswordValues,\n\t\tcallback: (err: string, resType: boolean) => void) => {\n\t\ttry {\n\t\t\tawait postV1AuthChangeUserPassword({ ...params, ...getToken() });\n\t\t\tcallback('Password Changed Successfully', true);\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t\tcallback(message, false);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst handleChangeUserPasswordByAdmin = async (params: changePasswordValues,\n\t\tcallback: (err: string, resType: boolean) => void) => {\n\t\ttry {\n\t\t\tawait postV1AuthChangeUserPasswordByAdmin({ ...params, ...getToken() });\n\t\t\tcallback('Password Changed Successfully', true);\n\t\t} catch (error) {\n\t\t\tlet message: string = 'Something went wrong';\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessage = isJsonParse(error.message).message || error.message;\n\t\t\t\tcallback(message, false);\n\t\t\t}\n\t\t}\n\t}\n\n\n\tconst values = {\n\t\tuser,\n\t\tauthToken,\n\t\tloading,\n\t\tsetUser,\n\t\tsetLoading,\n\t\tlogin: handleLogin,\n\t\tlogout: handleLogout,\n\t\tforgotPassword: handleForgotPassword,\n\t\tresetPassword: handleResetPassword,\n\t\tchangePassword: handleChangePassword,\n\t\tchangeUserPassword: handleChangeUserPassword,\n\t\tchangeUserPasswordByAdmin: handleChangeUserPasswordByAdmin\n\t};\n\n\treturn <AuthContext.Provider value={values}>{children}</AuthContext.Provider>;\n};\n\nexport { AuthContext, AuthProvider };\n"],"names":["defaultProvider","user","loading","authToken","setUser","setLoading","Boolean","login","Promise","resolve","logout","forgotPassword","resetPassword","changePassword","changeUserPassword","AuthContext","createContext","setBaseUrl","children","useState","setAuthToken","socketRef","useRef","navigate","useNavigate","isJsonParse","string","JSON","parse","error","useEffect","storedToken","window","localStorage","getItem","auth","storageTokenKeyName","storedUser","storageUserKeyName","publicRoutes","Pathname","LOGIN","FORGOT_PASSWORD","RESET_PASSWORD","CHANGE_PASSWORD","currentPath","location","pathname","includes","current","_a","disconnect","socket","io","transports","token","path","on","onAny","event","args","data","message","notificationData","notificationContent","url","moduleName","moduleId","routeMap","generateRouteWithId","PathnameGenerator","PathnameAccounting","VIEW_SALES_INVOICES","toString","VIEW_ASSET_TRANSFER","budgets","VIEW_BUDGET","VIEW_CASH_EXPENSE","VIEW_CREDIT_NOTE","VIEW_DEBIT_NOTE","VIEW_EXPENSE_REIMBURSEMENT","VIEW_JOURNAL_ENTRY","VIEW_PAYMENT_ENTRY","VIEW_PURCHASE_INVOICE","PathnameGeneratorInventory","PathnameInventory","VIEW_STOCK_TRANSFER","PathnameGeneratorManufacuring","PathnameManufacturing","VIEW_BILL_OF_MATERIAL","PathnameGeneratorPurchase","PathnamePurchase","VIEW_PURCHASE_AGREEMENT","is_rental","RENTALROUTES","VIEW","VIEW_PURCHASE_ORDER","vra","VIEW_VENDOR_RETURNS","PathnameGeneratorCrm","PathnameCrm","VIEW_CUSTOMER_RETURNS","VIEW_SALES_ORDER","PathnameGeneratorRental","PathnameRental","VIEW_RENTAL_ORDER","VIEW_AGREEMENT","VIEW_CROSS_HIRE_ORDER","VIEW_CROSS_HIRE_REQUEST","toLowerCase","call","getNotificationUrl","notification_type","enqueueSnackbar","String","variant","anchorOrigin","vertical","horizontal","autoHideDuration","content","key","jsx","CustomSnackbar","snackbarKey","linkUrl","errMsg","values","async","params","callback","DASHBOARD","loginUser","postV1AuthLogin","getToken","success","setItem","userData","full_name","first_name","last_name","stringify","Error","removeItem","storageAccessKeyName","postV1AuthForgotPassword","postV1AuthResetPassword","postV1AuthChangePassword","postV1AuthChangeUserPassword","changeUserPasswordByAdmin","postV1AuthChangeUserPasswordByAdmin","Provider","value"],"mappings":"67BAsIA,MAAMA,EAAwC,CAC7CC,KAAM,KACNC,SAAS,EACTC,UAAW,GACXC,QAAS,IAAM,KACfC,WAAY,IAAMC,QAClBC,MAAO,IAAMC,QAAQC,UACrBC,OAAQ,IAAMF,QAAQC,UACtBE,eAAgB,IAAMH,QAAQC,UAC9BG,cAAe,IAAMJ,QAAQC,UAC7BI,eAAgB,IAAML,QAAQC,UAC9BK,mBAAoB,IAAMN,QAAQC,WAG7BM,EAAcC,EAAAA,cAAchB,GAMlCiB,EAAAA,WAAW,8EAEuC,EAAGC,eAEpD,MAAOjB,EAAMG,GAAWe,EAAAA,SAASnB,EAAgBC,OAC1CE,EAAWiB,GAAgBD,EAAAA,SAAiB,KAC5CjB,EAASG,GAAcc,EAAAA,SAASnB,EAAgBE,SACjDmB,EAAYC,EAAAA,OAAs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IiC,EAAkB,uBAClBjC,aAAiBiH,QACpBhF,EAAUrC,EAAYI,EAAMiC,SAASA,SAAWjC,EAAMiC,SAGvDoE,GAAS,EAAOpE,EACjB,GAwEAlD,cArE2BoH,MAAOC,EAClCC,KACA,IAECA,QADuBgB,0BAAwB,IAAKjB,KAAWK,EAAAA,aAEhE,OAASzG,GACR,IAAIiC,EAAkB,uBAElBjC,aAAiBiH,QACpBhF,EAAUrC,EAAYI,EAAMiC,SAASA,SAAWjC,EAAMiC,QACtDoE,EAASpE,GAEX,GA0DAjD,eAvD4BmH,MAAOC,EACnCC,KACA,UACOiB,EAAAA,yBAAyB,IAAKlB,KAAWK,EAAAA,aAC/CJ,EAAS,KACV,OAASrG,GACR,IAAIiC,EAAkB,uBAElBjC,aAAiBiH,QACpBhF,EAAUrC,EAAYI,EAAMiC,SAASA,SAAWjC,EAAMiC,QACtDoE,EAASpE,GAEX,CACAoE,EAAS,UA2CTpH,mBAxCgCkH,MAAOC,EACvCC,KACA,UACOkB,EAAAA,6BAA6B,IAAKnB,KAAWK,EAAAA,aACnDJ,EAAS,iCAAiC,EAC3C,OAASrG,GACR,IAAIiC,EAAkB,uBAClBjC,aAAiBiH,QACpBhF,EAAUrC,EAAYI,EAAMiC,SAASA,SAAWjC,EAAMiC,QACtDoE,EAASpE,GAAS,GAEpB,GA8BAuF,0BA3BuCrB,MAAOC,EAC9CC,KACA,UACOoB,EAAAA,oCAAoC,IAAKrB,KAAWK,EAAAA,aAC1DJ,EAAS,iCAAiC,EAC3C,OAASrG,GACR,IAAIiC,EAAkB,uBAClBjC,aAAiBiH,QACpBhF,EAAUrC,EAAYI,EAAMiC,SAASA,SAAWjC,EAAMiC,QACtDoE,EAASpE,GAAS,GAEpB;AAmBD,aAAQ/C,EAAYwI,SAAZ,CAAqBC,MAAOzB,EAAS7G"}
|
|
@@ -80,7 +80,7 @@ const LanguageProvider = ({ children }) => {
|
|
|
80
80
|
const [state, dispatch] = useReducer(languageReducer, initialState);
|
|
81
81
|
const { i18n } = useTranslation();
|
|
82
82
|
useEffect(() => {
|
|
83
|
-
setBaseUrl(`${"
|
|
83
|
+
setBaseUrl(`${"https://apidev.erpforce.co"}/rbac`);
|
|
84
84
|
}, []);
|
|
85
85
|
const safeChangeLanguage = async (langCode) => {
|
|
86
86
|
if (i18n && typeof i18n.changeLanguage === "function") {
|