diff --git a/frontend/src/components/admin/Admin.js b/frontend/src/components/admin/Admin.js index a9fabca2e2..65832d2e17 100644 --- a/frontend/src/components/admin/Admin.js +++ b/frontend/src/components/admin/Admin.js @@ -29,6 +29,7 @@ import { Bullhorn, User, BatchJob, + ResultNew, Popup, Search, } from "@carbon/icons-react"; @@ -59,6 +60,35 @@ import BatchTestReassignmentAndCancelation from "./BatchTestReassignmentAndCance import TestNotificationConfigMenu from "./testNotificationConfigMenu/TestNotificationConfigMenu.js"; import TestNotificationConfigEdit from "./testNotificationConfigMenu/TestNotificationConfigEdit.js"; import SearchIndexManagement from "./searchIndexManagement/SearchIndexManagement"; +import TestManagementConfigMenu from "./testManagementConfigMenu/TestManagementConfigMenu.js"; +import ResultSelectListAdd from "./testManagementConfigMenu/ResultSelectListAdd.js"; +import TestAdd from "./testManagementConfigMenu/TestAdd.js"; +import TestModifyEntry from "./testManagementConfigMenu/TestModifyEntry.js"; +import TestOrderability from "./testManagementConfigMenu/TestOrderability.js"; +import MethodManagement from "./testManagementConfigMenu/MethodManagement.js"; +import MethodCreate from "./testManagementConfigMenu/MethodCreate.js"; +import TestSectionManagement from "./testManagementConfigMenu/TestSectionManagement.js"; +import TestSectionCreate from "./testManagementConfigMenu/TestSectionCreate.js"; +import TestSectionOrder from "./testManagementConfigMenu/TestSectionOrder.js"; +import SampleTypeManagement from "./testManagementConfigMenu/SampleTypeManagement.js"; +import TestSectionTestAssign from "./testManagementConfigMenu/TestSectionTestAssign.js"; +import SampleTypeOrder from "./testManagementConfigMenu/SampleTypeOrder.js"; +import SampleTypeCreate from "./testManagementConfigMenu/SampleTypeCreate.js"; +import SampleTypeTestAssign from "./testManagementConfigMenu/SampleTypeTestAssign.js"; +import UomManagement from "./testManagementConfigMenu/UomManagement.js"; +import UomCreate from "./testManagementConfigMenu/UomCreate.js"; +import PanelManagement from "./testManagementConfigMenu/PanelManagement.js"; +import PanelCreate from "./testManagementConfigMenu/PanelCreate.js"; +import PanelOrder from "./testManagementConfigMenu/PanelOrder.js"; +import PanelTestAssign from "./testManagementConfigMenu/PanelTestAssign.js"; +import TestActivation from "./testManagementConfigMenu/TestActivation.js"; +import TestRenameEntry from "./testManagementConfigMenu/TestRenameEntry.js"; +import PanelRenameEntry from "./testManagementConfigMenu/PanelRenameEntry.js"; +import SampleTypeRenameEntry from "./testManagementConfigMenu/SampleTypeRenameEntry.js"; +import TestSectionRenameEntry from "./testManagementConfigMenu/TestSectionRenameEntry.js"; +import UomRenameEntry from "./testManagementConfigMenu/UomRenameEntry.js"; +import SelectListRenameEntry from "./testManagementConfigMenu/SelectListRenameEntry.js"; +import MethodRenameEntry from "./testManagementConfigMenu/MethodRenameEntry.js"; function Admin() { const intl = useIntl(); @@ -93,12 +123,6 @@ function Admin() { - - - - - - @@ -133,6 +157,9 @@ function Admin() { + + + - + @@ -281,6 +308,90 @@ function Admin() { + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {notificationVisible === true ? : ""} +
+ + + +
+ + + +
+
+
+
+
+
+ + +
+ + + +
+
+
+
+ + ); +} + +export default injectIntl(MethodCreate); diff --git a/frontend/src/components/admin/testManagementConfigMenu/MethodManagement.js b/frontend/src/components/admin/testManagementConfigMenu/MethodManagement.js new file mode 100644 index 0000000000..02d413f58f --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/MethodManagement.js @@ -0,0 +1,101 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Form, + Heading, + Button, + Loading, + Grid, + Column, + Section, + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableSelectRow, + TableSelectAll, + TableContainer, + Pagination, + Search, + Select, + SelectItem, + Stack, + UnorderedList, + ListItem, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServer, + postToOpenElisServerFormData, + postToOpenElisServerFullResponse, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import CustomCheckBox from "../../common/CustomCheckBox.js"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.testUnit.manage", + link: "/MasterListsPage#MethodManagement", + }, +]; + +function MethodManagement() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + + return ( + <> + {notificationVisible === true ? : ""} +
+ + + +
+ + + +
+
+
+
+
+
+ + + + { + window.location.assign("/MasterListsPage#MethodCreate"); + }} + > + + + + + +
+ + ); +} + +export default injectIntl(MethodManagement); diff --git a/frontend/src/components/admin/testManagementConfigMenu/MethodRenameEntry.js b/frontend/src/components/admin/testManagementConfigMenu/MethodRenameEntry.js new file mode 100644 index 0000000000..9f25d9dbaa --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/MethodRenameEntry.js @@ -0,0 +1,237 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { Heading, Button, Grid, Column, Section } from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import RenameModelBox from "./renameModel/RenameModelBox.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.type.rename", + link: "/MasterListsPage#MethodRenameEntry", + }, +]; + +function MethodRenameEntry() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + const modalHeading = intl.formatMessage({ + id: "method.browse.title", + }); + + const [isLoading, setIsLoading] = useState(false); + const [finished, setFinished] = useState(true); + const [isAddModalOpen, setIsAddModalOpen] = useState(false); + const [confirmationStep, setConfirmationStep] = useState(false); + const [inputError, setInputError] = useState(false); + const [methodRename, setMethodRename] = useState({}); + const [methodListShow, setMethodListShow] = useState([]); + const [methodRenamePost, setMethodRenamePost] = useState({}); + const [entityNamesProvider, setEntityNamesProvider] = useState({ name: { english: "", french: "" },}); + const [entityNamesProviderPost, setEntityNamesProviderPost] = useState({ name: { english: "", french: ""},}); + const [entityId, setEntityId] = useState(); + const [entityName, setEntityName] = useState("method"); + const [selectedItem, setSelectedItem] = useState({}); + + useEffect(() => { + componentMounted.current = true; + getFromOpenElisServer("/rest/MethodRenameEntry", handleMethodRename); + return () => { + componentMounted.current = false; + }; + }, []); + + const handleMethodRename = (res) => { + if (!res) { + setIsLoading(true); + } else { + setMethodRename(res); + setMethodRenamePost(res); + setMethodListShow(res.methodList); + } + }; + + useEffect(() => { + if(entityId && entityName) { + getFromOpenElisServer( + `/rest/EntityNamesProvider?entityId=${entityId}&entityName=${entityName}`, + handelEntityNamesProvider, + ); + } + }, [entityId,entityName]); + + const handelEntityNamesProvider = (res) => { + if (!res) { + setIsLoading(true); + } else { + setEntityNamesProvider(res); + setEntityNamesProviderPost(res); + } + }; + + function methodRenameUpdatePost() { + setIsLoading(true); + if (confirmationStep) { + postToOpenElisServerJsonResponse( + `/rest/MethodRenameEntry`, + JSON.stringify(methodRenamePost), + (res) => { + methodRenameUpdatePostCallback(res); + }, + ); + } else { + setConfirmationStep(true); + } + } + + function methodRenameUpdatePostCallback(res) { + if (res) { + setIsLoading(false); + setFinished(false); + addNotification({ + title: intl.formatMessage({ + id: "notification.title", + }), + message: intl.formatMessage({ + id: "notification.user.post.save.success", + }), + kind: NotificationKinds.success, + }); + setNotificationVisible(true); + setIsAddModalOpen(false); + } else { + addNotification({ + kind: NotificationKinds.error, + title: intl.formatMessage({ id: "notification.title" }), + message: intl.formatMessage({ id: "server.error.msg" }), + }); + setNotificationVisible(true); + setTimeout(() => { + window.location.reload(); + }, 200); + } + } + + const openAppModle = (item) => { + setConfirmationStep(false); + setIsAddModalOpen(true); + setEntityId(item.id); + // setEntityName(test.value); + setSelectedItem(item); + }; + + const onInputChangeEn = (e) => { + const englishName = e.target.value; + setEntityNamesProviderPost((prev) => ({ + ...prev, + name: { + ...prev.name, + english: englishName, + }, + })); + setInputError(false); + }; + + const onInputChangeFr = (e) => { + const frenchName = e.target.value; + setEntityNamesProviderPost((prev) => ({ + ...prev, + name: { + ...prev.name, + french: frenchName, + }, + })); + setInputError(false); + }; + + useEffect(() => { + if (entityId && entityNamesProviderPost && entityNamesProviderPost.name) { + setMethodRenamePost((prev) => ({ + ...prev, + methodId: entityId, + nameEnglish: entityNamesProviderPost.name.english, + nameFrench: entityNamesProviderPost.name.french, + })); + } + }, [entityNamesProviderPost, entityId]); + + const closeAddModal = () => { + setIsAddModalOpen(false); + }; + + return ( + <> + {notificationVisible === true ? : ""} +
+ +
+ + +
+ + + +
+
+
+
+
+
+ + + + + +
+ +
+
+ + ); +} + +export default injectIntl(MethodRenameEntry); diff --git a/frontend/src/components/admin/testManagementConfigMenu/PanelCreate.js b/frontend/src/components/admin/testManagementConfigMenu/PanelCreate.js new file mode 100644 index 0000000000..78d49bcfb9 --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/PanelCreate.js @@ -0,0 +1,101 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Form, + Heading, + Button, + Loading, + Grid, + Column, + Section, + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableSelectRow, + TableSelectAll, + TableContainer, + Pagination, + Search, + Select, + SelectItem, + Stack, + UnorderedList, + ListItem, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServer, + postToOpenElisServerFormData, + postToOpenElisServerFullResponse, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import CustomCheckBox from "../../common/CustomCheckBox.js"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.panel.manage", + link: "/MasterListsPage#SampleTypeManagement", + }, + { + label: "configuration.panel.create", + link: "/MasterListsPage#PanelCreate", + }, +]; + +function PanelCreate() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + + return ( + <> + {notificationVisible === true ? : ""} +
+ + + +
+ + + +
+
+
+
+
+
+ + +
+ + + +
+
+
+
+ + ); +} + +export default injectIntl(PanelCreate); diff --git a/frontend/src/components/admin/testManagementConfigMenu/PanelManagement.js b/frontend/src/components/admin/testManagementConfigMenu/PanelManagement.js new file mode 100644 index 0000000000..d928ab988e --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/PanelManagement.js @@ -0,0 +1,117 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Form, + Heading, + Button, + Loading, + Grid, + Column, + Section, + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableSelectRow, + TableSelectAll, + TableContainer, + Pagination, + Search, + Select, + SelectItem, + Stack, + UnorderedList, + ListItem, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServer, + postToOpenElisServerFormData, + postToOpenElisServerFullResponse, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import CustomCheckBox from "../../common/CustomCheckBox.js"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.panel.manage", + link: "/MasterListsPage#PanelManagement", + }, +]; + +function PanelManagement() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + + return ( + <> + {notificationVisible === true ? : ""} +
+ + + +
+ + + +
+
+
+
+
+
+ + + + { + window.location.assign("/MasterListsPage#PanelCreate"); + }} + > + + +
+ { + window.location.assign("/MasterListsPage#PanelOrder"); + }} + > + + +
+ { + window.location.assign("/MasterListsPage#PanelTestAssign"); + }} + > + + +
+
+
+
+ + ); +} + +export default injectIntl(PanelManagement); diff --git a/frontend/src/components/admin/testManagementConfigMenu/PanelOrder.js b/frontend/src/components/admin/testManagementConfigMenu/PanelOrder.js new file mode 100644 index 0000000000..d44b532d55 --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/PanelOrder.js @@ -0,0 +1,103 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Form, + Heading, + Button, + Loading, + Grid, + Column, + Section, + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableSelectRow, + TableSelectAll, + TableContainer, + Pagination, + Search, + Select, + SelectItem, + Stack, + UnorderedList, + ListItem, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServer, + postToOpenElisServerFormData, + postToOpenElisServerFullResponse, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import CustomCheckBox from "../../common/CustomCheckBox.js"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.panel.manage", + link: "/MasterListsPage#PanelManagement", + }, + { + label: "configuration.panel.order", + link: "/MasterListsPage#PanelOrder", + }, +]; + +function PanelOrder() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + + return ( + <> + {notificationVisible === true ? : ""} +
+ + + +
+ + + +
+
+
+
+
+
+ + +
+ + + +
+
+
+
+ + ); +} + +export default injectIntl(PanelOrder); + +PanelOrder; diff --git a/frontend/src/components/admin/testManagementConfigMenu/PanelRenameEntry.js b/frontend/src/components/admin/testManagementConfigMenu/PanelRenameEntry.js new file mode 100644 index 0000000000..5a44f2a647 --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/PanelRenameEntry.js @@ -0,0 +1,234 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { Heading, Button, Grid, Column, Section } from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import RenameModelBox from "./renameModel/RenameModelBox.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "panel.panelName", + link: "/MasterListsPage#PanelRenameEntry", + }, +]; + +function PanelRenameEntry() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + const modalHeading = intl.formatMessage({ id: "field.panel" }); + + const componentMounted = useRef(false); + const [isLoading, setIsLoading] = useState(false); + const [finished, setFinished] = useState(true); + const [isAddModalOpen, setIsAddModalOpen] = useState(false); + const [confirmationStep, setConfirmationStep] = useState(false); + const [inputError, setInputError] = useState(false); + const [panel, setPanel] = useState({}); + const [panelListShow, setPanelListShow] = useState([]); + const [panelPost, setPanelPost] = useState({}); + const [entityNamesProvider, setEntityNamesProvider] = useState({ name : { english: "", french: "" } }); + const [entityNamesProviderPost, setEntityNamesProviderPost] = useState({ name: { + english: "", french: "" + }}); + const [entityId, setEntityId] = useState(); + const [entityName, setEntityName] = useState("panel"); + const [selectedItem, setSelectedItem] = useState({}); + + useEffect(() => { + componentMounted.current = true; + getFromOpenElisServer("/rest/PanelRenameEntry", handelPanelRename); + return () => { + componentMounted.current = false; + }; + }, []); + + const handelPanelRename = (res) => { + if (!res) { + setIsLoading(true); + } else { + setPanel(res); + setPanelPost(res); + setPanelListShow(res.panelList); + } + }; + + useEffect(() => { + if(entityId && entityName) { + getFromOpenElisServer( + `/rest/EntityNamesProvider?entityId=${entityId}&entityName=${entityName}`, + handelEntityNamesProvider, + ); + } + }, [entityId,entityName]); + + const handelEntityNamesProvider = (res) => { + if (!res) { + setIsLoading(true); + } else { + setEntityNamesProvider(res); + setEntityNamesProviderPost(res); + } + }; + + function panelUpdatePost() { + setIsLoading(true); + if (confirmationStep) { + postToOpenElisServerJsonResponse( + `/rest/PanelRenameEntry`, + JSON.stringify(panelPost), + (res) => { + panelUpdatePostCallback(res); + }, + ); + } else { + setConfirmationStep(true); + } + } + + function panelUpdatePostCallback(res) { + if (res) { + setIsLoading(false); + setFinished(false); + addNotification({ + title: intl.formatMessage({ + id: "notification.title", + }), + message: intl.formatMessage({ + id: "notification.user.post.save.success", + }), + kind: NotificationKinds.success, + }); + setNotificationVisible(true); + setIsAddModalOpen(false); + } else { + addNotification({ + kind: NotificationKinds.error, + title: intl.formatMessage({ id: "notification.title" }), + message: intl.formatMessage({ id: "server.error.msg" }), + }); + setNotificationVisible(true); + setTimeout(() => { + window.location.reload(); + }, 200); + } + } + + const openAppModle = (item) => { + setConfirmationStep(false); + setIsAddModalOpen(true); + setEntityId(item.id); + // setEntityName(test.value); + setSelectedItem(item); + }; + + const onInputChangeEn = (e) => { + const englishName = e.target.value; + setEntityNamesProviderPost((prev) => ({ + name: { + ...prev.name, + english: englishName, + }, + })); + setInputError(false); + }; + + const onInputChangeFr = (e) => { + const frenchName = e.target.value; + setEntityNamesProviderPost((prev) => ({ + name: { + ...prev.name, + french: frenchName, + }, + })); + setInputError(false); + }; + + useEffect(() => { + if (entityId && entityNamesProviderPost && entityNamesProviderPost.name) { + setPanelPost((prev) => ({ + ...prev, + panelId: entityId, + nameEnglish: entityNamesProviderPost.name.english, + nameFrench: entityNamesProviderPost.name.french, + })); + } + }, [entityNamesProviderPost, entityId]); + + const closeAddModal = () => { + setIsAddModalOpen(false); + }; + + return ( + <> + {notificationVisible === true ? : ""} +
+ +
+ + +
+ + + +
+
+
+
+
+
+ + + + + +
+ +
+
+ + ); +} + +export default injectIntl(PanelRenameEntry); diff --git a/frontend/src/components/admin/testManagementConfigMenu/PanelTestAssign.js b/frontend/src/components/admin/testManagementConfigMenu/PanelTestAssign.js new file mode 100644 index 0000000000..a9fde3b1d9 --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/PanelTestAssign.js @@ -0,0 +1,99 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Form, + Heading, + Button, + Loading, + Grid, + Column, + Section, + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableSelectRow, + TableSelectAll, + TableContainer, + Pagination, + Search, + Select, + SelectItem, + Stack, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServer, + postToOpenElisServerFormData, + postToOpenElisServerFullResponse, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import CustomCheckBox from "../../common/CustomCheckBox.js"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.panel.manage", + link: "/MasterListsPage#SampleTypeManagement", + }, + { + label: "configuration.panel.assign", + link: "/MasterListsPage#PanelTestAssign", + }, +]; + +function PanelTestAssign() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + + return ( + <> + {notificationVisible === true ? : ""} +
+ + + +
+ + + +
+
+
+
+
+
+ + +
+ + + +
+
+
+
+ + ); +} + +export default injectIntl(PanelTestAssign); diff --git a/frontend/src/components/admin/testManagementConfigMenu/ResultSelectListAdd.js b/frontend/src/components/admin/testManagementConfigMenu/ResultSelectListAdd.js new file mode 100644 index 0000000000..5eb60758f4 --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/ResultSelectListAdd.js @@ -0,0 +1,83 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Form, + Heading, + Button, + Loading, + Grid, + Column, + Section, + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableSelectRow, + TableSelectAll, + TableContainer, + Pagination, + Search, + Select, + SelectItem, + Stack, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServer, + postToOpenElisServerFormData, + postToOpenElisServerFullResponse, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import CustomCheckBox from "../../common/CustomCheckBox.js"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "label.resultSelectList", + link: "/MasterListsPage#ResultSelectListAdd", + }, +]; + +function ResultSelectListAdd() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + + return ( + <> + {notificationVisible === true ? : ""} +
+ + + +
+ + + +
+
+
+
+ + ); +} + +export default injectIntl(ResultSelectListAdd); diff --git a/frontend/src/components/admin/testManagementConfigMenu/SampleTypeCreate.js b/frontend/src/components/admin/testManagementConfigMenu/SampleTypeCreate.js new file mode 100644 index 0000000000..cf92594c46 --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/SampleTypeCreate.js @@ -0,0 +1,101 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Form, + Heading, + Button, + Loading, + Grid, + Column, + Section, + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableSelectRow, + TableSelectAll, + TableContainer, + Pagination, + Search, + Select, + SelectItem, + Stack, + UnorderedList, + ListItem, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServer, + postToOpenElisServerFormData, + postToOpenElisServerFullResponse, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import CustomCheckBox from "../../common/CustomCheckBox.js"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.sampleType.manage", + link: "/MasterListsPage#SampleTypeManagement", + }, + { + label: "configuration.sampleType.create", + link: "/MasterListsPage#SampleTypeCreate", + }, +]; + +function SampleTypeCreate() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + + return ( + <> + {notificationVisible === true ? : ""} +
+ + + +
+ + + +
+
+
+
+
+
+ + +
+ + + +
+
+
+
+ + ); +} + +export default injectIntl(SampleTypeCreate); diff --git a/frontend/src/components/admin/testManagementConfigMenu/SampleTypeManagement.js b/frontend/src/components/admin/testManagementConfigMenu/SampleTypeManagement.js new file mode 100644 index 0000000000..687f9dfeab --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/SampleTypeManagement.js @@ -0,0 +1,119 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Form, + Heading, + Button, + Loading, + Grid, + Column, + Section, + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableSelectRow, + TableSelectAll, + TableContainer, + Pagination, + Search, + Select, + SelectItem, + Stack, + UnorderedList, + ListItem, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServer, + postToOpenElisServerFormData, + postToOpenElisServerFullResponse, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import CustomCheckBox from "../../common/CustomCheckBox.js"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.sampleType.manage", + link: "/MasterListsPage#SampleTypeManagement", + }, +]; + +function TestSectionManagement() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + + return ( + <> + {notificationVisible === true ? : ""} +
+ + + +
+ + + +
+
+
+
+
+
+ + + + { + window.location.assign("/MasterListsPage#SampleTypeCreate"); + }} + > + + +
+ { + window.location.assign("/MasterListsPage#SampleTypeOrder"); + }} + > + + +
+ { + window.location.assign( + "/MasterListsPage#SampleTypeTestAssign", + ); + }} + > + + +
+
+
+
+ + ); +} + +export default injectIntl(TestSectionManagement); diff --git a/frontend/src/components/admin/testManagementConfigMenu/SampleTypeOrder.js b/frontend/src/components/admin/testManagementConfigMenu/SampleTypeOrder.js new file mode 100644 index 0000000000..8cdad7e0c3 --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/SampleTypeOrder.js @@ -0,0 +1,101 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Form, + Heading, + Button, + Loading, + Grid, + Column, + Section, + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableSelectRow, + TableSelectAll, + TableContainer, + Pagination, + Search, + Select, + SelectItem, + Stack, + UnorderedList, + ListItem, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServer, + postToOpenElisServerFormData, + postToOpenElisServerFullResponse, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import CustomCheckBox from "../../common/CustomCheckBox.js"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.sampleType.manage", + link: "/MasterListsPage#SampleTypeManagement", + }, + { + label: "configuration.sampleType.order", + link: "/MasterListsPage#SampleTypeOrder", + }, +]; + +function SampleTypeOrder() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + + return ( + <> + {notificationVisible === true ? : ""} +
+ + + +
+ + + +
+
+
+
+
+
+ + +
+ + + +
+
+
+
+ + ); +} + +export default injectIntl(SampleTypeOrder); diff --git a/frontend/src/components/admin/testManagementConfigMenu/SampleTypeRenameEntry.js b/frontend/src/components/admin/testManagementConfigMenu/SampleTypeRenameEntry.js new file mode 100644 index 0000000000..07cab97886 --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/SampleTypeRenameEntry.js @@ -0,0 +1,238 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { Heading, Button, Grid, Column, Section } from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import RenameModelBox from "./renameModel/RenameModelBox.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.type.rename", + link: "/MasterListsPage#SampleTypeRenameEntry", + }, +]; + +function SampleTypeRenameEntry() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + const modalHeading = intl.formatMessage({ id: "field.sampleType" }); + + const [isLoading, setIsLoading] = useState(false); + const [finished, setFinished] = useState(true); + const [isAddModalOpen, setIsAddModalOpen] = useState(false); + const [confirmationStep, setConfirmationStep] = useState(false); + const [inputError, setInputError] = useState(false); + const [sampleType, setSampleType] = useState({}); + const [sampleTypeListShow, setSampleTypeListShow] = useState([]); + const [sampleTypePost, setSampleTypePost] = useState({}); + const [entityNamesProvider, setEntityNamesProvider] = useState({ name : { english: "", french: "" } }); + const [entityNamesProviderPost, setEntityNamesProviderPost] = useState({ name: { + english: "", french: "" + }}); + const [entityId, setEntityId] = useState(); + const [entityName, setEntityName] = useState("sampleType"); + const [selectedItem, setSelectedItem] = useState({}); + + useEffect(() => { + componentMounted.current = true; + getFromOpenElisServer( + "/rest/SampleTypeRenameEntry", + handelSampleTypeRename, + ); + return () => { + componentMounted.current = false; + }; + }, []); + + const handelSampleTypeRename = (res) => { + if (!res) { + setIsLoading(true); + } else { + setSampleType(res); + setSampleTypePost(res); + setSampleTypeListShow(res.sampleTypeList); + } + }; + + useEffect(() => { + if(entityId && entityName) { + getFromOpenElisServer( + `/rest/EntityNamesProvider?entityId=${entityId}&entityName=${entityName}`, + handelEntityNamesProvider, + ); + } + }, [entityId,entityName]); + + const handelEntityNamesProvider = (res) => { + if (!res) { + setIsLoading(true); + } else { + setEntityNamesProvider(res); + setEntityNamesProviderPost(res); + } + }; + + function sampleTypeUpdatePost() { + setIsLoading(true); + if (confirmationStep) { + postToOpenElisServerJsonResponse( + `/rest/SampleTypeRenameEntry`, + JSON.stringify(sampleTypePost), + (res) => { + sampleTypeUpdatePostCallback(res); + }, + ); + } else { + setConfirmationStep(true); + } + } + + function sampleTypeUpdatePostCallback(res) { + if (res) { + setIsLoading(false); + setFinished(false); + addNotification({ + title: intl.formatMessage({ + id: "notification.title", + }), + message: intl.formatMessage({ + id: "notification.user.post.save.success", + }), + kind: NotificationKinds.success, + }); + setNotificationVisible(true); + setIsAddModalOpen(false); + } else { + addNotification({ + kind: NotificationKinds.error, + title: intl.formatMessage({ id: "notification.title" }), + message: intl.formatMessage({ id: "server.error.msg" }), + }); + setNotificationVisible(true); + setTimeout(() => { + window.location.reload(); + }, 200); + } + } + + const openAppModle = (item) => { + setConfirmationStep(false); + setIsAddModalOpen(true); + setEntityId(item.id); + // setEntityName(test.value); + setSelectedItem(item); + }; + + const onInputChangeEn = (e) => { + const englishName = e.target.value; + setEntityNamesProviderPost((prev) => ({ + name: { + ...prev.name, + english: englishName, + }, + })); + setInputError(false); + }; + + const onInputChangeFr = (e) => { + const frenchName = e.target.value; + setEntityNamesProviderPost((prev) => ({ + name: { + ...prev.name, + french: frenchName, + }, + })); + setInputError(false); + }; + + useEffect(() => { + if (entityId && entityNamesProviderPost && entityNamesProviderPost.name) { + setSampleTypePost((prev) => ({ + ...prev, + sampleTypeId: entityId, + nameEnglish: entityNamesProviderPost.name.english, + nameFrench: entityNamesProviderPost.name.french, + })); + } + }, [entityNamesProviderPost, entityId]); + + const closeAddModal = () => { + setIsAddModalOpen(false); + }; + + return ( + <> + {notificationVisible === true ? : ""} +
+ +
+ + +
+ + + +
+
+
+
+
+
+ + + + + +
+ +
+
+ + ); +} + +export default injectIntl(SampleTypeRenameEntry); diff --git a/frontend/src/components/admin/testManagementConfigMenu/SampleTypeTestAssign.js b/frontend/src/components/admin/testManagementConfigMenu/SampleTypeTestAssign.js new file mode 100644 index 0000000000..ce67990db5 --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/SampleTypeTestAssign.js @@ -0,0 +1,99 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Form, + Heading, + Button, + Loading, + Grid, + Column, + Section, + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableSelectRow, + TableSelectAll, + TableContainer, + Pagination, + Search, + Select, + SelectItem, + Stack, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServer, + postToOpenElisServerFormData, + postToOpenElisServerFullResponse, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import CustomCheckBox from "../../common/CustomCheckBox.js"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.sampleType.manage", + link: "/MasterListsPage#SampleTypeManagement", + }, + { + label: "configuration.panel.assign", + link: "/MasterListsPage#SampleTypeTestAssign", + }, +]; + +function SampleTypeTestAssign() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + + return ( + <> + {notificationVisible === true ? : ""} +
+ + + +
+ + + +
+
+
+
+
+
+ + +
+ + + +
+
+
+
+ + ); +} + +export default injectIntl(SampleTypeTestAssign); diff --git a/frontend/src/components/admin/testManagementConfigMenu/SelectListRenameEntry.js b/frontend/src/components/admin/testManagementConfigMenu/SelectListRenameEntry.js new file mode 100644 index 0000000000..cf9471d4de --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/SelectListRenameEntry.js @@ -0,0 +1,368 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Heading, + Button, + Grid, + Column, + Section, + Loading, + Modal, + TextInput, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.selectList.rename", + link: "/MasterListsPage#SelectListRenameEntry", + }, +]; + +function SelectListRenameEntry() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + const modalHeading = intl.formatMessage({ + id: "selectListRenameEntry.selectListEdit", + }); + + const [isLoading, setIsLoading] = useState(false); + const [finished, setFinished] = useState(true); + const [isAddModalOpen, setIsAddModalOpen] = useState(false); + const [confirmationStep, setConfirmationStep] = useState(false); + const [inputError, setInputError] = useState(false); + const [selectListRename, setSelectListRename] = useState({}); + const [selectListRenameListShow, setSelectListRenameListShow] = useState([]); + const [displayValueList, setDisplayValueList] = useState([]); + const [selectListRenamePost, setSelectListRenamePost] = useState({}); + const [selectedItem, setSelectedItem] = useState({}); + const [selectedItemChange, setSelectedItemChange] = useState({}); + + useEffect(() => { + componentMounted.current = true; + getFromOpenElisServer( + "/rest/SelectListRenameEntry", + handleSelectListRename, + ); + return () => { + componentMounted.current = false; + }; + }, []); + + const handleSelectListRename = (res) => { + if (!res) { + setIsLoading(true); + } else { + setSelectListRename(res); + setSelectListRenamePost(res); + setSelectListRenameListShow(res.resultSelectOptionList); + } + }; + + function selectListRenameUpdatePost() { + setIsLoading(true); + if (confirmationStep) { + postToOpenElisServerJsonResponse( + `/rest/SelectListRenameEntry`, + JSON.stringify(selectListRenamePost), + (res) => { + selectListRenameUpdatePostCallback(res); + }, + ); + } else { + setConfirmationStep(true); + } + } + + function selectListRenameUpdatePostCallback(res) { + if (res) { + setIsLoading(false); + setFinished(false); + addNotification({ + title: intl.formatMessage({ + id: "notification.title", + }), + message: intl.formatMessage({ + id: "notification.user.post.save.success", + }), + kind: NotificationKinds.success, + }); + setNotificationVisible(true); + setIsAddModalOpen(false); + } else { + addNotification({ + kind: NotificationKinds.error, + title: intl.formatMessage({ id: "notification.title" }), + message: intl.formatMessage({ id: "server.error.msg" }), + }); + setNotificationVisible(true); + setTimeout(() => { + window.location.reload(); + }, 200); + } + } + + const openAppModle = (item) => { + setConfirmationStep(false); + setIsAddModalOpen(true); + setSelectedItem(item); + setSelectedItemChange(item); + }; + + const onInputChangeEn = (e, index) => { + const updatedValue = e.target.value; + setDisplayValueList((prevList) => + prevList.map((item, i) => + i === index ? { ...item, displayValueEnglish: updatedValue } : item, + ), + ); + // setSelectedItem((prev) => ({ ...prev, displayValueEnglish: updatedValue })); + setSelectedItemChange((prev) => ({ + ...prev, + displayValueEnglish: updatedValue, + })); + setInputError(false); + }; + + const onInputChangeFr = (e, index) => { + const updatedValue = e.target.value; + setDisplayValueList((prevList) => + prevList.map((item, i) => + i === index ? { ...item, displayValueFrench: updatedValue } : item, + ), + ); + // setSelectedItem((prev) => ({ ...prev, displayValueFrench: updatedValue })); + setSelectedItemChange((prev) => ({ + ...prev, + displayValueFrench: updatedValue, + })); + setInputError(false); + }; + + useEffect(() => { + if (selectedItemChange) { + setSelectListRenamePost((prev) => ({ + ...prev, + resultSelectOptionId: selectedItemChange.id, + nameEnglish: selectedItemChange.displayValueEnglish, + nameFrench: selectedItemChange.displayValueFrench, + })); + } + }, [selectedItemChange]); + + const closeAddModal = () => { + setIsAddModalOpen(false); + }; + + useEffect(() => { + if (selectListRenameListShow && selectListRenameListShow.length > 0) { + const extractedValues = selectListRenameListShow.map((item) => ({ + id: item.id, + displayValueEnglish: item.displayValue, + displayValueFrench: item.displayValue, + })); + setDisplayValueList(extractedValues); + } + }, [selectListRenameListShow]); + + return ( + <> + {notificationVisible === true ? : ""} +
+ +
+ + +
+ + + +
+
+
+
+
+
+ + + + + +
+ {displayValueList ? ( + + {displayValueList.map((valueItem, index) => ( + + + + + ) : ( + <> + + + ) + } + secondaryButtonText={ + confirmationStep ? ( + <> + + + ) : ( + <> + + + ) + } + onRequestSubmit={selectListRenameUpdatePost} + onRequestClose={closeAddModal} + > + {displayValueList && + valueItem && + valueItem.id && + valueItem.displayValueEnglish && + valueItem.displayValueFrench ? ( + + +
+
+ + + +
+
+
+
+
+
+ + + +
+
+
+
+ <> + :{" "} + {selectedItem.displayValueEnglish} + +
+
+ { + onInputChangeEn(e, index); + }} + required + invalid={inputError} + invalidText={ + + } + /> +
+ <> + :{" "} + {selectedItem.displayValueFrench} + +
+
+ { + onInputChangeFr(e, index); + }} + required + invalid={inputError} + invalidText={ + + } + /> +
+
+ ) : ( + <> +
+ +
+ + )} +
+ {confirmationStep && ( + <> +
+
+
+ + + +
+
+
+ + )} +
+ +
+ ))} +
+ ) : ( + <> + + + )} +
+
+ + ); +} + +export default injectIntl(SelectListRenameEntry); diff --git a/frontend/src/components/admin/testManagementConfigMenu/TestActivation.js b/frontend/src/components/admin/testManagementConfigMenu/TestActivation.js new file mode 100644 index 0000000000..856503022e --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/TestActivation.js @@ -0,0 +1,101 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Form, + Heading, + Button, + Loading, + Grid, + Column, + Section, + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableSelectRow, + TableSelectAll, + TableContainer, + Pagination, + Search, + Select, + SelectItem, + Stack, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServer, + postToOpenElisServerFormData, + postToOpenElisServerFullResponse, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import CustomCheckBox from "../../common/CustomCheckBox.js"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.testUnit.manage", + link: "/MasterListsPage#TestSectionManagement", + }, + { + label: "configuration.testUnit.create", + link: "/MasterListsPage#TestActivation", + }, +]; + +function TestActivation() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + + return ( + <> + {notificationVisible === true ? : ""} +
+ + + +
+ + + +
+
+
+
+
+
+ + +
+
+ + + +
+
+
+
+
+ + ); +} + +export default injectIntl(TestActivation); diff --git a/frontend/src/components/admin/testManagementConfigMenu/TestAdd.js b/frontend/src/components/admin/testManagementConfigMenu/TestAdd.js new file mode 100644 index 0000000000..6bfdcb4ff0 --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/TestAdd.js @@ -0,0 +1,1636 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Form, + Heading, + Button, + Loading, + Grid, + Column, + Section, + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableSelectRow, + TableSelectAll, + TableContainer, + Pagination, + Search, + Select, + SelectItem, + Stack, + TextInput, + Checkbox, + Row, + FlexGrid, + Tag, + UnorderedList, + ListItem, + NumberInput, + RadioButtonGroup, + RadioButton, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServer, + postToOpenElisServerFormData, + postToOpenElisServerFullResponse, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import CustomCheckBox from "../../common/CustomCheckBox.js"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; +import { id } from "date-fns/locale"; +import { value } from "jsonpath"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.test.add", + link: "/MasterListsPage#TestAdd", + }, +]; + +function TestAdd() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + const [isLoading, setIsLoading] = useState(false); + const [lonic, setLonic] = useState(""); + const [testAdd, setTestAdd] = useState({}); + const [ageRangeList, setAgeRangeList] = useState([]); + const [gotSelectedAgeRangeList, setGotSelectedAgeRangeList] = useState([]); + const [labUnitList, setLabUnitList] = useState([]); + const [selectedLabUnitList, setSelectedLabUnitList] = useState({}); + const [panelList, setPanelList] = useState([]); + const [panelListTag, setPanelListTag] = useState([]); + const [uomList, setUomList] = useState([]); + const [selectedUomList, setSelectedUomList] = useState({}); + const [resultTypeList, setResultTypeList] = useState([]); + const [selectedResultTypeList, setSelectedResultTypeList] = useState({}); + const [sampleTypeList, setSampleTypeList] = useState([]); + const [selectedSampleTypeList, setSelectedSampleTypeList] = useState([]); + const [sampleTestTypeToGetTagList, setSampleTestTypeToGetTagList] = useState( + [], + ); + const [selectedSampleType, setSelectedSampleType] = useState([]); + const [selectedSampleTypeResp, setSelectedSampleTypeResp] = useState([]); + const [groupedDictionaryList, setGroupedDictionaryList] = useState([]); + const [selectedGroupedDictionaryList, setSelectedGroupedDictionaryList] = + useState([]); + const [dictionaryList, setDictionaryList] = useState([]); + const [dictionaryListTag, setDictionaryListTag] = useState([]); + const [singleSelectDictionaryList, setSingleSelectDictionaryList] = useState( + [], + ); + const [multiSelectDictionaryList, setMultiSelectDictionaryList] = useState([ + { id: "0", value: "Multiple" }, + ]); + const [multiSelectDictionaryListTag, setMultiSelectDictionaryListTag] = + useState([]); + const [sampleTypeSetupPage, setSampleTypeSetupPage] = useState(true); + const [rangeSetupPage, setRangeSetupPage] = useState(true); + const [onResultType, setOnResultType] = useState(true); + const [existingTestSetupPage, setExistingTestSetupPage] = useState(true); + const [finalSaveConfirmation, setFinalSaveConfirmation] = useState(true); + const [jsonWad, setJsonWad] = useState( + // { + // testNameEnglish: "aasdf", + // testNameFrench: "asdf", + // testReportNameEnglish: "aasdf", + // testReportNameFrench: "asdf", + // testSection: "56", + // panels: [{ id: "1" }, { id: "2" }], + // uom: "1", + // loinc: "asdf", + // resultType: "4", + // orderable: "Y", + // notifyResults: "Y", + // inLabOnly: "Y", + // antimicrobialResistance: "Y", + // active: "Y", + // sampleTypes: + // '[{"typeId": "31", "tests": [{"id": 301}, {"id": 0}]}, {"typeId": "3", "tests": [{"id": 306}, {"id": 304}, {"id": 308}, {"id": 319}, {"id": 317}, {"id": 311}, {"id": 314}, {"id": 3}, {"id": 32}, {"id": 40}, {"id": 41}, {"id": 56}, {"id": 47}, {"id": 49}, {"id": 51}, {"id": 0}]}]', + // lowValid: "-Infinity", + // highValid: "Infinity", + // lowReportingRange: "-Infinity", + // highReportingRange: "Infinity", + // lowCritical: "-Infinity", + // highCritical: "-Infinity", + // significantDigits: "", + // resultLimits: + // '[{"highAgeRange": "30", "gender": false, "lowNormal": "-Infinity", "highNormal": "Infinity"}, {"highAgeRange": "365", "gender": false, "lowNormal": "-Infinity", "highNormal": "Infinity"}, {"highAgeRange": "1825", "gender": false, "lowNormal": "-Infinity", "highNormal": "Infinity"}, {"highAgeRange": "5110", "gender": false, "lowNormal": "-Infinity", "highNormal": "Infinity"}, {"highAgeRange": "Infinity", "gender": false, "lowNormal": "-Infinity", "highNormal": "Infinity"}]', + // dictionary: + // '[{"value": "824", "qualified": "N"}, {"value": "826", "qualified": "N"}, {"value": "825", "qualified": "N"}, {"value": "822", "qualified": "N"}, {"value": "829", "qualified": "N"}, {"value": "821", "qualified": "N"}]', + // dictionaryReference: "824", + // defaultTestResult: "825", + // }, + { + testNameEnglish: "", + testNameFrench: "", + testReportNameEnglish: "", + testReportNameFrench: "", + testSection: "", + panels: [], + uom: "", + loinc: "", + resultType: "", + orderable: "Y", + notifyResults: "", + inLabOnly: "", + antimicrobialResistance: "", + active: "Y", + sampleTypes: [], + lowValid: "", + highValid: "", + lowReportingRange: "", + highReportingRange: "", + lowCritical: "", + highCritical: "", + significantDigits: "", + resultLimits: + '[{"highAgeRange": "30", "gender": false, "lowNormal": "-Infinity", "highNormal": "Infinity"}, {"highAgeRange": "365", "gender": false, "lowNormal": "-Infinity", "highNormal": "Infinity"}, {"highAgeRange": "1825", "gender": false, "lowNormal": "-Infinity", "highNormal": "Infinity"}, {"highAgeRange": "5110", "gender": false, "lowNormal": "-Infinity", "highNormal": "Infinity"}, {"highAgeRange": "Infinity", "gender": false, "lowNormal": "-Infinity", "highNormal": "Infinity"}]', + }, + ); + + useEffect(() => { + componentMounted.current = true; + setIsLoading(true); + getFromOpenElisServer(`/rest/TestAdd`, (res) => { + handleTestAddData(res); + }); + return () => { + componentMounted.current = false; + setIsLoading(false); + }; + }, []); + + function handleTestAddData(res) { + if (!res) { + setIsLoading(true); + } else { + setTestAdd(res); + } + } + + useEffect(() => { + if (testAdd) { + setLabUnitList([{ id: "0", value: "" }, ...(testAdd.labUnitList || [])]); + setPanelList([ + { id: "0", value: "Select Multiple" }, + ...(testAdd.panelList || []), + ]); + setUomList([{ id: "0", value: "" }, ...(testAdd.uomList || [])]); + setResultTypeList([ + { id: "0", value: "" }, + ...(testAdd.resultTypeList || []), + ]); + setSampleTypeList([ + { id: "0", value: "Select Multiple" }, + ...(testAdd.sampleTypeList || []), + ]); + setGroupedDictionaryList([ + // { id: "0", value: "Select Multiple" }, + ...(testAdd.groupedDictionaryList || []), + ]); + setDictionaryList([ + { id: "0", value: "Select Multiple" }, + ...(testAdd.dictionaryList || []), + ]); + setAgeRangeList([ + { id: "0", value: "" }, + ...(testAdd.ageRangeList || []), + ]); + } + }, [testAdd]); + + useEffect(() => { + if (selectedSampleType.length === 0) return; + + const fetchSampleTypeData = async (id) => { + return new Promise((resolve, reject) => { + try { + getFromOpenElisServer( + `/rest/sample-type-tests?sampleType=${id}`, + (res) => { + if (res) { + handleSampleType(res); + resolve(res); + } else { + reject(new Error("No response received")); + } + }, + ); + } catch (error) { + console.error(`Error fetching data for sample type ${id}:`, error); + reject(error); + } + }); + }; + + const fetchAllSampleTypesData = async () => { + try { + await Promise.all( + selectedSampleType.map((sampleType) => + fetchSampleTypeData(sampleType.id), + ), + ); + } catch (error) { + console.error("Error fetching all sample types:", error); + } + }; + + fetchAllSampleTypesData(); + }, [selectedSampleType]); + + function handleSampleType(res) { + setSelectedSampleTypeResp((prev) => { + const selectedSampleTypeIds = selectedSampleType.map((type) => type.id); + + const isInSelectedSampleType = selectedSampleTypeIds.includes( + res.sampleTypeId, + ); + + if (isInSelectedSampleType) { + const isAlreadyPresent = prev.some( + (item) => item.sampleTypeId === res.sampleTypeId, + ); + if (!isAlreadyPresent) { + return [...prev, res]; + } + } else { + return prev.filter((item) => item.sampleTypeId !== res.sampleTypeId); + } + return prev; + }); + } + + function testNameEn(e) { + setJsonWad((prev) => ({ + ...prev, + testNameEnglish: e.target.value, + })); + } + + function testNameFr(e) { + setJsonWad((prev) => ({ + ...prev, + testNameFrench: e.target.value, + })); + } + + function reportingTestNameEn(e) { + setJsonWad((prev) => ({ + ...prev, + testReportNameEnglish: e.target.value, + })); + } + + function reportingTestNameFr(e) { + setJsonWad((prev) => ({ + ...prev, + testReportNameFrench: e.target.value, + })); + } + + function copyInputValuesFromTestNameEnFr() { + setJsonWad((prev) => ({ + ...prev, + testReportNameEnglish: prev.testNameEnglish, + testReportNameFrench: prev.testNameFrench, + })); + } + + function handelTestSectionSelect(e) { + setJsonWad((prev) => ({ + ...prev, + testSection: e.target.value, + })); + + const selectedLabUnitObject = labUnitList.find( + (item) => item.id === e.target.value, + ); + + if (selectedLabUnitObject) { + setSelectedLabUnitList(selectedLabUnitObject); + } + } + + function handelUomSelect(e) { + setJsonWad((prev) => ({ ...prev, uom: e.target.value })); + + const selectedUomObject = uomList.find( + (item) => item.id === e.target.value, + ); + + if (selectedUomObject) { + setSelectedUomList(selectedUomObject); + } + } + + function handelLonicChange(e) { + const regex = /^(?!-)(?:\d+-)*\d*$/; + + const value = e.target.value; + + if (regex.test(value)) { + setLonic(value); + setJsonWad((prev) => ({ ...prev, loinc: value })); + } else { + addNotification({ + title: intl.formatMessage({ + id: "notification.title", + }), + message: intl.formatMessage({ + id: "notification.user.post.save.success", + }), + kind: NotificationKinds.error, + }); + setNotificationVisible(true); + } + } + + function handelResultType(e) { + setJsonWad((prev) => ({ ...prev, resultType: e.target.value })); + + const selectedResultTypeObject = resultTypeList.find( + (item) => item.id == e.target.value, + ); + + if (selectedResultTypeObject) { + setSelectedResultTypeList(selectedResultTypeObject); + } + } + + function handleAntimicrobialResistance(e) { + setJsonWad((prev) => ({ + ...prev, + antimicrobialResistance: e.target.checked ? "Y" : "N", + })); + } + function handleIsActive(e) { + setJsonWad((prev) => ({ ...prev, active: e.target.checked ? "Y" : "N" })); + } + function handleOrderable(e) { + setJsonWad((prev) => ({ + ...prev, + orderable: e.target.checked ? "Y" : "N", + })); + } + function handleNotifyPatientofResults(e) { + setJsonWad((prev) => ({ + ...prev, + notifyResults: e.target.checked ? "Y" : "N", + })); + } + function handleInLabOnly(e) { + setJsonWad((prev) => ({ + ...prev, + inLabOnly: e.target.checked ? "Y" : "N", + })); + } + + function handleSampleTypeSetup() { + setSampleTypeSetupPage(true); + } + + function handleRangeSetup() { + setRangeSetupPage(true); + } + + function handleOnResultType() { + setOnResultType(true); + } + + function handleExistingTestSetup() { + setExistingTestSetupPage(true); + } + + function handleFinalSaveConfirmation() { + setFinalSaveConfirmation(true); + } + + const handelPanelSelectSetTag = (e) => { + const selectedId = e.target.value; + const selectedValue = e.target.options[e.target.selectedIndex].text; + + setPanelListTag((prevTags) => { + const isTagPresent = prevTags.some((tag) => tag.id === selectedId); + if (isTagPresent) return prevTags; + + const newTag = { id: selectedId, value: selectedValue }; + const updatedTags = [...prevTags, newTag]; + + const updatedPanels = [...updatedTags.map((tag) => ({ id: tag.id }))]; + setJsonWad((prevJsonWad) => ({ + ...prevJsonWad, + panels: updatedPanels, + })); + + return updatedTags; + }); + }; + + const handlePanelRemoveTag = (idToRemove) => { + setPanelListTag((prevTags) => { + const updatedTags = prevTags.filter((tag) => tag.id !== idToRemove); + + const updatedPanels = updatedTags.map((tag) => ({ id: tag.id })); + setJsonWad((prevJsonWad) => ({ + ...prevJsonWad, + panels: updatedPanels, + })); + + return updatedTags; + }); + }; + + // const handleSampleTypeListSelectIdTestTag = (e) => { + // const selectedTestId = e.target.value; + // const testName = e.target.options[e.target.selectedIndex].text; + + // const existingIndex = sampleTestTypeToGetTagList.findIndex( + // (item) => item.id === selectedTestId, + // ); + + // let updatedList; + // if (existingIndex !== -1) { + // updatedList = [...sampleTestTypeToGetTagList]; + // updatedList.splice(existingIndex, 1); + // setSampleTestTypeToGetTagList(updatedList); + // } else { + // const selectedTest = { + // id: selectedTestId, + // name: testName, + // }; + // updatedList = [...sampleTestTypeToGetTagList, selectedTest]; + // setSampleTestTypeToGetTagList(updatedList); + // } + + // const updatedReplace = updatedList.map((item) => item.id); + // setJsonWad((prevJsonWad) => ({ + // ...prevJsonWad, + // replace: updatedReplace, + // })); + // }; + + const handleSampleTypeListSelectIdTestTag = (e) => { + const selectedId = e.target.value; + const selectedSampleTypeObject = sampleTypeList.find( + (type) => type.id === selectedId, + ); + + if (selectedSampleTypeObject) { + const isAlreadySelected = selectedSampleType.some( + (type) => type.id === selectedSampleTypeObject.id, + ); + + if (!isAlreadySelected) { + setSelectedSampleTypeList([ + ...selectedSampleTypeList, + selectedSampleTypeObject, + ]); + + setSampleTestTypeToGetTagList([ + ...sampleTestTypeToGetTagList, + selectedSampleTypeObject, + ]); + + setSelectedSampleType((prev) => [...prev, selectedSampleTypeObject]); + } + } + }; + + function handleRemoveSampleTypeListSelectIdTestTag(indexToRemove) { + setSampleTestTypeToGetTagList((prevTags) => { + const updatedTags = prevTags.filter( + (_, index) => index !== indexToRemove, + ); + + const updatedReplace = updatedTags.map((item) => item.id); + setJsonWad((prevJsonWad) => ({ + ...prevJsonWad, + replace: updatedReplace, + })); + + return updatedTags; + }); + + setSelectedSampleTypeList((prevList) => { + const updatedList = prevList.filter( + (_, index) => index !== indexToRemove, + ); + return updatedList; + }); + + setSelectedSampleType((prevList) => { + const updatedList = prevList.filter( + (_, index) => index !== indexToRemove, + ); + return updatedList; + }); + + setSelectedSampleTypeResp((prevState) => + prevState.filter((_, index) => index !== indexToRemove), + ); + } + + function testAddPostCall() { + setIsLoading(true); + postToOpenElisServerJsonResponse( + `/rest/TestAdd`, + JSON.stringify(jsonWad), + (res) => { + testAddPostCallback(res); + }, + ); + } + + function testAddPostCallback(res) { + if (res) { + setIsLoading(false); + addNotification({ + title: intl.formatMessage({ + id: "notification.title", + }), + message: intl.formatMessage({ + id: "notification.user.post.save.success", + }), + kind: NotificationKinds.success, + }); + setNotificationVisible(true); + setTimeout(() => { + window.location.reload(); + }, 200); + } else { + addNotification({ + kind: NotificationKinds.error, + title: intl.formatMessage({ id: "notification.title" }), + message: intl.formatMessage({ id: "server.error.msg" }), + }); + setNotificationVisible(true); + setTimeout(() => { + window.location.reload(); + }, 200); + } + } + + const handelSelectListOptions = (e) => { + const selectedId = e.target.value; + + const selectedObject = dictionaryList.find( + (item) => item.id === selectedId, + ); + + if (selectedObject) { + setSingleSelectDictionaryList((prev) => [...prev, selectedObject]); + setMultiSelectDictionaryList((prev) => [...prev, selectedObject]); + + setDictionaryListTag((prev) => [...prev, selectedObject]); + } + + //set the data object in jsonWad + }; + + const handleSelectQualifiersTag = (e) => { + const selectedId = e.target.value; + + const selectedObject = multiSelectDictionaryList.find( + (item) => item.id === selectedId, + ); + + if (selectedObject) { + setMultiSelectDictionaryListTag((prev) => [...prev, selectedObject]); + } + + //set the data object in jsonWad + }; + + const handleLabUnitSelect = (e) => { + const selectedLabUnitId = e.target.value; + + setJsonWad((prev) => ({ ...prev, testSection: selectedLabUnitId })); + }; + + if (!isLoading) { + return ( + <> + + + ); + } + + return ( + <> + {notificationVisible === true ? : ""} +
+ +
+ + +
+ + + +
+
+
+
+
+
+ + +
+ <> + + * + +
+ +
+
+
+ <> + + * + +
+
+ +
+ +
+ +
+ +
+
+
+ <> + + * + +
+
+ +
+
+ +
+ +
+ +
+ +
+
+ + + +
+ {panelListTag && panelListTag.length ? ( +
+ <> + {panelListTag.map((panel) => ( + handlePanelRemoveTag(panel.id)} + style={{ marginRight: "0.5rem" }} + type={"green"} + > + {panel.value} + + ))} + +
+ ) : ( + <> + )} +
+ + +
+ +
+ <> + + * + +
+ +
+
+
+ +
+ { + handelLonicChange(e); + }} + /> +
+
+
+ + } + id="antimicrobial-resistance" + onChange={handleAntimicrobialResistance} + checked={jsonWad?.antimicrobialResistance === "Y"} + /> + + } + id="is-active" + onChange={handleIsActive} + checked={jsonWad?.active === "Y"} + /> + } + id="orderable" + onChange={handleOrderable} + checked={jsonWad?.orderable === "Y"} + /> + } + id="notify-patient-of-results" + onChange={handleNotifyPatientofResults} + checked={jsonWad?.notifyResults === "Y"} + /> + } + id="in-lab-only" + onChange={handleInLabOnly} + checked={jsonWad?.inLabOnly === "Y"} + /> +
+
+
+
+ + {" "} + + +
+
+
+
+ {sampleTypeSetupPage ? ( + <> + + + +
+ +
+ {sampleTestTypeToGetTagList && + sampleTestTypeToGetTagList.length ? ( +
+ <> + {sampleTestTypeToGetTagList.map((section, index) => ( + + handleRemoveSampleTypeListSelectIdTestTag(index) + } + style={{ marginRight: "0.5rem" }} + type={"green"} + > + {section.value} + + ))} + +
+ ) : ( + <> + )} +
+
+ +
+
+
+ + + +
+
+
+
+ {selectedSampleTypeResp.length > 0 ? ( + selectedSampleTypeResp.map((item, index) => ( + <> +
+
+ + {item.tests.map((test) => ( + {test.name} + ))} + +
+
+
+ + )) + ) : ( + <> + )} +
+
+
+ + {" "} + + +
+
+
+
+ + ) : ( + <> + )} + {onResultType ? ( + <> + + + + {/* map the Select list options */} +
+ + {/* tags need to display */} +
+ {/* need to add tags */} + {dictionaryListTag && dictionaryListTag.length ? ( +
+ <> + {dictionaryListTag.map((dict, index) => ( + + // handleRemoveSampleTypeListSelectIdTestTag(index) + // } + style={{ marginRight: "0.5rem" }} + type={"green"} + > + {dict.value} + + ))} + +
+ ) : ( + <> + )} +
+
+ +
+
+
+ + + +
+
+
+ {/* remeder dragable & Select list options */} +
+
+ +
+ {/* single Select */} + +
+
+ +
+ {/* single Select */} + +
+
+ +
+ +
+ {/* need to add tags */} + {multiSelectDictionaryListTag && + multiSelectDictionaryListTag.length ? ( +
+ <> + {multiSelectDictionaryListTag.map((dict, index) => ( + + // handleRemoveSampleTypeListSelectIdTestTag(index) + // } + style={{ marginRight: "0.5rem" }} + type={"green"} + > + {dict.value} + + ))} + +
+ ) : ( + <> + )} +
+
+
+
+ + {" "} + + +
+
+
+
+ + ) : ( + <> + )} + {rangeSetupPage ? ( + <> + + +
+
+
+ + + +
+
+
+
+
+
+
+
+ + + +
+
+ } + // onChange={() => {}} + /> + {/* render male & female on checkbox*/} + + + + + + + +
+
+
+
+ + +
+
+ + + {/* render two extra fields for TextInput on Click of Check box */} +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+
+ + + +
+
+
+ + + {" : "} + +
+
+
+
+ + + +
+
+
+ + + {" "} + + + +
+
+
+ + ) : ( + <> + )} + {existingTestSetupPage ? ( + <> + + +
+
+
+ + + +
+
+
+
+
+
+
+
+ + {groupedDictionaryList.map((innerArray, outerIndex) => ( + <> + { + setSelectedGroupedDictionaryList([ + ...selectedGroupedDictionaryList, + innerArray, + ]); + }} + > +
+ + {innerArray.map((item) => ( + + {item.value} + + ))} + {/* need to fix console log here */} + +
+
+
+ + ))} +
+
+ + + {" "} + + + +
+
+
+ + ) : ( + <> + )} + {finalSaveConfirmation ? ( + <> + + + +
+ + {" : "} + {jsonWad?.testNameEnglish} +
+ + {" : "} + {jsonWad?.testNameFrench} +
+
+ +
+ + {" : "} + {jsonWad?.reportingTestNameEn} +
+ + {" : "} + {jsonWad?.reportingTestNameFr} +
+
+ + {" : "} + {selectedLabUnitList?.value} +
+
+ + {" : "} + {/* map the {panelList[0].value} in and there values in line*/} + {panelListTag.length > 0 ? ( + + {panelListTag.map((tag) => ( +
+ {tag.value} +
+ ))} +
+ ) : ( + <> + )} +
+
+ + {" : "} + {selectedUomList?.value} +
+
+ + {" : "} + {jsonWad?.loinc} +
+
+ + {" : "} + {selectedResultTypeList.value} +
+
+ + {" : "} + {jsonWad?.antimicrobialResistance} +
+
+ + {" : "} + {jsonWad?.active} +
+
+ + {" : "} + {jsonWad?.orderable} +
+
+ + {" : "} + {jsonWad?.notifyResults} +
+
+ + {" : "} + {jsonWad?.inLabOnly} +
+
+ + + {/* Mapp the combbination of the selecte[sampleType] & tests of [sampleType] in sorted order */} +
+ {selectedSampleTypeList.length > 0 ? ( + + {selectedSampleTypeList.map((type, index) => ( +
+ {type.value} +
+ {selectedSampleTypeResp + .filter((resp) => resp.sampleTypeId === type.id) + .map((item, respIndex) => ( +
+
+ + {item.tests.map((test) => ( + + {test.name} + + ))} + +
+
+ ))} +
+ ))} +
+ ) : ( + <> + )} +
+
+
+
+
+ + ) : ( + <> + )} + + + {" "} + + + + + + + + +
+
+ + ); +} + +export default injectIntl(TestAdd); diff --git a/frontend/src/components/admin/testManagementConfigMenu/TestManagementConfigMenu.js b/frontend/src/components/admin/testManagementConfigMenu/TestManagementConfigMenu.js new file mode 100644 index 0000000000..d7f8ff04ab --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/TestManagementConfigMenu.js @@ -0,0 +1,416 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Form, + Heading, + Button, + Loading, + Grid, + Column, + Section, + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableSelectRow, + TableSelectAll, + TableContainer, + Pagination, + Search, + Select, + SelectItem, + Stack, + UnorderedList, + ListItem, + ClickableTile, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServer, + postToOpenElisServerFormData, + postToOpenElisServerFullResponse, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import CustomCheckBox from "../../common/CustomCheckBox.js"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, +]; + +function TestManagementConfigMenu() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + + return ( + <> + {notificationVisible === true ? : ""} +
+ + + +
+ + + +
+
+
+
+
+ + +
+
+
+ + + +
+
+
+
+
+
+
+
+ + + + + { + window.location.assign("/admin#TestRenameEntry"); + }} + > + + + + + + + + +
+ + { + window.location.assign("/admin#PanelRenameEntry"); + }} + > + + + + + + + + +
+ + { + window.location.assign("/admin#SampleTypeRenameEntry"); + }} + > + + + + + + + + +
+ + { + window.location.assign("/admin#TestSectionRenameEntry"); + }} + > + + + + + + + + +
+ + { + window.location.assign("/admin#UomRenameEntry"); + }} + > + + + + + + + + +
+ + { + window.location.assign("/admin#SelectListRenameEntry"); + }} + > + + + + + + + + +
+ + { + window.location.assign("/admin#MethodRenameEntry"); + }} + > + + + + + + + + +
+
+
+
+
+
+ + +
+
+
+ + + +
+
+
+
+
+
+
+
+ + + + + { + window.location.assign("/admin#TestCatalog"); + }} + > + + + + + + + + +
+ + { + window.location.assign("/admin#MethodManagement"); + }} + > + + + + + + + + +
+ + { + window.location.assign("/api/OpenELIS-Global/TestAdd"); + }} + > + + + + + + + + +
+ + { + window.location.assign("/api/OpenELIS-Global/TestModifyEntry"); + }} + > + + + + + + + + +
+ + { + window.location.assign("/api/OpenELIS-Global/TestActivation"); + }} + > + + + + + + + + +
+ + { + window.location.assign("/api/OpenELIS-Global/TestOrderability"); + }} + > + + + + + + + + +
+ + { + window.location.assign("/api/OpenELIS-Global/TestSectionManagement"); + }} + > + + + + + + + + +
+ + { + window.location.assign("/api/OpenELIS-Global/SampleTypeManagement"); + }} + > + + + + + + + + +
+ + { + window.location.assign("/api/OpenELIS-Global/UomManagement"); + }} + > + + + + + + + + +
+ + { + window.location.assign("/api/OpenELIS-Global/PanelManagement"); + }} + > + + + + + + + + +
+ + { + window.location.assign("/api/OpenELIS-Global/ResultSelectListAdd"); + }} + > + + + + + + + + + + + +
+ + { + window.location.assign("/admin"); + }} + > + + + +
+
+
+
+
+
+
+
+ + ); +} + +export default injectIntl(TestManagementConfigMenu); diff --git a/frontend/src/components/admin/testManagementConfigMenu/TestModifyEntry.js b/frontend/src/components/admin/testManagementConfigMenu/TestModifyEntry.js new file mode 100644 index 0000000000..ae5c982df0 --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/TestModifyEntry.js @@ -0,0 +1,83 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Form, + Heading, + Button, + Loading, + Grid, + Column, + Section, + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableSelectRow, + TableSelectAll, + TableContainer, + Pagination, + Search, + Select, + SelectItem, + Stack, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServer, + postToOpenElisServerFormData, + postToOpenElisServerFullResponse, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import CustomCheckBox from "../../common/CustomCheckBox.js"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.test.modify", + link: "/MasterListsPage#TestModifyEntry", + }, +]; + +function TestModifyEntry() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + + return ( + <> + {notificationVisible === true ? : ""} +
+ + + +
+ + + +
+
+
+
+ + ); +} + +export default injectIntl(TestModifyEntry); diff --git a/frontend/src/components/admin/testManagementConfigMenu/TestOrderability.js b/frontend/src/components/admin/testManagementConfigMenu/TestOrderability.js new file mode 100644 index 0000000000..1e28c3d72b --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/TestOrderability.js @@ -0,0 +1,83 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Form, + Heading, + Button, + Loading, + Grid, + Column, + Section, + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableSelectRow, + TableSelectAll, + TableContainer, + Pagination, + Search, + Select, + SelectItem, + Stack, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServer, + postToOpenElisServerFormData, + postToOpenElisServerFullResponse, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import CustomCheckBox from "../../common/CustomCheckBox.js"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.test.orderable", + link: "/MasterListsPage#TestOrderability", + }, +]; + +function TestOrderability() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + + return ( + <> + {notificationVisible === true ? : ""} +
+ + + +
+ + + +
+
+
+
+ + ); +} + +export default injectIntl(TestOrderability); diff --git a/frontend/src/components/admin/testManagementConfigMenu/TestRenameEntry.js b/frontend/src/components/admin/testManagementConfigMenu/TestRenameEntry.js new file mode 100644 index 0000000000..c43a5d91ee --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/TestRenameEntry.js @@ -0,0 +1,394 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Heading, + Button, + Loading, + Grid, + Column, + Section, + Modal, + TextInput, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "label.testName", + link: "/MasterListsPage#TestRenameEntry", + }, +]; + +function TestRenameEntry() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + const [isLoading, setIsLoading] = useState(true); + const [finished, setFinished] = useState(true); + const [isAddModalOpen, setIsAddModalOpen] = useState(false); + const [confirmationStep, setConfirmationStep] = useState(false); + const [inputError, setInputError] = useState(false); + const [testNames, setTestNames] = useState({}); + const [testNamePost, setTestNamesPost] = useState({}); + const [testNamesShow, setTestNamesShow] = useState([]); + const [selectedTest, setSelectedTest] = useState({}); + const [testNamesLangs, setTestNamesLangs] = useState({ name: { english: "", french: "" }, reportingName: { english: "", french: "" }, }); + const [testNamesLangsPost, setTestNamesLangsPost] = useState({ name: { english: "", french: "" }, reportingName: { english: "", french: "" }, }); + + useEffect(() => { + componentMounted.current = true; + getFromOpenElisServer("/rest/TestRenameEntry", handleTestNames); + return () => { + componentMounted.current = false; + }; + }, []); + + const handleTestNames = (res) => { + if (!res) { + setIsLoading(true); + } else { + setTestNames(res); + setTestNamesPost(res); + setTestNamesShow(res?.testList); + } + }; + + useEffect(() => { + if (selectedTest && selectedTest.id) { + getFromOpenElisServer( + `/rest/TestNamesProvider?testId=${selectedTest?.id}`, + handleTestNamesLangs, + ); + } + }, [selectedTest]); + + const handleTestNamesLangs = (res) => { + if (!res) { + setIsLoading(true); + } else { + setTestNamesLangs(res); + setTestNamesLangsPost(res); + } + }; + + function testRenameEntryPost() { + setIsLoading(true); + if (confirmationStep) { + postToOpenElisServerJsonResponse( + `/rest/TestRenameEntry`, + JSON.stringify(testNamePost), + (res) => { + testRenameEntryPostCallback(res); + }, + ); + } else { + setConfirmationStep(true); + } + } + + function testRenameEntryPostCallback(res) { + if (res) { + setIsLoading(false); + setFinished(false); + addNotification({ + title: intl.formatMessage({ + id: "notification.title", + }), + message: intl.formatMessage({ + id: "notification.user.post.save.success", + }), + kind: NotificationKinds.success, + }); + setNotificationVisible(true); + setIsAddModalOpen(false); + } else { + addNotification({ + kind: NotificationKinds.error, + title: intl.formatMessage({ id: "notification.title" }), + message: intl.formatMessage({ id: "server.error.msg" }), + }); + setNotificationVisible(true); + setTimeout(() => { + window.location.reload(); + }, 200); + } + } + + const openAppModle = (test) => { + setConfirmationStep(false); + setIsAddModalOpen(true); + setSelectedTest(test); + }; + + useEffect(() => { + if (selectedTest && testNamesLangsPost && testNamesLangsPost.name) { + setTestNamesPost((prev) => ({ + ...prev, + testId: selectedTest?.id, + nameEnglish: testNamesLangsPost.name.english, + nameFrench: testNamesLangsPost.name.french, + reportNameEnglish: testNamesLangsPost.reportingName.english, + reportNameFrench: testNamesLangsPost.reportingName.french, + })); + } + }, [testNamesLangsPost, selectedTest]); + + const closeAddModal = () => { + setIsAddModalOpen(false); + }; + + return ( + <> + {notificationVisible === true ? : ""} +
+ +
+ + +
+ + + +
+
+
+
+
+
+ + + + + +
+ {testNamesShow ? ( + + {testNamesShow.map((test, index) => ( + + + + + ) : ( + <> + + + ) + } + secondaryButtonText={ + confirmationStep ? ( + <> + + + ) : ( + <> + + + ) + } + onRequestSubmit={testRenameEntryPost} + onRequestClose={closeAddModal} + > + {testNamesLangs && testNamesLangs.name ? ( + + + +
+
+ <> + :{" "} + {testNamesLangs?.name.english} + + { + const englishName = e.target.value; + setTestNamesLangsPost((prev) => ({ + ...prev, + name: { + ...prev.name, + english: englishName, + }, + })); + setInputError(false); + }} + required + invalid={inputError} + invalidText={ + + } + /> +
+ <> + :{" "} + {testNamesLangs?.name?.french} + + { + const frenchName = e.target.value; + setTestNamesLangsPost((prev) => ({ + ...prev, + name: { + ...prev.name, + french: frenchName, + }, + })); + setInputError(false); + }} + required + invalid={inputError} + invalidText={ + + } + /> +
+
+ +
+
+ <> + :{" "} + {testNamesLangs?.reportingName?.english} + + { + const englishName = e.target.value; + setTestNamesLangsPost((prev) => ({ + ...prev, + reportingName: { + ...prev.reportingName, + english: englishName, + }, + })); + setInputError(false); + }} + required + invalid={inputError} + invalidText={ + + } + /> +
+ <> + :{" "} + {testNamesLangs?.reportingName?.french} + + { + const frenchName = e.target.value; + setTestNamesLangsPost((prev) => ({ + ...prev, + reportingName: { + ...prev.reportingName, + french: frenchName, + }, + })); + setInputError(false); + }} + required + invalid={inputError} + invalidText={ + + } + /> +
+
+ ) : ( + <> +
+ +
+ + )} +
+ {confirmationStep && ( + <> +
+
+
+ + + +
+
+
+ + )} +
+ +
+ ))} +
+ ) : ( + <> + + + )} +
+
+ + ); +} + +export default injectIntl(TestRenameEntry); diff --git a/frontend/src/components/admin/testManagementConfigMenu/TestSectionCreate.js b/frontend/src/components/admin/testManagementConfigMenu/TestSectionCreate.js new file mode 100644 index 0000000000..e037a50d46 --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/TestSectionCreate.js @@ -0,0 +1,99 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Form, + Heading, + Button, + Loading, + Grid, + Column, + Section, + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableSelectRow, + TableSelectAll, + TableContainer, + Pagination, + Search, + Select, + SelectItem, + Stack, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServer, + postToOpenElisServerFormData, + postToOpenElisServerFullResponse, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import CustomCheckBox from "../../common/CustomCheckBox.js"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.testUnit.manage", + link: "/MasterListsPage#TestSectionManagement", + }, + { + label: "configuration.testUnit.create", + link: "/MasterListsPage#TestSectionCreate", + }, +]; + +function TestSectionCreate() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + + return ( + <> + {notificationVisible === true ? : ""} +
+ + + +
+ + + +
+
+
+
+
+
+ + +
+ + + +
+
+
+
+ + ); +} + +export default injectIntl(TestSectionCreate); diff --git a/frontend/src/components/admin/testManagementConfigMenu/TestSectionManagement.js b/frontend/src/components/admin/testManagementConfigMenu/TestSectionManagement.js new file mode 100644 index 0000000000..d3d8b4a362 --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/TestSectionManagement.js @@ -0,0 +1,119 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Form, + Heading, + Button, + Loading, + Grid, + Column, + Section, + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableSelectRow, + TableSelectAll, + TableContainer, + Pagination, + Search, + Select, + SelectItem, + Stack, + UnorderedList, + ListItem, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServer, + postToOpenElisServerFormData, + postToOpenElisServerFullResponse, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import CustomCheckBox from "../../common/CustomCheckBox.js"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.testUnit.manage", + link: "/MasterListsPage#TestSectionManagement", + }, +]; + +function TestSectionManagement() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + + return ( + <> + {notificationVisible === true ? : ""} +
+ + + +
+ + + +
+
+
+
+
+
+ + + + { + window.location.assign("/MasterListsPage#TestSectionCreate"); + }} + > + + +
+ { + window.location.assign("/MasterListsPage#TestSectionOrder"); + }} + > + + +
+ { + window.location.assign( + "/MasterListsPage#TestSectionTestAssign", + ); + }} + > + + +
+
+
+
+ + ); +} + +export default injectIntl(TestSectionManagement); diff --git a/frontend/src/components/admin/testManagementConfigMenu/TestSectionOrder.js b/frontend/src/components/admin/testManagementConfigMenu/TestSectionOrder.js new file mode 100644 index 0000000000..bb2dae061a --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/TestSectionOrder.js @@ -0,0 +1,99 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Form, + Heading, + Button, + Loading, + Grid, + Column, + Section, + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableSelectRow, + TableSelectAll, + TableContainer, + Pagination, + Search, + Select, + SelectItem, + Stack, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServer, + postToOpenElisServerFormData, + postToOpenElisServerFullResponse, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import CustomCheckBox from "../../common/CustomCheckBox.js"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.testUnit.manage", + link: "/MasterListsPage#TestSectionManagement", + }, + { + label: "configuration.testUnit.order", + link: "/MasterListsPage#TestSectionOrder", + }, +]; + +function TestSectionOrder() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + + return ( + <> + {notificationVisible === true ? : ""} +
+ + + +
+ + + +
+
+
+
+
+
+ + +
+ + + +
+
+
+
+ + ); +} + +export default injectIntl(TestSectionOrder); diff --git a/frontend/src/components/admin/testManagementConfigMenu/TestSectionRenameEntry.js b/frontend/src/components/admin/testManagementConfigMenu/TestSectionRenameEntry.js new file mode 100644 index 0000000000..af6877aa0b --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/TestSectionRenameEntry.js @@ -0,0 +1,240 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { Heading, Button, Grid, Column, Section } from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import RenameModelBox from "./renameModel/RenameModelBox.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.type.rename", + link: "/MasterListsPage#TestSectionRenameEntry", + }, +]; + +function TestSectionRenameEntry() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + const modalHeading = intl.formatMessage({ + id: "test.section.label", + }); + + const [isLoading, setIsLoading] = useState(false); + const [finished, setFinished] = useState(true); + const [isAddModalOpen, setIsAddModalOpen] = useState(false); + const [confirmationStep, setConfirmationStep] = useState(false); + const [inputError, setInputError] = useState(false); + const [testSectionName, setTestSectionName] = useState({}); + const [testSectionListShow, setTestSectionListShow] = useState([]); + const [testSectionPost, setTestSectionPost] = useState({}); + const [entityNamesProvider, setEntityNamesProvider] = useState({ name: { english: "", french: "" },}); + const [entityNamesProviderPost, setEntityNamesProviderPost] = useState({ name: { + english: "", french: "" + }}); + const [entityId, setEntityId] = useState(); + const [entityName, setEntityName] = useState("testSection"); + const [selectedItem, setSelectedItem] = useState({}); + + useEffect(() => { + componentMounted.current = true; + getFromOpenElisServer( + "/rest/TestSectionRenameEntry", + handelTestSectionRename, + ); + return () => { + componentMounted.current = false; + }; + }, []); + + const handelTestSectionRename = (res) => { + if (!res) { + setIsLoading(true); + } else { + setTestSectionName(res); + setTestSectionPost(res); + setTestSectionListShow(res.testSectionList); + } + }; + + useEffect(() => { + if(entityId && entityName) { + getFromOpenElisServer( + `/rest/EntityNamesProvider?entityId=${entityId}&entityName=${entityName}`, + handelEntityNamesProvider, + ); + } + }, [entityId,entityName]); + + const handelEntityNamesProvider = (res) => { + if (!res) { + setIsLoading(true); + } else { + setEntityNamesProvider(res); + setEntityNamesProviderPost(res); + } + }; + + function testSectionUpdatePost() { + setIsLoading(true); + if (confirmationStep) { + postToOpenElisServerJsonResponse( + `/rest/TestSectionRenameEntry`, + JSON.stringify(testSectionPost), + (res) => { + testSectionUpdatePostCallback(res); + }, + ); + } else { + setConfirmationStep(true); + } + } + + function testSectionUpdatePostCallback(res) { + if (res) { + setIsLoading(false); + setFinished(false); + addNotification({ + title: intl.formatMessage({ + id: "notification.title", + }), + message: intl.formatMessage({ + id: "notification.user.post.save.success", + }), + kind: NotificationKinds.success, + }); + setNotificationVisible(true); + setIsAddModalOpen(false); + } else { + addNotification({ + kind: NotificationKinds.error, + title: intl.formatMessage({ id: "notification.title" }), + message: intl.formatMessage({ id: "server.error.msg" }), + }); + setNotificationVisible(true); + setTimeout(() => { + window.location.reload(); + }, 200); + } + } + + const openAppModle = (item) => { + setConfirmationStep(false); + setIsAddModalOpen(true); + setEntityId(item.id); + // setEntityName(test.value); + setSelectedItem(item); + }; + + const onInputChangeEn = (e) => { + const englishName = e.target.value; + setEntityNamesProviderPost((prev) => ({ + name: { + ...prev.name, + english: englishName, + }, + })); + setInputError(false); + }; + + const onInputChangeFr = (e) => { + const frenchName = e.target.value; + setEntityNamesProviderPost((prev) => ({ + name: { + ...prev.name, + french: frenchName, + }, + })); + setInputError(false); + }; + + useEffect(() => { + if (entityId && entityNamesProviderPost && entityNamesProviderPost.name) { + setTestSectionPost((prev) => ({ + ...prev, + testSectionId: entityId, + nameEnglish: entityNamesProviderPost.name.english, + nameFrench: entityNamesProviderPost.name.french, + })); + } + }, [entityNamesProviderPost, entityId]); + + const closeAddModal = () => { + setIsAddModalOpen(false); + }; + + return ( + <> + {notificationVisible === true ? : ""} +
+ +
+ + +
+ + + +
+
+
+
+
+
+ + + + + +
+ +
+
+ + ); +} + +export default injectIntl(TestSectionRenameEntry); diff --git a/frontend/src/components/admin/testManagementConfigMenu/TestSectionTestAssign.js b/frontend/src/components/admin/testManagementConfigMenu/TestSectionTestAssign.js new file mode 100644 index 0000000000..da6a78e592 --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/TestSectionTestAssign.js @@ -0,0 +1,99 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Form, + Heading, + Button, + Loading, + Grid, + Column, + Section, + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableSelectRow, + TableSelectAll, + TableContainer, + Pagination, + Search, + Select, + SelectItem, + Stack, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServer, + postToOpenElisServerFormData, + postToOpenElisServerFullResponse, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import CustomCheckBox from "../../common/CustomCheckBox.js"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.testUnit.manage", + link: "/MasterListsPage#TestSectionManagement", + }, + { + label: "configuration.panel.assign", + link: "/MasterListsPage#TestSectionTestAssign", + }, +]; + +function TestSectionTestAssign() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + + return ( + <> + {notificationVisible === true ? : ""} +
+ + + +
+ + + +
+
+
+
+
+
+ + +
+ + + +
+
+
+
+ + ); +} + +export default injectIntl(TestSectionTestAssign); diff --git a/frontend/src/components/admin/testManagementConfigMenu/UomCreate.js b/frontend/src/components/admin/testManagementConfigMenu/UomCreate.js new file mode 100644 index 0000000000..0b4aaa6bfa --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/UomCreate.js @@ -0,0 +1,99 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Form, + Heading, + Button, + Loading, + Grid, + Column, + Section, + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableSelectRow, + TableSelectAll, + TableContainer, + Pagination, + Search, + Select, + SelectItem, + Stack, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServer, + postToOpenElisServerFormData, + postToOpenElisServerFullResponse, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import CustomCheckBox from "../../common/CustomCheckBox.js"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.uom.manage", + link: "/MasterListsPage#MethodManagement", + }, + { + label: "configuration.uom.create", + link: "/MasterListsPage#UomCreate", + }, +]; + +function UomCreate() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + + return ( + <> + {notificationVisible === true ? : ""} +
+ + + +
+ + + +
+
+
+
+
+
+ + +
+ + + +
+
+
+
+ + ); +} + +export default injectIntl(UomCreate); diff --git a/frontend/src/components/admin/testManagementConfigMenu/UomManagement.js b/frontend/src/components/admin/testManagementConfigMenu/UomManagement.js new file mode 100644 index 0000000000..8024732956 --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/UomManagement.js @@ -0,0 +1,101 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Form, + Heading, + Button, + Loading, + Grid, + Column, + Section, + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableSelectRow, + TableSelectAll, + TableContainer, + Pagination, + Search, + Select, + SelectItem, + Stack, + UnorderedList, + ListItem, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServer, + postToOpenElisServerFormData, + postToOpenElisServerFullResponse, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import CustomCheckBox from "../../common/CustomCheckBox.js"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.uom.manage", + link: "/MasterListsPage#UomManagement", + }, +]; + +function UomManagement() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + + return ( + <> + {notificationVisible === true ? : ""} +
+ + + +
+ + + +
+
+
+
+
+
+ + + + { + window.location.assign("/MasterListsPage#UomCreate"); + }} + > + + + + + +
+ + ); +} + +export default injectIntl(UomManagement); diff --git a/frontend/src/components/admin/testManagementConfigMenu/UomRenameEntry.js b/frontend/src/components/admin/testManagementConfigMenu/UomRenameEntry.js new file mode 100644 index 0000000000..daa607a02b --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/UomRenameEntry.js @@ -0,0 +1,239 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { Heading, Button, Grid, Column, Section } from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils.js"; +import { NotificationContext } from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import RenameModelBox from "./renameModel/RenameModelBox.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "master.lists.page.test.management", + link: "/MasterListsPage#testManagementConfigMenu", + }, + { + label: "configuration.uom.rename", + link: "/MasterListsPage#UomRenameEntry", + }, +]; + +function UomRenameEntry() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + const modalHeading = intl.formatMessage({ + id: "uom.browse.title", + }); + + const [isLoading, setIsLoading] = useState(false); + const [finished, setFinished] = useState(true); + const [isAddModalOpen, setIsAddModalOpen] = useState(false); + const [confirmationStep, setConfirmationStep] = useState(false); + const [inputError, setInputError] = useState(false); + const [uomRename, setUomRename] = useState({}); + const [uomListShow, setUomListShow] = useState([]); + const [uomRenamePost, setUomRenamePost] = useState({}); + const [entityNamesProvider, setEntityNamesProvider] = useState({ + name: { english: "", french: "" }, + }); + const [entityNamesProviderPost, setEntityNamesProviderPost] = useState({ name: { + english: "", french: "" + }}); + const [entityId, setEntityId] = useState(); + const [entityName, setEntityName] = useState("unitOfMeasure"); + const [selectedItem, setSelectedItem] = useState({}); + + useEffect(() => { + componentMounted.current = true; + getFromOpenElisServer("/rest/UomRenameEntry", handleUomRename); + return () => { + componentMounted.current = false; + }; + }, []); + + const handleUomRename = (res) => { + if (!res) { + setIsLoading(true); + } else { + setUomRename(res); + setUomRenamePost(res); + setUomListShow(res.uomList); + } + }; + + useEffect(() => { + if(entityId && entityName) { + getFromOpenElisServer( + `/rest/EntityNamesProvider?entityId=${entityId}&entityName=${entityName}`, + handelEntityNamesProvider, + ); + } + }, [entityId,entityName]); + + const handelEntityNamesProvider = (res) => { + if (!res) { + setIsLoading(true); + } else { + setEntityNamesProvider(res); + setEntityNamesProviderPost(res); + } + }; + + function uomRenameUpdatePost() { + setIsLoading(true); + if (confirmationStep) { + postToOpenElisServerJsonResponse( + `/rest/UomRenameEntry`, + JSON.stringify(uomRenamePost), + (res) => { + uomRenameUpdatePostCallback(res); + }, + ); + } else { + setConfirmationStep(true); + } + } + + function uomRenameUpdatePostCallback(res) { + if (res) { + setIsLoading(false); + setFinished(false); + addNotification({ + title: intl.formatMessage({ + id: "notification.title", + }), + message: intl.formatMessage({ + id: "notification.user.post.save.success", + }), + kind: NotificationKinds.success, + }); + setNotificationVisible(true); + setIsAddModalOpen(false); + } else { + addNotification({ + kind: NotificationKinds.error, + title: intl.formatMessage({ id: "notification.title" }), + message: intl.formatMessage({ id: "server.error.msg" }), + }); + setNotificationVisible(true); + setTimeout(() => { + window.location.reload(); + }, 200); + } + } + + const openAppModle = (item) => { + setConfirmationStep(false); + setIsAddModalOpen(true); + setEntityId(item.id); + // setEntityName(test.value); + setSelectedItem(item); + }; + + const onInputChangeEn = (e) => { + const englishName = e.target.value; + setEntityNamesProviderPost((prev) => ({ + name: { + ...prev.name, + english: englishName, + }, + })); + setInputError(false); + }; + + const onInputChangeFr = (e) => { + const frenchName = e.target.value; + setEntityNamesProviderPost((prev) => ({ + name: { + ...prev.name, + french: frenchName, + }, + })); + setInputError(false); + }; + + useEffect(() => { + if (entityId && entityNamesProviderPost && entityNamesProviderPost.name) { + setUomRenamePost((prev) => ({ + ...prev, + uomId: entityId, + nameEnglish: entityNamesProviderPost.name.english, + nameFrench: entityNamesProviderPost.name.french, + })); + } + }, [entityNamesProviderPost, entityId]); + + const closeAddModal = () => { + setIsAddModalOpen(false); + }; + + return ( + <> + {notificationVisible === true ? : ""} +
+ +
+ + +
+ + + +
+
+
+
+
+
+ + + + + +
+ +
+
+ + ); +} + +export default injectIntl(UomRenameEntry); diff --git a/frontend/src/components/admin/testManagementConfigMenu/renameModel/RenameModelBox.js b/frontend/src/components/admin/testManagementConfigMenu/renameModel/RenameModelBox.js new file mode 100644 index 0000000000..8e46d79f7d --- /dev/null +++ b/frontend/src/components/admin/testManagementConfigMenu/renameModel/RenameModelBox.js @@ -0,0 +1,197 @@ +import React from "react"; +import { + Heading, + Button, + Loading, + Grid, + Column, + Section, + Modal, + TextInput, +} from "@carbon/react"; +import { FormattedMessage, injectIntl } from "react-intl"; +import PropTypes from "prop-types"; + +const RenameModelBox = ({ + data, + isModalOpen, + openModel, + closeModel, + onSubmit, + onInputChangeEn, + onInputChangeFr, + isLoading, + modalHeading, + heading, + mainLabel, + confirmationStep, + inputError, + lang, + langPost, + selectedItem, +}) => { + return ( + <> + {data ? ( + + {data.map((item, index) => ( + + + + + ) : ( + <> + + + ) + } + secondaryButtonText={ + confirmationStep ? ( + <> + + + ) : ( + <> + + + ) + } + onRequestSubmit={onSubmit} + onRequestClose={closeModel} + > + {lang && lang?.name && langPost && langPost?.name && langPost?.name?.english && langPost?.name?.french ? ( + + + {/* Edit or Confirmation */} +
+
+ + + +
+
+
+
+
+
+ + {/* main blue lable */} + + +
+
+
+
+ <> + :{" "} + {lang?.name?.english} + +
+
+ { + onInputChangeEn(e); + }} + required + invalid={inputError} + invalidText={ + + } + /> +
+ <> + :{" "} + {lang?.name?.french} + +
+
+ { + onInputChangeFr(e); + }} + required + invalid={inputError} + invalidText={ + + } + /> +
+
+ ) : ( + <> +
+ +
+ + )} +
+ {confirmationStep && ( + <> +
+
+
+ + + +
+
+
+ + )} +
+ +
+ ))} +
+ ) : ( + <> + + + )} + + ); +}; + +RenameModelBox.propTypes = { + data: PropTypes.arrayOf(PropTypes.object).isRequired, + isModalOpen: PropTypes.bool.isRequired, + closeModel: PropTypes.func.isRequired, + onSubmit: PropTypes.func.isRequired, + onInputChangeEn: PropTypes.func.isRequired, + onInputChangeFr: PropTypes.func.isRequired, + isLoading: PropTypes.bool.isRequired, + modalHeading: PropTypes.string.isRequired, + heading: PropTypes.string.isRequired, + mainLabel: PropTypes.string.isRequired, + confirmationStep: PropTypes.bool.isRequired, + inputError: PropTypes.bool.isRequired, + lang: PropTypes.object.isRequired, + langPost: PropTypes.object.isRequired, + selectedItem: PropTypes.object.isRequired, +}; + +export default injectIntl(RenameModelBox); diff --git a/frontend/src/components/layout/search/searchBar.css b/frontend/src/components/layout/search/searchBar.css index e202ea237d..6e9b048cc5 100644 --- a/frontend/src/components/layout/search/searchBar.css +++ b/frontend/src/components/layout/search/searchBar.css @@ -17,7 +17,6 @@ .search-input { width: 100%; position: relative; - } .search-bar-container:hover { @@ -52,11 +51,8 @@ cursor: pointer; } - /* Large screens (1208px and up) */ @media (min-width: 1208px) { - - .search-bar-container { width: 45%; margin-top: 0%; @@ -77,7 +73,7 @@ right: 130px; box-shadow: 0em 0.1em 0.5em #ccc; } - + .patientHead { overflow-y: auto; width: 600px; diff --git a/frontend/src/components/layout/search/searchBar.js b/frontend/src/components/layout/search/searchBar.js index a3223b6b28..e1db0c5216 100644 --- a/frontend/src/components/layout/search/searchBar.js +++ b/frontend/src/components/layout/search/searchBar.js @@ -148,4 +148,4 @@ const SearchBar = (props) => { ); }; -export default SearchBar; \ No newline at end of file +export default SearchBar; diff --git a/frontend/src/index.css b/frontend/src/index.css index 5aa3ee2f3b..3d6c7d3bef 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -71,7 +71,7 @@ code { .slide-over-panel { width: 25%; /* Use percentage for width on larger screens */ - /* max-width: 25%;*/ + /* max-width: 25%;*/ max-width: 50%; /* Use percentage for max-width on larger screens */ } diff --git a/frontend/src/languages/en.json b/frontend/src/languages/en.json index ef5cef801b..ad1336c2b3 100644 --- a/frontend/src/languages/en.json +++ b/frontend/src/languages/en.json @@ -274,7 +274,7 @@ "sidenav.label.reports.study": "Study", "sidenav.label.admin": "Admin", "banner.menu.administration": "Admin", - "sidenav.label.admin.testmgt": "Test Management", + "sidenav.label.admin.testmgt": "Relex Tests Configuration", "sidenav.label.admin.testmgt.reflex": "Reflex Tests Management", "sidenav.label.admin.testmgt.calculated": "Calculated Value Tests Management", "sidenav.label.admin.testmgt.ViewtestCatalog": "View Test Catalog", @@ -1241,13 +1241,102 @@ "label.test.batch.cancel.finish": "This is non-reversible.", "label.test.batch.replace.start": "The following", "label.test.batch.no.change.finish": "tests will not be changed.", + "configuration.selectList.header": "Create new result selection option", + "label.resultSelectList": "Result select list", + "configuration.test.orderable": "Enable/disable test orderability", + "configuration.test.modify": "Modify tests", + "configuration.test.add": "Add new tests", + "configuration.testUnit.manage": "Manage Test Units", + "configuration.method.create": "Create New Method", + "configuration.testUnit.order": "Set Test Unit Order", + "configuration.panel.assign": "Test Assignment", + "configuration.testUnit.create": "Create New Test Unit", + "configuration.testUnit.order.explain": "Sort lab units by clicking a unit and dragging it into the proper order.", + "configuration.sampleType.manage": "Manage Sample Types", + "configuration.sampleType.manage.explain": "Use to create, set display order or assign tests to sample types", + "configuration.sampleType.create": "Create New Sample Type", + "configuration.sampleType.order": "Set Sample Type Order", + "configuration.sampleType.order.explain": "Sort sample types by clicking a type and dragging it into the proper order.", + "configuration.uom.manage": "Manage Units of Measure", + "configuration.uom.manage.explain": "Use to create Units of Measure", + "configuration.uom.create": "Create New Units of Measure", + "configuration.panel.create": "Create New Panel", + "configuration.panel.create.duplicate": "An existing panel type with the same name has been found. Please cancel or use a different name.", + "configuration.panel.manage": "Manage Panels", + "configuration.panel.manage.explain": "Use to create, set display order or assign tests to panels", + "configuration.panel.order": "Set Panel Order", + "configuration.panel.order.explain": "Sort panels by clicking a type and dragging it into the proper order.", + "manage.testing.algorithms.add.reflex.tests": "Manage Testing Algorithms and Reflex tests", + "configuration.test.management.organization": "Test Organization", + "configuration.test.management.spelling": "Spelling corrections", + "configuration.test.rename": "Rename existing test names", + "configuration.test.rename.explain": "Use to rename existing tests. Will not change test, only how the user sees them in OpenELIS and on reports", + "configuration.testSection.rename": "Rename Existing Test Sections", + "configuration.testSection.rename.explain": "Use to correct the name of existing test sections.", + "configuration.selectList.rename": "Rename existing result list options", + "configuration.selectList.rename.explain": "Rename existing result list options", + "configuration.type.rename": "Rename Existing Sample Types", + "configuration.type.rename.explain": "Use to correct the name of existing panels.", + "configuration.uom.rename": "Rename Existing Unit of Measure Entries", + "configuration.uom.rename.explain": "Use to correct the name of existing unit of measure entries.", + "configuration.panel.rename": "Rename Existing Panels", + "configuration.panel.rename.explain": "Use to correct the name of existing panels.", + "configuration.method.rename": "Rename existing method names", + "configuration.method.rename.explain": "Use to correct the name of existing methods", + "configuration.test.catalog": "View Test Catalog", + "configuration.test.catalog.explain": "View the current test catalog", + "configuration.method": "Manage Methods", + "configuration.method.explain": "Use to create a new method, activate or deactivate a method", + "configuration.test.add.explain": "Use to add new tests to the system. Modification of existing tests should be done through the other test management links", + "configuration.test.modify.explain": "Use to modify existing tests in the system.", + "configuration.test.activate": "Activate/Deactivate tests", + "configuration.test.activate.explain": "Use to activate or deactivate an existing test.", + "configuration.test.orderable.explain": "Tests that are orderable can be ordered on intake. If they are not orderable then they can only be ordered as a result of a reflex", + "configuration.testUnit.manage.explain": "Use to create, set display order or assign tests to test units", + "configuration.selectList.add": "Add result select list", + "configuration.selectList.add.alert": "To change spelling of current result list entries use Rename existing result list options", + "configuration.selectList.add.explain": "use to create result select list for test results", + "label.testActivate": "Test Activation", + "instructions.test.activation": "Active Tests: a checked box indicates an already active test. To activate a test, check the box; to deactivate, uncheck the box. Any sample types without an existing active test are deactivated and appear at the bottom, under 'Inactive Sample Types'. If one of the tests is activated, the sample type will be activated.", + "label.button.finished": "Finished", + "panel.panelName": "Panel Name", + "label.testName": "Test names", + "reporting.label.testName": "Reporting Test Name", + "french.current": "FRENCH current", + "english.current": "ENGLISH current", + "required.invalidtext": "This field is required", + "confirmation.rename": "Confirm Changes above you made.", + "sampleType.typeName": "Sample Type Name", + "testsection.testSectionName": "Test Section Name", + "uom.uomName": "Unit Of Measure Name", + "uom.browse.title": "Unit Of Measure", + "method.methodName": "Method Name", + "method.browse.title": "Method Section", + "selectListRenameEntry.selectList": "Select List Rename Entry", + "selectListRenameEntry.selectListEdit": "Select List Rename Entry Edit", + "label.loinc": "LOINC", + "test.add.copy.name": "Copy from Test Name", + "test.antimicrobialResistance": "Antimicrobial Resistance", + "label.orderable": "Orderable", + "test.notifyResults": "Notify Patient Of Results", + "test.inLabOnly": "In Lab Only", + "label.test.display.order": "Test display order", + "label.sex.dependent": "Sex dependent", + "label.critical.range": "Critical range", + "label.reporting.range": "Reporting range", + "sample.type.and.test.sort.order": "Sample type and test sort order", + "label.existing.test.sets": "Existing test sets", + "label.select.list.options": "Select list options", + "label.result.order": "Result order", + "label.reference.value": "Reference value", + "label.default.result": "Default result", + "label.qualifiers": "Qualifiers", "notification.slideover.button.unsubscribe": "Unsubscribe", "notification.slideover.button.unsubscribe.success": "Unsubscribed successfully", "notification.slideover.button.unsubscribe.fail": "Unsubscribe failed", "notification.slideover.button.subscribe.success": "Subscribed successfully", "notification.slideover.button.subscribe.fail": "Subscribe failed", "testnotificationconfig.browse.title": "Test Notification Configuration", - "label.testName": "Test names", "testnotification.instructionis.variables.body": "[testName] : Name of the test this is for", "testnotification.instructionis.variables.body.0": "[testResult] : Result of the test", "testnotification.instructionis.variables.body.1": "[patientFirstName] : Patient's first name ", diff --git a/frontend/src/languages/fr.json b/frontend/src/languages/fr.json index b0e0e85faf..0a07f94856 100644 --- a/frontend/src/languages/fr.json +++ b/frontend/src/languages/fr.json @@ -254,7 +254,7 @@ "sidenav.label.reports.study": "Étude", "sidenav.label.admin": "Administration", "banner.menu.administration": "Administration", - "sidenav.label.admin.testmgt": "Gestion des Tests", + "sidenav.label.admin.testmgt": "Configuration des tests réflexes", "sidenav.label.admin.testmgt.reflex": "Gestion des tests de réflexes", "sidenav.label.admin.testmgt.calculated": "Gestion des tests de valeur calculée", "sidenav.label.admin.testmgt.ViewtestCatalog": "Voir le catalogue des tests", @@ -1142,13 +1142,102 @@ "label.test.batch.cancel.finish": "Cette action est irréversible.", "label.test.batch.replace.start": "Les tests suivants", "label.test.batch.no.change.finish": "ne seront pas modifiés.", + "configuration.selectList.header": "Créer une nouvelle option de sélection de résultat", + "label.resultSelectList": "Liste de sélection des résultats", + "configuration.test.orderable": "Activer/désactiver la commandabilité des tests", + "configuration.test.modify": "Modifier les tests", + "configuration.test.add": "Ajouter de nouveaux tests", + "configuration.testUnit.manage": "Gérer les unités de test", + "configuration.method.create": "Créer une nouvelle méthode", + "configuration.testUnit.order": "Définir l'ordre des unités de test", + "configuration.panel.assign": "Affectation des tests", + "configuration.testUnit.create": "Créer une nouvelle unité de test", + "configuration.testUnit.order.explain": "Triez les unités de laboratoire en cliquant sur une unité et en la faisant glisser dans le bon ordre.", + "configuration.sampleType.manage": "Gérer les types d'échantillons", + "configuration.sampleType.manage.explain": "Utilisez pour créer, définir l'ordre d'affichage ou attribuer des tests aux types d'échantillons", + "configuration.sampleType.create": "Créer un nouveau type d'échantillon", + "configuration.sampleType.order": "Définir l'ordre des types d'échantillons", + "configuration.sampleType.order.explain": "Triez les types d'échantillons en cliquant sur un type et en le faisant glisser dans le bon ordre.", + "configuration.uom.manage": "Gérer les unités de mesure", + "configuration.uom.manage.explain": "Utilisez pour créer des unités de mesure", + "configuration.uom.create": "Créer de nouvelles unités de mesure", + "configuration.panel.create": "Créer un nouveau panel", + "configuration.panel.create.duplicate": "Un type de panel existant avec le même nom a été trouvé. Veuillez annuler ou utiliser un nom différent.", + "configuration.panel.manage": "Gérer les panels", + "configuration.panel.manage.explain": "Utilisez pour créer, définir l'ordre d'affichage ou attribuer des tests aux panels", + "configuration.panel.order": "Définir l'ordre des panels", + "configuration.panel.order.explain": "Triez les panels en cliquant sur un type et en le faisant glisser dans le bon ordre.", + "manage.testing.algorithms.add.reflex.tests": "Gérer les algorithmes de test et les tests réflexes", + "configuration.test.management.organization": "Organisation des tests", + "configuration.test.management.spelling": "Corrections orthographiques", + "configuration.test.rename": "Renommer les noms de test existants", + "configuration.test.rename.explain": "Utilisez pour renommer les tests existants. Cela ne changera pas le test, seulement la façon dont l'utilisateur les voit dans OpenELIS et sur les rapports", + "configuration.testSection.rename": "Renommer les sections de test existantes", + "configuration.testSection.rename.explain": "Utilisez pour corriger le nom des sections de test existantes.", + "configuration.selectList.rename": "Renommer les options de liste de résultats existantes", + "configuration.selectList.rename.explain": "Renommer les options de liste de résultats existantes", + "configuration.type.rename": "Renommer les types d'échantillons existants", + "configuration.type.rename.explain": "Utilisez pour corriger le nom des panels existants.", + "configuration.uom.rename": "Renommer les entrées d'unité de mesure existantes", + "configuration.uom.rename.explain": "Utilisez pour corriger le nom des entrées d'unité de mesure existantes.", + "configuration.panel.rename": "Renommer les panels existants", + "configuration.panel.rename.explain": "Utilisez pour corriger le nom des panels existants.", + "configuration.method.rename": "Renommer les noms de méthode existants", + "configuration.method.rename.explain": "Utilisez pour corriger le nom des méthodes existantes", + "configuration.test.catalog": "Voir le catalogue des tests", + "configuration.test.catalog.explain": "Voir le catalogue des tests actuel", + "configuration.method": "Gérer les méthodes", + "configuration.method.explain": "Utilisez pour créer une nouvelle méthode, activer ou désactiver une méthode", + "configuration.test.add.explain": "Utilisez pour ajouter de nouveaux tests au système. La modification des tests existants doit se faire via les autres liens de gestion des tests", + "configuration.test.modify.explain": "Utilisez pour modifier les tests existants dans le système.", + "configuration.test.activate": "Activer/Désactiver les tests", + "configuration.test.activate.explain": "Utilisez pour activer ou désactiver un test existant.", + "configuration.test.orderable.explain": "Les tests commandables peuvent être commandés à l'admission. S'ils ne sont pas commandables, ils ne peuvent être commandés qu'en tant que résultat d'un réflexe", + "configuration.testUnit.manage.explain": "Utilisez pour créer, définir l'ordre d'affichage ou attribuer des tests aux unités de test", + "configuration.selectList.add": "Ajouter une liste de sélection des résultats", + "configuration.selectList.add.alert": "Pour modifier l'orthographe des entrées de la liste de résultats actuelles, utilisez Renommer les options de liste de résultats existantes", + "configuration.selectList.add.explain": "Utilisez pour créer une liste de sélection des résultats pour les résultats de test", + "label.testActivate": "Activation des tests", + "instructions.test.activation": "Tests actifs: une case cochée indique un test déjà actif. Pour activer un test, cochez la case; pour désactiver, décochez la case. Tous les types d'échantillons sans test actif existant sont désactivés et apparaissent en bas, sous 'Types d'échantillons inactifs'. Si l'un des tests est activé, le type d'échantillon sera activé.", + "label.button.finished": "Terminé", + "panel.panelName": "Nom du panel", + "label.testName": "Noms des tests", + "reporting.label.testName": "Nom du test dans les rapports", + "french.current": "FRANÇAIS actuel", + "english.current": "ANGLAIS actuel", + "required.invalidtext": "Ce champ est requis", + "confirmation.rename": "Confirmez les modifications ci-dessus que vous avez apportées.", + "sampleType.typeName": "Nom du type d'échantillon", + "testsection.testSectionName": "Nom de la section de test", + "uom.uomName": "Nom de l'unité de mesure", + "uom.browse.title": "Unité de mesure", + "method.methodName": "Nom de la méthode", + "method.browse.title": "Section de méthode", + "selectListRenameEntry.selectList": "Renommer une entrée de liste de sélection", + "selectListRenameEntry.selectListEdit": "Renommer une entrée de liste de sélection", + "label.loinc": "LOINC", + "test.add.copy.name": "Copier depuis le nom du test", + "test.antimicrobialResistance": "Résistance aux antimicrobiens", + "label.orderable": "Commandable", + "test.notifyResults": "Notifier le patient des résultats", + "test.inLabOnly": "Uniquement en laboratoire", + "label.test.display.order": "Ordre d'affichage du test", + "label.sex.dependent": "Dépendant du sexe", + "label.critical.range": "Plage critique", + "label.reporting.range": "Plage de rapport", + "sample.type.and.test.sort.order": "Ordre de tri des types d'échantillons et des tests", + "label.existing.test.sets": "Ensembles de tests existants", + "label.select.list.options": "Options de la liste de sélection", + "label.result.order": "Ordre des résultats", + "label.reference.value": "Valeur de référence", + "label.default.result": "Résultat par défaut", + "label.qualifiers": "Qualificateurs", "notification.slideover.button.unsubscribe": "Se désabonner", "notification.slideover.button.unsubscribe.success": "Désabonnement réussi", "notification.slideover.button.unsubscribe.fail": "Échec de l'annulation de l'abonnement", "notification.slideover.button.subscribe.success": "Abonnement réussi", "notification.slideover.button.subscribe.fail": "Échec de l'abonnement", "testnotificationconfig.browse.title": "Configuration des notifications de test", - "label.testName": "Noms des tests", "testnotification.instructionis.variables.body": "[testName] : Nom du test pour lequel cela est", "testnotification.instructionis.variables.body.0": "[testResult] : Résultat du test", "testnotification.instructionis.variables.body.1": "[patientFirstName] : Prénom du patient", diff --git a/src/main/java/org/openelisglobal/common/management/controller/rest/MethodManagementRestController.java b/src/main/java/org/openelisglobal/common/management/controller/rest/MethodManagementRestController.java index b6318227f7..7c0f818dc5 100644 --- a/src/main/java/org/openelisglobal/common/management/controller/rest/MethodManagementRestController.java +++ b/src/main/java/org/openelisglobal/common/management/controller/rest/MethodManagementRestController.java @@ -6,12 +6,15 @@ import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/rest") public class MethodManagementRestController extends BaseController { - @RequestMapping(value = "/MethodManagement", produces = MediaType.APPLICATION_JSON_VALUE) + + @RequestMapping(value = "/MethodManagement", produces = MediaType.APPLICATION_JSON_VALUE, method = { + RequestMethod.GET, RequestMethod.POST }) public ResponseEntity showMethodManagement(HttpServletRequest request) { MethodManagementForm form = new MethodManagementForm(); diff --git a/src/main/java/org/openelisglobal/common/management/controller/rest/PanelManagementRestController.java b/src/main/java/org/openelisglobal/common/management/controller/rest/PanelManagementRestController.java new file mode 100644 index 0000000000..f2daa5218d --- /dev/null +++ b/src/main/java/org/openelisglobal/common/management/controller/rest/PanelManagementRestController.java @@ -0,0 +1,40 @@ +package org.openelisglobal.common.management.controller.rest; + +import javax.servlet.http.HttpServletRequest; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.management.form.PanelManagementForm; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class PanelManagementRestController extends BaseController { + + @RequestMapping(value = "/PanelManagement", method = { RequestMethod.GET, RequestMethod.POST }) + public PanelManagementForm showPanelManagement(HttpServletRequest request) { + PanelManagementForm form = new PanelManagementForm(); + + // return findForward(FWD_SUCCESS, form); + return form; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "panelManagementDefinition"; + } else { + return "PageNotFound"; + } + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } +} diff --git a/src/main/java/org/openelisglobal/common/management/controller/rest/SampleTypeManagementRestController.java b/src/main/java/org/openelisglobal/common/management/controller/rest/SampleTypeManagementRestController.java new file mode 100644 index 0000000000..61d8ccce45 --- /dev/null +++ b/src/main/java/org/openelisglobal/common/management/controller/rest/SampleTypeManagementRestController.java @@ -0,0 +1,39 @@ +package org.openelisglobal.common.management.controller.rest; + +import javax.servlet.http.HttpServletRequest; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.management.form.SampleTypeManagementForm; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class SampleTypeManagementRestController extends BaseController { + + @RequestMapping(value = "/SampleTypeManagement", method = { RequestMethod.GET, RequestMethod.POST }) + public SampleTypeManagementForm showSampleTypeManagement(HttpServletRequest request) { + SampleTypeManagementForm form = new SampleTypeManagementForm(); + // return findForward(FWD_SUCCESS, form); + return form; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "sampleTypeManagementDefinition"; + } else { + return "PageNotFound"; + } + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } +} diff --git a/src/main/java/org/openelisglobal/common/management/controller/rest/TestManagementConfigMenuRestController.java b/src/main/java/org/openelisglobal/common/management/controller/rest/TestManagementConfigMenuRestController.java new file mode 100644 index 0000000000..6fc8fcf229 --- /dev/null +++ b/src/main/java/org/openelisglobal/common/management/controller/rest/TestManagementConfigMenuRestController.java @@ -0,0 +1,40 @@ +package org.openelisglobal.common.management.controller.rest; + +import javax.servlet.http.HttpServletRequest; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.management.form.TestManagementConfigForm; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class TestManagementConfigMenuRestController extends BaseController { + + @RequestMapping(value = "/TestManagementConfigMenu", method = { RequestMethod.GET, RequestMethod.POST }) + public TestManagementConfigForm showTestManagementConfigMenu(HttpServletRequest request) { + TestManagementConfigForm form = new TestManagementConfigForm(); + + // return findForward(FWD_SUCCESS, form); + return form; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "testManagementConfigDefinition"; + } else { + return "PageNotFound"; + } + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } +} diff --git a/src/main/java/org/openelisglobal/common/management/controller/rest/TestSectionManagementRestController.java b/src/main/java/org/openelisglobal/common/management/controller/rest/TestSectionManagementRestController.java new file mode 100644 index 0000000000..4b1364e9e7 --- /dev/null +++ b/src/main/java/org/openelisglobal/common/management/controller/rest/TestSectionManagementRestController.java @@ -0,0 +1,40 @@ +package org.openelisglobal.common.management.controller.rest; + +import javax.servlet.http.HttpServletRequest; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.management.form.TestSectionManagementForm; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class TestSectionManagementRestController extends BaseController { + + @RequestMapping(value = "/TestSectionManagement", method = { RequestMethod.GET, RequestMethod.POST }) + public TestSectionManagementForm showTestSectionManagement(HttpServletRequest request) { + TestSectionManagementForm form = new TestSectionManagementForm(); + + // return findForward(FWD_SUCCESS, form); + return form; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "testSectionManagementDefinition"; + } else { + return "PageNotFound"; + } + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } +} diff --git a/src/main/java/org/openelisglobal/common/management/controller/rest/UomManagementRestController.java b/src/main/java/org/openelisglobal/common/management/controller/rest/UomManagementRestController.java new file mode 100644 index 0000000000..b8ddb40744 --- /dev/null +++ b/src/main/java/org/openelisglobal/common/management/controller/rest/UomManagementRestController.java @@ -0,0 +1,49 @@ +package org.openelisglobal.common.management.controller.rest; + +import javax.servlet.http.HttpServletRequest; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.management.form.UomManagementForm; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class UomManagementRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] {}; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @RequestMapping(value = "/UomManagement", method = { RequestMethod.GET, RequestMethod.POST }) + public UomManagementForm showUomManagement(HttpServletRequest request) { + UomManagementForm form = new UomManagementForm(); + + // return findForward(FWD_SUCCESS, form); + return form; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "uomManagementDefinition"; + } else { + return "PageNotFound"; + } + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } +} diff --git a/src/main/java/org/openelisglobal/common/provider/query/rest/EntityNamesProviderRestController.java b/src/main/java/org/openelisglobal/common/provider/query/rest/EntityNamesProviderRestController.java new file mode 100644 index 0000000000..d41c81a8ca --- /dev/null +++ b/src/main/java/org/openelisglobal/common/provider/query/rest/EntityNamesProviderRestController.java @@ -0,0 +1,148 @@ +/* + * The contents of this file are subject to the Mozilla Public License + * Version 1.1 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" + * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the + * License for the specific language governing rights and limitations under + * the License. + * + * The Original Code is OpenELIS code. + * + * Copyright (C) ITECH, University of Washington, Seattle WA. All Rights Reserved. + */ +package org.openelisglobal.common.provider.query.rest; + +import java.util.Locale; +import org.apache.commons.validator.GenericValidator; +import org.json.simple.JSONObject; +import org.openelisglobal.localization.valueholder.Localization; +import org.openelisglobal.panel.service.PanelService; +import org.openelisglobal.renamemethod.service.RenameMethodService; +import org.openelisglobal.renametestsection.service.RenameTestSectionService; +import org.openelisglobal.typeofsample.service.TypeOfSampleService; +import org.openelisglobal.unitofmeasure.service.UnitOfMeasureService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class EntityNamesProviderRestController { + + @Autowired + private PanelService panelService; + + @Autowired + private RenameTestSectionService renameTestSectionService; + + @Autowired + private TypeOfSampleService typeOfSampleService; + + @Autowired + private UnitOfMeasureService unitOfMeasureService; + + @Autowired + private RenameMethodService renameMethodService; + + public static final String PANEL = "panel"; + public static final String SAMPLE_TYPE = "sampleType"; + public static final String TEST_SECTION = "testSection"; + public static final String UNIT_OF_MEASURE = "unitOfMeasure"; + public static final String METHOD = "method"; + String INVALID = "invalid"; + String VALID = "valid"; + + @SuppressWarnings("unchecked") + @GetMapping("/EntityNamesProvider") + public ResponseEntity processRequest(@RequestParam("entityId") String id, + @RequestParam("entityName") String entityName) { + + if (GenericValidator.isBlankOrNull(id) || GenericValidator.isBlankOrNull(entityName)) { + String errorMessage = "Internal error, please contact Admin and file bug report"; + JSONObject errorJson = new JSONObject(); + errorJson.put("status", INVALID); + errorJson.put("message", errorMessage); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorJson); + } + + JSONObject jsonResult = new JSONObject(); + String status = createJsonTestNames(id, entityName, jsonResult); + + if (status.equals(VALID)) { + return ResponseEntity.ok(jsonResult); + } else { + JSONObject errorJson = new JSONObject(); + errorJson.put("status", INVALID); + errorJson.put("message", "No localization found for the given entity."); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorJson); + } + } + + @SuppressWarnings("unchecked") + private String createJsonTestNames(String id, String entityName, JSONObject jsonResult) + throws IllegalStateException { + + Localization localization = null; + + if (PANEL.equals(entityName)) { + localization = getLocalizationForPanel(id); + } else if (SAMPLE_TYPE.equals(entityName)) { + localization = getLocalizationForSampleType(id); + } else if (TEST_SECTION.equals(entityName)) { + localization = getLocalizationForRenameTestSection(id); + } else if (UNIT_OF_MEASURE.equals(entityName)) { + localization = getLocalizationForUnitOfMeasure(id); + } else if (METHOD.equals(entityName)) { + localization = getLocalizationForRenameMethod(id); + } + // add entity types as needed + + if (localization != null) { + + JSONObject nameObject = new JSONObject(); + addAllLocalizations(nameObject, localization); + // nameObject.put("english", localization.getEnglish()); + // nameObject.put("french", localization.getFrench()); + jsonResult.put("name", nameObject); + + return VALID; + } + + return INVALID; + } + + @SuppressWarnings("unchecked") + private void addAllLocalizations(JSONObject jsonObject, Localization localization) { + for (Locale locale : localization.getLocalesWithValue()) { + jsonObject.put(locale.getDisplayLanguage(Locale.ENGLISH).toLowerCase(), + localization.getLocalizedValue(locale)); + } + } + + private Localization getLocalizationForPanel(String id) { + return panelService.getLocalizationForPanel(id); + } + + private Localization getLocalizationForSampleType(String id) { + return typeOfSampleService.getLocalizationForSampleType(id); + } + + private Localization getLocalizationForRenameTestSection(String id) { + return renameTestSectionService.getLocalizationForRenameTestSection(id); + } + + private Localization getLocalizationForUnitOfMeasure(String id) { + return unitOfMeasureService.getLocalizationForUnitOfMeasure(id); + } + + private Localization getLocalizationForRenameMethod(String id) { + return renameMethodService.getLocalizationForRenameMethod(id); + } +} diff --git a/src/main/java/org/openelisglobal/common/provider/query/rest/TestNamesProviderRestController.java b/src/main/java/org/openelisglobal/common/provider/query/rest/TestNamesProviderRestController.java new file mode 100644 index 0000000000..44889f0d9d --- /dev/null +++ b/src/main/java/org/openelisglobal/common/provider/query/rest/TestNamesProviderRestController.java @@ -0,0 +1,115 @@ +/* + * The contents of this file are subject to the Mozilla Public License + * Version 1.1 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" + * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the + * License for the specific language governing rights and limitations under + * the License. + * + * The Original Code is OpenELIS code. + * + * Copyright (C) ITECH, University of Washington, Seattle WA. All Rights Reserved. + */ +package org.openelisglobal.common.provider.query.rest; + +import java.util.Locale; +import org.apache.commons.validator.GenericValidator; +import org.json.simple.JSONObject; +import org.openelisglobal.common.log.LogEvent; +import org.openelisglobal.localization.valueholder.Localization; +import org.openelisglobal.spring.util.SpringContext; +import org.openelisglobal.test.service.TestService; +import org.openelisglobal.test.valueholder.Test; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class TestNamesProviderRestController { + + private final TestService testService; + + public TestNamesProviderRestController(TestService testService) { + this.testService = testService; + } + + @GetMapping("/TestNamesProvider") + public ResponseEntity processRequest(@RequestParam("testId") String testId) { + + String jResult; + JSONObject jsonResult = new JSONObject(); + String jString; + + if (GenericValidator.isBlankOrNull(testId)) { + jResult = "INVALID"; + jString = "Internal error, please contact Admin and file bug report"; + return ResponseEntity.badRequest().body(createErrorResponse(jString)); + } else { + try { + jResult = createJsonTestNames(testId, jsonResult); + jString = jsonResult.toJSONString(); + } catch (IllegalStateException e) { + LogEvent.logDebug(e); + jResult = "INVALID"; + jString = "Internal error, please contact Admin and file bug report"; + return ResponseEntity.status(500).body(createErrorResponse(jString)); + } + } + return ResponseEntity.ok(jsonResult); + } + + @SuppressWarnings("unchecked") + private String createJsonTestNames(String testId, JSONObject jsonResult) throws IllegalStateException { + + String INVALID = "invalid"; + String VALID = "valid"; + + if (GenericValidator.isBlankOrNull(testId)) { + throw new IllegalStateException("TestNamesProvider testId was blank. It must have a value"); + } + + Test test = SpringContext.getBean(TestService.class).get(testId); + if (test != null) { + Localization nameLocalization = test.getLocalizedTestName(); + Localization reportNameLocalization = test.getLocalizedReportingName(); + + JSONObject nameObject = new JSONObject(); + addAllLocalizations(nameObject, nameLocalization); + // nameObject.put("english", nameLocalization.getEnglish()); + // nameObject.put("french", nameLocalization.getFrench()); + jsonResult.put("name", nameObject); + + JSONObject reportingNameObject = new JSONObject(); + addAllLocalizations(reportingNameObject, reportNameLocalization); + // reportingNameObject.put("english", reportNameLocalization.getEnglish()); + // reportingNameObject.put("french", reportNameLocalization.getFrench()); + jsonResult.put("reportingName", reportingNameObject); + + return VALID; + } + + return INVALID; + } + + @SuppressWarnings("unchecked") + private void addAllLocalizations(JSONObject jsonObject, Localization localization) { + for (Locale locale : localization.getLocalesWithValue()) { + jsonObject.put(locale.getDisplayLanguage(Locale.ENGLISH).toLowerCase(), + localization.getLocalizedValue(locale)); + } + } + + @SuppressWarnings("unchecked") + private JSONObject createErrorResponse(String message) { + JSONObject errorResponse = new JSONObject(); + errorResponse.put("status", "error"); + errorResponse.put("message", message); + return errorResponse; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/controller/rest/MethodRenameEntryRestController.java b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/MethodRenameEntryRestController.java new file mode 100644 index 0000000000..2949f8db9d --- /dev/null +++ b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/MethodRenameEntryRestController.java @@ -0,0 +1,113 @@ +package org.openelisglobal.testconfiguration.controller.rest; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import org.hibernate.HibernateException; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.log.LogEvent; +import org.openelisglobal.common.services.DisplayListService; +import org.openelisglobal.localization.service.LocalizationService; +import org.openelisglobal.localization.valueholder.Localization; +import org.openelisglobal.method.service.MethodService; +import org.openelisglobal.method.valueholder.Method; +import org.openelisglobal.testconfiguration.form.MethodRenameEntryForm; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class MethodRenameEntryRestController extends BaseController { + private static final String[] ALLOWED_FIELDS = new String[] { "methodId", "nameEnglish", "nameFrench" }; + + @Autowired + LocalizationService localizationService; + @Autowired + MethodService methodService; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/MethodRenameEntry") + public MethodRenameEntryForm showMethodRenameEntry(HttpServletRequest request) { + MethodRenameEntryForm form = new MethodRenameEntryForm(); + + form.setMethodList(DisplayListService.getInstance().getList(DisplayListService.ListType.METHODS)); + + // return findForward(FWD_SUCCESS, form); + return form; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "methodRenameDefinition"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "redirect:/MethodRenameEntry"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "methodRenameDefinition"; + } else { + return "PageNotFound"; + } + } + + @PostMapping(value = "/MethodRenameEntry") + public MethodRenameEntryForm updateMethodRenameEntry(HttpServletRequest request, + @RequestBody @Valid MethodRenameEntryForm form, BindingResult result) { + if (result.hasErrors()) { + saveErrors(result); + form.setMethodList(DisplayListService.getInstance().getList(DisplayListService.ListType.METHODS)); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + + String methodId = form.getMethodId(); + String nameEnglish = form.getNameEnglish(); + String nameFrench = form.getNameFrench(); + String userId = getSysUserId(request); + + updateMethodNames(methodId, nameEnglish, nameFrench, userId); + + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } + + private void updateMethodNames(String methodId, String nameEnglish, String nameFrench, String userId) { + Method method = methodService.get(methodId); + + if (method != null) { + + Localization name = method.getLocalization(); + name.setEnglish(nameEnglish.trim()); + name.setFrench(nameFrench.trim()); + name.setSysUserId(userId); + + try { + localizationService.update(name); + } catch (HibernateException e) { + LogEvent.logDebug(e); + } + } + + // Refresh method names + DisplayListService.getInstance().getFreshList(DisplayListService.ListType.METHODS); + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/controller/rest/PanelCreateRestController.java b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/PanelCreateRestController.java new file mode 100644 index 0000000000..8fac99ed6c --- /dev/null +++ b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/PanelCreateRestController.java @@ -0,0 +1,215 @@ +package org.openelisglobal.testconfiguration.controller.rest; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import org.openelisglobal.common.constants.Constants; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.exception.LIMSRuntimeException; +import org.openelisglobal.common.log.LogEvent; +import org.openelisglobal.common.services.DisplayListService; +import org.openelisglobal.common.util.IdValuePair; +import org.openelisglobal.localization.valueholder.Localization; +import org.openelisglobal.panel.service.PanelService; +import org.openelisglobal.panel.valueholder.Panel; +import org.openelisglobal.role.service.RoleService; +import org.openelisglobal.role.valueholder.Role; +import org.openelisglobal.systemmodule.valueholder.SystemModule; +import org.openelisglobal.systemusermodule.valueholder.RoleModule; +import org.openelisglobal.testconfiguration.action.PanelTestConfigurationUtil; +import org.openelisglobal.testconfiguration.action.SampleTypePanel; +import org.openelisglobal.testconfiguration.form.PanelCreateForm; +import org.openelisglobal.testconfiguration.service.PanelCreateService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class PanelCreateRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] { "panelEnglishName", "panelFrenchName", + "sampleTypeId", }; + + @Autowired + private PanelService panelService; + @Autowired + private RoleService roleService; + @Autowired + private PanelTestConfigurationUtil panelTestConfigurationUtil; + @Autowired + private PanelCreateService panelCreateService; + + public static final String NAME_SEPARATOR = "$"; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/PanelCreate") + public PanelCreateForm showPanelCreate(HttpServletRequest request) { + PanelCreateForm form = new PanelCreateForm(); + + setupDisplayItems(form); + + // return findForward(FWD_SUCCESS, form); + return form; + } + + private void setupDisplayItems(PanelCreateForm form) { + HashMap> existingSampleTypePanelMap = panelTestConfigurationUtil + .createTypeOfSamplePanelMap(true); + HashMap> inactiveSampleTypePanelMap = panelTestConfigurationUtil + .createTypeOfSamplePanelMap(false); + form.setExistingSampleTypeList( + DisplayListService.getInstance().getList(DisplayListService.ListType.SAMPLE_TYPE_ACTIVE)); + + List panels = panelService.getAllPanels(); + form.setExistingEnglishNames(getExistingTestNames(panels, Locale.ENGLISH)); + form.setExistingFrenchNames(getExistingTestNames(panels, Locale.FRENCH)); + + List sampleTypePanelsExists = new ArrayList<>(); + List sampleTypePanelsInactive = new ArrayList<>(); + + for (IdValuePair typeOfSample : DisplayListService.getInstance() + .getList(DisplayListService.ListType.SAMPLE_TYPE_ACTIVE)) { + SampleTypePanel sampleTypePanel = new SampleTypePanel(typeOfSample.getValue()); + sampleTypePanel.setPanels(existingSampleTypePanelMap.get(typeOfSample.getValue())); + sampleTypePanelsExists.add(sampleTypePanel); + SampleTypePanel sampleTypePanelInactive = new SampleTypePanel(typeOfSample.getValue()); + sampleTypePanelInactive.setPanels(inactiveSampleTypePanelMap.get(typeOfSample.getValue())); + sampleTypePanelsInactive.add(sampleTypePanelInactive); + } + + form.setExistingPanelList(sampleTypePanelsExists); + form.setInactivePanelList(sampleTypePanelsInactive); + } + + private String getExistingTestNames(List panels, Locale locale) { + StringBuilder builder = new StringBuilder(NAME_SEPARATOR); + + for (Panel panel : panels) { + builder.append(panel.getLocalization().getLocalizedValue(locale)); + builder.append(NAME_SEPARATOR); + } + + return builder.toString(); + } + + @PostMapping(value = "/PanelCreate") + public PanelCreateForm postPanelCreate(HttpServletRequest request, @RequestBody @Valid PanelCreateForm form, + BindingResult result) { + if (result.hasErrors()) { + saveErrors(result); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + + String identifyingName = form.getPanelEnglishName(); + String sampleTypeId = form.getSampleTypeId(); + String systemUserId = getSysUserId(request); + + Localization localization = createLocalization(form.getPanelFrenchName(), identifyingName, systemUserId); + + Panel panel = createPanel(identifyingName, systemUserId); + SystemModule workplanModule = createSystemModule("Workplan", identifyingName, systemUserId); + SystemModule resultModule = createSystemModule("LogbookResults", identifyingName, systemUserId); + SystemModule validationModule = createSystemModule("ResultValidation", identifyingName, systemUserId); + + Role resultsEntryRole = roleService.getRoleByName(Constants.ROLE_RESULTS); + Role validationRole = roleService.getRoleByName(Constants.ROLE_VALIDATION); + + RoleModule workplanResultModule = createRoleModule(systemUserId, workplanModule, resultsEntryRole); + RoleModule resultResultModule = createRoleModule(systemUserId, resultModule, resultsEntryRole); + RoleModule validationValidationModule = createRoleModule(systemUserId, validationModule, validationRole); + + try { + panelCreateService.insert(localization, panel, workplanModule, resultModule, validationModule, + workplanResultModule, resultResultModule, validationValidationModule, sampleTypeId, systemUserId); + } catch (LIMSRuntimeException e) { + LogEvent.logDebug(e); + } + + DisplayListService.getInstance().refreshList(DisplayListService.ListType.PANELS); + DisplayListService.getInstance().refreshList(DisplayListService.ListType.PANELS_INACTIVE); + + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } + + private Localization createLocalization(String french, String english, String currentUserId) { + Localization localization = new Localization(); + localization.setEnglish(english); + localization.setFrench(french); + localization.setDescription("panel name"); + localization.setSysUserId(currentUserId); + return localization; + } + + private RoleModule createRoleModule(String userId, SystemModule workplanModule, Role role) { + RoleModule roleModule = new RoleModule(); + roleModule.setRole(role); + roleModule.setSystemModule(workplanModule); + roleModule.setSysUserId(userId); + roleModule.setHasAdd("Y"); + roleModule.setHasDelete("Y"); + roleModule.setHasSelect("Y"); + roleModule.setHasUpdate("Y"); + return roleModule; + } + + private Panel createPanel(String identifyingName, String userId) { + Panel panel = new Panel(); + panel.setDescription(identifyingName); + panel.setPanelName(identifyingName); + panel.setIsActive("N"); + panel.setSortOrderInt(Integer.MAX_VALUE); + panel.setSysUserId(userId); + return panel; + } + + private SystemModule createSystemModule(String menuItem, String identifyingName, String userId) { + SystemModule module = new SystemModule(); + module.setSystemModuleName(menuItem + ":" + identifyingName); + module.setDescription(menuItem + "=>panel=>" + identifyingName); + module.setSysUserId(userId); + module.setHasAddFlag("Y"); + module.setHasDeleteFlag("Y"); + module.setHasSelectFlag("Y"); + module.setHasUpdateFlag("Y"); + return module; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "panelCreateDefinition"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "redirect:/PanelCreate"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "panelCreateDefinition"; + } else { + return "PageNotFound"; + } + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/controller/rest/PanelOrderRestController.java b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/PanelOrderRestController.java new file mode 100644 index 0000000000..081be7b993 --- /dev/null +++ b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/PanelOrderRestController.java @@ -0,0 +1,186 @@ +package org.openelisglobal.testconfiguration.controller.rest; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.exception.LIMSRuntimeException; +import org.openelisglobal.common.log.LogEvent; +import org.openelisglobal.common.services.DisplayListService; +import org.openelisglobal.common.util.IdValuePair; +import org.openelisglobal.panel.service.PanelService; +import org.openelisglobal.panel.valueholder.Panel; +import org.openelisglobal.panel.valueholder.PanelSortOrderComparator; +import org.openelisglobal.testconfiguration.action.PanelTestConfigurationUtil; +import org.openelisglobal.testconfiguration.action.SampleTypePanel; +import org.openelisglobal.testconfiguration.form.PanelOrderForm; +import org.openelisglobal.testconfiguration.validator.PanelOrderFormValidator; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class PanelOrderRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] { "jsonChangeList" }; + + @Autowired + PanelOrderFormValidator formValidator; + @Autowired + PanelService panelService; + @Autowired + PanelTestConfigurationUtil panelTestConfigurationUtil; + + @GetMapping(value = "/PanelOrder") + public PanelOrderForm showPanelOrder(HttpServletRequest request) { + PanelOrderForm form = new PanelOrderForm(); + + setupDisplayItems(form); + + // return findForward(FWD_SUCCESS, form); + return form; + } + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + protected void setupDisplayItems(PanelOrderForm form) { + form.setPanelList(DisplayListService.getInstance().getList(DisplayListService.ListType.PANELS)); + form.setExistingSampleTypeList( + DisplayListService.getInstance().getList(DisplayListService.ListType.SAMPLE_TYPE_ACTIVE)); + + HashMap> existingSampleTypePanelMap = panelTestConfigurationUtil + .createTypeOfSamplePanelMap(true); + HashMap> inactiveSampleTypePanelMap = panelTestConfigurationUtil + .createTypeOfSamplePanelMap(false); + List sampleTypePanelsExists = new ArrayList<>(); + List sampleTypePanelsInactive = new ArrayList<>(); + + for (IdValuePair typeOfSample : DisplayListService.getInstance() + .getList(DisplayListService.ListType.SAMPLE_TYPE_ACTIVE)) { + SampleTypePanel sampleTypePanel = new SampleTypePanel(typeOfSample.getValue()); + sampleTypePanel.setPanels(existingSampleTypePanelMap.get(typeOfSample.getValue())); + if (sampleTypePanel.getPanels() != null && sampleTypePanel.getPanels().size() > 0) { + Collections.sort(sampleTypePanel.getPanels(), PanelSortOrderComparator.SORT_ORDER_COMPARATOR); + } + + sampleTypePanelsExists.add(sampleTypePanel); + SampleTypePanel sampleTypePanelInactive = new SampleTypePanel(typeOfSample.getValue()); + sampleTypePanelInactive.setPanels(inactiveSampleTypePanelMap.get(typeOfSample.getValue())); + if (sampleTypePanelInactive.getPanels() != null && sampleTypePanelInactive.getPanels().size() > 0) { + Collections.sort(sampleTypePanelInactive.getPanels(), PanelSortOrderComparator.SORT_ORDER_COMPARATOR); + } + + sampleTypePanelsInactive.add(sampleTypePanelInactive); + } + + form.setExistingPanelList(sampleTypePanelsExists); + form.setInactivePanelList(sampleTypePanelsInactive); + } + + @PostMapping(value = "/PanelOrder") + public PanelOrderForm postPanelOrder(HttpServletRequest request, @RequestBody @Valid PanelOrderForm form, + BindingResult result) throws ParseException { + formValidator.validate(form, result); + if (result.hasErrors()) { + saveErrors(result); + setupDisplayItems(form); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + + String changeList = form.getJsonChangeList(); + + JSONParser parser = new JSONParser(); + JSONObject obj = (JSONObject) parser.parse(changeList); + List orderSet = getActivateSetForActions("panels", obj, parser); + List panels = new ArrayList<>(); + + String currentUserId = getSysUserId(request); + for (ActivateSet sets : orderSet) { + Panel panel = panelService.getPanelById(sets.id); + panel.setSortOrderInt(sets.sortOrder); + panel.setSysUserId(currentUserId); + panels.add(panel); + } + + try { + panelService.updateAll(panels); + } catch (LIMSRuntimeException e) { + LogEvent.logDebug(e); + } + + DisplayListService.getInstance().refreshList(DisplayListService.ListType.PANELS); + DisplayListService.getInstance().refreshList(DisplayListService.ListType.PANELS_INACTIVE); + DisplayListService.getInstance().refreshList(DisplayListService.ListType.PANELS_ACTIVE); + + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } + + private class ActivateSet { + public String id; + public Integer sortOrder; + } + + private List getActivateSetForActions(String key, JSONObject root, JSONParser parser) { + List list = new ArrayList<>(); + + String action = (String) root.get(key); + + try { + JSONArray actionArray = (JSONArray) parser.parse(action); + + for (int i = 0; i < actionArray.size(); i++) { + ActivateSet set = new ActivateSet(); + set.id = String.valueOf(((JSONObject) actionArray.get(i)).get("id")); + Long longSort = (Long) ((JSONObject) actionArray.get(i)).get("sortOrder"); + set.sortOrder = longSort.intValue(); + list.add(set); + } + } catch (ParseException e) { + LogEvent.logDebug(e); + } + + return list; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "panelOrderDefinition"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "redirect:/PanelOrder"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "panelOrderDefinition"; + } else { + return "PageNotFound"; + } + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/controller/rest/PanelRenameEntryRestController.java b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/PanelRenameEntryRestController.java new file mode 100644 index 0000000000..8410fb7d8e --- /dev/null +++ b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/PanelRenameEntryRestController.java @@ -0,0 +1,111 @@ +package org.openelisglobal.testconfiguration.controller.rest; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.exception.LIMSRuntimeException; +import org.openelisglobal.common.log.LogEvent; +import org.openelisglobal.common.services.DisplayListService; +import org.openelisglobal.localization.service.LocalizationService; +import org.openelisglobal.localization.valueholder.Localization; +import org.openelisglobal.panel.service.PanelService; +import org.openelisglobal.panel.valueholder.Panel; +import org.openelisglobal.testconfiguration.form.PanelRenameEntryForm; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class PanelRenameEntryRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] { "panelId", "nameEnglish", "nameFrench" }; + + @Autowired + PanelService panelService; + @Autowired + LocalizationService localizationService; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/PanelRenameEntry") + public PanelRenameEntryForm showPanelRenameEntry(HttpServletRequest request) { + PanelRenameEntryForm form = new PanelRenameEntryForm(); + form.setPanelList(DisplayListService.getInstance().getList(DisplayListService.ListType.PANELS)); + + // return findForward(FWD_SUCCESS, form); + return form; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "panelRenameDefinition"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "redirect:/PanelRenameEntry"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "panelRenameDefinition"; + } else { + return "PageNotFound"; + } + } + + @PostMapping(value = "/PanelRenameEntry") + public PanelRenameEntryForm updatePanelRenameEntry(HttpServletRequest request, + @RequestBody @Valid PanelRenameEntryForm form, BindingResult result) { + if (result.hasErrors()) { + saveErrors(result); + form.setPanelList(DisplayListService.getInstance().getList(DisplayListService.ListType.PANELS)); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + + String panelId = form.getPanelId(); + String nameEnglish = form.getNameEnglish(); + String nameFrench = form.getNameFrench(); + String userId = getSysUserId(request); + + updatePanelNames(panelId, nameEnglish, nameFrench, userId); + + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } + + private void updatePanelNames(String panelId, String nameEnglish, String nameFrench, String userId) { + Panel panel = panelService.getPanelById(panelId); + + if (panel != null) { + + Localization name = panel.getLocalization(); + name.setEnglish(nameEnglish.trim()); + name.setFrench(nameFrench.trim()); + name.setSysUserId(userId); + + try { + localizationService.update(name); + } catch (LIMSRuntimeException e) { + LogEvent.logDebug(e); + } + } + DisplayListService.getInstance().getFreshList(DisplayListService.ListType.PANELS); + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/controller/rest/PanelTestAssignRestController.java b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/PanelTestAssignRestController.java new file mode 100644 index 0000000000..e5fc7d23ff --- /dev/null +++ b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/PanelTestAssignRestController.java @@ -0,0 +1,183 @@ +package org.openelisglobal.testconfiguration.controller.rest; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import org.apache.commons.validator.GenericValidator; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.exception.LIMSRuntimeException; +import org.openelisglobal.common.log.LogEvent; +import org.openelisglobal.common.services.DisplayListService; +import org.openelisglobal.common.util.IdValuePair; +import org.openelisglobal.panel.service.PanelService; +import org.openelisglobal.panel.valueholder.Panel; +import org.openelisglobal.panelitem.service.PanelItemService; +import org.openelisglobal.panelitem.valueholder.PanelItem; +import org.openelisglobal.test.service.TestService; +import org.openelisglobal.test.service.TestServiceImpl; +import org.openelisglobal.test.valueholder.Test; +import org.openelisglobal.test.valueholder.TestComparator; +import org.openelisglobal.testconfiguration.action.PanelTests; +import org.openelisglobal.testconfiguration.form.PanelTestAssignForm; +import org.owasp.encoder.Encode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +@RestController +@RequestMapping("/rest") +public class PanelTestAssignRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] { "panelId", "deactivatePanelId", "currentTests*", + "availableTests*" }; + + @Autowired + private PanelService panelService; + @Autowired + private PanelItemService panelItemService; + @Autowired + private TestService testService; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/PanelTestAssign") + public PanelTestAssignForm showPanelTestAssign(@Valid @RequestBody PanelTestAssignForm oldForm, + BindingResult result, HttpServletRequest request) { + PanelTestAssignForm form = new PanelTestAssignForm(); + + if (!result.hasFieldErrors("panelId")) { + String panelId = oldForm.getPanelId(); + if (panelId == null) { + panelId = ""; + } + form.setPanelId(panelId); + } + + setupDisplayItems(form); + + addFlashMsgsToRequest(request); + + // return findForward(FWD_SUCCESS, form); + return form; + } + + private void setupDisplayItems(PanelTestAssignForm form) { + List panels = DisplayListService.getInstance().getList(DisplayListService.ListType.PANELS); + + form.setPanelList(panels); + + if (!GenericValidator.isBlankOrNull(form.getPanelId())) { + Panel panel = panelService.getPanelById(form.getPanelId()); + IdValuePair panelPair = new IdValuePair(panel.getId(), panel.getLocalizedName()); + + List tests = new ArrayList<>(); + + List testList = getAllTestsByPanelId(panel.getId(), false); + + PanelTests panelTests = new PanelTests(panelPair); + HashSet testIdSet = new HashSet<>(); + + for (Test test : testList) { + if (test.isActive()) { + tests.add(new IdValuePair(test.getId(), TestServiceImpl.getUserLocalizedTestName(test))); + testIdSet.add(test.getId()); + } + } + panelTests.setTests(tests, testIdSet); + + form.setSelectedPanel(panelTests); + } + } + + public List getAllTestsByPanelId(String panelId, boolean alphabetical) { + List testList = new ArrayList<>(); + + List testLinks = panelItemService.getPanelItemsForPanel(panelId); + + for (PanelItem link : testLinks) { + testList.add(link.getTest()); + } + + if (alphabetical) { + Collections.sort(testList, TestComparator.NAME_COMPARATOR); + } + return testList; + } + + @PostMapping(value = "/PanelTestAssign") + public PanelTestAssignForm postPanelTestAssign(HttpServletRequest request, + @RequestBody @Valid PanelTestAssignForm form, BindingResult result, RedirectAttributes redirectAttributes) { + if (result.hasErrors()) { + saveErrors(result); + setupDisplayItems(form); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + + String panelId = form.getPanelId(); + String currentUser = getSysUserId(request); + boolean updatePanel = false; + + Panel panel = panelService.getPanelById(panelId); + + if (!GenericValidator.isBlankOrNull(panelId)) { + List panelItems = panelItemService.getPanelItemsForPanel(panelId); + + List newTestIds = form.getCurrentTests(); + List newTests = new ArrayList<>(); + for (String testId : newTestIds) { + newTests.add(testService.get(testId)); + } + + try { + panelItemService.updatePanelItems(panelItems, panel, updatePanel, currentUser, newTests); + } catch (LIMSRuntimeException e) { + LogEvent.logDebug(e); + } + } + + DisplayListService.getInstance().refreshList(DisplayListService.ListType.PANELS); + DisplayListService.getInstance().refreshList(DisplayListService.ListType.PANELS_INACTIVE); + + redirectAttributes.addFlashAttribute(FWD_SUCCESS, true); + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "panelAssignDefinition"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + String url = "/PanelTestAssign?panelId=" + Encode.forUriComponent(request.getParameter("panelId")); + return "redirect:" + url; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "panelAssignDefinition"; + } else { + return "PageNotFound"; + } + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/controller/rest/ResultSelectListAddRestController.java b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/ResultSelectListAddRestController.java new file mode 100644 index 0000000000..160cfdfa5c --- /dev/null +++ b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/ResultSelectListAddRestController.java @@ -0,0 +1,100 @@ +package org.openelisglobal.testconfiguration.controller.rest; + +import javax.servlet.http.HttpServletRequest; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.services.DisplayListService; +import org.openelisglobal.common.services.DisplayListService.ListType; +import org.openelisglobal.test.service.TestService; +import org.openelisglobal.testconfiguration.form.ResultSelectListForm; +import org.openelisglobal.testconfiguration.service.ResultSelectListService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +@RestController +@RequestMapping("/rest") +public class ResultSelectListAddRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] { "nameEnglish", "nameFrench", "testSelectListJson" }; + + @Autowired + private TestService testService; + @Autowired + private ResultSelectListService resultSelectListService; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/ResultSelectListAdd") + public ResultSelectListForm showCreateResultSelectList(HttpServletRequest request) { + ResultSelectListForm form = new ResultSelectListForm(); + form.setPage("1"); + addFlashMsgsToRequest(request); + // return findForward(FWD_SUCCESS, form); + return form; + } + + @PostMapping(value = "/ResultSelectListAdd") + public ResultSelectListForm showResultSelectListAddToTest(HttpServletRequest request, + @RequestBody ResultSelectListForm form) { + form.setPage("2"); + if ("".equalsIgnoreCase(form.getNameEnglish())) { + form.setNameEnglish(form.getNameFrench()); + } else if ("".equalsIgnoreCase(form.getNameFrench())) { + form.setNameFrench(form.getNameEnglish()); + } + form.setTests(testService.getAllTestsByDictionaryResult()); + form.setTestDictionary(resultSelectListService.getTestSelectDictionary()); + addFlashMsgsToRequest(request); + // return findForward(FWD_SUCCESS, form); + return form; + } + + @PostMapping(value = "/SaveResultSelectList") + public ResultSelectListForm SaveResultSelectList(HttpServletRequest request, @RequestBody ResultSelectListForm form, + RedirectAttributes redirectAttributes) { + + addFlashMsgsToRequest(request); + String currentUserId = getSysUserId(request); + boolean saved = resultSelectListService.addResultSelectList(form, currentUserId); + if (saved) { + redirectAttributes.addFlashAttribute(FWD_SUCCESS, true); + DisplayListService.getInstance().refreshList(ListType.DICTIONARY_TEST_RESULTS); + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "resultSelectListDefinition"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "redirect:/ResultSelectListAdd"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "resultSelectListDefinition"; + } else { + return "PageNotFound"; + } + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/controller/rest/SampleTypeCreateRestController.java b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/SampleTypeCreateRestController.java new file mode 100644 index 0000000000..9663c9ca4a --- /dev/null +++ b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/SampleTypeCreateRestController.java @@ -0,0 +1,193 @@ +package org.openelisglobal.testconfiguration.controller.rest; + +import java.util.List; +import java.util.Locale; +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import org.openelisglobal.common.constants.Constants; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.exception.LIMSRuntimeException; +import org.openelisglobal.common.log.LogEvent; +import org.openelisglobal.common.services.DisplayListService; +import org.openelisglobal.localization.valueholder.Localization; +import org.openelisglobal.role.service.RoleService; +import org.openelisglobal.role.valueholder.Role; +import org.openelisglobal.systemmodule.valueholder.SystemModule; +import org.openelisglobal.systemusermodule.valueholder.RoleModule; +import org.openelisglobal.testconfiguration.form.SampleTypeCreateForm; +import org.openelisglobal.testconfiguration.service.SampleTypeCreateService; +import org.openelisglobal.typeofsample.service.TypeOfSampleService; +import org.openelisglobal.typeofsample.valueholder.TypeOfSample; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class SampleTypeCreateRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] { "sampleTypeEnglishName", "sampleTypeFrenchName" }; + + public static final String NAME_SEPARATOR = "$"; + + @Autowired + private TypeOfSampleService typeOfSampleService; + @Autowired + private RoleService roleService; + @Autowired + private SampleTypeCreateService sampleTypeCreateService; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/SampleTypeCreate") + public SampleTypeCreateForm showSampleTypeCreate(HttpServletRequest request) { + + SampleTypeCreateForm form = new SampleTypeCreateForm(); + + setupDisplayItems(form); + + // return findForward(FWD_SUCCESS, form); + return form; + } + + private void setupDisplayItems(SampleTypeCreateForm form) { + form.setExistingSampleTypeList( + DisplayListService.getInstance().getList(DisplayListService.ListType.SAMPLE_TYPE_ACTIVE)); + form.setInactiveSampleTypeList( + DisplayListService.getInstance().getList(DisplayListService.ListType.SAMPLE_TYPE_INACTIVE)); + List typeOfSamples = typeOfSampleService.getAllTypeOfSamples(); + form.setExistingEnglishNames(getExistingTestNames(typeOfSamples, Locale.ENGLISH)); + form.setExistingFrenchNames(getExistingTestNames(typeOfSamples, Locale.FRENCH)); + } + + private String getExistingTestNames(List typeOfSamples, Locale locale) { + StringBuilder builder = new StringBuilder(NAME_SEPARATOR); + + for (TypeOfSample typeOfSample : typeOfSamples) { + builder.append(typeOfSample.getLocalization().getLocalizedValue(locale)); + builder.append(NAME_SEPARATOR); + } + + return builder.toString(); + } + + @PostMapping(value = "/SampleTypeCreate") + public SampleTypeCreateForm postSampleTypeCreate(HttpServletRequest request, + @RequestBody @Valid SampleTypeCreateForm form, BindingResult result) { + if (result.hasErrors()) { + saveErrors(result); + setupDisplayItems(form); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + String identifyingName = form.getSampleTypeEnglishName(); + String userId = getSysUserId(request); + + Localization localization = createLocalization(form.getSampleTypeFrenchName(), identifyingName, userId); + + TypeOfSample typeOfSample = createTypeOfSample(identifyingName, userId); + + SystemModule workplanModule = createSystemModule("Workplan", identifyingName, userId); + SystemModule resultModule = createSystemModule("LogbookResults", identifyingName, userId); + SystemModule validationModule = createSystemModule("ResultValidation", identifyingName, userId); + + Role resultsEntryRole = roleService.getRoleByName(Constants.ROLE_RESULTS); + Role validationRole = roleService.getRoleByName(Constants.ROLE_VALIDATION); + + RoleModule workplanResultModule = createRoleModule(userId, workplanModule, resultsEntryRole); + RoleModule resultResultModule = createRoleModule(userId, resultModule, resultsEntryRole); + RoleModule validationValidationModule = createRoleModule(userId, validationModule, validationRole); + + try { + sampleTypeCreateService.createAndInsertSampleType(localization, typeOfSample, workplanModule, resultModule, + validationModule, workplanResultModule, resultResultModule, validationValidationModule); + } catch (LIMSRuntimeException e) { + LogEvent.logDebug(e); + } + DisplayListService.getInstance().refreshList(DisplayListService.ListType.SAMPLE_TYPE); + DisplayListService.getInstance().refreshList(DisplayListService.ListType.SAMPLE_TYPE_ACTIVE); + DisplayListService.getInstance().refreshList(DisplayListService.ListType.SAMPLE_TYPE_INACTIVE); + + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } + + private Localization createLocalization(String french, String english, String currentUserId) { + Localization localization = new Localization(); + localization.setEnglish(english); + localization.setFrench(french); + localization.setDescription("type of sample name"); + localization.setSysUserId(currentUserId); + return localization; + } + + private RoleModule createRoleModule(String userId, SystemModule workplanModule, Role role) { + RoleModule roleModule = new RoleModule(); + roleModule.setRole(role); + roleModule.setSystemModule(workplanModule); + roleModule.setSysUserId(userId); + roleModule.setHasAdd("Y"); + roleModule.setHasDelete("Y"); + roleModule.setHasSelect("Y"); + roleModule.setHasUpdate("Y"); + return roleModule; + } + + private TypeOfSample createTypeOfSample(String identifyingName, String userId) { + TypeOfSample typeOfSample = new TypeOfSample(); + typeOfSample.setDescription(identifyingName); + typeOfSample.setDomain("H"); + typeOfSample.setLocalAbbreviation( + identifyingName.length() > 10 ? identifyingName.substring(0, 10) : identifyingName); + typeOfSample.setIsActive(false); + typeOfSample.setSortOrder(Integer.MAX_VALUE); + typeOfSample.setSysUserId(userId); + String identifyingNameKey = identifyingName.replaceAll(" ", "_"); + typeOfSample.setNameKey("Sample.type." + identifyingNameKey); + return typeOfSample; + } + + private SystemModule createSystemModule(String menuItem, String identifyingName, String userId) { + SystemModule module = new SystemModule(); + module.setSystemModuleName(menuItem + ":" + identifyingName); + module.setDescription(menuItem + "=>" + identifyingName); + module.setSysUserId(userId); + module.setHasAddFlag("Y"); + module.setHasDeleteFlag("Y"); + module.setHasSelectFlag("Y"); + module.setHasUpdateFlag("Y"); + return module; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "sampleTypeCreateDefinition"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "redirect:/SampleTypeCreate"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "sampleTypeCreateDefinition"; + } else { + return "PageNotFound"; + } + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/controller/rest/SampleTypeOrderRestController.java b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/SampleTypeOrderRestController.java new file mode 100644 index 0000000000..785cb192af --- /dev/null +++ b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/SampleTypeOrderRestController.java @@ -0,0 +1,148 @@ +package org.openelisglobal.testconfiguration.controller.rest; + +import java.util.ArrayList; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import org.hibernate.HibernateException; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.log.LogEvent; +import org.openelisglobal.common.services.DisplayListService; +import org.openelisglobal.testconfiguration.form.SampleTypeOrderForm; +import org.openelisglobal.testconfiguration.validator.SampleTypeOrderFormValidator; +import org.openelisglobal.typeofsample.service.TypeOfSampleService; +import org.openelisglobal.typeofsample.valueholder.TypeOfSample; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class SampleTypeOrderRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] { "jsonChangeList" }; + + @Autowired + SampleTypeOrderFormValidator formValidator; + @Autowired + TypeOfSampleService typeOfSampleService; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/SampleTypeOrder") + public SampleTypeOrderForm showSampleTypeOrder(HttpServletRequest request) { + SampleTypeOrderForm form = new SampleTypeOrderForm(); + + setupDisplayItems(form); + + // return findForward(FWD_SUCCESS, form); + return form; + } + + private void setupDisplayItems(SampleTypeOrderForm form) { + form.setSampleTypeList(DisplayListService.getInstance().getList(DisplayListService.ListType.SAMPLE_TYPE)); + } + + private class ActivateSet { + public String id; + public Integer sortOrder; + } + + @PostMapping(value = "/SampleTypeOrder") + public SampleTypeOrderForm postSampleTypeOrder(HttpServletRequest request, + @RequestBody @Valid SampleTypeOrderForm form, BindingResult result) throws ParseException { + formValidator.validate(form, result); + if (result.hasErrors()) { + saveErrors(result); + setupDisplayItems(form); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + + String changeList = form.getJsonChangeList(); + + JSONParser parser = new JSONParser(); + JSONObject obj = (JSONObject) parser.parse(changeList); + List orderSet = getActivateSetForActions("sampleTypes", obj, parser); + List typeOfSamples = new ArrayList<>(); + + String currentUserId = getSysUserId(request); + for (ActivateSet sets : orderSet) { + TypeOfSample typeOfSample = typeOfSampleService.getTypeOfSampleById(sets.id); + typeOfSample.setSortOrder(sets.sortOrder); + typeOfSample.setSysUserId(currentUserId); + typeOfSamples.add(typeOfSample); + } + + try { + typeOfSampleService.updateAll(typeOfSamples); + } catch (HibernateException e) { + LogEvent.logDebug(e); + } + + DisplayListService.getInstance().refreshList(DisplayListService.ListType.SAMPLE_TYPE); + DisplayListService.getInstance().refreshList(DisplayListService.ListType.SAMPLE_TYPE_ACTIVE); + DisplayListService.getInstance().refreshList(DisplayListService.ListType.SAMPLE_TYPE_INACTIVE); + + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } + + private List getActivateSetForActions(String key, JSONObject root, JSONParser parser) { + List list = new ArrayList<>(); + + String action = (String) root.get(key); + + try { + JSONArray actionArray = (JSONArray) parser.parse(action); + + for (int i = 0; i < actionArray.size(); i++) { + ActivateSet set = new ActivateSet(); + set.id = String.valueOf(((JSONObject) actionArray.get(i)).get("id")); + Long longSort = (Long) ((JSONObject) actionArray.get(i)).get("sortOrder"); + set.sortOrder = longSort.intValue(); + list.add(set); + } + } catch (ParseException e) { + LogEvent.logDebug(e); + } + + return list; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "sampleTypeOrderDefinition"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "redirect:/SampleTypeOrder"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "sampleTypeOrderDefinition"; + } else { + return "PageNotFound"; + } + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/controller/rest/SampleTypeRenameEntryRestController.java b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/SampleTypeRenameEntryRestController.java new file mode 100644 index 0000000000..a711e33623 --- /dev/null +++ b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/SampleTypeRenameEntryRestController.java @@ -0,0 +1,119 @@ +package org.openelisglobal.testconfiguration.controller.rest; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import org.hibernate.HibernateException; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.log.LogEvent; +import org.openelisglobal.common.services.DisplayListService; +import org.openelisglobal.localization.service.LocalizationService; +import org.openelisglobal.localization.valueholder.Localization; +import org.openelisglobal.testconfiguration.form.SampleTypeRenameEntryForm; +import org.openelisglobal.typeofsample.service.TypeOfSampleService; +import org.openelisglobal.typeofsample.valueholder.TypeOfSample; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class SampleTypeRenameEntryRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] { "sampleTypeId", "nameEnglish", "nameFrench" }; + + @Autowired + private TypeOfSampleService typeOfSampleService; + @Autowired + private LocalizationService localizationService; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/SampleTypeRenameEntry") + public SampleTypeRenameEntryForm showSampleTypeRenameEntry(HttpServletRequest request) { + SampleTypeRenameEntryForm form = new SampleTypeRenameEntryForm(); + + form.setSampleTypeList( + DisplayListService.getInstance().getList(DisplayListService.ListType.SAMPLE_TYPE_ACTIVE)); + + // return findForward(FWD_SUCCESS, form); + return form; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "sampleTypeRenameDefinition"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "redirect:/SampleTypeRenameEntry"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "sampleTypeRenameDefinition"; + } else { + return "PageNotFound"; + } + } + + @PostMapping(value = "/SampleTypeRenameEntry") + public SampleTypeRenameEntryForm updateSampleTypeRenameEntry(HttpServletRequest request, + @RequestBody @Valid SampleTypeRenameEntryForm form, BindingResult result) { + if (result.hasErrors()) { + saveErrors(result); + form.setSampleTypeList( + DisplayListService.getInstance().getList(DisplayListService.ListType.SAMPLE_TYPE_ACTIVE)); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + + String sampleTypeId = form.getSampleTypeId(); + String nameEnglish = form.getNameEnglish(); + String nameFrench = form.getNameFrench(); + String userId = getSysUserId(request); + + updateSampleTypeNames(sampleTypeId, nameEnglish, nameFrench, userId); + + form.setSampleTypeList( + DisplayListService.getInstance().getList(DisplayListService.ListType.SAMPLE_TYPE_ACTIVE)); + + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } + + private void updateSampleTypeNames(String sampleTypeId, String nameEnglish, String nameFrench, String userId) { + TypeOfSample typeOfSample = typeOfSampleService.getTypeOfSampleById(sampleTypeId); + + if (typeOfSample != null) { + + Localization name = typeOfSample.getLocalization(); + name.setEnglish(nameEnglish.trim()); + name.setFrench(nameFrench.trim()); + name.setSysUserId(userId); + + try { + localizationService.update(name); + } catch (HibernateException e) { + LogEvent.logDebug(e); + } + } + + // Refresh SampleType names + DisplayListService.getInstance().getFreshList(DisplayListService.ListType.SAMPLE_TYPE_ACTIVE); + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/controller/rest/SampleTypeTestAssignRestController.java b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/SampleTypeTestAssignRestController.java new file mode 100644 index 0000000000..70e998cc7a --- /dev/null +++ b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/SampleTypeTestAssignRestController.java @@ -0,0 +1,179 @@ +package org.openelisglobal.testconfiguration.controller.rest; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.stream.Collectors; +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import org.hibernate.HibernateException; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.log.LogEvent; +import org.openelisglobal.common.services.DisplayListService; +import org.openelisglobal.common.util.IdValuePair; +import org.openelisglobal.spring.util.SpringContext; +import org.openelisglobal.test.service.TestServiceImpl; +import org.openelisglobal.test.valueholder.Test; +import org.openelisglobal.testconfiguration.form.SampleTypeTestAssignForm; +import org.openelisglobal.testconfiguration.service.SampleTypeTestAssignService; +import org.openelisglobal.typeofsample.service.TypeOfSampleService; +import org.openelisglobal.typeofsample.service.TypeOfSampleTestService; +import org.openelisglobal.typeofsample.valueholder.TypeOfSample; +import org.openelisglobal.typeofsample.valueholder.TypeOfSampleTest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class SampleTypeTestAssignRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] { "testId", "sampleTypeId", "deactivateSampleTypeId" }; + + @Autowired + private TypeOfSampleService typeOfSampleService; + @Autowired + private TypeOfSampleTestService typeOfSampleTestService; + @Autowired + private SampleTypeTestAssignService sampleTypeTestAssignService; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/SampleTypeTestAssign") + public SampleTypeTestAssignForm showSampleTypeTestAssign(HttpServletRequest request) { + SampleTypeTestAssignForm form = new SampleTypeTestAssignForm(); + + setupDisplayItems(form); + + // return findForward(FWD_SUCCESS, form); + return form; + } + + private void setupDisplayItems(SampleTypeTestAssignForm form) { + List typeOfSamples = DisplayListService.getInstance() + .getListWithLeadingBlank(DisplayListService.ListType.SAMPLE_TYPE); + LinkedHashMap> sampleTypesTestsMap = new LinkedHashMap<>(typeOfSamples.size()); + + for (IdValuePair sampleTypePair : typeOfSamples) { + List tests = new ArrayList<>(); + sampleTypesTestsMap.put(sampleTypePair, tests); + List testList = typeOfSampleService.getAllTestsBySampleTypeId(sampleTypePair.getId()); + + for (Test test : testList) { + if (test.isActive()) { + tests.add(new IdValuePair(test.getId(), TestServiceImpl.getLocalizedTestNameWithType(test))); + } + } + } + + // we can't just append the original list because that list is in the cache + List joinedList = new ArrayList<>(typeOfSamples); + joinedList.addAll(DisplayListService.getInstance().getList(DisplayListService.ListType.SAMPLE_TYPE_INACTIVE)); + form.setSampleTypeList(joinedList); + form.setSampleTypeTestList(sampleTypesTestsMap); + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "sampleTypeAssignDefinition"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "redirect:/SampleTypeTestAssign"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "sampleTypeAssignDefinition"; + } else { + return "PageNotFound"; + } + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } + + @PostMapping(value = "/SampleTypeTestAssign") + public SampleTypeTestAssignForm postSampleTypeTestAssign(HttpServletRequest request, + @RequestBody @Valid SampleTypeTestAssignForm form, BindingResult result) { + if (result.hasErrors()) { + saveErrors(result); + setupDisplayItems(form); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + String testId = form.getTestId(); + String sampleTypeId = form.getSampleTypeId(); + String deactivateSampleTypeId = form.getDeactivateSampleTypeId(); + boolean updateTypeOfSample = false; + String systemUserId = getSysUserId(request); + + TypeOfSample typeOfSample = SpringContext.getBean(TypeOfSampleService.class) + .getTransientTypeOfSampleById(sampleTypeId); + TypeOfSample deActivateTypeOfSample = null; + + // Test test = new TestService(testId).getTest(); + + // This covers the case that they are moving the test to the same sample type + // they are moving it from + if (sampleTypeId.equals(deactivateSampleTypeId)) { + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } + + List typeOfSampleTestOld = typeOfSampleTestService.getTypeOfSampleTestsForTest(testId); + boolean deleteExistingTypeOfSampleTest = false; + List typeOfSamplesTestID = new ArrayList<>(); + + if (typeOfSampleTestOld != null) { + typeOfSamplesTestID = typeOfSampleTestOld.stream().map(e -> e.getId()).collect(Collectors.toList()); + deleteExistingTypeOfSampleTest = true; + } + // --------------------------- + /* + * if( "N".equals(typeOfSample.getIsActive())){ typeOfSample.setIsActive(true); + * typeOfSample.setSysUserId(currentUser); updateTypeOfSample = true; } + */ + + // Boolean value = false; + if (typeOfSample.getIsActive() == false) { + typeOfSample.setIsActive(true); + typeOfSample.setSysUserId(systemUserId); + updateTypeOfSample = true; + } + + // ------------------------------------------ + if (!org.apache.commons.validator.GenericValidator.isBlankOrNull(deactivateSampleTypeId)) { + deActivateTypeOfSample = SpringContext.getBean(TypeOfSampleService.class) + .getTransientTypeOfSampleById(deactivateSampleTypeId); + deActivateTypeOfSample.setIsActive(false); + deActivateTypeOfSample.setSysUserId(systemUserId); + } + + try { + sampleTypeTestAssignService.update(typeOfSample, testId, typeOfSamplesTestID, sampleTypeId, + deleteExistingTypeOfSampleTest, updateTypeOfSample, deActivateTypeOfSample, systemUserId); + } catch (HibernateException e) { + LogEvent.logError(e); + } + + DisplayListService.getInstance().refreshList(DisplayListService.ListType.SAMPLE_TYPE); + DisplayListService.getInstance().refreshList(DisplayListService.ListType.SAMPLE_TYPE_ACTIVE); + DisplayListService.getInstance().refreshList(DisplayListService.ListType.SAMPLE_TYPE_INACTIVE); + + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/controller/rest/SelectListRenameEntryRestController.java b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/SelectListRenameEntryRestController.java new file mode 100644 index 0000000000..a7e0bc9896 --- /dev/null +++ b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/SelectListRenameEntryRestController.java @@ -0,0 +1,90 @@ +package org.openelisglobal.testconfiguration.controller.rest; + +import javax.servlet.http.HttpServletRequest; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.services.DisplayListService; +import org.openelisglobal.common.services.DisplayListService.ListType; +import org.openelisglobal.common.validator.BaseErrors; +import org.openelisglobal.internationalization.MessageUtil; +import org.openelisglobal.testconfiguration.form.ResultSelectListRenameForm; +import org.openelisglobal.testconfiguration.service.ResultSelectListService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.Errors; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +@RestController +@RequestMapping("/rest") +public class SelectListRenameEntryRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] { "nameEnglish", "nameFrench", "resultSelectOptionId" }; + + @Autowired + private ResultSelectListService resultSelectListService; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/SelectListRenameEntry") + public ResultSelectListRenameForm showUomRenameEntry(HttpServletRequest request) { + ResultSelectListRenameForm form = new ResultSelectListRenameForm(); + + form.setResultSelectOptionList(resultSelectListService.getAllSelectListOptions()); + // return findForward(FWD_SUCCESS, form); + return form; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "resultSelectListRenameDefinition"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "redirect:/SelectListRenameEntry"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "resultSelectListRenameDefinition"; + } else { + return "PageNotFound"; + } + } + + @PostMapping(value = "/SelectListRenameEntry") + public ResultSelectListRenameForm updateUomRenameEntry(HttpServletRequest request, + @RequestBody ResultSelectListRenameForm form, RedirectAttributes redirectAttributes) { + + boolean renamed = resultSelectListService.renameOption(form, getSysUserId(request)); + DisplayListService.getInstance().refreshList(ListType.DICTIONARY_TEST_RESULTS); + + if (renamed) { + redirectAttributes.addFlashAttribute(FWD_SUCCESS, true); + form.setResultSelectOptionList(resultSelectListService.getAllSelectListOptions()); + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } else { + Errors errors = new BaseErrors(); + errors.reject(MessageUtil.getMessage("alert.error")); + saveErrors(errors); + form.setResultSelectOptionList(resultSelectListService.getAllSelectListOptions()); + + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestActivationRestController.java b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestActivationRestController.java new file mode 100644 index 0000000000..bb81caccb4 --- /dev/null +++ b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestActivationRestController.java @@ -0,0 +1,307 @@ +package org.openelisglobal.testconfiguration.controller.rest; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import org.apache.commons.lang.math.NumberUtils; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.exception.LIMSRuntimeException; +import org.openelisglobal.common.log.LogEvent; +import org.openelisglobal.common.services.DisplayListService; +import org.openelisglobal.common.util.IdValuePair; +import org.openelisglobal.spring.util.SpringContext; +import org.openelisglobal.test.beanItems.TestActivationBean; +import org.openelisglobal.test.service.TestService; +import org.openelisglobal.test.service.TestServiceImpl; +import org.openelisglobal.test.valueholder.Test; +import org.openelisglobal.testconfiguration.form.TestActivationForm; +import org.openelisglobal.testconfiguration.service.TestActivationService; +import org.openelisglobal.testconfiguration.validator.TestActivationFormValidator; +import org.openelisglobal.typeofsample.service.TypeOfSampleService; +import org.openelisglobal.typeofsample.valueholder.TypeOfSample; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class TestActivationRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] { "jsonChangeList", "activeTestList*.sampleType.id", + "inactiveTestList*.sampleType.id" }; + + @Autowired + private TestActivationFormValidator formValidator; + @Autowired + private TypeOfSampleService typeOfSampleService; + @Autowired + private TestActivationService testActivationService; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/TestActivation") + public TestActivationForm showTestActivation(HttpServletRequest request) { + TestActivationForm form = new TestActivationForm(); + + setupDisplayItems(form); + + // return findForward(FWD_SUCCESS, form); + return form; + } + + private void setupDisplayItems(TestActivationForm form) { + List activeTestList = createTestList(true, false); + List inactiveTestList = createTestList(false, false); + form.setActiveTestList(activeTestList); + form.setInactiveTestList(inactiveTestList); + } + + private List createTestList(boolean active, boolean refresh) { + ArrayList testList = new ArrayList<>(); + + if (refresh) { + DisplayListService.getInstance().refreshList(active ? DisplayListService.ListType.SAMPLE_TYPE_ACTIVE + : DisplayListService.ListType.SAMPLE_TYPE_INACTIVE); + } + + List sampleTypeList = DisplayListService.getInstance() + .getList(active ? DisplayListService.ListType.SAMPLE_TYPE_ACTIVE + : DisplayListService.ListType.SAMPLE_TYPE_INACTIVE); + + // if not active we use alphabetical ordering, the default is display order + if (!active) { + IdValuePair.sortByValue(sampleTypeList); + } + + for (IdValuePair pair : sampleTypeList) { + TestActivationBean bean = new TestActivationBean(); + + List tests = typeOfSampleService.getAllTestsBySampleTypeId(pair.getId()); + List activeTests = new ArrayList<>(); + List inactiveTests = new ArrayList<>(); + + // initial ordering will be by display order. Inactive tests will then be + // re-ordered alphabetically + Collections.sort(tests, new Comparator() { + @Override + public int compare(Test o1, Test o2) { + // compare sort order + if (NumberUtils.isNumber(o1.getSortOrder()) && NumberUtils.isNumber(o2.getSortOrder())) { + return Integer.parseInt(o1.getSortOrder()) - Integer.parseInt(o2.getSortOrder()); + // if o2 has no sort order o1 does, o2 is assumed to be higher + } else if (NumberUtils.isNumber(o1.getSortOrder())) { + return -1; + // if o1 has no sort order o2 does, o1 is assumed to be higher + } else if (NumberUtils.isNumber(o2.getSortOrder())) { + return 1; + // else they are considered equal + } else { + return 0; + } + } + }); + + for (Test test : tests) { + if (test.isActive()) { + activeTests.add(new IdValuePair(test.getId(), TestServiceImpl.getUserLocalizedTestName(test))); + } else { + inactiveTests.add(new IdValuePair(test.getId(), TestServiceImpl.getUserLocalizedTestName(test))); + } + } + + IdValuePair.sortByValue(inactiveTests); + + bean.setActiveTests(activeTests); + bean.setInactiveTests(inactiveTests); + if (!activeTests.isEmpty() || !inactiveTests.isEmpty()) { + bean.setSampleType(pair); + testList.add(bean); + } + } + + return testList; + } + + @PostMapping(value = "/TestActivation") + public TestActivationForm postTestActivation(HttpServletRequest request, + @RequestBody @Valid TestActivationForm form, BindingResult result) throws ParseException { + formValidator.validate(form, result); + if (result.hasErrors()) { + saveErrors(result); + setupDisplayItems(form); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + + String changeList = form.getJsonChangeList(); + + JSONParser parser = new JSONParser(); + + JSONObject obj = (JSONObject) parser.parse(changeList); + + List activateSampleSets = getActivateSetForActions("activateSample", obj, parser); + List deactivateSampleIds = getIdsForActions("deactivateSample", obj, parser); + List activateTestSets = getActivateSetForActions("activateTest", obj, parser); + List deactivateTestIds = getIdsForActions("deactivateTest", obj, parser); + + List deactivateTests = getDeactivatedTests(deactivateTestIds); + List activateTests = getActivatedTests(activateTestSets); + List deactivateSampleTypes = getDeactivatedSampleTypes(deactivateSampleIds); + List activateSampleTypes = getActivatedSampleTypes(activateSampleSets); + + try { + testActivationService.updateAll(deactivateTests, activateTests, deactivateSampleTypes, activateSampleTypes); + } catch (LIMSRuntimeException e) { + LogEvent.logDebug(e); + } + + List activeTestList = createTestList(true, true); + List inactiveTestList = createTestList(false, true); + form.setActiveTestList(activeTestList); + form.setInactiveTestList(inactiveTestList); + + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } + + private List getDeactivatedTests(List testIds) { + List tests = new ArrayList<>(); + + for (String testId : testIds) { + Test test = SpringContext.getBean(TestService.class).get(testId); + + test.setIsActive("N"); + test.setSysUserId(getSysUserId(request)); + tests.add(test); + } + + return tests; + } + + private List getActivatedTests(List testIds) { + List tests = new ArrayList<>(); + + for (ActivateSet set : testIds) { + Test test = SpringContext.getBean(TestService.class).get(set.id); + test.setIsActive("Y"); + test.setSortOrder(String.valueOf(set.sortOrder * 10)); + test.setSysUserId(getSysUserId(request)); + tests.add(test); + } + + return tests; + } + + private List getDeactivatedSampleTypes(List sampleTypeIds) { + List sampleTypes = new ArrayList<>(); + + for (String id : sampleTypeIds) { + TypeOfSample typeOfSample = SpringContext.getBean(TypeOfSampleService.class) + .getTransientTypeOfSampleById(id); + typeOfSample.setActive(false); + typeOfSample.setSysUserId(getSysUserId(request)); + sampleTypes.add(typeOfSample); + } + + return sampleTypes; + } + + private List getActivatedSampleTypes(List sampleTypeSets) { + List sampleTypes = new ArrayList<>(); + + for (ActivateSet set : sampleTypeSets) { + TypeOfSample typeOfSample = SpringContext.getBean(TypeOfSampleService.class) + .getTransientTypeOfSampleById(set.id); + typeOfSample.setActive(true); + typeOfSample.setSortOrder(set.sortOrder * 10); + typeOfSample.setSysUserId(getSysUserId(request)); + sampleTypes.add(typeOfSample); + } + + return sampleTypes; + } + + private List getIdsForActions(String key, JSONObject root, JSONParser parser) { + List list = new ArrayList<>(); + + String action = (String) root.get(key); + + try { + JSONArray actionArray = (JSONArray) parser.parse(action); + + for (int i = 0; i < actionArray.size(); i++) { + list.add((String) ((JSONObject) actionArray.get(i)).get("id")); + } + } catch (ParseException e) { + LogEvent.logDebug(e); + } + + return list; + } + + private List getActivateSetForActions(String key, JSONObject root, JSONParser parser) { + List list = new ArrayList<>(); + + String action = (String) root.get(key); + + try { + JSONArray actionArray = (JSONArray) parser.parse(action); + + for (int i = 0; i < actionArray.size(); i++) { + ActivateSet set = new ActivateSet(); + set.id = String.valueOf(((JSONObject) actionArray.get(i)).get("id")); + Long longSort = (Long) ((JSONObject) actionArray.get(i)).get("sortOrder"); + set.sortOrder = longSort.intValue(); + list.add(set); + } + } catch (ParseException e) { + LogEvent.logDebug(e); + } + + return list; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "testActivationDefinition"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "testActivationDefinition"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "testActivationDefinition"; + } else { + return "PageNotFound"; + } + } + + private class ActivateSet { + public String id; + public Integer sortOrder; + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestAddRestController.java b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestAddRestController.java new file mode 100644 index 0000000000..98f0803c8f --- /dev/null +++ b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestAddRestController.java @@ -0,0 +1,613 @@ +package org.openelisglobal.testconfiguration.controller.rest; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import org.apache.commons.validator.GenericValidator; +import org.hibernate.HibernateException; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.log.LogEvent; +import org.openelisglobal.common.services.DisplayListService; +import org.openelisglobal.common.services.DisplayListService.ListType; +import org.openelisglobal.common.util.IdValuePair; +import org.openelisglobal.common.util.StringUtil; +import org.openelisglobal.dictionary.service.DictionaryService; +import org.openelisglobal.dictionary.valueholder.Dictionary; +import org.openelisglobal.localization.service.LocalizationServiceImpl; +import org.openelisglobal.localization.valueholder.Localization; +import org.openelisglobal.panel.service.PanelService; +import org.openelisglobal.panelitem.valueholder.PanelItem; +import org.openelisglobal.resultlimit.service.ResultLimitService; +import org.openelisglobal.resultlimits.valueholder.ResultLimit; +import org.openelisglobal.spring.util.SpringContext; +import org.openelisglobal.test.service.TestSectionService; +import org.openelisglobal.test.service.TestService; +import org.openelisglobal.test.valueholder.Test; +import org.openelisglobal.test.valueholder.TestSection; +import org.openelisglobal.testconfiguration.form.TestAddForm; +import org.openelisglobal.testconfiguration.service.TestAddService; +import org.openelisglobal.testconfiguration.validator.TestAddFormValidator; +import org.openelisglobal.testresult.service.TestResultService; +import org.openelisglobal.testresult.valueholder.TestResult; +import org.openelisglobal.typeofsample.service.TypeOfSampleService; +import org.openelisglobal.typeofsample.valueholder.TypeOfSample; +import org.openelisglobal.typeofsample.valueholder.TypeOfSampleTest; +import org.openelisglobal.typeoftestresult.service.TypeOfTestResultService; +import org.openelisglobal.typeoftestresult.service.TypeOfTestResultServiceImpl; +import org.openelisglobal.unitofmeasure.service.UnitOfMeasureService; +import org.openelisglobal.unitofmeasure.valueholder.UnitOfMeasure; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.BindingResult; +import org.springframework.validation.Errors; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class TestAddRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] { "jsonWad", "loinc" }; + + @Autowired + private TestAddFormValidator formValidator; + @Autowired + private DisplayListService displayListService; + @Autowired + private DictionaryService dictionaryService; + @Autowired + private PanelService panelService; + @Autowired + private TypeOfSampleService typeOfSampleService; + @Autowired + private TestResultService testResultService; + @Autowired + private UnitOfMeasureService unitOfMeasureService; + @Autowired + private TestAddService testAddService; + @Autowired + private TestSectionService testSectionService; + @Autowired + private TestService testService; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/TestAdd") + public TestAddForm showTestAdd(HttpServletRequest request) { + LogEvent.logTrace(this.getClass().getSimpleName(), "showTestAdd", + "Hibernate Version: " + org.hibernate.Version.getVersionString()); + + TestAddForm form = new TestAddForm(); + Test test = new Test(); + + List allSampleTypesList = new ArrayList<>(); + allSampleTypesList.addAll(DisplayListService.getInstance().getList(ListType.SAMPLE_TYPE_ACTIVE)); + allSampleTypesList.addAll(DisplayListService.getInstance().getList(ListType.SAMPLE_TYPE_INACTIVE)); + + form.setSampleTypeList(allSampleTypesList); + form.setPanelList(DisplayListService.getInstance().getList(ListType.PANELS)); + form.setResultTypeList(DisplayListService.getInstance().getList(ListType.RESULT_TYPE_LOCALIZED)); + form.setUomList(DisplayListService.getInstance().getList(ListType.UNIT_OF_MEASURE)); + + List allLabUnitsList = new ArrayList<>(); + allLabUnitsList.addAll(DisplayListService.getInstance().getList(ListType.TEST_SECTION_ACTIVE)); + allLabUnitsList.addAll(DisplayListService.getInstance().getList(ListType.TEST_SECTION_INACTIVE)); + form.setLabUnitList(allLabUnitsList); + form.setAgeRangeList(SpringContext.getBean(ResultLimitService.class).getPredefinedAgeRanges()); + form.setDictionaryList(DisplayListService.getInstance().getList(ListType.DICTIONARY_TEST_RESULTS)); + form.setGroupedDictionaryList(createGroupedDictionaryList()); + form.setLoinc(test.getLoinc()); + + // return findForward(FWD_SUCCESS, form); + return form; + } + + @PostMapping(value = "/TestAdd") + public TestAddForm postTestAdd(HttpServletRequest request, @RequestBody @Valid TestAddForm form, + BindingResult result) { + formValidator.validate(form, result); + if (result.hasErrors()) { + saveErrors(result); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + + String currentUserId = getSysUserId(request); + String jsonString = (form.getJsonWad()); + + JSONParser parser = new JSONParser(); + + JSONObject obj = null; + try { + obj = (JSONObject) parser.parse(jsonString); + } catch (ParseException e) { + LogEvent.logError(e.getMessage(), e); + } + TestAddParams testAddParams = extractTestAddParms(obj, parser); + validateLoinc(testAddParams.loinc, result); + List testSets = createTestSets(testAddParams); + Localization nameLocalization = createNameLocalization(testAddParams); + Localization reportingNameLocalization = createReportingNameLocalization(testAddParams); + + try { + testAddService.addTestsRest(testSets, nameLocalization, reportingNameLocalization, currentUserId); + } catch (HibernateException e) { + LogEvent.logDebug(e); + } + + testService.refreshTestNames(); + displayListService.refreshList(DisplayListService.ListType.SAMPLE_TYPE_ACTIVE); + displayListService.refreshList(DisplayListService.ListType.SAMPLE_TYPE_INACTIVE); + displayListService.refreshList(DisplayListService.ListType.PANELS_ACTIVE); + displayListService.refreshList(DisplayListService.ListType.PANELS_INACTIVE); + displayListService.refreshList(DisplayListService.ListType.PANELS); + displayListService.refreshList(DisplayListService.ListType.TEST_SECTION_ACTIVE); + displayListService.refreshList(DisplayListService.ListType.TEST_SECTION_BY_NAME); + displayListService.refreshList(DisplayListService.ListType.TEST_SECTION_INACTIVE); + SpringContext.getBean(TypeOfSampleService.class).clearCache(); + + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } + + private Errors validateLoinc(String loincCode, Errors errors) { + List tests = testService.getTestsByLoincCode(loincCode); + for (Test test : tests) { + if (test.getLoinc().equals(loincCode)) { + errors.reject("entry.invalid.loinc.number.used", "entry.invalid.loinc.number.used"); + } + } + return errors; + } + + private Localization createNameLocalization(TestAddParams testAddParams) { + return LocalizationServiceImpl.createNewLocalization(testAddParams.testNameEnglish, + testAddParams.testNameFrench, LocalizationServiceImpl.LocalizationType.TEST_NAME); + } + + private Localization createReportingNameLocalization(TestAddParams testAddParams) { + return LocalizationServiceImpl.createNewLocalization(testAddParams.testReportNameEnglish, + testAddParams.testReportNameFrench, LocalizationServiceImpl.LocalizationType.REPORTING_TEST_NAME); + } + + private List createTestSets(TestAddParams testAddParams) { + Double lowValid = null; + Double highValid = null; + Double lowReportingRange = null; + Double highReportingRange = null; + Double lowCritical = null; + Double highCritical = null; + String significantDigits = testAddParams.significantDigits; + boolean numericResults = TypeOfTestResultServiceImpl.ResultType.isNumericById(testAddParams.resultTypeId); + boolean dictionaryResults = TypeOfTestResultServiceImpl.ResultType + .isDictionaryVarientById(testAddParams.resultTypeId); + List testSets = new ArrayList<>(); + UnitOfMeasure uom = null; + if (!GenericValidator.isBlankOrNull(testAddParams.uomId) || "0".equals(testAddParams.uomId)) { + uom = unitOfMeasureService.getUnitOfMeasureById(testAddParams.uomId); + } + TestSection testSection = testSectionService.get(testAddParams.testSectionId); + + if (numericResults) { + lowValid = StringUtil.doubleWithInfinity(testAddParams.lowValid); + highValid = StringUtil.doubleWithInfinity(testAddParams.highValid); + lowReportingRange = StringUtil.doubleWithInfinity(testAddParams.lowReportingRange); + highReportingRange = StringUtil.doubleWithInfinity(testAddParams.highReportingRange); + lowCritical = StringUtil.doubleWithInfinity(testAddParams.lowCritical); + highCritical = StringUtil.doubleWithInfinity(testAddParams.highCritical); + } + // The number of test sets depend on the number of sampleTypes + for (int i = 0; i < testAddParams.sampleList.size(); i++) { + TypeOfSample typeOfSample = typeOfSampleService + .getTypeOfSampleById(testAddParams.sampleList.get(i).sampleTypeId); + if (typeOfSample == null) { + continue; + } else { + typeOfSample.setActive("Y".equals(testAddParams.active)); + } + TestSet testSet = new TestSet(); + testSet.typeOfSample = typeOfSample; + Test test = new Test(); + test.setUnitOfMeasure(uom); + test.setLoinc(testAddParams.loinc); + test.setDescription(testAddParams.testNameEnglish + "(" + typeOfSample.getDescription() + ")"); + // TODO remove test name if possible. Tests should be identified by LOINC and + // use a localization + test.setName(testAddParams.testNameEnglish); + test.setLocalCode(testAddParams.testNameEnglish); + test.setIsActive(testAddParams.active); + test.setOrderable("Y".equals(testAddParams.orderable)); + test.setNotifyResults("Y".equals(testAddParams.notifyResults)); + test.setInLabOnly("Y".equals(testAddParams.inLabOnly)); + test.setAntimicrobialResistance("Y".equals(testAddParams.antimicrobialResistance)); + test.setIsReportable("N"); + test.setTestSection(testSection); + test.setGuid(String.valueOf(UUID.randomUUID())); + ArrayList orderedTests = testAddParams.sampleList.get(i).orderedTests; + for (int j = 0; j < orderedTests.size(); j++) { + if ("0".equals(orderedTests.get(j))) { + test.setSortOrder(String.valueOf(j)); + } else { + Test orderedTest = SpringContext.getBean(TestService.class).get(orderedTests.get(j)); + orderedTest.setSortOrder(String.valueOf(j)); + testSet.sortedTests.add(orderedTest); + } + } + + testSet.test = test; + + TypeOfSampleTest typeOfSampleTest = new TypeOfSampleTest(); + typeOfSampleTest.setTypeOfSampleId(typeOfSample.getId()); + testSet.sampleTypeTest = typeOfSampleTest; + + createPanelItems(testSet.panelItems, testAddParams); + createTestResults(testSet.testResults, significantDigits, testAddParams); + if (numericResults) { + testSet.resultLimits = createResultLimits(lowValid, highValid, lowReportingRange, highReportingRange, + testAddParams, highCritical, lowCritical); + } else if (dictionaryResults) { + testSet.resultLimits = createDictionaryResultLimit(testAddParams); + } + + testSets.add(testSet); + } + + return testSets; + } + + private ArrayList createDictionaryResultLimit(TestAddParams testAddParams) { + ArrayList resultLimits = new ArrayList<>(); + if (!GenericValidator.isBlankOrNull(testAddParams.dictionaryReferenceId)) { + ResultLimit limit = new ResultLimit(); + limit.setResultTypeId(testAddParams.resultTypeId); + limit.setDictionaryNormalId(testAddParams.dictionaryReferenceId); + resultLimits.add(limit); + } + + return resultLimits; + } + + private ArrayList createResultLimits(Double lowValid, Double highValid, Double lowReportingRange, + Double highReportingRange, TestAddParams testAddParams, Double highCritical, Double lowCritical) { + ArrayList resultLimits = new ArrayList<>(); + for (ResultLimitParams params : testAddParams.limits) { + ResultLimit limit = new ResultLimit(); + limit.setResultTypeId(testAddParams.resultTypeId); + limit.setGender(params.gender); + limit.setMinAge(StringUtil.doubleWithInfinity(params.lowAge)); + limit.setMaxAge(StringUtil.doubleWithInfinity(params.highAge)); + limit.setLowNormal(StringUtil.doubleWithInfinity(params.lowNormalLimit)); + limit.setHighNormal(StringUtil.doubleWithInfinity(params.highNormalLimit)); + limit.setLowValid(lowValid); + limit.setHighValid(highValid); + if (lowCritical != null && highCritical != null) { + limit.setLowReportingRange(lowReportingRange); + limit.setHighReportingRange(highReportingRange); + limit.setLowCritical(lowCritical); + limit.setHighCritical(highCritical); + } + resultLimits.add(limit); + } + + return resultLimits; + } + + private void createPanelItems(ArrayList panelItems, TestAddParams testAddParams) { + for (String panelId : testAddParams.panelList) { + PanelItem panelItem = new PanelItem(); + panelItem.setPanel(panelService.getPanelById(panelId)); + panelItems.add(panelItem); + } + } + + private void createTestResults(ArrayList testResults, String significantDigits, + TestAddParams testAddParams) { + TypeOfTestResultServiceImpl.ResultType type = SpringContext.getBean(TypeOfTestResultService.class) + .getResultTypeById(testAddParams.resultTypeId); + + if (TypeOfTestResultServiceImpl.ResultType.isTextOnlyVariant(type) + || TypeOfTestResultServiceImpl.ResultType.isNumeric(type)) { + TestResult testResult = new TestResult(); + testResult.setTestResultType(type.getCharacterValue()); + testResult.setSortOrder("1"); + testResult.setIsActive(true); + testResult.setSignificantDigits(significantDigits); + testResults.add(testResult); + } else if (TypeOfTestResultServiceImpl.ResultType.isDictionaryVariant(type.getCharacterValue())) { + int sortOrder = 10; + for (DictionaryParams params : testAddParams.dictionaryParamList) { + TestResult testResult = new TestResult(); + testResult.setTestResultType(type.getCharacterValue()); + testResult.setSortOrder(String.valueOf(sortOrder)); + sortOrder += 10; + testResult.setIsActive(true); + testResult.setValue(params.dictionaryId); + testResult.setDefault(params.isDefault); + testResult.setIsQuantifiable(params.isQuantifiable); + testResults.add(testResult); + } + } + } + + private TestAddParams extractTestAddParms(JSONObject obj, JSONParser parser) { + TestAddParams testAddParams = new TestAddParams(); + try { + + testAddParams.testNameEnglish = (String) obj.get("testNameEnglish"); + testAddParams.testNameFrench = (String) obj.get("testNameFrench"); + testAddParams.testReportNameEnglish = (String) obj.get("testReportNameEnglish"); + testAddParams.testReportNameFrench = (String) obj.get("testReportNameFrench"); + testAddParams.testSectionId = (String) obj.get("testSection"); + testAddParams.dictionaryReferenceId = (String) obj.get("dictionaryReference"); + extractPanels(obj, parser, testAddParams); + testAddParams.uomId = (String) obj.get("uom"); + testAddParams.loinc = (String) obj.get("loinc"); + testAddParams.resultTypeId = (String) obj.get("resultType"); + extractSampleTypes(obj, parser, testAddParams); + testAddParams.active = (String) obj.get("active"); + testAddParams.orderable = (String) obj.get("orderable"); + testAddParams.notifyResults = (String) obj.get("notifyResults"); + testAddParams.inLabOnly = (String) obj.get("inLabOnly"); + testAddParams.antimicrobialResistance = (String) obj.get("antimicrobialResistance"); + if (TypeOfTestResultServiceImpl.ResultType.isNumericById(testAddParams.resultTypeId)) { + testAddParams.lowValid = (String) obj.get("lowValid"); + testAddParams.highValid = (String) obj.get("highValid"); + testAddParams.lowReportingRange = (String) obj.get("lowReportingRange"); + testAddParams.highReportingRange = (String) obj.get("highReportingRange"); + testAddParams.lowCritical = (String) obj.get("lowCritical"); + testAddParams.highCritical = (String) obj.get("highCritical"); + testAddParams.significantDigits = (String) obj.get("significantDigits"); + extractLimits(obj, parser, testAddParams); + } else if (TypeOfTestResultServiceImpl.ResultType.isDictionaryVarientById(testAddParams.resultTypeId)) { + String dictionary = (String) obj.get("dictionary"); + JSONArray dictionaryArray = (JSONArray) parser.parse(dictionary); + for (int i = 0; i < dictionaryArray.size(); i++) { + DictionaryParams params = new DictionaryParams(); + params.dictionaryId = (String) ((JSONObject) dictionaryArray.get(i)).get("value"); + params.isQuantifiable = "Y".equals(((JSONObject) dictionaryArray.get(i)).get("qualified")); + params.isDefault = params.dictionaryId.equals(obj.get("defaultTestResult")); + testAddParams.dictionaryParamList.add(params); + } + } + + } catch (ParseException e) { + LogEvent.logDebug(e); + } + + return testAddParams; + } + + private void extractLimits(JSONObject obj, JSONParser parser, TestAddParams testAddParams) throws ParseException { + String lowAge = "0"; + String limits = (String) obj.get("resultLimits"); + JSONArray limitArray = (JSONArray) parser.parse(limits); + for (int i = 0; i < limitArray.size(); i++) { + ResultLimitParams params = new ResultLimitParams(); + Boolean gender = (Boolean) ((JSONObject) limitArray.get(i)).get("gender"); + if (gender) { + params.gender = "M"; + } + String highAge = (String) (((JSONObject) limitArray.get(i)).get("highAgeRange")); + params.displayRange = (String) (((JSONObject) limitArray.get(i)).get("reportingRange")); + params.lowNormalLimit = (String) (((JSONObject) limitArray.get(i)).get("lowNormal")); + params.highNormalLimit = (String) (((JSONObject) limitArray.get(i)).get("highNormal")); + params.lowCritical = (String) (((JSONObject) limitArray.get(i)).get("lowCritical")); + params.highCritical = (String) (((JSONObject) limitArray.get(i)).get("highCritical")); + params.lowAge = lowAge; + params.highAge = highAge; + testAddParams.limits.add(params); + + if (gender) { + params = new ResultLimitParams(); + params.gender = "F"; + params.lowNormalLimit = (String) (((JSONObject) limitArray.get(i)).get("lowNormalFemale")); + params.highNormalLimit = (String) (((JSONObject) limitArray.get(i)).get("highNormalFemale")); + params.lowAge = lowAge; + params.highAge = highAge; + testAddParams.limits.add(params); + } + + lowAge = highAge; + } + } + + private void extractPanels(JSONObject obj, JSONParser parser, TestAddParams testAddParams) throws ParseException { + String panels = (String) obj.get("panels"); + JSONArray panelArray = (JSONArray) parser.parse(panels); + + for (int i = 0; i < panelArray.size(); i++) { + testAddParams.panelList.add((String) (((JSONObject) panelArray.get(i)).get("id"))); + } + } + + private void extractSampleTypes(JSONObject obj, JSONParser parser, TestAddParams testAddParams) + throws ParseException { + String sampleTypes = (String) obj.get("sampleTypes"); + JSONArray sampleTypeArray = (JSONArray) parser.parse(sampleTypes); + + for (int i = 0; i < sampleTypeArray.size(); i++) { + SampleTypeListAndTestOrder sampleTypeTests = new SampleTypeListAndTestOrder(); + sampleTypeTests.sampleTypeId = (String) (((JSONObject) sampleTypeArray.get(i)).get("typeId")); + + JSONArray testArray = (JSONArray) (((JSONObject) sampleTypeArray.get(i)).get("tests")); + for (int j = 0; j < testArray.size(); j++) { + sampleTypeTests.orderedTests.add(String.valueOf(((JSONObject) testArray.get(j)).get("id"))); + } + testAddParams.sampleList.add(sampleTypeTests); + } + } + + private List> createGroupedDictionaryList() { + List testResults = testResultService.getAllSortedTestResults(); // getSortedTestResults(); + + HashSet dictionaryIdGroups = getDictionaryIdGroups(testResults); + + return getGroupedDictionaryPairs(dictionaryIdGroups); + } + + /* + * @SuppressWarnings("unchecked") private List + * getSortedTestResults() { List testResults = + * testResultService.getAllTestResults(); + * + * Collections.sort(testResults, new Comparator() { + * + * @Override public int compare(TestResult o1, TestResult o2) { int result = + * o1.getTest().getId().compareTo(o2.getTest().getId()); + * + * if (result != 0) { return result; } + * + * return GenericValidator.isBlankOrNull(o1.getSortOrder()) || + * GenericValidator.isBlankOrNull(o2.getSortOrder()) ? 0 : + * Integer.parseInt(o1.getSortOrder()) - Integer.parseInt(o2.getSortOrder()); } + * }); return testResults; } + */ + + private HashSet getDictionaryIdGroups(List testResults) { + HashSet dictionaryIdGroups = new HashSet<>(); + String currentTestId = null; + String dictionaryIdGroup = null; + for (TestResult testResult : testResults) { + if (TypeOfTestResultServiceImpl.ResultType.isDictionaryVariant(testResult.getTestResultType())) { + if (testResult.getTest().getId().equals(currentTestId)) { + dictionaryIdGroup += "," + testResult.getValue(); + } else { + currentTestId = testResult.getTest().getId(); + if (dictionaryIdGroup != null) { + dictionaryIdGroups.add(dictionaryIdGroup); + } + + dictionaryIdGroup = testResult.getValue(); + } + } + } + + if (dictionaryIdGroup != null) { + dictionaryIdGroups.add(dictionaryIdGroup); + } + + return dictionaryIdGroups; + } + + private List> getGroupedDictionaryPairs(HashSet dictionaryIdGroups) { + List> groups = new ArrayList<>(); + for (String group : dictionaryIdGroups) { + List dictionaryPairs = new ArrayList<>(); + for (String id : group.split(",")) { + Dictionary dictionary = dictionaryService.getDictionaryById(id); + if (dictionary != null) { + dictionaryPairs.add(new IdValuePair(id, dictionary.getLocalizedName())); + } + } + groups.add(dictionaryPairs); + } + + Collections.sort(groups, new Comparator>() { + @Override + public int compare(List o1, List o2) { + return o1.size() - o2.size(); + } + }); + return groups; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "testAddDefinition"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "redirect:/TestAdd"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "testAddDefinition"; + } else { + return "PageNotFound"; + } + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } + + public class TestAddParams { + String testId; + public String testNameEnglish; + public String testNameFrench; + public String testReportNameEnglish; + public String testReportNameFrench; + String testSectionId; + ArrayList panelList = new ArrayList<>(); + String uomId; + String loinc; + String resultTypeId; + ArrayList sampleList = new ArrayList<>(); + String active; + String orderable; + String notifyResults; + String inLabOnly; + String antimicrobialResistance; + String lowValid; + String highValid; + String lowReportingRange; + String highReportingRange; + String lowCritical; + String highCritical; + public String significantDigits; + String dictionaryReferenceId; + ArrayList limits = new ArrayList<>(); + public ArrayList dictionaryParamList = new ArrayList<>(); + } + + public class TestSet { + public Test test; + public TypeOfSampleTest sampleTypeTest; + public TypeOfSample typeOfSample; + public ArrayList sortedTests = new ArrayList<>(); + public ArrayList panelItems = new ArrayList<>(); + public ArrayList testResults = new ArrayList<>(); + public ArrayList resultLimits = new ArrayList<>(); + } + + public class SampleTypeListAndTestOrder { + String sampleTypeId; + ArrayList orderedTests = new ArrayList<>(); + } + + public class ResultLimitParams { + String gender; + String lowAge; + String highAge; + String lowNormalLimit; + String highNormalLimit; + String displayRange; + String lowCritical; + String highCritical; + } + + public class DictionaryParams { + public boolean isDefault; + public String dictionaryId; + public boolean isQuantifiable = false; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestModifyEntryRestController.java b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestModifyEntryRestController.java new file mode 100644 index 0000000000..867badb9ac --- /dev/null +++ b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestModifyEntryRestController.java @@ -0,0 +1,850 @@ +package org.openelisglobal.testconfiguration.controller.rest; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.validator.GenericValidator; +import org.hibernate.HibernateException; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.log.LogEvent; +import org.openelisglobal.common.services.DisplayListService; +import org.openelisglobal.common.services.DisplayListService.ListType; +import org.openelisglobal.common.util.IdValuePair; +import org.openelisglobal.common.util.StringUtil; +import org.openelisglobal.dictionary.service.DictionaryService; +import org.openelisglobal.dictionary.valueholder.Dictionary; +import org.openelisglobal.localization.service.LocalizationService; +import org.openelisglobal.localization.service.LocalizationServiceImpl; +import org.openelisglobal.localization.valueholder.Localization; +import org.openelisglobal.panel.service.PanelService; +import org.openelisglobal.panel.valueholder.Panel; +import org.openelisglobal.panelitem.valueholder.PanelItem; +import org.openelisglobal.resultlimit.service.ResultLimitService; +import org.openelisglobal.resultlimits.valueholder.ResultLimit; +import org.openelisglobal.spring.util.SpringContext; +import org.openelisglobal.test.service.TestSectionService; +import org.openelisglobal.test.service.TestService; +import org.openelisglobal.test.valueholder.Test; +import org.openelisglobal.test.valueholder.TestSection; +import org.openelisglobal.testconfiguration.beans.ResultLimitBean; +import org.openelisglobal.testconfiguration.beans.TestCatalogBean; +import org.openelisglobal.testconfiguration.form.TestModifyEntryForm; +import org.openelisglobal.testconfiguration.service.TestModifyService; +import org.openelisglobal.testconfiguration.validator.TestModifyEntryFormValidator; +import org.openelisglobal.testresult.service.TestResultService; +import org.openelisglobal.testresult.valueholder.TestResult; +import org.openelisglobal.typeofsample.service.TypeOfSampleService; +import org.openelisglobal.typeofsample.valueholder.TypeOfSample; +import org.openelisglobal.typeofsample.valueholder.TypeOfSampleTest; +import org.openelisglobal.typeoftestresult.service.TypeOfTestResultService; +import org.openelisglobal.typeoftestresult.service.TypeOfTestResultServiceImpl; +import org.openelisglobal.unitofmeasure.service.UnitOfMeasureService; +import org.openelisglobal.unitofmeasure.valueholder.UnitOfMeasure; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class TestModifyEntryRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] { "jsonWad", "testId", "loinc" }; + + @Autowired + private TestModifyEntryFormValidator formValidator; + @Autowired + private DictionaryService dictionaryService; + @Autowired + private PanelService panelService; + @Autowired + private TypeOfSampleService typeOfSampleService; + @Autowired + private TestService testService; + @Autowired + private TestResultService testResultService; + @Autowired + private UnitOfMeasureService unitOfMeasureService; + @Autowired + private TestModifyService testModifyService; + @Autowired + private LocalizationService localizationService; + @Autowired + private TestSectionService testSectionService; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/TestModifyEntry") + public TestModifyEntryForm showTestModifyEntry(HttpServletRequest request) { + + TestModifyEntryForm form = new TestModifyEntryForm(); + setupDisplayItems(form); + + // return findForward(FWD_SUCCESS, form); + return form; + } + + private void setupDisplayItems(TestModifyEntryForm form) { + + List allSampleTypesList = new ArrayList<>(); + allSampleTypesList.addAll(DisplayListService.getInstance().getList(ListType.SAMPLE_TYPE_ACTIVE)); + allSampleTypesList.addAll(DisplayListService.getInstance().getList(ListType.SAMPLE_TYPE_INACTIVE)); + + form.setSampleTypeList(allSampleTypesList); + form.setPanelList(DisplayListService.getInstance().getList(ListType.PANELS)); + form.setResultTypeList(DisplayListService.getInstance().getList(ListType.RESULT_TYPE_LOCALIZED)); + form.setUomList(DisplayListService.getInstance().getList(ListType.UNIT_OF_MEASURE)); + form.setLabUnitList(DisplayListService.getInstance().getList(ListType.TEST_SECTION_ACTIVE)); + form.setAgeRangeList(SpringContext.getBean(ResultLimitService.class).getPredefinedAgeRanges()); + form.setDictionaryList(DisplayListService.getInstance().getList(ListType.DICTIONARY_TEST_RESULTS)); + form.setGroupedDictionaryList(createGroupedDictionaryList()); + form.setTestList(DisplayListService.getInstance().getFreshList(DisplayListService.ListType.ALL_TESTS)); + + // gnr: ALL_TESTS calls getActiveTests, this could be a way to enable + // maintenance of inactive tests + // form.setTestListInactive( DisplayListService.getInstance().getList( + // DisplayListService.ListType.ALL_TESTS_INACTIVE ) + // ); + + List testCatBeanList = createTestCatBeanList(); + form.setTestCatBeanList(testCatBeanList); + } + + private List createTestCatBeanList() { + List beanList = new ArrayList<>(); + + List testList = testService.getAllTests(false); + + for (Test test : testList) { + + TestCatalogBean bean = new TestCatalogBean(); + TestService testService = SpringContext.getBean(TestService.class); + String resultType = testService.getResultType(test); + bean.setId(test.getId()); + bean.setLocalization(test.getLocalizedTestName()); + bean.setReportLocalization(test.getLocalizedReportingName()); + if (test.getSortOrder() != null) { + bean.setTestSortOrder(Integer.parseInt(test.getSortOrder())); + } + + bean.setTestUnit(testService.getTestSectionName(test)); + bean.setPanel(createPanelList(testService, test)); + bean.setResultType(resultType); + TypeOfSample typeOfSample = testService.getTypeOfSample(test); + bean.setSampleType(typeOfSample != null ? typeOfSample.getLocalizedName() : "n/a"); + bean.setOrderable(test.getOrderable() ? "Orderable" : "Not orderable"); + bean.setNotifyResults(test.isNotifyResults()); + bean.setInLabOnly(test.isInLabOnly()); + bean.setAntimicrobialResistance(test.getAntimicrobialResistance()); + bean.setLoinc(test.getLoinc()); + bean.setActive(test.isActive() ? "Active" : "Not active"); + bean.setUom(testService.getUOM(test, false)); + if (TypeOfTestResultServiceImpl.ResultType.NUMERIC.matches(resultType) + && testResultService.getAllActiveTestResultsPerTest(test).size() != 0) { + bean.setSignificantDigits( + testResultService.getAllActiveTestResultsPerTest(test).get(0).getSignificantDigits()); + bean.setHasLimitValues(true); + bean.setResultLimits(getResultLimits(test, bean.getSignificantDigits())); + } + bean.setHasDictionaryValues( + TypeOfTestResultServiceImpl.ResultType.isDictionaryVariant(bean.getResultType())); + if (bean.isHasDictionaryValues()) { + bean.setDictionaryValues(createDictionaryValues(testService, test)); + bean.setReferenceValue(createReferenceValueForDictionaryType(test)); + bean.setDictionaryIds(createDictionaryIds(testService, test)); + bean.setReferenceId(createReferenceIdForDictionaryType(test)); + bean.setReferenceId(getDictionaryIdByDictEntry(bean.getReferenceValue(), bean.getDictionaryIds(), + bean.getDictionaryValues())); + } + beanList.add(bean); + } + + Collections.sort(beanList, new Comparator() { + @Override + public int compare(TestCatalogBean o1, TestCatalogBean o2) { + // sort by test section, sample type, panel, sort order + int comparison = o1.getTestUnit().compareTo(o2.getTestUnit()); + if (comparison != 0) { + return comparison; + } + + comparison = o1.getSampleType().compareTo(o2.getSampleType()); + if (comparison != 0) { + return comparison; + } + + comparison = o1.getPanel().compareTo(o2.getPanel()); + if (comparison != 0) { + return comparison; + } + + return o1.getTestSortOrder() - o2.getTestSortOrder(); + } + }); + + return beanList; + } + + private List getResultLimits(Test test, String significantDigits) { + List limitBeans = new ArrayList<>(); + + List resultLimitList = SpringContext.getBean(ResultLimitService.class).getResultLimits(test); + + Collections.sort(resultLimitList, new Comparator() { + @Override + public int compare(ResultLimit o1, ResultLimit o2) { + return (int) (o1.getMinAge() - o2.getMinAge()); + } + }); + + for (ResultLimit limit : resultLimitList) { + ResultLimitBean bean = new ResultLimitBean(); + bean.setNormalRange(SpringContext.getBean(ResultLimitService.class).getDisplayReferenceRange(limit, + significantDigits, "-")); + bean.setValidRange(SpringContext.getBean(ResultLimitService.class).getDisplayValidRange(limit, + significantDigits, "-")); + bean.setReportingRange(SpringContext.getBean(ResultLimitService.class).getDisplayReportingRange(limit, + significantDigits, "-")); + bean.setCriticalRange(SpringContext.getBean(ResultLimitService.class).getDisplayCriticalRange(limit, + significantDigits, "-")); + bean.setGender(limit.getGender()); + bean.setAgeRange(SpringContext.getBean(ResultLimitService.class).getDisplayAgeRange(limit, "-")); + limitBeans.add(bean); + } + return limitBeans; + } + + private String createReferenceValueForDictionaryType(Test test) { + List resultLimits = SpringContext.getBean(ResultLimitService.class).getResultLimits(test); + + if (resultLimits.isEmpty()) { + return "n/a"; + } + + return SpringContext.getBean(ResultLimitService.class).getDisplayReferenceRange(resultLimits.get(0), null, + null); + } + + private List createDictionaryValues(TestService testService, Test test) { + List dictionaryList = new ArrayList<>(); + List testResultList = testService.getPossibleTestResults(test); + for (TestResult testResult : testResultList) { + CollectionUtils.addIgnoreNull(dictionaryList, getDictionaryValue(testResult)); + } + + return dictionaryList; + } + + private String getDictionaryValue(TestResult testResult) { + + if (TypeOfTestResultServiceImpl.ResultType.isDictionaryVariant(testResult.getTestResultType())) { + Dictionary dictionary = dictionaryService.getDataForId(testResult.getValue()); + String displayValue = dictionary.getLocalizedName(); + + if ("unknown".equals(displayValue)) { + displayValue = !org.apache.commons.validator.GenericValidator.isBlankOrNull(dictionary.getDictEntry()) + ? dictionary.getDictEntry() + : dictionary.getLocalAbbreviation(); + } + + if (testResult.getIsQuantifiable()) { + displayValue += " Qualifiable"; + } + return displayValue; + } + + return null; + } + + private String createReferenceIdForDictionaryType(Test test) { + List resultLimits = SpringContext.getBean(ResultLimitService.class).getResultLimits(test); + + if (resultLimits.isEmpty()) { + return "n/a"; + } + + return SpringContext.getBean(ResultLimitService.class).getDisplayReferenceRange(resultLimits.get(0), null, + null); + } + + private List createDictionaryIds(TestService testService, Test test) { + List dictionaryList = new ArrayList<>(); + List testResultList = testService.getPossibleTestResults(test); + for (TestResult testResult : testResultList) { + CollectionUtils.addIgnoreNull(dictionaryList, getDictionaryId(testResult)); + } + + return dictionaryList; + } + + private String getDictionaryIdByDictEntry(String dict_entry, List ids, List values) { + + if ("n/a".equals(dict_entry)) { + return null; + } + + for (int i = 0; i < ids.size(); i++) { + if (values.get(i).equals(dict_entry)) { + return ids.get(i); + } + } + + return null; + } + + private String getDictionaryId(TestResult testResult) { + + if (TypeOfTestResultServiceImpl.ResultType.isDictionaryVariant(testResult.getTestResultType())) { + Dictionary dictionary = dictionaryService.getDataForId(testResult.getValue()); + String displayId = dictionary.getId(); + + if ("unknown".equals(displayId)) { + displayId = !org.apache.commons.validator.GenericValidator.isBlankOrNull(dictionary.getDictEntry()) + ? dictionary.getDictEntry() + : dictionary.getLocalAbbreviation(); + } + + if (testResult.getIsQuantifiable()) { + displayId += " Qualifiable"; + } + return displayId; + } + + return null; + } + + private String createPanelList(TestService testService, Test test) { + StringBuilder builder = new StringBuilder(); + + List panelList = testService.getPanels(test); + for (Panel panel : panelList) { + builder.append(localizationService.getLocalizedValueById(panel.getLocalization().getId())); + builder.append(", "); + } + + String panelString = builder.toString(); + if (panelString.isEmpty()) { + panelString = "None"; + } else { + panelString = panelString.substring(0, panelString.length() - 2); + } + + return panelString; + } + + private List> createGroupedDictionaryList() { + List testResults = getSortedTestResults(); + + HashSet dictionaryIdGroups = getDictionaryIdGroups(testResults); + + return getGroupedDictionaryPairs(dictionaryIdGroups); + } + + private List getSortedTestResults() { + List testResults = testResultService.getAllTestResults(); + + Collections.sort(testResults, new Comparator() { + @Override + public int compare(TestResult o1, TestResult o2) { + int result = o1.getTest().getId().compareTo(o2.getTest().getId()); + + if (result != 0) { + return result; + } + + return (GenericValidator.isBlankOrNull(o1.getSortOrder()) + || GenericValidator.isBlankOrNull(o2.getSortOrder())) ? 0 + : Integer.parseInt(o1.getSortOrder()) - Integer.parseInt(o2.getSortOrder()); + } + }); + return testResults; + } + + private HashSet getDictionaryIdGroups(List testResults) { + HashSet dictionaryIdGroups = new HashSet<>(); + String currentTestId = null; + String dictionaryIdGroup = null; + for (TestResult testResult : testResults) { + if (TypeOfTestResultServiceImpl.ResultType.isDictionaryVariant(testResult.getTestResultType())) { + if (testResult.getTest().getId().equals(currentTestId)) { + dictionaryIdGroup += "," + testResult.getValue(); + } else { + currentTestId = testResult.getTest().getId(); + if (dictionaryIdGroup != null) { + dictionaryIdGroups.add(dictionaryIdGroup); + } + + dictionaryIdGroup = testResult.getValue(); + } + } + } + + if (dictionaryIdGroup != null) { + dictionaryIdGroups.add(dictionaryIdGroup); + } + + return dictionaryIdGroups; + } + + private List> getGroupedDictionaryPairs(HashSet dictionaryIdGroups) { + List> groups = new ArrayList<>(); + for (String group : dictionaryIdGroups) { + List dictionaryPairs = new ArrayList<>(); + for (String id : group.split(",")) { + Dictionary dictionary = dictionaryService.getDictionaryById(id); + if (dictionary != null) { + dictionaryPairs.add(new IdValuePair(id, dictionary.getLocalizedName())); + } + } + groups.add(dictionaryPairs); + } + + Collections.sort(groups, new Comparator>() { + @Override + public int compare(List o1, List o2) { + return o1.size() - o2.size(); + } + }); + return groups; + } + + @PostMapping(value = "/TestModifyEntry") + public TestModifyEntryForm postTestModifyEntry(HttpServletRequest request, + @RequestBody @Valid TestModifyEntryForm form, BindingResult result) { + formValidator.validate(form, result); + if (result.hasErrors()) { + // saveErrors(result); + setupDisplayItems(form); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + String currentUserId = getSysUserId(request); + String changeList = form.getJsonWad(); + + JSONParser parser = new JSONParser(); + JSONObject obj = null; + try { + obj = (JSONObject) parser.parse(changeList); + } catch (ParseException e) { + LogEvent.logError(e.getMessage(), e); + } + + TestAddParams testAddParams = extractTestAddParms(obj, parser); + + Localization nameLocalization = createNameLocalization(testAddParams); + Localization reportingNameLocalization = createReportingNameLocalization(testAddParams); + + List testSets = createTestSets(testAddParams); + + try { + testModifyService.updateTestSetsRest(testSets, testAddParams, nameLocalization, reportingNameLocalization, + currentUserId); + } catch (HibernateException e) { + LogEvent.logDebug(e); + result.reject("error.hibernate.exception"); + setupDisplayItems(form); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } catch (Exception e) { + LogEvent.logDebug(e); + result.reject("error.exception"); + setupDisplayItems(form); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + + testService.refreshTestNames(); + SpringContext.getBean(TypeOfSampleService.class).clearCache(); + + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } + + private void createPanelItems(ArrayList panelItems, TestAddParams testAddParams) { + for (String panelId : testAddParams.panelList) { + PanelItem panelItem = new PanelItem(); + panelItem.setPanel(panelService.getPanelById(panelId)); + panelItems.add(panelItem); + } + } + + private void createTestResults(ArrayList testResults, String significantDigits, + TestAddParams testAddParams) { + TypeOfTestResultServiceImpl.ResultType type = SpringContext.getBean(TypeOfTestResultService.class) + .getResultTypeById(testAddParams.resultTypeId); + + if (TypeOfTestResultServiceImpl.ResultType.isTextOnlyVariant(type) + || TypeOfTestResultServiceImpl.ResultType.isNumeric(type)) { + TestResult testResult = new TestResult(); + testResult.setTestResultType(type.getCharacterValue()); + testResult.setSortOrder("1"); + testResult.setIsActive(true); + testResult.setSignificantDigits(significantDigits); + testResults.add(testResult); + } else if (TypeOfTestResultServiceImpl.ResultType.isDictionaryVariant(type.getCharacterValue())) { + int sortOrder = 10; + for (DictionaryParams params : testAddParams.dictionaryParamList) { + TestResult testResult = new TestResult(); + testResult.setTestResultType(type.getCharacterValue()); + testResult.setSortOrder(String.valueOf(sortOrder)); + sortOrder += 10; + testResult.setIsActive(true); + testResult.setValue(params.dictionaryId); + testResult.setDefault(params.isDefault); + testResult.setIsQuantifiable(params.isQuantifiable); + testResults.add(testResult); + } + } + } + + private Localization createNameLocalization(TestAddParams testAddParams) { + return LocalizationServiceImpl.createNewLocalization(testAddParams.testNameEnglish, + testAddParams.testNameFrench, LocalizationServiceImpl.LocalizationType.TEST_NAME); + } + + private Localization createReportingNameLocalization(TestAddParams testAddParams) { + return LocalizationServiceImpl.createNewLocalization(testAddParams.testReportNameEnglish, + testAddParams.testReportNameFrench, LocalizationServiceImpl.LocalizationType.REPORTING_TEST_NAME); + } + + private List createTestSets(TestAddParams testAddParams) { + Double lowValid = null; + Double highValid = null; + Double lowReportingRange = null; + Double highReportingRange = null; + Double lowCritical = null; + Double highCritical = null; + String significantDigits = testAddParams.significantDigits; + boolean numericResults = TypeOfTestResultServiceImpl.ResultType.isNumericById(testAddParams.resultTypeId); + boolean dictionaryResults = TypeOfTestResultServiceImpl.ResultType + .isDictionaryVarientById(testAddParams.resultTypeId); + List testSets = new ArrayList<>(); + UnitOfMeasure uom = null; + if (!org.apache.commons.validator.GenericValidator.isBlankOrNull(testAddParams.uomId) + || "0".equals(testAddParams.uomId)) { + uom = unitOfMeasureService.getUnitOfMeasureById(testAddParams.uomId); + } + TestSection testSection = testSectionService.get(testAddParams.testSectionId); + + if (numericResults) { + lowValid = StringUtil.doubleWithInfinity(testAddParams.lowValid); + highValid = StringUtil.doubleWithInfinity(testAddParams.highValid); + lowReportingRange = StringUtil.doubleWithInfinity(testAddParams.lowReportingRange); + highReportingRange = StringUtil.doubleWithInfinity(testAddParams.highReportingRange); + lowCritical = StringUtil.doubleWithInfinity(testAddParams.lowCritical); + highCritical = StringUtil.doubleWithInfinity(testAddParams.highCritical); + } + // The number of test sets depend on the number of sampleTypes + for (int i = 0; i < testAddParams.sampleList.size(); i++) { + TypeOfSample typeOfSample = typeOfSampleService + .getTypeOfSampleById(testAddParams.sampleList.get(i).sampleTypeId); + if (typeOfSample == null) { + continue; + } + TestSet testSet = new TestSet(); + Test test = new Test(); + test.setId(testAddParams.testId); + + test.setUnitOfMeasure(uom); + test.setDescription(testAddParams.testNameEnglish + "(" + typeOfSample.getDescription() + ")"); + test.setLocalCode(testAddParams.testNameEnglish); + test.setIsActive(testAddParams.active); + test.setOrderable("Y".equals(testAddParams.orderable)); + test.setNotifyResults("Y".equals(testAddParams.notifyResults)); + test.setInLabOnly("Y".equals(testAddParams.inLabOnly)); + test.setAntimicrobialResistance("Y".equals(testAddParams.antimicrobialResistance)); + test.setIsReportable("N"); + test.setTestSection(testSection); + if (GenericValidator.isBlankOrNull(test.getGuid())) { + test.setGuid(String.valueOf(UUID.randomUUID())); + } + ArrayList orderedTests = testAddParams.sampleList.get(i).orderedTests; + for (int j = 0; j < orderedTests.size(); j++) { + if ("0".equals(orderedTests.get(j))) { + test.setSortOrder(String.valueOf(j)); + testSet.sortedTests.add(test); + } else { + Test orderedTest = SpringContext.getBean(TestService.class).get(orderedTests.get(j)); + orderedTest.setSortOrder(String.valueOf(j)); + testSet.sortedTests.add(orderedTest); + } + } + + testSet.test = test; + + TypeOfSampleTest typeOfSampleTest = new TypeOfSampleTest(); + typeOfSampleTest.setTypeOfSampleId(typeOfSample.getId()); + testSet.sampleTypeTest = typeOfSampleTest; + + createPanelItems(testSet.panelItems, testAddParams); + createTestResults(testSet.testResults, significantDigits, testAddParams); + if (numericResults) { + testSet.resultLimits = createResultLimits(lowValid, highValid, lowReportingRange, highReportingRange, + testAddParams, highCritical, lowCritical); + } else if (dictionaryResults) { + testSet.resultLimits = createDictionaryResultLimit(testAddParams); + } + + testSets.add(testSet); + } + + return testSets; + } + + private ArrayList createDictionaryResultLimit(TestAddParams testAddParams) { + + List testResults = testResultService.getActiveTestResultsByTest(testAddParams.testId); + for (int i = 0; i < testResults.size(); i++) { + testResults.get(i).setIsActive(false); + } + testResultService.updateAll(testResults); + + ArrayList resultLimits = new ArrayList<>(); + if (!org.apache.commons.validator.GenericValidator.isBlankOrNull(testAddParams.dictionaryReferenceId)) { + ResultLimit limit = new ResultLimit(); + limit.setResultTypeId(testAddParams.resultTypeId); + limit.setDictionaryNormalId(testAddParams.dictionaryReferenceId); + resultLimits.add(limit); + } + + return resultLimits; + } + + private ArrayList createResultLimits(Double lowValid, Double highValid, Double lowReportingRange, + Double highReportingRange, TestAddParams testAddParams, Double highCritical, Double lowCritical) { + ArrayList resultLimits = new ArrayList<>(); + for (ResultLimitParams params : testAddParams.limits) { + ResultLimit limit = new ResultLimit(); + limit.setResultTypeId(testAddParams.resultTypeId); + limit.setGender(params.gender); + limit.setMinAge(StringUtil.doubleWithInfinity(params.lowAge)); + limit.setMaxAge(StringUtil.doubleWithInfinity(params.highAge)); + limit.setLowNormal(StringUtil.doubleWithInfinity(params.lowNormalLimit)); + limit.setHighNormal(StringUtil.doubleWithInfinity(params.highNormalLimit)); + limit.setLowValid(lowValid); + limit.setHighValid(highValid); + if (lowReportingRange != null && highReportingRange != null && lowCritical != null + && highCritical != null) { + limit.setLowReportingRange(lowReportingRange); + limit.setHighReportingRange(highReportingRange); + limit.setLowCritical(lowCritical); + limit.setHighCritical(highCritical); + } + resultLimits.add(limit); + } + + return resultLimits; + } + + private TestAddParams extractTestAddParms(JSONObject obj, JSONParser parser) { + TestAddParams testAddParams = new TestAddParams(); + try { + + testAddParams.testId = (String) obj.get("testId"); + testAddParams.testNameEnglish = (String) obj.get("testNameEnglish"); + testAddParams.testNameFrench = (String) obj.get("testNameFrench"); + testAddParams.testReportNameEnglish = (String) obj.get("testReportNameEnglish"); + testAddParams.testReportNameFrench = (String) obj.get("testReportNameFrench"); + testAddParams.testSectionId = (String) obj.get("testSection"); + testAddParams.dictionaryReferenceId = (String) obj.get("dictionaryReference"); + extractPanels(obj, parser, testAddParams); + testAddParams.uomId = (String) obj.get("uom"); + testAddParams.loinc = (String) obj.get("loinc"); + testAddParams.resultTypeId = (String) obj.get("resultType"); + extractSampleTypes(obj, parser, testAddParams); + testAddParams.active = (String) obj.get("active"); + testAddParams.orderable = (String) obj.get("orderable"); + testAddParams.notifyResults = (String) obj.get("notifyResults"); + testAddParams.inLabOnly = (String) obj.get("inLabOnly"); + testAddParams.antimicrobialResistance = (String) obj.get("antimicrobialResistance"); + if (TypeOfTestResultServiceImpl.ResultType.isNumericById(testAddParams.resultTypeId)) { + testAddParams.lowValid = (String) obj.get("lowValid"); + testAddParams.highValid = (String) obj.get("highValid"); + testAddParams.lowReportingRange = (String) obj.get("lowReportingRange"); + testAddParams.highReportingRange = (String) obj.get("highReportingRange"); + testAddParams.lowCritical = (String) obj.get("lowCritical"); + testAddParams.highCritical = (String) obj.get("highCritical"); + testAddParams.significantDigits = (String) obj.get("significantDigits"); + extractLimits(obj, parser, testAddParams); + } else if (TypeOfTestResultServiceImpl.ResultType.isDictionaryVarientById(testAddParams.resultTypeId)) { + String dictionary = (String) obj.get("dictionary"); + JSONArray dictionaryArray = (JSONArray) parser.parse(dictionary); + for (int i = 0; i < dictionaryArray.size(); i++) { + DictionaryParams params = new DictionaryParams(); + params.dictionaryId = (String) ((JSONObject) dictionaryArray.get(i)).get("value"); + params.isQuantifiable = "Y".equals(((JSONObject) dictionaryArray.get(i)).get("qualified")); + params.isDefault = params.dictionaryId.equals(obj.get("defaultTestResult")); + testAddParams.dictionaryParamList.add(params); + } + } + + } catch (ParseException e) { + LogEvent.logDebug(e); + } + + return testAddParams; + } + + private void extractLimits(JSONObject obj, JSONParser parser, TestAddParams testAddParams) throws ParseException { + String lowAge = "0"; + if (obj.containsKey("resultLimits")) { + String limits = (String) obj.get("resultLimits"); + JSONArray limitArray = (JSONArray) parser.parse(limits); + for (int i = 0; i < limitArray.size(); i++) { + ResultLimitParams params = new ResultLimitParams(); + Boolean gender = (Boolean) ((JSONObject) limitArray.get(i)).get("gender"); + if (gender) { + params.gender = "M"; + } + String highAge = (String) (((JSONObject) limitArray.get(i)).get("highAgeRange")); + params.displayRange = (String) (((JSONObject) limitArray.get(i)).get("reportingRange")); + params.lowNormalLimit = (String) (((JSONObject) limitArray.get(i)).get("lowNormal")); + params.highNormalLimit = (String) (((JSONObject) limitArray.get(i)).get("highNormal")); + params.lowCritical = (String) (((JSONObject) limitArray.get(i)).get("lowCritical")); + params.highCritical = (String) (((JSONObject) limitArray.get(i)).get("highCritical")); + params.lowAge = lowAge; + params.highAge = highAge; + testAddParams.limits.add(params); + + if (gender) { + params = new ResultLimitParams(); + params.gender = "F"; + params.lowNormalLimit = (String) (((JSONObject) limitArray.get(i)).get("lowNormalFemale")); + params.highNormalLimit = (String) (((JSONObject) limitArray.get(i)).get("highNormalFemale")); + params.lowAge = lowAge; + params.highAge = highAge; + testAddParams.limits.add(params); + } + + lowAge = highAge; + } + } + } + + private void extractPanels(JSONObject obj, JSONParser parser, TestAddParams testAddParams) throws ParseException { + String panels = (String) obj.get("panels"); + JSONArray panelArray = (JSONArray) parser.parse(panels); + + for (int i = 0; i < panelArray.size(); i++) { + testAddParams.panelList.add((String) (((JSONObject) panelArray.get(i)).get("id"))); + } + } + + private void extractSampleTypes(JSONObject obj, JSONParser parser, TestAddParams testAddParams) + throws ParseException { + String sampleTypes = (String) obj.get("sampleTypes"); + JSONArray sampleTypeArray = (JSONArray) parser.parse(sampleTypes); + + for (int i = 0; i < sampleTypeArray.size(); i++) { + SampleTypeListAndTestOrder sampleTypeTests = new SampleTypeListAndTestOrder(); + sampleTypeTests.sampleTypeId = (String) (((JSONObject) sampleTypeArray.get(i)).get("typeId")); + + JSONArray testArray = (JSONArray) (((JSONObject) sampleTypeArray.get(i)).get("tests")); + for (int j = 0; j < testArray.size(); j++) { + sampleTypeTests.orderedTests.add(String.valueOf(((JSONObject) testArray.get(j)).get("id"))); + } + testAddParams.sampleList.add(sampleTypeTests); + } + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "testModifyDefinition"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "testModifyDefinition"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "redirect:/TestModifyEntry"; + } else { + return "PageNotFound"; + } + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } + + public class TestAddParams { + public String testId; + public String testNameEnglish; + public String testNameFrench; + public String testReportNameEnglish; + public String testReportNameFrench; + public String testSectionId; + ArrayList panelList = new ArrayList<>(); + public String uomId; + public String loinc; + String resultTypeId; + ArrayList sampleList = new ArrayList<>(); + String active; + String orderable; + public String notifyResults; + public String inLabOnly; + public String antimicrobialResistance; + String lowValid; + String highValid; + String lowReportingRange; + String highReportingRange; + String lowCritical; + String highCritical; + public String significantDigits; + String dictionaryReferenceId; + ArrayList limits = new ArrayList<>(); + public ArrayList dictionaryParamList = new ArrayList<>(); + } + + public class SampleTypeListAndTestOrder { + String sampleTypeId; + ArrayList orderedTests = new ArrayList<>(); + } + + public class ResultLimitParams { + String gender; + String lowAge; + String highAge; + String lowNormalLimit; + String highNormalLimit; + String displayRange; + String lowCritical; + String highCritical; + } + + public class TestSet { + public Test test; + public TypeOfSampleTest sampleTypeTest; + public ArrayList sortedTests = new ArrayList<>(); + public ArrayList panelItems = new ArrayList<>(); + public ArrayList testResults = new ArrayList<>(); + public ArrayList resultLimits = new ArrayList<>(); + } + + public class DictionaryParams { + public Boolean isDefault; + public String dictionaryId; + public boolean isQuantifiable = false; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestOrderabilityRestController.java b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestOrderabilityRestController.java new file mode 100644 index 0000000000..5a1a20e1d1 --- /dev/null +++ b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestOrderabilityRestController.java @@ -0,0 +1,219 @@ +package org.openelisglobal.testconfiguration.controller.rest; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import org.apache.commons.lang.math.NumberUtils; +import org.hibernate.HibernateException; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.log.LogEvent; +import org.openelisglobal.common.services.DisplayListService; +import org.openelisglobal.common.util.IdValuePair; +import org.openelisglobal.spring.util.SpringContext; +import org.openelisglobal.test.beanItems.TestActivationBean; +import org.openelisglobal.test.service.TestService; +import org.openelisglobal.test.service.TestServiceImpl; +import org.openelisglobal.test.valueholder.Test; +import org.openelisglobal.testconfiguration.form.TestOrderabilityForm; +import org.openelisglobal.testconfiguration.validator.TestOrderabilityFormValidator; +import org.openelisglobal.typeofsample.service.TypeOfSampleService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class TestOrderabilityRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] { "jsonChangeList" }; + + @Autowired + TestOrderabilityFormValidator formValidator; + @Autowired + TestService testService; + + @Autowired + TypeOfSampleService typeOfSampleService; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/TestOrderability") + public TestOrderabilityForm showTestOrderability(HttpServletRequest request) { + TestOrderabilityForm form = new TestOrderabilityForm(); + setupDisplayItems(form); + // return findForward(FWD_SUCCESS, form); + return form; + } + + private void setupDisplayItems(TestOrderabilityForm form) { + List orderableTestList = createTestList(false); + form.setOrderableTestList(orderableTestList); + } + + private List createTestList(boolean refresh) { + ArrayList testList = new ArrayList<>(); + + if (refresh) { + DisplayListService.getInstance().refreshList(DisplayListService.ListType.SAMPLE_TYPE_ACTIVE); + } + + List sampleTypeList = DisplayListService.getInstance() + .getList(DisplayListService.ListType.SAMPLE_TYPE_ACTIVE); + + for (IdValuePair pair : sampleTypeList) { + TestActivationBean bean = new TestActivationBean(); + + List tests = typeOfSampleService.getAllTestsBySampleTypeId(pair.getId()); + List orderableTests = new ArrayList<>(); + List inorderableTests = new ArrayList<>(); + + // initial ordering will be by display order. Inactive tests will then be + // re-ordered alphabetically + Collections.sort(tests, new Comparator() { + @Override + public int compare(Test o1, Test o2) { + // compare sort order + if (NumberUtils.isNumber(o1.getSortOrder()) && NumberUtils.isNumber(o2.getSortOrder())) { + return Integer.parseInt(o1.getSortOrder()) - Integer.parseInt(o2.getSortOrder()); + // if o2 has no sort order o1 does, o2 is assumed to be higher + } else if (NumberUtils.isNumber(o1.getSortOrder())) { + return -1; + // if o1 has no sort order o2 does, o1 is assumed to be higher + } else if (NumberUtils.isNumber(o2.getSortOrder())) { + return 1; + // else they are considered equal + } else { + return 0; + } + } + }); + + for (Test test : tests) { + if (test.getOrderable()) { + orderableTests.add(new IdValuePair(test.getId(), TestServiceImpl.getUserLocalizedTestName(test))); + } else { + inorderableTests.add(new IdValuePair(test.getId(), TestServiceImpl.getUserLocalizedTestName(test))); + } + } + + IdValuePair.sortByValue(orderableTests); + + bean.setActiveTests(orderableTests); + bean.setInactiveTests(inorderableTests); + if (!orderableTests.isEmpty() || !inorderableTests.isEmpty()) { + bean.setSampleType(pair); + testList.add(bean); + } + } + + return testList; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "testOrderabilityDefinition"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "testOrderabilityDefinition"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "testOrderabilityDefinition"; + } else { + return "PageNotFound"; + } + } + + @PostMapping(value = "/TestOrderability") + public TestOrderabilityForm postTestOrderability(HttpServletRequest request, + @RequestBody @Valid TestOrderabilityForm form, BindingResult result) throws ParseException { + formValidator.validate(form, result); + if (result.hasErrors()) { + // saveErrors(result); + setupDisplayItems(form); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + + String changeList = form.getJsonChangeList(); + + JSONParser parser = new JSONParser(); + + JSONObject obj = (JSONObject) parser.parse(changeList); + + List orderableTestIds = getIdsForActions("activateTest", obj, parser); + List unorderableTestIds = getIdsForActions("deactivateTest", obj, parser); + + List tests = getTests(unorderableTestIds, false); + tests.addAll(getTests(orderableTestIds, true)); + + try { + testService.updateAll(tests); + } catch (HibernateException e) { + LogEvent.logDebug(e); + } + + SpringContext.getBean(TypeOfSampleService.class).clearCache(); + + List orderableTestList = createTestList(true); + form.setOrderableTestList(orderableTestList); + + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } + + private List getTests(List testIds, boolean orderable) { + List tests = new ArrayList<>(); + + for (String testId : testIds) { + Test test = SpringContext.getBean(TestService.class).get(testId); + test.setOrderable(orderable); + test.setSysUserId(getSysUserId(request)); + tests.add(test); + } + + return tests; + } + + private List getIdsForActions(String key, JSONObject root, JSONParser parser) { + List list = new ArrayList<>(); + + String action = (String) root.get(key); + + try { + JSONArray actionArray = (JSONArray) parser.parse(action); + + for (int i = 0; i < actionArray.size(); i++) { + list.add((String) ((JSONObject) actionArray.get(i)).get("id")); + } + } catch (ParseException e) { + LogEvent.logDebug(e); + } + + return list; + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestRenameEntryRestController.java b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestRenameEntryRestController.java new file mode 100644 index 0000000000..42fde2957e --- /dev/null +++ b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestRenameEntryRestController.java @@ -0,0 +1,128 @@ +package org.openelisglobal.testconfiguration.controller.rest; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.exception.LIMSRuntimeException; +import org.openelisglobal.common.log.LogEvent; +import org.openelisglobal.common.services.DisplayListService; +import org.openelisglobal.localization.service.LocalizationService; +import org.openelisglobal.localization.valueholder.Localization; +import org.openelisglobal.test.service.TestService; +import org.openelisglobal.test.valueholder.Test; +import org.openelisglobal.testconfiguration.form.TestRenameEntryForm; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +@RestController +@RequestMapping("/rest") +public class TestRenameEntryRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] { "testId", "nameEnglish", "nameFrench", + "reportNameEnglish", "reportNameFrench" }; + + @Autowired + private LocalizationService localizationService; + @Autowired + private TestService testService; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/TestRenameEntry") + public TestRenameEntryForm showTestRenameEntry(HttpServletRequest request) { + LogEvent.logInfo(this.getClass().getSimpleName(), "method unkown", + "Hibernate Version: " + org.hibernate.Version.getVersionString()); + // String forward = FWD_SUCCESS; + TestRenameEntryForm form = new TestRenameEntryForm(); + + form.setTestList(DisplayListService.getInstance().getList(DisplayListService.ListType.ALL_TESTS)); + + // return findForward(forward, form); + return form; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "testRenameDefinition"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "redirect:/TestRenameEntry"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "testRenameDefinition"; + } else { + return "PageNotFound"; + } + } + + @PostMapping(value = "/TestRenameEntry") + public TestRenameEntryForm updateTestRenameEntry(HttpServletRequest request, + @RequestBody @Valid TestRenameEntryForm form, BindingResult result, RedirectAttributes redirectAttributes) { + if (result.hasErrors()) { + // saveErrors(result); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + + form.setCancelAction("CancelDictionary"); + + String testId = form.getTestId(); + String nameEnglish = form.getNameEnglish(); + String nameFrench = form.getNameFrench(); + String reportNameEnglish = form.getReportNameEnglish(); + String reportNameFrench = form.getReportNameFrench(); + String userId = getSysUserId(request); + + updateTestNames(testId, nameEnglish, nameFrench, reportNameEnglish, reportNameFrench, userId); + + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } + + private void updateTestNames(String testId, String nameEnglish, String nameFrench, String reportNameEnglish, + String reportNameFrench, String userId) { + Test test = testService.get(testId); + + if (test != null) { + + Localization name = test.getLocalizedTestName(); + Localization reportingName = test.getLocalizedReportingName(); + name.setEnglish(nameEnglish.trim()); + name.setFrench(nameFrench.trim()); + name.setSysUserId(userId); + reportingName.setEnglish(reportNameEnglish.trim()); + reportingName.setFrench(reportNameFrench.trim()); + reportingName.setSysUserId(userId); + + try { + localizationService.updateTestNames(name, reportingName); + } catch (LIMSRuntimeException e) { + LogEvent.logError(e); + } + } + + // Refresh test names + DisplayListService.getInstance().getFreshList(DisplayListService.ListType.ALL_TESTS); + DisplayListService.getInstance().getFreshList(DisplayListService.ListType.ORDERABLE_TESTS); + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestSectionCreateRestController.java b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestSectionCreateRestController.java new file mode 100644 index 0000000000..ae94cf963b --- /dev/null +++ b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestSectionCreateRestController.java @@ -0,0 +1,195 @@ +package org.openelisglobal.testconfiguration.controller.rest; + +import java.util.List; +import java.util.Locale; +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import org.openelisglobal.common.constants.Constants; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.exception.LIMSRuntimeException; +import org.openelisglobal.common.log.LogEvent; +import org.openelisglobal.common.services.DisplayListService; +import org.openelisglobal.localization.valueholder.Localization; +import org.openelisglobal.role.service.RoleService; +import org.openelisglobal.role.valueholder.Role; +import org.openelisglobal.systemmodule.valueholder.SystemModule; +import org.openelisglobal.systemusermodule.valueholder.RoleModule; +import org.openelisglobal.test.service.TestSectionService; +import org.openelisglobal.test.valueholder.TestSection; +import org.openelisglobal.testconfiguration.form.TestSectionCreateForm; +import org.openelisglobal.testconfiguration.service.TestSectionCreateService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class TestSectionCreateRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] { "testUnitEnglishName", "testUnitFrenchName" }; + + public static final String NAME_SEPARATOR = "$"; + + @Autowired + private TestSectionService testSectionService; + @Autowired + private RoleService roleService; + @Autowired + private TestSectionCreateService testSectionCreateService; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/TestSectionCreate") + public TestSectionCreateForm showTestSectionCreate(HttpServletRequest request) { + TestSectionCreateForm form = new TestSectionCreateForm(); + + setupDisplayItems(form); + + // return findForward(FWD_SUCCESS, form); + return form; + } + + private void setupDisplayItems(TestSectionCreateForm form) { + form.setExistingTestUnitList( + DisplayListService.getInstance().getList(DisplayListService.ListType.TEST_SECTION_ACTIVE)); + form.setInactiveTestUnitList( + DisplayListService.getInstance().getList(DisplayListService.ListType.TEST_SECTION_INACTIVE)); + List testSections = testSectionService.getAllTestSections(); + form.setExistingEnglishNames(getExistingTestNames(testSections, Locale.ENGLISH)); + + form.setExistingFrenchNames(getExistingTestNames(testSections, Locale.FRENCH)); + } + + private String getExistingTestNames(List testSections, Locale locale) { + StringBuilder builder = new StringBuilder(NAME_SEPARATOR); + + for (TestSection testSection : testSections) { + builder.append(testSection.getLocalization().getLocalizedValue(locale)); + builder.append(NAME_SEPARATOR); + } + + return builder.toString(); + } + + @PostMapping(value = "/TestSectionCreate") + public TestSectionCreateForm postTestSectionCreate(HttpServletRequest request, + @RequestBody @Valid TestSectionCreateForm form, BindingResult result) { + if (result.hasErrors()) { + saveErrors(result); + setupDisplayItems(form); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + + String identifyingName = form.getTestUnitEnglishName(); + String userId = getSysUserId(request); + + Localization localization = createLocalization(form.getTestUnitFrenchName(), identifyingName, userId); + + TestSection testSection = createTestSection(identifyingName, userId); + + SystemModule workplanModule = createSystemModule("Workplan", identifyingName, userId); + SystemModule resultModule = createSystemModule("LogbookResults", identifyingName, userId); + SystemModule validationModule = createSystemModule("ResultValidation", identifyingName, userId); + + Role resultsEntryRole = roleService.getRoleByName(Constants.ROLE_RESULTS); + Role validationRole = roleService.getRoleByName(Constants.ROLE_VALIDATION); + + RoleModule workplanResultModule = createRoleModule(userId, workplanModule, resultsEntryRole); + RoleModule resultResultModule = createRoleModule(userId, resultModule, resultsEntryRole); + RoleModule validationValidationModule = createRoleModule(userId, validationModule, validationRole); + + try { + testSectionCreateService.insertTestSection(localization, testSection, workplanModule, resultModule, + validationModule, workplanResultModule, resultResultModule, validationValidationModule); + } catch (LIMSRuntimeException e) { + LogEvent.logDebug(e); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + + DisplayListService.getInstance().refreshList(DisplayListService.ListType.TEST_SECTION_ACTIVE); + DisplayListService.getInstance().refreshList(DisplayListService.ListType.TEST_SECTION_INACTIVE); + + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } + + private Localization createLocalization(String french, String english, String currentUserId) { + Localization localization = new Localization(); + localization.setEnglish(english); + localization.setFrench(french); + localization.setDescription("test unit name"); + localization.setSysUserId(currentUserId); + return localization; + } + + private RoleModule createRoleModule(String userId, SystemModule workplanModule, Role role) { + RoleModule roleModule = new RoleModule(); + roleModule.setRole(role); + roleModule.setSystemModule(workplanModule); + roleModule.setSysUserId(userId); + roleModule.setHasAdd("Y"); + roleModule.setHasDelete("Y"); + roleModule.setHasSelect("Y"); + roleModule.setHasUpdate("Y"); + return roleModule; + } + + private TestSection createTestSection(String identifyingName, String userId) { + TestSection testSection = new TestSection(); + testSection.setDescription(identifyingName); + testSection.setTestSectionName(identifyingName); + testSection.setIsActive("N"); + String identifyingNameKey = identifyingName.replaceAll(" ", "_"); + testSection.setNameKey("testSection." + identifyingNameKey); + + testSection.setSortOrderInt(Integer.MAX_VALUE); + testSection.setSysUserId(userId); + return testSection; + } + + private SystemModule createSystemModule(String menuItem, String identifyingName, String userId) { + SystemModule module = new SystemModule(); + module.setSystemModuleName(menuItem + ":" + identifyingName); + module.setDescription(menuItem + "=>" + identifyingName); + module.setSysUserId(userId); + module.setHasAddFlag("Y"); + module.setHasDeleteFlag("Y"); + module.setHasSelectFlag("Y"); + module.setHasUpdateFlag("Y"); + return module; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "testSectionCreateDefinition"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "redirect:/TestSectionCreate"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "testSectionCreateDefinition"; + } else { + return "PageNotFound"; + } + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestSectionOrderRestController.java b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestSectionOrderRestController.java new file mode 100644 index 0000000000..a1f4e1a0da --- /dev/null +++ b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestSectionOrderRestController.java @@ -0,0 +1,147 @@ +package org.openelisglobal.testconfiguration.controller.rest; + +import java.util.ArrayList; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import org.hibernate.HibernateException; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.log.LogEvent; +import org.openelisglobal.common.services.DisplayListService; +import org.openelisglobal.test.service.TestSectionService; +import org.openelisglobal.test.valueholder.TestSection; +import org.openelisglobal.testconfiguration.form.TestSectionOrderForm; +import org.openelisglobal.testconfiguration.validator.TestSectionOrderFormValidator; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class TestSectionOrderRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] { "jsonChangeList" }; + + @Autowired + TestSectionOrderFormValidator formValidator; + @Autowired + TestSectionService testSectionService; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/TestSectionOrder") + public TestSectionOrderForm showTestSectionOrder(HttpServletRequest request) { + TestSectionOrderForm form = new TestSectionOrderForm(); + + setupDisplayItems(form); + + // return findForward(FWD_SUCCESS, form); + return form; + } + + private void setupDisplayItems(TestSectionOrderForm form) { + form.setTestSectionList( + DisplayListService.getInstance().getList(DisplayListService.ListType.TEST_SECTION_ACTIVE)); + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "testSectionOrderDefinition"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "redirect:/TestSectionOrder"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "testSectionOrderDefinition"; + } else { + return "PageNotFound"; + } + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } + + private class ActivateSet { + public String id; + public Integer sortOrder; + } + + @PostMapping(value = "/TestSectionOrder") + public TestSectionOrderForm postTestSectionOrder(HttpServletRequest request, + @RequestBody @Valid TestSectionOrderForm form, BindingResult result) throws ParseException { + formValidator.validate(form, result); + if (result.hasErrors()) { + saveErrors(result); + setupDisplayItems(form); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + String changeList = form.getJsonChangeList(); + + JSONParser parser = new JSONParser(); + JSONObject obj = (JSONObject) parser.parse(changeList); + List orderSet = getActivateSetForActions("testSections", obj, parser); + List testSections = new ArrayList<>(); + + String currentUserId = getSysUserId(request); + for (ActivateSet sets : orderSet) { + TestSection testSection = testSectionService.getTestSectionById(sets.id); + testSection.setSortOrderInt(sets.sortOrder); + testSection.setSysUserId(currentUserId); + testSections.add(testSection); + } + + try { + testSectionService.updateAll(testSections); + } catch (HibernateException e) { + LogEvent.logDebug(e); + } + + DisplayListService.getInstance().refreshList(DisplayListService.ListType.TEST_SECTION_ACTIVE); + DisplayListService.getInstance().refreshList(DisplayListService.ListType.TEST_SECTION_INACTIVE); + + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } + + private List getActivateSetForActions(String key, JSONObject root, JSONParser parser) { + List list = new ArrayList<>(); + + String action = (String) root.get(key); + + try { + JSONArray actionArray = (JSONArray) parser.parse(action); + + for (int i = 0; i < actionArray.size(); i++) { + ActivateSet set = new ActivateSet(); + set.id = String.valueOf(((JSONObject) actionArray.get(i)).get("id")); + Long longSort = (Long) ((JSONObject) actionArray.get(i)).get("sortOrder"); + set.sortOrder = longSort.intValue(); + list.add(set); + } + } catch (ParseException e) { + LogEvent.logDebug(e); + } + + return list; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestSectionRenameEntryRestController.java b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestSectionRenameEntryRestController.java new file mode 100644 index 0000000000..fc55566c33 --- /dev/null +++ b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestSectionRenameEntryRestController.java @@ -0,0 +1,116 @@ +package org.openelisglobal.testconfiguration.controller.rest; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import org.hibernate.HibernateException; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.log.LogEvent; +import org.openelisglobal.common.services.DisplayListService; +import org.openelisglobal.localization.service.LocalizationService; +import org.openelisglobal.localization.valueholder.Localization; +import org.openelisglobal.test.service.TestSectionService; +import org.openelisglobal.test.valueholder.TestSection; +import org.openelisglobal.testconfiguration.form.TestSectionRenameEntryForm; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class TestSectionRenameEntryRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] { "testSectionId", "nameEnglish", "nameFrench" }; + + @Autowired + LocalizationService localizationService; + @Autowired + TestSectionService testSectionService; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/TestSectionRenameEntry") + public TestSectionRenameEntryForm showTestSectionRenameEntry(HttpServletRequest request) { + TestSectionRenameEntryForm form = new TestSectionRenameEntryForm(); + + form.setTestSectionList( + DisplayListService.getInstance().getList(DisplayListService.ListType.TEST_SECTION_ACTIVE)); + + // return findForward(FWD_SUCCESS, form); + return form; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "testSectionRenameDefinition"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "redirect:/TestSectionRenameEntry"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "testSectionRenameDefinition"; + } else { + return "PageNotFound"; + } + } + + @PostMapping(value = "/TestSectionRenameEntry") + public TestSectionRenameEntryForm updateTestSectionRenameEntry(HttpServletRequest request, + @RequestBody @Valid TestSectionRenameEntryForm form, BindingResult result) { + if (result.hasErrors()) { + saveErrors(result); + form.setTestSectionList( + DisplayListService.getInstance().getList(DisplayListService.ListType.TEST_SECTION_ACTIVE)); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + + String testSectionId = form.getTestSectionId(); + String nameEnglish = form.getNameEnglish(); + String nameFrench = form.getNameFrench(); + String userId = getSysUserId(request); + + updateTestSectionNames(testSectionId, nameEnglish, nameFrench, userId); + + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } + + private void updateTestSectionNames(String testSectionId, String nameEnglish, String nameFrench, String userId) { + TestSection testSection = testSectionService.getTestSectionById(testSectionId); + + if (testSection != null) { + + Localization name = testSection.getLocalization(); + name.setEnglish(nameEnglish.trim()); + name.setFrench(nameFrench.trim()); + name.setSysUserId(userId); + + try { + localizationService.update(name); + } catch (HibernateException e) { + LogEvent.logDebug(e); + } + } + + // Refresh Test Section names + DisplayListService.getInstance().getFreshList(DisplayListService.ListType.TEST_SECTION_ACTIVE); + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestSectionTestAssignRestController.java b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestSectionTestAssignRestController.java new file mode 100644 index 0000000000..fe6ba5010e --- /dev/null +++ b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/TestSectionTestAssignRestController.java @@ -0,0 +1,159 @@ +package org.openelisglobal.testconfiguration.controller.rest; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import org.hibernate.HibernateException; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.log.LogEvent; +import org.openelisglobal.common.services.DisplayListService; +import org.openelisglobal.common.util.IdValuePair; +import org.openelisglobal.spring.util.SpringContext; +import org.openelisglobal.test.service.TestSectionService; +import org.openelisglobal.test.service.TestService; +import org.openelisglobal.test.service.TestServiceImpl; +import org.openelisglobal.test.valueholder.Test; +import org.openelisglobal.test.valueholder.TestSection; +import org.openelisglobal.testconfiguration.form.TestSectionTestAssignForm; +import org.openelisglobal.testconfiguration.service.TestSectionTestAssignService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class TestSectionTestAssignRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] { "testId", "testSectionId", + "deactivateTestSectionId" }; + + @Autowired + private TestSectionTestAssignService testSectionTestAssignService; + @Autowired + private TestSectionService testSectionService; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/TestSectionTestAssign") + public TestSectionTestAssignForm showTestSectionTestAssign(HttpServletRequest request) { + TestSectionTestAssignForm form = new TestSectionTestAssignForm(); + + setupDisplayItems(form); + + // return findForward(FWD_SUCCESS, form); + return form; + } + + private void setupDisplayItems(TestSectionTestAssignForm form) { + List testSections = DisplayListService.getInstance() + .getListWithLeadingBlank(DisplayListService.ListType.TEST_SECTION_ACTIVE); + LinkedHashMap> testSectionTestsMap = new LinkedHashMap<>(testSections.size()); + + for (IdValuePair sectionPair : testSections) { + List tests = new ArrayList<>(); + testSectionTestsMap.put(sectionPair, tests); + List testList = testSectionService.getTestsInSection(sectionPair.getId()); + + for (Test test : testList) { + if (test.isActive()) { + tests.add(new IdValuePair(test.getId(), TestServiceImpl.getLocalizedTestNameWithType(test))); + } + } + } + + // we can't just append the original list because that list is in the cache + List joinedList = new ArrayList<>(testSections); + joinedList.addAll(DisplayListService.getInstance().getList(DisplayListService.ListType.TEST_SECTION_INACTIVE)); + + form.setTestSectionList(joinedList); + form.setSectionTestList(testSectionTestsMap); + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "testSectionAssignDefinition"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "redirect:/TestSectionTestAssign"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "testSectionAssignDefinition"; + } else { + return "PageNotFound"; + } + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } + + @PostMapping(value = "/TestSectionTestAssign") + public TestSectionTestAssignForm postTestSectionTestAssign(HttpServletRequest request, + @RequestBody @Valid TestSectionTestAssignForm form, BindingResult result) { + if (result.hasErrors()) { + saveErrors(result); + setupDisplayItems(form); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + + String testId = form.getTestId(); + String testSectionId = form.getTestSectionId(); + String deactivateTestSectionId = form.getDeactivateTestSectionId(); + boolean updateTestSection = false; + String currentUser = getSysUserId(request); + Test test = SpringContext.getBean(TestService.class).get(testId); + TestSection testSection = testSectionService.get(testSectionId); + TestSection deActivateTestSection = null; + test.setTestSection(testSection); + test.setSysUserId(currentUser); + + // This covers the case that they are moving the test to the same test section + // they are moving it from + if (testSectionId.equals(deactivateTestSectionId)) { + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } + + if ("N".equals(testSection.getIsActive())) { + testSection.setIsActive("Y"); + testSection.setSysUserId(currentUser); + updateTestSection = true; + } + + if (!org.apache.commons.validator.GenericValidator.isBlankOrNull(deactivateTestSectionId)) { + deActivateTestSection = testSectionService.get(deactivateTestSectionId); + deActivateTestSection.setIsActive("N"); + deActivateTestSection.setSysUserId(currentUser); + } + + try { + testSectionTestAssignService.updateTestAndTestSections(test, testSection, deActivateTestSection, + updateTestSection); + } catch (HibernateException e) { + LogEvent.logDebug(e); + } + + DisplayListService.getInstance().refreshList(DisplayListService.ListType.TEST_SECTION_ACTIVE); + DisplayListService.getInstance().refreshList(DisplayListService.ListType.TEST_SECTION_INACTIVE); + + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/controller/rest/UomCreateRestController.java b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/UomCreateRestController.java new file mode 100644 index 0000000000..b8fcc0677e --- /dev/null +++ b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/UomCreateRestController.java @@ -0,0 +1,131 @@ +package org.openelisglobal.testconfiguration.controller.rest; + +import java.util.List; +import java.util.Locale; +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.exception.LIMSRuntimeException; +import org.openelisglobal.common.log.LogEvent; +import org.openelisglobal.common.services.DisplayListService; +import org.openelisglobal.testconfiguration.form.UomCreateForm; +import org.openelisglobal.unitofmeasure.service.UnitOfMeasureService; +import org.openelisglobal.unitofmeasure.valueholder.UnitOfMeasure; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class UomCreateRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] { "uomEnglishName" }; + + public static final String NAME_SEPARATOR = "$"; + + @Autowired + UnitOfMeasureService unitOfMeasureService; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/UomCreate") + public UomCreateForm showUomCreate(HttpServletRequest request) { + UomCreateForm form = new UomCreateForm(); + + setupDisplayItems(form); + + // return findForward(FWD_SUCCESS, form); + return form; + } + + private void setupDisplayItems(UomCreateForm form) { + form.setExistingUomList(DisplayListService.getInstance().getList(DisplayListService.ListType.UNIT_OF_MEASURE)); + form.setInactiveUomList( + DisplayListService.getInstance().getList(DisplayListService.ListType.UNIT_OF_MEASURE_INACTIVE)); + List uoms = unitOfMeasureService.getAll(); + form.setExistingEnglishNames(getExistingUomNames(uoms, Locale.ENGLISH)); + form.setExistingFrenchNames(getExistingUomNames(uoms, Locale.FRENCH)); + } + + private String getExistingUomNames(List uoms, Locale locale) { + StringBuilder builder = new StringBuilder(NAME_SEPARATOR); + + for (UnitOfMeasure uom : uoms) { + builder.append(uom.getLocalization().getLocalizedValue(locale)); + builder.append(NAME_SEPARATOR); + } + + return builder.toString(); + } + + @PostMapping(value = "/UomCreate") + public UomCreateForm postUomCreate(HttpServletRequest request, @RequestBody @Valid UomCreateForm form, + BindingResult result) { + if (result.hasErrors()) { + saveErrors(result); + setupDisplayItems(form); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + + String identifyingName = form.getUomEnglishName(); + String userId = getSysUserId(request); + + // Localization localization = + // createLocalization(dynaform.getUomFrenchName(), identifyingName, + // userId); + + UnitOfMeasure unitOfMeasure = createUnitOfMeasure(identifyingName, userId); + + try { + unitOfMeasureService.insert(unitOfMeasure); + } catch (LIMSRuntimeException e) { + LogEvent.logDebug(e); + } + + DisplayListService.getInstance().refreshList(DisplayListService.ListType.UNIT_OF_MEASURE); + DisplayListService.getInstance().refreshList(DisplayListService.ListType.UNIT_OF_MEASURE_INACTIVE); + + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } + + private UnitOfMeasure createUnitOfMeasure(String identifyingName, String userId) { + UnitOfMeasure unitOfMeasure = new UnitOfMeasure(); + unitOfMeasure.setDescription(identifyingName); + unitOfMeasure.setUnitOfMeasureName(identifyingName); + return unitOfMeasure; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "uomCreateDefinition"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "redirect:/UomCreate"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "uomCreateDefinition"; + } else { + return "PageNotFound"; + } + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/controller/rest/UomRenameEntryRestController.java b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/UomRenameEntryRestController.java new file mode 100644 index 0000000000..69f67a25bc --- /dev/null +++ b/src/main/java/org/openelisglobal/testconfiguration/controller/rest/UomRenameEntryRestController.java @@ -0,0 +1,113 @@ +package org.openelisglobal.testconfiguration.controller.rest; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import org.hibernate.HibernateException; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.log.LogEvent; +import org.openelisglobal.common.services.DisplayListService; +import org.openelisglobal.testconfiguration.form.UomRenameEntryForm; +import org.openelisglobal.unitofmeasure.service.UnitOfMeasureService; +import org.openelisglobal.unitofmeasure.valueholder.UnitOfMeasure; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class UomRenameEntryRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] { "uomId", "nameEnglish" }; + + @Autowired + UnitOfMeasureService unitOfMeasureService; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/UomRenameEntry") + public UomRenameEntryForm showUomRenameEntry(HttpServletRequest request) { + UomRenameEntryForm form = new UomRenameEntryForm(); + form.setUomList(DisplayListService.getInstance().getList(DisplayListService.ListType.UNIT_OF_MEASURE)); + + // return findForward(FWD_SUCCESS, form); + return form; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "uomRenameDefinition"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "redirect:/UomRenameEntry"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "uomRenameDefinition"; + } else { + return "PageNotFound"; + } + } + + @PostMapping(value = "/UomRenameEntry") + public UomRenameEntryForm updateUomRenameEntry(HttpServletRequest request, + @RequestBody @Valid UomRenameEntryForm form, BindingResult result) { + if (result.hasErrors()) { + saveErrors(result); + form.setUomList(DisplayListService.getInstance().getList(DisplayListService.ListType.UNIT_OF_MEASURE)); + // return findForward(FWD_FAIL_INSERT, form); + return form; + } + String uomId = form.getUomId(); + String nameEnglish = form.getNameEnglish(); + String userId = getSysUserId(request); + + updateUomNames(uomId, nameEnglish, userId); + + // return findForward(FWD_SUCCESS_INSERT, form); + return form; + } + + private void updateUomNames(String uomId, String nameEnglish, String userId) { + UnitOfMeasure unitOfMeasure = unitOfMeasureService.getUnitOfMeasureById(uomId); + + if (unitOfMeasure != null) { + + // not using localization for UOM + + // Localization name = unitOfMeasure.getLocalization(); + // + // name.setEnglish( nameEnglish.trim() ); + // name.setFrench( nameFrench.trim() ); + // name.setSysUserId( userId ); + + unitOfMeasure.setUnitOfMeasureName(nameEnglish.trim()); + unitOfMeasure.setSysUserId(userId); + + try { + unitOfMeasureService.update(unitOfMeasure); + } catch (HibernateException e) { + LogEvent.logDebug(e); + } + } + + // Refresh Uom names + DisplayListService.getInstance().getFreshList(DisplayListService.ListType.UNIT_OF_MEASURE); + } + + @Override + protected String getPageTitleKey() { + return null; + } + + @Override + protected String getPageSubtitleKey() { + return null; + } +} diff --git a/src/main/java/org/openelisglobal/testconfiguration/service/TestAddService.java b/src/main/java/org/openelisglobal/testconfiguration/service/TestAddService.java index c69b4e8e99..2bfe21b5cb 100644 --- a/src/main/java/org/openelisglobal/testconfiguration/service/TestAddService.java +++ b/src/main/java/org/openelisglobal/testconfiguration/service/TestAddService.java @@ -8,4 +8,7 @@ public interface TestAddService { void addTests(List testSets, Localization nameLocalization, Localization reportingNameLocalization, String currentUserId); + + void addTestsRest(List testSets, + Localization nameLocalization, Localization reportingNameLocalization, String currentUserId); } diff --git a/src/main/java/org/openelisglobal/testconfiguration/service/TestAddServiceImpl.java b/src/main/java/org/openelisglobal/testconfiguration/service/TestAddServiceImpl.java index 19dd98bc52..2e21477d3b 100644 --- a/src/main/java/org/openelisglobal/testconfiguration/service/TestAddServiceImpl.java +++ b/src/main/java/org/openelisglobal/testconfiguration/service/TestAddServiceImpl.java @@ -108,4 +108,69 @@ public void addTests(List testSets, Localization nameLocalization, Loca } } } + + @Override + public void addTestsRest( + List testSets, + Localization nameLocalization, Localization reportingNameLocalization, String currentUserId) { + nameLocalization.setSysUserId(currentUserId); + localizationService.insert(nameLocalization); + reportingNameLocalization.setSysUserId(currentUserId); + localizationService.insert(reportingNameLocalization); + + for (org.openelisglobal.testconfiguration.controller.rest.TestAddRestController.TestSet set : testSets) { + set.test.setSysUserId(currentUserId); + set.test.setLocalizedTestName(nameLocalization); + set.test.setLocalizedReportingName(reportingNameLocalization); + testService.insert(set.test); + + TestSection testSection = set.test.getTestSection(); + if ("N".equals(testSection.getIsActive())) { + testSection.setIsActive("Y"); + testSection.setSysUserId(currentUserId); + testSectionService.update(testSection); + } + + for (Test test : set.sortedTests) { + test.setSysUserId(currentUserId); + testService.update(test); + } + + set.typeOfSample.setSysUserId(currentUserId); + typeOfSampleService.update(set.typeOfSample); + + set.sampleTypeTest.setSysUserId(currentUserId); + set.sampleTypeTest.setTestId(set.test.getId()); + typeOfSampleTestService.insert(set.sampleTypeTest); + + for (PanelItem item : set.panelItems) { + item.setSysUserId(currentUserId); + item.setTest(set.test); + panelItemService.insert(item); + if (item.getPanel() != null) { + Panel panel = item.getPanel(); + if ("N".equals(panel.getIsActive())) { + panel.setIsActive("Y"); + panel.setSysUserId(currentUserId); + panelService.update(panel); + } + } + } + + for (TestResult testResult : set.testResults) { + testResult.setSysUserId(currentUserId); + testResult.setTest(set.test); + testResultService.insert(testResult); + if (testResult.getDefault()) { + set.test.setDefaultTestResult(testResult); + } + } + + for (ResultLimit resultLimit : set.resultLimits) { + resultLimit.setSysUserId(currentUserId); + resultLimit.setTestId(set.test.getId()); + resultLimitService.insert(resultLimit); + } + } + } } diff --git a/src/main/java/org/openelisglobal/testconfiguration/service/TestModifyService.java b/src/main/java/org/openelisglobal/testconfiguration/service/TestModifyService.java index 7b1650c8cf..d39d38f97d 100644 --- a/src/main/java/org/openelisglobal/testconfiguration/service/TestModifyService.java +++ b/src/main/java/org/openelisglobal/testconfiguration/service/TestModifyService.java @@ -9,4 +9,9 @@ public interface TestModifyService { void updateTestSets(List testSets, TestAddParams testAddParams, Localization nameLocalization, Localization reportingNameLocalization, String currentUserId); + + void updateTestSetsRest( + List testSets, + org.openelisglobal.testconfiguration.controller.rest.TestModifyEntryRestController.TestAddParams testAddParams, + Localization nameLocalization, Localization reportingNameLocalization, String currentUserId); } diff --git a/src/main/java/org/openelisglobal/testconfiguration/service/TestModifyServiceImpl.java b/src/main/java/org/openelisglobal/testconfiguration/service/TestModifyServiceImpl.java index 4a632ef435..571c470bb4 100644 --- a/src/main/java/org/openelisglobal/testconfiguration/service/TestModifyServiceImpl.java +++ b/src/main/java/org/openelisglobal/testconfiguration/service/TestModifyServiceImpl.java @@ -213,4 +213,100 @@ private void updateTestNames(String testId, Localization nameLocalization, Local DisplayListService.getInstance().getFreshList(DisplayListService.ListType.ALL_TESTS); DisplayListService.getInstance().getFreshList(DisplayListService.ListType.ORDERABLE_TESTS); } + + @Override + public void updateTestSetsRest( + List testSets, + org.openelisglobal.testconfiguration.controller.rest.TestModifyEntryRestController.TestAddParams testAddParams, + Localization nameLocalization, Localization reportingNameLocalization, String currentUserId) { + List typeOfSampleTest = typeOfSampleTestService + .getTypeOfSampleTestsForTest(testAddParams.testId); + String[] typeOfSamplesTestIDs = new String[typeOfSampleTest.size()]; + for (int i = 0; i < typeOfSampleTest.size(); i++) { + typeOfSamplesTestIDs[i] = typeOfSampleTest.get(i).getId(); + typeOfSampleTestService.delete(typeOfSamplesTestIDs[i], currentUserId); + } + + List panelItems = panelItemService.getPanelItemByTestId(testAddParams.testId); + for (PanelItem item : panelItems) { + item.setSysUserId(currentUserId); + } + panelItemService.deleteAll(panelItems); + + List resultLimitItems = resultLimitService.getAllResultLimitsForTest(testAddParams.testId); + for (ResultLimit item : resultLimitItems) { + item.setSysUserId(currentUserId); + resultLimitService.delete(item); + } + // resultLimitService.delete(resultLimitItems); + + for (org.openelisglobal.testconfiguration.controller.rest.TestModifyEntryRestController.TestSet set : testSets) { + set.test.setSysUserId(currentUserId); + set.test.setLocalizedTestName(nameLocalization); + set.test.setLocalizedReportingName(reportingNameLocalization); + + TestSection testSection = set.test.getTestSection(); + if ("N".equals(testSection.getIsActive())) { + testSection.setIsActive("Y"); + testSection.setSysUserId(currentUserId); + testSectionService.update(testSection); + } + + // gnr: based on testAddUpdate, + // added existing testId to process in createTestSets using + // testAddParams.testId, delete then insert to modify for most elements + + for (Test test : set.sortedTests) { + updateTestSortOrder(test.getId(), test.getSortOrder(), currentUserId); + } + + updateTestNames(testAddParams.testId, nameLocalization, reportingNameLocalization, currentUserId); + updateTestEntities(testAddParams.testId, testAddParams.loinc, currentUserId, testAddParams.uomId, + testAddParams.testSectionId, set.test.isNotifyResults(), set.test.isInLabOnly(), + set.test.getAntimicrobialResistance(), set.test.getIsActive(), set.test.getOrderable()); + + set.sampleTypeTest.setSysUserId(currentUserId); + set.sampleTypeTest.setTestId(set.test.getId()); + typeOfSampleTestService.insert(set.sampleTypeTest); + + for (PanelItem item : set.panelItems) { + item.setSysUserId(currentUserId); + Test nonTransiantTest = testService.getTestById(set.test.getId()); + item.setTest(nonTransiantTest); + panelItemService.insert(item); + if (item.getPanel() != null) { + TypeOfSample sampleType = typeOfSampleService.get(set.sampleTypeTest.getTypeOfSampleId()); + if (typeOfSamplePanelService.getTypeOfSamplePanelsForSampleType(sampleType.getId()).isEmpty()) { + TypeOfSamplePanel tosp = new TypeOfSamplePanel(); + tosp.setPanelId(item.getPanel().getId()); + tosp.setTypeOfSampleId(sampleType.getId()); + typeOfSamplePanelService.insert(tosp); + } + Panel panel = item.getPanel(); + if ("N".equals(panel.getIsActive())) { + panel.setIsActive("Y"); + panel.setSysUserId(currentUserId); + panelService.update(panel); + } + } + } + + for (TestResult testResult : set.testResults) { + testResult.setSysUserId(currentUserId); + Test nonTransiantTest = testService.getTestById(set.test.getId()); + testResult.setTest(nonTransiantTest); + testResultService.insert(testResult); + if (testResult.getDefault()) { + set.test.setDefaultTestResult(testResult); + updateTestDefault(testAddParams.testId, testResult, currentUserId); + } + } + + for (ResultLimit resultLimit : set.resultLimits) { + resultLimit.setSysUserId(currentUserId); + resultLimit.setTestId(set.test.getId()); + resultLimitService.insert(resultLimit); + } + } + } }