import { t } from "i18next"; import { useEffect, useState } from "react"; import Card from "react-bootstrap/Card"; import Col from "react-bootstrap/Col"; import Form from "react-bootstrap/Form"; import Row from "react-bootstrap/Row"; import { toast } from "react-hot-toast"; import { BsFillTrash3Fill } from "react-icons/bs"; import { FaCopy, FaPaste } from "react-icons/fa"; import { FiEdit } from "react-icons/fi"; import { useLocation, useNavigate, useParams } from "react-router-dom"; import Select from "react-select"; import { SyncLoader } from "react-spinners"; import PatternsGrid from "../../../../application-components/grid-view/DataGrid/PatternsGrid"; import CTIButton from "../../../../application-components/reuseables/formComponents/CTIButton"; import { AccessCodeSip } from "../../../../application-components/user/Permissions/AccessCodes"; import { RequestActions } from "../../../../services/Globals"; import PlineTools from "../../../../services/PlineTools"; import RequestService from "../../../../services/RequestService"; interface InputItem { ParamType: string; parameter: string; value: string; } interface ResultObject { id?: number; endpoint: { [key: string]: string }; auth: { [key: string]: string }; aor: { [key: string]: string }; contact: { [key: string]: string }; transport: { [key: string]: string }; } const SipParams = () => { const initialState = { endpoint: {}, auth: {}, aor: {}, contact: {}, transport: {}, }; //state for overlay const [loading, setLoading] = useState(true); //url params comes here name and id const profileParam = useParams(); const [editingRow, setEditingRow] = useState(null); //grid data comes here const [rowData, setRowData] = useState([]); //skeleton loading state for reRendering Form const [editLoading, setEditLoading] = useState(false); //change label Edit Button is Create or Update const [mode, setMode] = useState(false); const [selected, setSelected] = useState([]); //First Select and categories of params const [selectedParamType, setSelectedParamType] = useState(null); //selected parameter form categories const [selectedParam, setSelectedParam] = useState([]); //state render dynamic form const location = useLocation(); const [renderedFormControls, setRenderedFormControls] = useState< JSX.Element[] >([]); //main and all parameters comes here const [params, setParams] = useState({ endpoint: [], auth: [], transport: [], contact: [], aor: [], }); //create and update data from store here const [state, setState] = useState(initialState); const getRowKey = (row: Pick) => JSON.stringify([row.ParamType, row.parameter]); const navigate = useNavigate(); //grid Cols const columns = [ { field: "ParamType", headerName: t("sipProfile.params.param_type"), headerCheckboxSelection: true, checkboxSelection: true, cellRenderer: (params: any) => { return PlineTools.stringToLabel(params.data.ParamType); }, }, { field: "parameter", headerName: t("sipProfile.params.parameter"), resizable: true, cellRenderer: (params: any) => { return PlineTools.stringToLabel(params.data.parameter); }, sortable: false, }, { field: "value", headerName: t("sipProfile.params.value"), resizable: true, sortable: false, }, { field: "", headerName: t("featureCodes.row_operation"), maxWidth: "120", cellRenderer: DeleteRow, filter: false, sortable: false, }, ]; const resetParam = (e: any) => { const target = params[e][0]; setSelectedParam(target); }; //convert array params to object for save in backend function convertArrayToObject(inputArray: InputItem[]): ResultObject { const result: ResultObject = { id: profileParam.id ? parseInt(profileParam.id, 10) : undefined, endpoint: {}, auth: {}, aor: {}, contact: {}, transport: {}, }; inputArray.forEach((item) => { const { ParamType, parameter, value } = item; if (ParamType === "endpoint") { result.endpoint[parameter] = value; } else if (ParamType === "auth") { result.auth[parameter] = value; } else if (ParamType === "aor") { result.aor[parameter] = value; } else if (ParamType === "contact") { result.contact[parameter] = value; } else if (ParamType === "transport") { result.transport[parameter] = value; } }); return result; } //Draw Is Dynamic Function Renders Parameter Fields const draw = (_type: string, v: any, i: number) => { if (state[_type] === undefined) { state[_type] = {}; } let select: any = {}; if (v[1] === "Custom") { let obj: any = []; Object.keys(v[2]).forEach((val: any) => { obj.push({ value: val, label: PlineTools.stringToLabel(v[2][val]), }); if (state[_type][v[0]] === undefined) { if (v[3] === val) { select = { value: val, label: PlineTools.stringToLabel(v[2][val]) }; } } else { let data = rowData.find((item: any) => item.parameter === v[0]); try { data = JSON.parse(data.value); } catch {} if (Array.isArray(data)) { select = []; data.forEach((e: any) => { select.push({ value: e, label: PlineTools.stringToLabel(v[2][e]), }); }); } else { select = { value: data.value, label: PlineTools.stringToLabel(data.value), }; } } }); //default value select works fine return ( t("globals.noOp")} key={JSON.stringify(booleanOptions)} options={booleanOptions} defaultValue={booleanOptions.find( (option) => option.value === select )} onChange={(e: any) => { let tmp = { ...state }; tmp[_type][v[0]] = e.value; setState(tmp); }} /> {v[4]} ); } else if (v[1] === "Integer") { const i = v[3]; return ( { let tmp = { ...state }; tmp[_type][v[0]] = e.target.value; setState(tmp); }} /> {v[4]} ); } else { const i = v[3]; return ( { let tmp = { ...state }; tmp[_type][v[0]] = e.target.value; setState(tmp); }} /> {v[4]} ); } }; //save change and commit const save = async () => { const final = convertArrayToObject(rowData); RequestService.PostRequest( "/sip-profile-details/save", final, AccessCodeSip.SipProfilesParameters, RequestActions.Update ) .then((result: any) => { if (result) { if (!result.hasPermission) { navigate("/sip-profiles/index"); return; } if (!result.Error) { var sipProfileP = location.state; if (sipProfileP.path) { var [pageSize, paging] = sipProfileP.path.split("-"); navigate("/sip-profiles/index", { state: { profile: `${pageSize}-${paging}` }, }); } else { navigate("/sip-profiles/index"); } toast.success(t("toasts.successful_save"), { id: "success-save" }); } } }) .catch((error: any) => {}); }; //get Data of params and profiles params useEffect(() => { const timerId = setTimeout(async () => { RequestService.GetRequest( "/sip-profile-details/get?id=" + id, AccessCodeSip.SipProfilesParameters, RequestActions.Read ) .then((data: any) => { if (data) { if (!data.hasPermission) { navigate("/home"); return; } if (!data.Error) { RequestService.GetRequest( "/sip-profile-details/params", AccessCodeSip.SipProfilesParameters, RequestActions.Read ).then((result: any) => { if (result) { if (!result.hasPermission) { navigate("/sip-profiles/index"); return; } if (!result.Error) { setParams({ aor: result.data.aor, contact: result.data.contact, endpoint: result.data.endpoint, auth: result.data.auth, transport: result.data.transport, }); setRowData(convertObjectToArray(data.data)); setLoading(false); } } }); } } }) .finally(() => { setLoading(false); }); }, 1000); const id = profileParam.id; return () => { clearTimeout(timerId); }; }, []); //change selected category and change second selected options const handleParamTypeChange = (selectedOption: any) => { setSelectedParamType(String(selectedOption)); }; //after selected draw call trigger is this const handleParamChange = (selectedOption: any) => { if (selectedParam === selectedOption.value) { } else { // setMode(false) setSelectedParam(selectedOption.value); setRenderedFormControls([]); } }; //edit function of grid is more complex than every time const handleEditRow = (rowData: any) => { setMode(true); setEditLoading(true); setSelectedParamType(null); setSelectedParam([]); setRenderedFormControls([]); const { ParamType, parameter, value } = rowData; handleParamTypeChange(ParamType); const Options = ParamType ? params[ParamType].map((param: any) => ({ label: PlineTools.stringToLabel(param[0]), value: param, })) : []; const target = Options.find((opt: any) => opt.value[0] === parameter); const updatedValueArray = [...target.value]; updatedValueArray[3] = value; // Update the target with the new array target.value = updatedValueArray; handleParamChange(target); setTimeout(() => { setEditLoading(false); }, 600); setState({ ...state, [ParamType]: { ...state[ParamType], [parameter]: value }, }); }; //Delete params from grid function DeleteRow(params: any) { const rowKey = getRowKey(params.data); return ( <> { if (editingRow !== rowKey) { handleEditRow(params.data); setEditingRow(rowKey); } }} /> { setRowData((currentRows: InputItem[]) => currentRows.filter((row) => getRowKey(row) !== rowKey) ); setSelected((currentRows: InputItem[]) => currentRows.filter((row) => getRowKey(row) !== rowKey) ); setState((currentState: any) => { const updatedType = { ...currentState[params.data.ParamType] }; delete updatedType[params.data.parameter]; return { ...currentState, [params.data.ParamType]: updatedType }; }); if (editingRow === rowKey) { setEditingRow(null); setMode(false); setSelectedParamType(null); setSelectedParam([]); setRenderedFormControls([]); } }} size={28} /> ); } //params categories options create here from params State const paramTypesOptions = Object.keys(params).map((paramType) => ({ label: paramType, value: paramType, })); //parameters options create here from selectedParamType const paramOptions = selectedParamType ? params[selectedParamType].map((param: any) => ({ label: PlineTools.stringToLabel(param[0]), value: param, })) : []; //Function add params to rowData const ParameterTrigger = () => { if (selectedParamType && selectedParam) { const formControl: JSX.Element | null = draw( selectedParamType, selectedParam, 0 ); if (formControl) { setRenderedFormControls([formControl]); } } }; //trigger render with Draw useEffect(() => { ParameterTrigger(); }, [selectedParam]); //convert for final round before save data rowData makes ready for save function convertObjectToArray(inputObject: object) { const resultArray: any[] = []; function iterateObject(obj: object, paramType: any) { for (const [parameter, value] of Object.entries(obj)) { if (typeof value === "object" && !Array.isArray(value)) { iterateObject(value, parameter); } else { resultArray.push({ ParamType: paramType, parameter, value }); } } } for (const [paramType, params] of Object.entries(inputObject)) { iterateObject(params, paramType); } return resultArray; } /** * Adds a parameter to the grid. * * @remarks * This function checks if the selected parameter type and parameter are valid and not empty. * If valid, it checks if the parameter already exists in the grid. If it exists, it updates the existing row with the new value. * If it does not exist, it adds a new row to the grid with the parameter details. * Finally, if the mode is set, it resets the mode. */ const addParameterToGrid = () => { // Check if selectedParamType, selectedParam, and selectedParam length are valid if (selectedParamType && selectedParam && selectedParam.length > 0) { // Create a key using selectedParamType and selectedParam const key = `${selectedParamType}-${selectedParam[0]}`; // // Find the index of the existing row with the same key const existingRowIndex = rowData.findIndex( (row: any) => `${row.ParamType}-${row.parameter}` === key ); // Check if an existing row with the same key is found if (existingRowIndex !== -1) { if (mode) { const updatedRowData = [...rowData]; // Update the existing row with the new value updatedRowData[existingRowIndex] = { ParamType: selectedParamType, parameter: selectedParam[0], value: state[selectedParamType][selectedParam[0]], }; // Set the updated rowData setRowData(updatedRowData); } else { toast.error(t("sipProfile.params.duplicate")); } // If found, create a copy of rowData } else { // If no existing row is found, create a new parameter object const newParameter = { ParamType: selectedParamType, parameter: selectedParam[0], value: state[selectedParamType][selectedParam[0]] || selectedParam[3], }; // Add the new parameter to the rowData setRowData((prevRowData: any) => { const newRowData = [...prevRowData]; // Create a shallow copy of the array newRowData.unshift(newParameter); // Add newParameter to the beginning return newRowData; }); } setLoading(true); setSelectedParamType(null); setSelectedParam([]); setRenderedFormControls([]); if (mode) { setMode(false); setEditingRow(null); } setLoading(false); } }; const saveToLocalStorage = (data: any) => { localStorage.setItem("copiedParameters", JSON.stringify(data)); }; const getFromLocalStorage = () => { const data = localStorage.getItem("copiedParameters"); return data ? JSON.parse(data) : []; }; const isValidParameter = (obj: any) => { // Define the expected structure for patterns const patternKeys = ["ParamType", "parameter", "value"]; // Check if the object has all the expected keys for patterns return patternKeys.every((key) => obj.hasOwnProperty(key)); }; return (

{" "} {`${t("sip_profile_parameter.title")} :${profileParam.name}`}

{editLoading ? (
) : ( <> opt.value[0] === selectedParam[0] )} onChange={(e: any) => { if (mode) { setMode(false); setEditingRow(null); } handleParamChange(e); }} options={paramOptions} placeholder={`Select ${selectedParamType} Params`} /> )} {renderedFormControls.map((control: any, index: number) => ( {control} ))} {" "} save()} /> { var sipProfileP = location.state; if (sipProfileP.profile) { var [pageSize, paging] = sipProfileP.profile.split("-"); navigate("/sip-profiles/index", { state: { profile: `${pageSize}-${paging}` }, }); } else { navigate("/sip-profiles/index"); } }} /> )}
Parameters
} onClick={() => { if (selected && selected.length > 0) { saveToLocalStorage(selected); toast.success("Parameters Copied", { id: "success-paste" }); } else { toast.error("Nothing to copy. No Parameter selected.", { id: "error-paste", }); } }} />{" "} } onClick={() => { const clipboardData = getFromLocalStorage(); if (clipboardData.length > 0) { if ( clipboardData.every((obj: any) => isValidParameter(obj)) ) { const newData = clipboardData.filter((newData: any) => { const isDuplicate = rowData.some( (existingData: any) => existingData.ParamType === newData.ParamType && existingData.parameter === newData.parameter ); return !isDuplicate; }); if (newData.length > 0) { setRowData([...rowData, ...newData]); toast.success("Data pasted from clipboard", { id: "success-copy", }); } else { toast.error( "No new data to paste or duplicate data exist", { id: "error-copy" } ); } } else { toast.error("Invalid structure in clipboard", { id: "invalid-structure", }); } } else { toast.error("Clipboard is empty", { id: "empty-clipboard", }); } }} />
); }; export default SipParams;