Files
cti/cti_app/src/components/pages/sip/sip-profiles/sip-profile-parameters/SipParams.tsx
2026-11-04 10:18:19 +03:30

813 lines
27 KiB
TypeScript

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<string | null>(null);
//grid data comes here
const [rowData, setRowData] = useState<any>([]);
//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<any>([]);
//First Select and categories of params
const [selectedParamType, setSelectedParamType] = useState<any>(null);
//selected parameter form categories
const [selectedParam, setSelectedParam] = useState<string[]>([]);
//state render dynamic form
const location = useLocation();
const [renderedFormControls, setRenderedFormControls] = useState<
JSX.Element[]
>([]);
//main and all parameters comes here
const [params, setParams] = useState<any>({
endpoint: [],
auth: [],
transport: [],
contact: [],
aor: [],
});
//create and update data from store here
const [state, setState] = useState<any>(initialState);
const getRowKey = (row: Pick<InputItem, "ParamType" | "parameter">) =>
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 (
<Row key={i}>
<Col className="dark-select">
<Form.Group controlId={v[0]}>
<label>{PlineTools.stringToLabel(v[0])}</label>
<Select
noOptionsMessage={() => t("globals.noOp")}
key={JSON.stringify(obj)}
isMulti={v[5] === undefined ? false : v[5]}
options={obj}
defaultValue={select}
onChange={(e) => {
let tmp = { ...state };
if (Array.isArray(e)) {
let arr: any[] = [];
e.forEach((val) => {
arr.push(val.value);
});
tmp[_type][v[0]] = JSON.stringify(arr);
} else {
tmp[_type][v[0]] = e.value;
}
setState(tmp);
}}
/>
<Form.Text className="text-muted">{v[4]}</Form.Text>
</Form.Group>
</Col>
</Row>
);
} else if (v[1] === "Boolean") {
const booleanOptions = [
{ value: "yes", label: "Yes" },
{ value: "no", label: "No" },
];
let select = "";
if (mode) {
select = String(state[_type][v[0]]);
} else {
select = String(v[3]);
}
// const defaultValue = booleanOptions.find((option) => option.value === select);
return (
<Row key={i}>
<Col className="dark-select">
<Form.Group controlId={v[0]}>
<label>{PlineTools.stringToLabel(v[0])}</label>
<Select
noOptionsMessage={() => 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);
}}
/>
<Form.Text className="text-muted">{v[4]}</Form.Text>
</Form.Group>
</Col>
</Row>
);
} else if (v[1] === "Integer") {
const i = v[3];
return (
<Row key={i}>
<Col>
<Form.Group controlId={v[0]}>
<label>{PlineTools.stringToLabel(v[0])}</label>
<Form.Control
type="number"
name={v[0]}
defaultValue={i}
onChange={(e) => {
let tmp = { ...state };
tmp[_type][v[0]] = e.target.value;
setState(tmp);
}}
/>
<Form.Text className="text-muted">{v[4]}</Form.Text>
</Form.Group>
</Col>
</Row>
);
} else {
const i = v[3];
return (
<Row key={i}>
<Col>
<Form.Group controlId={v[0]}>
<label>{PlineTools.stringToLabel(v[0])}</label>
<Form.Control
type="text"
name={v[0]}
defaultValue={i}
onChange={(e) => {
let tmp = { ...state };
tmp[_type][v[0]] = e.target.value;
setState(tmp);
}}
/>
<Form.Text className="text-muted">{v[4]}</Form.Text>
</Form.Group>
</Col>
</Row>
);
}
};
//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 (
<>
<FiEdit
size={22}
className="mx-2 edit-icon"
// Only call handleEditRow if the row is not currently being edited
onClick={() => {
if (editingRow !== rowKey) {
handleEditRow(params.data);
setEditingRow(rowKey);
}
}}
/>
<BsFillTrash3Fill
style={{ paddingLeft: "8px" }}
className="delete-icon"
onClick={() => {
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 (
<Col md={{ span: 10, offset: 1 }}>
<Row>
<Col md={{ span: 10, offset: 1 }}>
<h3>
{" "}
{`${t("sip_profile_parameter.title")} :${profileParam.name}`}
</h3>
{editLoading ? (
<Row
style={{
justifyContent: "center",
alignItems: "center",
height: "200px", // Set the desired height
}}
>
<Card>
<Card.Body
style={{ display: "flex", justifyContent: "center" }}
>
<Col md={10}>
<div style={{ textAlign: "center" }}>
<SyncLoader color="#55efc4" size={25} />
</div>
</Col>
</Card.Body>
</Card>
</Row>
) : (
<>
<Card className="card-forms">
<Card.Body>
<Row>
<Col md={3} className="dark-select">
<label aria-label="aria-param" htmlFor="aria-param">
{t("sipProfile.params.param_type")}
</label>
<Select
noOptionsMessage={() => t("globals.noOp")}
inputId="aria-parameter"
name="aria-param"
value={paramTypesOptions.find(
(opt: any) => opt.value === selectedParamType
)}
onChange={(e: any) => {
handleParamTypeChange(e.value);
resetParam(e.value);
}}
options={paramTypesOptions}
placeholder={t(
"sipProfile.params.param_type_placeholder"
)}
/>
</Col>
<Col md={4} className="dark-select">
{selectedParamType && (
<>
<label
aria-label="params-select"
htmlFor="params-select"
>
{t("sipProfile.params.parameter")}
</label>
<Select
inputId="params-select"
name="params-select"
value={paramOptions.find(
(opt: any) => opt.value[0] === selectedParam[0]
)}
onChange={(e: any) => {
if (mode) {
setMode(false);
setEditingRow(null);
}
handleParamChange(e);
}}
options={paramOptions}
placeholder={`Select ${selectedParamType} Params`}
/>
</>
)}
</Col>
{renderedFormControls.map((control: any, index: number) => (
<Col md={4} key={index}>
{control}
</Col>
))}
</Row>
<Row className="mt-3">
<Col md={6}>
<CTIButton
className="mx-1"
color="blue"
label={`${
mode
? t("sipProfile.params.update")
: t("sipProfile.params.add")
}`}
onClick={addParameterToGrid}
/>{" "}
<CTIButton
label={t("buttons.save")}
className="mx-1"
color="green"
onClick={() => save()}
/>
<CTIButton
label={t("buttons.cancel")}
className="mx-1"
color="red"
onClick={() => {
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");
}
}}
/>
</Col>
</Row>
</Card.Body>
</Card>
</>
)}
<Card className="mt-3 card-forms">
<Card.Header className="queue-header">
<h5>Parameters</h5>
</Card.Header>
<div className="mt-3 mx-3">
<CTIButton
color="purple"
className="mx-1"
label="Copy"
icon={<FaCopy />}
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",
});
}
}}
/>{" "}
<CTIButton
color="yellow"
label="Paste"
icon={<FaPaste />}
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",
});
}
}}
/>
</div>
<Card.Body>
<PatternsGrid
columnDefs={columns}
loading={loading}
setSelected={setSelected}
rowData={rowData}
paging={true}
pageSize={50}
/>
</Card.Body>
</Card>
</Col>
</Row>
</Col>
);
};
export default SipParams;