pbn-voip-modules
Version:
PBN VOIP Component Library
275 lines (245 loc) • 7.72 kB
JavaScript
import axios from "axios";
import { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import shortUUID from "short-uuid";
import {
getJWTHeader,
getServerErrorMessage,
} from "../../general/common/utils";
import useBaseAPI from "../../general/hooks/useBaseAPI";
import useDispatchWarning from "../../general/hooks/useDispatchWarning";
import { useFetchPBNInfo } from "../../general/hooks/useFetchPBNInfo";
import useObjectState from "../../general/hooks/useObjectState";
import {
onSetListCallLog,
onUpdateCallLog,
onSetExtensions,
} from "../../redux-toolkit/call-logs";
import {
REACT_APP_BASE_MIDDLEWARE_URL,
REACT_APP_BASE_PBN_URL,
} from "../../general/common/constants";
import { convertLocalTimeZonetoUTC } from "../../general/common/utils";
import { filterExtensionBasedOnPracticeId } from "../common/utils/helper";
import { get } from "lodash";
import useCancelTokenManager from "../../general/hooks/useCancelTokenManager";
import { successTostify } from "../../general/components/tostify/Tostify";
const apiConfig = {
withCredentials: false,
timeout: 20000,
actions: {
GET: {
CALL_LOGS: {
url: REACT_APP_BASE_PBN_URL + "voip/api/phone-call-log",
onFetch: onSetListCallLog,
enableUIHandling: false,
},
EXTENSIONS: {
url: REACT_APP_BASE_MIDDLEWARE_URL + "v2/extensions",
onFetch: onSetExtensions,
enableUIHandling: false,
},
},
PUT: {
url: REACT_APP_BASE_MIDDLEWARE_URL + "update/call/logs",
onFetch: onUpdateCallLog,
enableUIHandling: true,
},
},
};
const useFetchCallLogs = () => {
const jwt = useSelector((state) => state.shared.jwt);
const { currentUser, isCurrentUserApiCalled } = useSelector(
(state) => state.user
);
const { callLogs, extensions } = useSelector((state) => state.callLogs);
const filterAPI = useSelector((state) => state.callLogs.filterAPI);
const [enableSelectPhone, setEnableSelectPhone] = useState(false);
const { organization_id, practice_id, fetchParams } = useFetchPBNInfo();
const [setCallLog] = useObjectState({
organization_id,
});
const dispactcher = useDispatch();
const { dispatchError } = useDispatchWarning();
const {
createCancelTokenSource: createCallLogsCancelToken,
cancelAllPreviousRequests: cancelAllCallLogsRequests,
} = useCancelTokenManager();
const {
createCancelTokenSource: createExtensionsCancelToken,
cancelAllPreviousRequests: cancelAllExtensionsRequests,
} = useCancelTokenManager();
const { fetchData, postData, updateData, deleteData, ...restParams } =
useBaseAPI(apiConfig);
// Cleanup on unmount - for both call logs and extensions requests
useEffect(() => {
return () => {
cancelAllCallLogsRequests();
cancelAllExtensionsRequests();
};
}, []);
const handleGetExtensions = async () => {
try {
// Create new cancel token specifically for extensions request
const { source, id } = createExtensionsCancelToken();
// Cancel all previous extension requests
cancelAllExtensionsRequests(id);
const extensions = await fetchData(
getJWTHeader(jwt.content),
{},
apiConfig.actions.GET.EXTENSIONS,
{ cancelToken: source.token }
);
return extensions;
} catch (error) {
if (axios.isCancel(error)) {
console.log("Extensions request canceled:", error.message);
return;
}
console.error("Error fetching extensions:", error);
}
};
const getExtensionNumberListHandler = async (params) => {
let updatedParams = {};
if (
(get(window, "user_is_super_admin", false) && currentUser === null) ||
get(
window,
"voip_current_user_permission.view_call_logs_for_all_extensions",
false
)
) {
const extensionResponse = await handleGetExtensions();
const filteredExtension = filterExtensionBasedOnPracticeId(
extensionResponse?.content || [],
practice_id,
currentUser
);
let extension_number = null;
if (currentUser && currentUser?.extension?.length) {
extension_number = currentUser?.extension[0]?.extension_number;
} else {
extension_number = filteredExtension[0].basic_settings.extension_number;
}
dispactcher(onSetExtensions({ content: filteredExtension }));
updatedParams = {
...params,
extension_number,
};
}
return updatedParams;
};
const handleGetCallLogs = async (params) => {
try {
if (!isCurrentUserApiCalled) {
return;
}
// Create new cancel token for call logs request
const { source, id } = createCallLogsCancelToken();
// Cancel all previous call logs requests
cancelAllCallLogsRequests(id);
console.log("STEP 1", params);
let updatedParams = params;
if (
extensions?.content?.length === 0 ||
(Array.isArray(extensions) && extensions.length === 0)
) {
const updatedParamsWithExtension = await getExtensionNumberListHandler(
params
);
updatedParams = {
...updatedParams,
...updatedParamsWithExtension,
};
}
let searchParams = {};
if (currentUser) {
searchParams = {
extension_number:
currentUser?.extension?.length > 0
? currentUser?.extension[0]?.extension_number
: "",
...fetchParams,
};
}
if (params) {
searchParams = {
...searchParams,
...updatedParams,
...fetchParams,
from_date: convertLocalTimeZonetoUTC(params.from_date, true),
to_date: convertLocalTimeZonetoUTC(params.to_date),
};
}
restParams.onSetLoading();
try {
const callLogs = await fetchData(
{},
searchParams,
apiConfig.actions.GET.CALL_LOGS,
{ cancelToken: source.token }
);
if (callLogs) {
restParams.onSetPending();
dispactcher(onSetListCallLog(callLogs));
}
} catch (error) {
if (axios.isCancel(error)) {
console.log("Call logs request canceled:", error.message);
return;
}
console.error("Error fetching call logs:", error);
restParams.onSetPending();
}
} catch (error) {
console.error("Error in handleGetCallLogs:", error);
restParams.onSetPending();
}
};
const handleUpdateCallLog = async (putParams) => {
try {
await updateData(
{
...putParams,
practice_id,
},
getJWTHeader(jwt.content),
null,
fetchParams
);
successTostify("Call log updated successfully");
} catch (error) {
console.log("handleUpdateCallLog", error);
dispatchError(
{ message: getServerErrorMessage(error), buttonTxt: "Ok, got it" },
restParams.onSetPending
);
}
};
const getCallLogFilterParams = () => {
const filterKeys = Object.keys(filterAPI);
let params = {};
filterKeys.forEach((key) => {
if (
filterAPI[key].value !== "" &&
filterAPI[key].value !== null &&
filterAPI[key].value !== undefined
)
params[key] = filterAPI[key].value;
});
return params;
};
return {
...restParams,
filterAPI,
setCallLog,
handleUpdateCallLog,
enableSelectPhone,
setEnableSelectPhone,
handleGetExtensions,
handleGetCallLogs,
getCallLogFilterParams,
callLogs,
};
};
export default useFetchCallLogs;