Next round of refactoring done

This commit is contained in:
Colin Dawson 2026-01-30 20:58:58 +00:00
parent 04c1875d5d
commit f3deae0842
18 changed files with 1149 additions and 927 deletions

View File

@ -1,7 +1,10 @@
{
"Activate": "Activate",
"Admin": "Admin",
"AnEmailWithPasswordResetLinkHasBeenSent": "An email with a password reset link has been sent.",
"AnErrorOccurred": "An error occurred",
"Application": "Application",
"Applications": "Applications",
"AuditLog": "Audit Logs",
"AuditLogs": "Audit Logs",
"BlockedIPAddresses": "Blocked IP addresses",
@ -13,42 +16,49 @@
"ConfirmPassword": "Confirm Password",
"CustomFieldManager": "Custom Field Manager",
"CustomFields": "Custom Fields",
"DisableAuthenticator": "Disable Authenticator",
"DisplayName": "Display Name",
"EntityDisplayName": "Entity Display Name",
"e-print": "e-print",
"e-suite": "e-suite",
"e-suiteLogo": "e-suite logo",
"EntityDisplayName": "Entity Display Name",
"ErrorLogs": "Error Logs",
"ExceptionJson": "Exception JSON",
"ExceptionLogs": "Exception Logs",
"FailedToDisableAuthenticator": "Failed to disable authenticator:",
"Forms": "Forms",
"FormTemplateManager": "Form Template Manager",
"Glossaries": "Glossaries",
"GlossaryManager": "Glossary Manager",
"Home": "Home",
"Id": "Id",
"Application": "Application",
"Message": "Message",
"ShowJSON": "Show JSON",
"ShowStackTrace": "Show stack trace",
"OccuredAt": "Occured At",
"IPAddress": "IP Address",
"IPAddressUnblocked": "IP Address '{{ip}}' unblocked.",
"Loading": "Loading",
"LoggingOut": "Logging out",
"Message": "Message",
"Name": "Name",
"NumberOfAttempts": "Number Of Attempts",
"NewPassword": "New Password",
"NewValue": "New Value",
"NotFound": "Not found",
"NumberOfAttempts": "Number Of Attempts",
"OccuredAt": "Occured At",
"OldValue": "Old Value",
"Password": "Password",
"PasswordIsRequired": "Password is required",
"PasswordMinLength": "Password must be at least {{minPasswordLength}} characters",
"PasswordsMustMatch": "You need to confirm by typing exactly the same as the new password",
"PressAgainToUnblock": "Press again to unblock",
"ResetPassword": "Reset Password",
"Save": "Save",
"Sequence": "Sequence",
"SequenceManager": "Sequence Manager",
"ShowJSON": "Show JSON",
"ShowStackTrace": "Show stack trace",
"SiteManager": "Site Manager",
"SpecificationManager": "Specification Manager",
"StackTrace": "Stack Trace",
"SsoManager": "Sso Manager",
"StackTrace": "Stack Trace",
"Support": "Support",
"SupportingData": "Supporting Data",
"Timing": "Timing",
@ -56,5 +66,7 @@
"UnblockedInMinutes": "Unblocked In (Minutes)",
"UserManager": "User Manager",
"UserName": "User Name",
"UsernameIsRequired": "Username is required",
"UsernameMustBeValidEmail": "Username must be a valid email",
"Users": "Users"
}

View File

@ -1,15 +1,26 @@
import { FunctionComponent } from "react";
import logo from "./E-SUITE_logo.svg"
import logo from "./E-SUITE_logo.svg";
import { useTranslation } from "react-i18next";
import { Namespaces } from "../i18n/i18n";
interface LogoProps {
className? : string;
height? : string
width? : string
alt?: string
className?: string;
height?: string;
width?: string;
}
const Logo: FunctionComponent<LogoProps> = (props:LogoProps) => {
return ( <img className={props.className} height={props.height} width={props.width} alt={props.alt} src={logo}/>);
}
export default Logo;
const Logo: FunctionComponent<LogoProps> = (props: LogoProps) => {
const { t } = useTranslation(Namespaces.Common);
return (
<img
className={props.className}
height={props.height}
width={props.width}
alt={t("e-suiteLogo") as string}
src={logo}
/>
);
};
export default Logo;

View File

@ -6,7 +6,6 @@ import { useTranslation } from "react-i18next";
import { Namespaces } from "../../../i18n/i18n";
import ExpandableCell from "../../../components/common/ExpandableCell";
import { max } from "date-fns";
export default function ErrorLogsTable(
props: PublishedTableProps<ErrorLog>,

View File

@ -1,63 +1,63 @@
import Form, { FormState, FormData } from "../../../components/common/Form";
import Joi from "joi";
import React, { useState } from "react";
import authentication from "../services/authenticationService";
import { IEmailUserAction } from "../models/IEmailUserAction";
import { FormData } from "../../../components/common/Form";
import Button, { ButtonType } from "../../../components/common/Button";
import { useTranslation } from "react-i18next";
import { Namespaces } from "../../../i18n/i18n";
export interface EmailUserActionDiableTwoFactorAuthenticationData extends FormData {
authenticatorDisabled: boolean;
authenticatorDisabled: boolean;
}
export interface EmailUserActionDiableTwoFactorAuthenticationState extends FormState {
data: EmailUserActionDiableTwoFactorAuthenticationData;
interface Props {
emailUserAction: IEmailUserAction;
}
class EmailUserActionDiableTwoFactorAuthentication extends Form<any, any, EmailUserActionDiableTwoFactorAuthenticationState> {
state = {
loaded: true,
data: { authenticatorDisabled: false },
errors: {},
const EmailUserActionDiableTwoFactorAuthentication: React.FC<Props> = ({
emailUserAction,
}) => {
const { t } = useTranslation<typeof Namespaces.Common>();
const [authenticatorDisabled, setAuthenticatorDisabled] = useState(false);
const LABEL_DISABLE_AUTHENTICATOR = t("DisableAuthenticator");
const handleSubmit = async () => {
const action: IEmailUserAction = {
email: emailUserAction.email,
token: emailUserAction.token,
password: "",
emailActionType: emailUserAction.emailActionType,
};
labelChangePassword = "Disable Authenticator";
schema = {
authenticatorDisabled: Joi.boolean(),
};
doSubmit = async () => {
const { emailUserAction } = this.props;
const action: IEmailUserAction = {
email: emailUserAction.email,
token: emailUserAction.token,
password: "",
emailActionType: emailUserAction.emailActionType,
};
const callResult = await authentication.completeEmailAction(action);
if (callResult === 1) {
let data = { ...this.state.data };
data.authenticatorDisabled = true;
this.setState({ data });
}
};
render() {
const { authenticatorDisabled } = this.state.data;
if (authenticatorDisabled) {
return <div>Your authenticator has been disabled. You can now log in without two factor authentication</div>;
}
return (
<>
<div>Disable two factor authentication</div>
<Button buttonType={ButtonType.link} onClick={this.doSubmit}>Disable Authenticator</Button>
</>
);
try {
const callResult = await authentication.completeEmailAction(action);
if (callResult === 1) {
setAuthenticatorDisabled(true);
}
} catch (error) {
console.error(t("FailedToDisableAuthenticator"), error);
}
}
};
if (authenticatorDisabled) {
return (
<div>
Your authenticator has been disabled. You can now log in without two
factor authentication
</div>
);
}
return (
<>
<div>Disable two factor authentication</div>
<Button buttonType={ButtonType.link} onClick={handleSubmit}>
{LABEL_DISABLE_AUTHENTICATOR}
</Button>
</>
);
};
export default EmailUserActionDiableTwoFactorAuthentication;

View File

@ -1,136 +1,173 @@
import Joi from "joi";
import Form, { businessValidationResult, FormData, FormState } from "../../../components/common/Form";
import React, { useState } from "react";
import { InputType } from "../../../components/common/Input";
import { IEmailUserAction } from "../models/IEmailUserAction";
import authentication from "../services/authenticationService";
import { FormData } from "../../../components/common/Form";
import Input from "../../../components/common/Input";
import Button, { ButtonType } from "../../../components/common/Button";
import ErrorBlock from "../../../components/common/ErrorBlock";
import { useTranslation } from "react-i18next";
import { Namespaces } from "../../../i18n/i18n";
export interface EmailUserActionPasswordResetData extends FormData {
password: string;
confirmPassword: string;
passwordChanged: boolean;
password: string;
confirmPassword: string;
passwordChanged: boolean;
}
export interface EmailUserActionPasswordResetState extends FormState {
data: EmailUserActionPasswordResetData;
interface Props {
emailUserAction: IEmailUserAction;
}
class EmailUserActionPasswordReset extends Form<any, any, EmailUserActionPasswordResetState> {
state = {
loaded: true,
passwordMaxLenght: 255,
data: { password: "", confirmPassword: "", passwordChanged: false },
errors: {},
hasTwelveCharacters: false,
hasSpecialCharacter: false,
hasUppercaseLetter: false,
hasLowercaseLetter: false,
hasNumber: false
};
const EmailUserActionPasswordReset: React.FC<Props> = ({ emailUserAction }) => {
const { t } = useTranslation<typeof Namespaces.Common>();
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [passwordChanged, setPasswordChanged] = useState(false);
const [generalError, setGeneralError] = useState("");
const [errors, setErrors] = useState<{ [key: string]: string }>({});
const [hasTwelveCharacters, setHasTwelveCharacters] = useState(false);
const [hasSpecialCharacter, setHasSpecialCharacter] = useState(false);
const [hasUppercaseLetter, setHasUppercaseLetter] = useState(false);
const [hasLowercaseLetter, setHasLowercaseLetter] = useState(false);
const [hasNumber, setHasNumber] = useState(false);
labelPassword = "New Password";
labelConfirmPassword = "Confirm Password";
labelChangePassword = "Save";
const LABEL_PASSWORD = t("NewPassword");
const LABEL_CONFIRM_PASSWORD = t("ConfirmPassword");
const LABEL_CHANGE_PASSWORD = t("Save");
const PASSWORD_MAX_LENGTH = 255;
schema = {
password: Joi.string().required().min(12).label(this.labelPassword),
confirmPassword: Joi.string()
.when("password", {
is: "",
then: Joi.optional(),
otherwise: Joi.valid(Joi.ref("password")).error(() => {
const e = new Error("Passwords must match");
e.name = "confirmPassword";
return e;
}),
})
.label(this.labelConfirmPassword),
const handlePasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newPassword = e.currentTarget.value;
setPassword(newPassword);
setConfirmPassword("");
setHasNumber(/\d+/g.test(newPassword));
setHasLowercaseLetter(/[a-z]/g.test(newPassword));
setHasUppercaseLetter(/[A-Z]/g.test(newPassword));
setHasSpecialCharacter(
/[ ~`! @#$%^&*()_+\-=[\]{};:\\|,.'"<>/?]/.test(newPassword),
);
setHasTwelveCharacters(newPassword.length >= 12);
};
passwordChanged: Joi.boolean(),
};
const handleConfirmPasswordChange = (
e: React.ChangeEvent<HTMLInputElement>,
) => {
setConfirmPassword(e.currentTarget.value);
};
BusinessValidation(): businessValidationResult | null {
const { password, confirmPassword } = this.state.data;
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const newErrors: { [key: string]: string } = {};
if (password !== confirmPassword) {
return {
details: [
{
path: "confirmPassword",
message: "You need to confirm by typing exactly the same as the new password",
},
],
};
}
const minPasswordLength = 12;
return null;
// Validation
if (!password) {
newErrors.password = t("PasswordIsRequired");
} else if (password.length < minPasswordLength) {
newErrors.password = t("PasswordMinLength", {
minPasswordLength: minPasswordLength,
});
}
handlePasswordChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const { data } = this.state;
data.password = e.currentTarget.value;
data.confirmPassword = "";
const stateData = this.state;
stateData.hasNumber = /\d+/g.test(data.password);
stateData.hasLowercaseLetter = /[a-z]/g.test(data.password);
stateData.hasUppercaseLetter = /[A-Z]/g.test(data.password);;
stateData.hasSpecialCharacter = /[ ~`! @#$%^&*()_+\-=[\]{};:\\|,.'"<>/?]/.test(data.password);
stateData.hasTwelveCharacters = data.password.length >= 12;
this.setState(stateData);
};
doSubmit = async (buttonName: string) => {
const { emailUserAction } = this.props;
const { password } = this.state.data;
const action: IEmailUserAction = {
email: emailUserAction.email,
token: emailUserAction.token,
password: password,
emailActionType: emailUserAction.emailActionType,
};
try {
const callResult = await authentication.completeEmailAction(action);
if (callResult === 1) {
let data = { ...this.state.data };
data.passwordChanged = true;
this.setState({ data });
setTimeout(function () {
window.location.replace('/login');
}, 1000);
}
}
catch (ex: any) {
this.handleGeneralError(ex);
}
};
render() {
const { passwordChanged, password, confirmPassword } = this.state.data;
const { hasNumber, hasLowercaseLetter, hasSpecialCharacter, hasUppercaseLetter, hasTwelveCharacters, passwordMaxLenght } = this.state;
const isFormValid = password !== "" && password === confirmPassword && hasNumber && hasLowercaseLetter && hasSpecialCharacter && hasUppercaseLetter && hasTwelveCharacters;
if (passwordChanged) {
return <div className="alert alert-info">Your password has been reset. Please contact your admin if this wasn't you.</div>;
}
return (
<>
<form onSubmit={this.handleSubmit}>
{this.renderError("_general")}
{this.renderInputWithChangeEvent("password", "", InputType.password, undefined, this.handlePasswordChange, undefined, this.labelPassword, passwordMaxLenght)}
<div className={hasTwelveCharacters ? "checked" : "unchecked"}>Password requires a minimum of 12 characters containing a combination of:</div>
<ul>
<li className={hasSpecialCharacter ? "checked" : ""}>At least 1 symbol</li>
<li className={hasNumber ? "checked" : ""}>At least 1 number</li>
<li className={hasLowercaseLetter ? "checked" : ""}>At least 1 lowercase letter</li>
<li className={hasUppercaseLetter ? "checked" : ""}>At least 1 uppercase letter</li>
</ul>
{this.renderInput("confirmPassword", "", InputType.password, undefined, undefined, this.labelConfirmPassword, passwordMaxLenght)}
{this.renderButton(this.labelChangePassword, "save", undefined, undefined, isFormValid)}
</form>
</>
);
if (password && password !== confirmPassword) {
newErrors.confirmPassword = t("PasswordsMustMatch");
}
}
if (Object.keys(newErrors).length > 0) {
setErrors(newErrors);
return;
}
setErrors({});
try {
const action: IEmailUserAction = {
email: emailUserAction.email,
token: emailUserAction.token,
password: password,
emailActionType: emailUserAction.emailActionType,
};
const callResult = await authentication.completeEmailAction(action);
if (callResult === 1) {
setPasswordChanged(true);
setTimeout(() => {
window.location.replace("/login");
}, 1000);
}
} catch (ex: any) {
setGeneralError(ex?.message || t("AnErrorOccurred"));
}
};
const isFormValid =
password !== "" &&
password === confirmPassword &&
hasNumber &&
hasLowercaseLetter &&
hasSpecialCharacter &&
hasUppercaseLetter &&
hasTwelveCharacters;
if (passwordChanged) {
return (
<div className="alert alert-info">
Your password has been reset. Please contact your admin if this wasn't
you.
</div>
);
}
return (
<>
<form onSubmit={handleSubmit}>
{generalError && <ErrorBlock error={generalError} />}
<Input
name="password"
label={LABEL_PASSWORD}
type={InputType.password}
value={password}
onChange={handlePasswordChange}
maxLength={PASSWORD_MAX_LENGTH}
error={errors.password}
/>
<div className={hasTwelveCharacters ? "checked" : "unchecked"}>
Password requires a minimum of 12 characters containing a combination
of:
</div>
<ul>
<li className={hasSpecialCharacter ? "checked" : ""}>
At least 1 symbol
</li>
<li className={hasNumber ? "checked" : ""}>At least 1 number</li>
<li className={hasLowercaseLetter ? "checked" : ""}>
At least 1 lowercase letter
</li>
<li className={hasUppercaseLetter ? "checked" : ""}>
At least 1 uppercase letter
</li>
</ul>
<Input
name="confirmPassword"
label={LABEL_CONFIRM_PASSWORD}
type={InputType.password}
value={confirmPassword}
onChange={handleConfirmPasswordChange}
maxLength={PASSWORD_MAX_LENGTH}
error={errors.confirmPassword}
/>
<Button
buttonType={ButtonType.primary}
disabled={!isFormValid}
onClick={() => {}}
>
{LABEL_CHANGE_PASSWORD}
</Button>
</form>
</>
);
};
export default EmailUserActionPasswordReset;

View File

@ -1,69 +1,86 @@
import Joi from "joi";
import Form, { FormData, FormState } from "../../../components/common/Form";
import React, { useState } from "react";
import { FormData } from "../../../components/common/Form";
import authentication from "../services/authenticationService";
import Input, { InputType } from "../../../components/common/Input";
import Button, { ButtonType } from "../../../components/common/Button";
import ErrorBlock from "../../../components/common/ErrorBlock";
import { useTranslation } from "react-i18next";
import { Namespaces } from "../../../i18n/i18n";
export interface ForgotPasswordData extends FormData {
username: string;
emailSent: boolean;
username: string;
emailSent: boolean;
}
export interface ForgotPasswordtate extends FormState {
data: ForgotPasswordData;
}
const ForgotPassword: React.FC = () => {
const { t } = useTranslation<typeof Namespaces.Common>();
const [username, setUsername] = useState("");
const [emailSent, setEmailSent] = useState(false);
const [generalError, setGeneralError] = useState("");
const [errors, setErrors] = useState<{ [key: string]: string }>({});
class ForgotPassword extends Form<any, any, ForgotPasswordtate> {
state = {
loaded: true,
data: { username: "", emailSent: false },
errors: {},
};
const validateEmail = (email: string): boolean => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
};
schema = {
username: Joi.string()
.required()
.email({ tlds: { allow: false } })
.label("Username"),
emailSent: Joi.boolean().required(),
};
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const newErrors: { [key: string]: string } = {};
doSubmit = async (buttonName : string) => {
try {
let { data } = this.state;
const response = await authentication.forgotPassword(data.username);
if (response) {
data.emailSent = true;
this.setState({ data });
}
}
catch(ex: any) {
this.handleGeneralError(ex);
}
};
render() {
const { emailSent } = this.state.data;
let content = (
<form onSubmit={this.handleSubmit}>
{this.renderError("_general")}
{this.renderInput("username", "Username")}
{this.renderButton("Reset password")}
</form>
);
if (emailSent) {
content = <div>An email with a password reset link has been sent.</div>;
}
return (
<div>
<div className="forgottenLink">
<h1>Forgot password</h1>
</div>
{content}
</div>
);
// Validation
if (!username) {
newErrors.username = t("UsernameIsRequired");
} else if (!validateEmail(username)) {
newErrors.username = t("UsernameMustBeValidEmail");
}
}
if (Object.keys(newErrors).length > 0) {
setErrors(newErrors);
return;
}
setErrors({});
try {
const response = await authentication.forgotPassword(username);
if (response) {
setEmailSent(true);
}
} catch (ex: any) {
setGeneralError(ex?.message || t("AnErrorOccurred"));
}
};
let content = (
<form onSubmit={handleSubmit}>
{generalError && <ErrorBlock error={generalError} />}
<Input
type={InputType.text}
name="username"
label={t("Username")}
value={username}
onChange={(e) => setUsername(e.currentTarget.value)}
error={errors.username}
/>
<Button buttonType={ButtonType.primary} onClick={() => {}}>
{t("ResetPassword")}
</Button>
</form>
);
if (emailSent) {
content = <div>{t("AnEmailWithPasswordResetLinkHasBeenSent")}</div>;
}
return (
<div>
<div className="forgottenLink">
<h1>Forgot password</h1>
</div>
{content}
</div>
);
};
export default ForgotPassword;

View File

@ -1,49 +1,45 @@
import { IconDefinition } from "@fortawesome/pro-thin-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import React, { Component } from "react";
import { Link } from "react-router-dom";
import withRouter, { RouterProps } from "../../../utils/withRouter";
import React from "react";
import { Link, useLocation } from "react-router-dom";
interface LeftMenuItemProps extends RouterProps {
to : string;
icon? : IconDefinition;
label : string;
interface LeftMenuItemProps {
to: string;
icon?: IconDefinition;
label: string;
}
class LOCLeftMenuItem extends Component<LeftMenuItemProps> {
isSelected = ():boolean => {
const { to } = this.props;
const { pathname } = this.props.router.location;
let isSelected : boolean = false;
if (to === '/' ? (pathname === to) : pathname.toLowerCase().startsWith(to)){
isSelected = true;
}
const LeftMenuItem: React.FC<LeftMenuItemProps> = ({ to, icon, label }) => {
const location = useLocation();
return isSelected;
}
const isSelected = (): boolean => {
const pathname = location.pathname;
return to === "/" ? pathname === to : pathname.toLowerCase().startsWith(to);
};
render() {
const { to, icon, label } = this.props;
let className = "";
let className = "";
if (isSelected()) {
className += " leftMenuSelected";
}
if (this.isSelected()) {
className += " leftMenuSelected";
}
if (icon) {
return (
<div className="LeftMenuItem">
<Link className={className} to={to}>
<FontAwesomeIcon className="leftMenuItemIcon" icon={icon} />
<div className="leftMenuItemLabel">{label}</div>
</Link>
</div>
);
}
if ( icon) {
return (
<div className="LeftMenuItem"><Link className={className} to={to} ><FontAwesomeIcon className="leftMenuItemIcon" icon={icon}/><div className="leftMenuItemLabel">{label}</div></Link></div>
);
}
return (
<Link className={className} to={to}>
{label}
</Link>
);
};
return (
<Link className={className} to={to} >{label}</Link>
);
}
}
const LeftMenuItem = withRouter(LOCLeftMenuItem);
export default LeftMenuItem;
export { LOCLeftMenuItem };
export { LeftMenuItem as LOCLeftMenuItem };

View File

@ -3,71 +3,74 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import React from "react";
import withRouter, { RouterProps } from "../../../utils/withRouter";
interface LeftMenuSubMenuProps extends RouterProps{
icon : IconDefinition;
label : string;
openMenu? : LOCLeftMenuSubMenu;
children : (false | JSX.Element)[];
onClick? : ( menuItem : LOCLeftMenuSubMenu ) => void;
interface LeftMenuSubMenuProps extends RouterProps {
icon: IconDefinition;
label: string;
openMenu?: LOCLeftMenuSubMenu;
children: (false | JSX.Element)[];
onClick?: (menuItem: LOCLeftMenuSubMenu) => void;
}
interface LeftMenuSubMenuState {
interface LeftMenuSubMenuState {}
class LOCLeftMenuSubMenu extends React.Component<
LeftMenuSubMenuProps,
LeftMenuSubMenuState
> {
state = {};
handleClick = (): void => {
const { onClick } = this.props;
if (onClick !== undefined) onClick(this);
};
isChildSelected = (child: JSX.Element): boolean => {
const { to } = child.props;
const { pathname } = this.props.router.location;
let isSelected: boolean = false;
if (to === "/" ? pathname === to : pathname.toLowerCase().startsWith(to)) {
isSelected = true;
}
return isSelected;
};
isAnyChildSelected = (): boolean => {
const { children } = this.props;
let childIsSelected = false;
children.forEach((child) => {
if (child === false) {
return;
}
if (this.isChildSelected(child)) childIsSelected = true;
});
return childIsSelected;
};
render() {
const { icon, label, openMenu } = this.props;
const selected = this === openMenu || this.isAnyChildSelected();
let className = "LeftMenuItem leftMenuSubMenu";
if (selected) {
className += " leftMenuSubMenuOpen";
}
return (
<div className={className} onClick={this.handleClick}>
<FontAwesomeIcon className="leftMenuItemIcon" icon={icon} />
<div className="leftMenuItemLabel">{label}</div>
</div>
);
}
}
class LOCLeftMenuSubMenu extends React.Component<LeftMenuSubMenuProps, LeftMenuSubMenuState> {
state = { }
handleClick = (): void =>
{
const { onClick } = this.props;
if (onClick !== undefined)
onClick(this);
}
isChildSelected = (child : JSX.Element):boolean => {
const { to } = child.props;
const { pathname } = this.props.router.location;
let isSelected : boolean = false;
if (to === '/' ? (pathname === to) : pathname.toLowerCase().startsWith(to)){
isSelected = true;
}
return isSelected;
}
isAnyChildSelected = ():boolean => {
const { children } = this.props;
let childIsSelected = false;
children.forEach(child => {
if (child === false){
return;
}
if (this.isChildSelected(child))
childIsSelected = true;
});
return childIsSelected;
}
render() {
const { icon, label, openMenu } = this.props;
const selected = this === openMenu || this.isAnyChildSelected();
let className = "LeftMenuItem leftMenuSubMenu";
if (selected) {
className += " leftMenuSubMenuOpen";
}
return ( <div className={className} onClick={this.handleClick}><FontAwesomeIcon className="leftMenuItemIcon" icon={icon}/><div className="leftMenuItemLabel">{label}</div></div> );
}
}
const LeftMenuSubMenu = withRouter(LOCLeftMenuSubMenu);
export default LeftMenuSubMenu;
export {LOCLeftMenuSubMenu}
export { LOCLeftMenuSubMenu };

View File

@ -8,159 +8,223 @@ import { ButtonType } from "../../../components/common/Button";
//import '../../../Sass/login.scss';
export interface LoginFormStateData extends FormData {
username: string;
password: string;
tfaNeeded: boolean;
requestTfaRemoval: boolean;
securityCode: string;
username: string;
password: string;
tfaNeeded: boolean;
requestTfaRemoval: boolean;
securityCode: string;
}
export interface LoginFormState extends FormState {
passwordMaxLength: number,
isInNextStage: boolean,
emailSent: boolean,
data: LoginFormStateData;
passwordMaxLength: number;
isInNextStage: boolean;
emailSent: boolean;
data: LoginFormStateData;
}
class LoginForm extends Form<any, any, LoginFormState> {
state = {
loaded: true,
passwordMaxLength: 255,
isInNextStage: false,
emailSent: false,
data: {
username: "",
password: "",
tfaNeeded: false,
requestTfaRemoval: false,
securityCode: "",
},
errors: {},
};
state = {
loaded: true,
passwordMaxLength: 255,
isInNextStage: false,
emailSent: false,
data: {
username: "",
password: "",
tfaNeeded: false,
requestTfaRemoval: false,
securityCode: "",
},
errors: {},
};
schema = {
username: Joi.string()
.required()
.email({ tlds: { allow: false } })
.label("Email"),
password: Joi.string().required().label("Password"),
tfaNeeded: Joi.boolean().required(),
requestTfaRemoval: Joi.boolean().required(),
securityCode: Joi.string().allow("").label("Authenticate"),
};
schema = {
username: Joi.string()
.required()
.email({ tlds: { allow: false } })
.label("Email"),
password: Joi.string().required().label("Password"),
tfaNeeded: Joi.boolean().required(),
requestTfaRemoval: Joi.boolean().required(),
securityCode: Joi.string().allow("").label("Authenticate"),
};
doSubmit = async (buttonName : string) => {
const { data } = this.state;
await this.performLogin(data);
};
doSubmit = async (buttonName: string) => {
const { data } = this.state;
await this.performLogin(data);
};
handleNextClick = async (event: React.MouseEvent) => {
const data: LoginFormStateData = { ...this.state.data };
var validationResult = this.schema.username.validate(data.username);
if (validationResult.error === undefined) {
const stateData = this.state;
stateData.isInNextStage = true;
this.setState(stateData);
}
handleNextClick = async (event: React.MouseEvent) => {
const data: LoginFormStateData = { ...this.state.data };
var validationResult = this.schema.username.validate(data.username);
if (validationResult.error === undefined) {
const stateData = this.state;
stateData.isInNextStage = true;
this.setState(stateData);
}
};
handleForgetPassword = async () => {
try {
const stateData = this.state;
await authentication.forgotPassword(stateData.data.username);
stateData.emailSent = true;
stateData.data.username = "";
stateData.data.password = "";
this.setState(stateData);
}
catch (ex: any) {
this.handleGeneralError(ex);
}
};
authenticationWorkAround = async () => {
const data: LoginFormStateData = { ...this.state.data };
data.requestTfaRemoval = true;
await this.performLogin(data);
this.setState({ data });
};
private async performLogin(data: LoginFormStateData) {
try {
let result = await authentication.login(data.username, data.password, data.securityCode, data.requestTfaRemoval);
switch (result) {
case 1: //requires tfa
const { data } = this.state;
if (data.tfaNeeded === true) {
//TFA removal Request accepted.
} else {
data.tfaNeeded = true;
this.setState({ data });
}
break;
case 2: //logged in
window.location.href = "/";
break;
default:
break; //treat at though not logged in.
}
} catch (ex: any) {
this.handleGeneralError(ex);
}
handleForgetPassword = async () => {
try {
const stateData = this.state;
await authentication.forgotPassword(stateData.data.username);
stateData.emailSent = true;
stateData.data.username = "";
stateData.data.password = "";
this.setState(stateData);
} catch (ex: any) {
this.handleGeneralError(ex);
}
};
render() {
window.location.replace("/login");
const { tfaNeeded, requestTfaRemoval} = this.state.data;
const { isInNextStage, data, emailSent, passwordMaxLength } = this.state;
const result = this.schema.username.validate(data.username);
const validEmail = (result.error === undefined) ? true : false;
authenticationWorkAround = async () => {
const data: LoginFormStateData = { ...this.state.data };
data.requestTfaRemoval = true;
if (authentication.getCurrentUser()) return <Navigate to="/" />;
await this.performLogin(data);
const requestTfaRemovalPanel = <div>An email has been sent to you so that you can regain control of your account.</div>;
this.setState({ data });
};
const loginPanel = (
<><form onSubmit={this.handleSubmit}>
{this.renderInput("username", "", InputType.text, isInNextStage, undefined, "Email", undefined, undefined,"username")}
{this.renderInput("password", "", InputType.password, emailSent, undefined, "Password", passwordMaxLength, isInNextStage, "current-password")}
{!isInNextStage && this.renderButton("Next", "login", this.handleNextClick, "next", validEmail, ButtonType.primary, true)}
{isInNextStage && <div className="clickables">
{this.renderButton("Login", "login", undefined, "login", !emailSent)}
</div>
}
</form>
{isInNextStage && <div className="forgottenLink">
{this.renderButton("Forgotten Password", "forgot-password", this.handleForgetPassword, "forgot-password", validEmail, ButtonType.secondary, true)}
</div>}
{emailSent && <div className="alert alert-info emailSent">If you have a registered account, you will receive an email.</div>}
{this.renderError("_general")}
</>
);
private async performLogin(data: LoginFormStateData) {
try {
let result = await authentication.login(
data.username,
data.password,
data.securityCode,
data.requestTfaRemoval,
);
const tfaPanel = (
<form onSubmit={this.handleSubmit}>
{this.renderError("_general")}
{this.renderInput("securityCode", "Authenticate")}
{this.renderButton("Authenticate")}
<Link to="#" onClick={this.authenticationWorkAround}>
My Authenticator is not working
</Link>
</form>
);
switch (result) {
case 1: //requires tfa
const { data } = this.state;
return (
<div>
{requestTfaRemoval ? requestTfaRemovalPanel : tfaNeeded ? tfaPanel : loginPanel}
if (data.tfaNeeded === true) {
//TFA removal Request accepted.
} else {
data.tfaNeeded = true;
this.setState({ data });
}
break;
case 2: //logged in
window.location.href = "/";
break;
default:
break; //treat at though not logged in.
}
} catch (ex: any) {
this.handleGeneralError(ex);
}
}
render() {
window.location.replace("/login");
const { tfaNeeded, requestTfaRemoval } = this.state.data;
const { isInNextStage, data, emailSent, passwordMaxLength } = this.state;
const result = this.schema.username.validate(data.username);
const validEmail = result.error === undefined ? true : false;
if (authentication.getCurrentUser()) return <Navigate to="/" />;
const requestTfaRemovalPanel = (
<div>
An email has been sent to you so that you can regain control of your
account.
</div>
);
const loginPanel = (
<>
<form onSubmit={this.handleSubmit}>
{this.renderInput(
"username",
"",
InputType.text,
isInNextStage,
undefined,
"Email",
undefined,
undefined,
"username",
)}
{this.renderInput(
"password",
"",
InputType.password,
emailSent,
undefined,
"Password",
passwordMaxLength,
isInNextStage,
"current-password",
)}
{!isInNextStage &&
this.renderButton(
"Next",
"login",
this.handleNextClick,
"next",
validEmail,
ButtonType.primary,
true,
)}
{isInNextStage && (
<div className="clickables">
{this.renderButton(
"Login",
"login",
undefined,
"login",
!emailSent,
)}
</div>
);
}
)}
</form>
{isInNextStage && (
<div className="forgottenLink">
{this.renderButton(
"Forgotten Password",
"forgot-password",
this.handleForgetPassword,
"forgot-password",
validEmail,
ButtonType.secondary,
true,
)}
</div>
)}
{emailSent && (
<div className="alert alert-info emailSent">
If you have a registered account, you will receive an email.
</div>
)}
{this.renderError("_general")}
</>
);
const tfaPanel = (
<form onSubmit={this.handleSubmit}>
{this.renderError("_general")}
{this.renderInput("securityCode", "Authenticate")}
{this.renderButton("Authenticate")}
<Link to="#" onClick={this.authenticationWorkAround}>
My Authenticator is not working
</Link>
</form>
);
return (
<div>
{requestTfaRemoval
? requestTfaRemovalPanel
: tfaNeeded
? tfaPanel
: loginPanel}
</div>
);
}
}
export default LoginForm;

View File

@ -1,20 +1,20 @@
import * as React from "react";
import React, { useEffect } from "react";
import { useTranslation } from "react-i18next";
import authentication from "../services/authenticationService";
class Logout extends React.Component {
componentDidMount() {
authentication.logout();
if (window.__RUNTIME_CONFIG__.EXTERNAL_LOGIN) {
window.location.href = "/account/logout"
}
else {
window.location.href = "/"
}
}
const Logout: React.FC = () => {
const { t } = useTranslation();
render() {
return <div>Logging out</div>;
useEffect(() => {
authentication.logout();
if (window.__RUNTIME_CONFIG__.EXTERNAL_LOGIN) {
window.location.href = "/account/logout";
} else {
window.location.href = "/";
}
}
}, []);
return <div>{t("LoggingOut")}</div>;
};
export default Logout;

View File

@ -1,23 +1,23 @@
import * as React from "react";
import React from "react";
import TopMenu from "./TopMenu";
import LeftMenu from "./LeftMenu";
import "../../../Sass/_frame.scss";
type MainFrameProps = {
title?: string | undefined | null;
children?: React.ReactNode; // 👈️ type children
title?: string | null;
children?: React.ReactNode;
};
const Mainframe = (props: MainFrameProps): JSX.Element => {
const Mainframe: React.FC<MainFrameProps> = ({ title, children }) => {
return (
<div className="frame">
<TopMenu title={props.title ? props.title : undefined} />
<TopMenu title={title} />
<div className="frame-row">
<div className="frame-leftMenu">
<LeftMenu />
</div>
<div className="frame-workArea">{props.children}</div>
<div className="frame-workArea">{children}</div>
</div>
</div>
);

View File

@ -1,7 +1,10 @@
import * as React from "react";
import React from "react";
import { useTranslation } from "react-i18next";
function NotFound() {
return <h1>Not found</h1>;
}
const NotFound: React.FC = () => {
const { t } = useTranslation();
return <h1>{t("NotFound")}</h1>;
};
export default NotFound;

View File

@ -1,49 +0,0 @@
import * as React from "react";
export interface SwitchProps {
children: React.ReactNode;
}
export class Switch extends React.PureComponent<SwitchProps> {
render() {
const children = React.Children.toArray(this.props.children);
let caseComponent: any = children.filter((c:any) => {
return c.type === Case && c.props.condition === true;
});
if (!caseComponent || caseComponent.length === 0) {
caseComponent = children.filter((c: any) => c.type === Else);
}
return (
<React.Fragment>
{ caseComponent }
</React.Fragment>
);
}
}
export interface CaseProps {
condition: boolean;
children: React.ReactNode;
}
export class Case extends React.PureComponent<CaseProps> {
render() {
const { condition, children } = this.props;
return (
<React.Fragment>
{ condition ? children : null }
</React.Fragment>
);
}
}
export class Else extends React.PureComponent<SwitchProps>
{
render() {
return this.props.children;
}
}

View File

@ -12,7 +12,7 @@ import { getCurrentUser } from "../services/authenticationService";
import { LanguageSelectorMenuItem } from "./LanguageSelector";
export interface TopMenuProps {
title?: string;
title: string | undefined | null;
}
function TopMenu(props: TopMenuProps) {
@ -21,7 +21,7 @@ function TopMenu(props: TopMenuProps) {
return (
<Navbar className="navbar bg-body-tertiary px-4 Header">
<Navbar.Brand href="/">
<Logo alt="esuite logo" />
<Logo />
</Navbar.Brand>
<div className="navbar-left">{props.title}</div>
<div className="navbar-right">

View File

@ -5,34 +5,24 @@ import "../../../Sass/login.scss";
import Logo from "../../../img/logo";
interface LoginFrameProps {
children?: JSX.Element
children?: JSX.Element;
}
interface LoginFrameState {
const LoginFrame: React.FC<LoginFrameProps> = ({ children }) => {
return (
<div className="container-fluid vh-100">
<div className="col-md-2">
<div className="loginFormContainer">
<div className="col-12 logo">
<Logo height="120px" width="120px" />
</div>
<div className="col-12">{children}</div>
</div>
</div>
}
<div className="col-md-8"></div>
</div>
);
};
class LoginFrame extends React.Component<LoginFrameProps, LoginFrameState> {
render() {
const { children } = this.props;
return (<div className="container-fluid vh-100">
<div className="col-md-2">
<div className="loginFormContainer">
<div className="col-12 logo">
<Logo alt="esuite logo" height="120px" width="120px" />
</div>
<div className="col-12">
{children}
</div>
</div>
</div>
<div className="col-md-8"></div>
</div>);
}
}
export default LoginFrame;
export default LoginFrame;

View File

@ -1,13 +1,23 @@
import * as React from "react";
import React from "react";
function EnvPage() {
return (
<>
<p>This is the Environment</p>
<br></br>
<p>window.__RUNTIME_CONFIG__.API_URL = {window.__RUNTIME_CONFIG__.API_URL}</p>
</>
);
}
const EnvPage: React.FC = () => {
return (
<>
<p>This is the Environment</p>
<br />
<p>
window.__RUNTIME_CONFIG__.NODE_ENV ={" "}
{window.__RUNTIME_CONFIG__.NODE_ENV}
</p>
<p>
window.__RUNTIME_CONFIG__.API_URL = {window.__RUNTIME_CONFIG__.API_URL}
</p>
<p>
window.__RUNTIME_CONFIG__.EXTERNAL_LOGIN ={" "}
{window.__RUNTIME_CONFIG__.EXTERNAL_LOGIN ? "true" : "false"}
</p>
</>
);
};
export default EnvPage;

View File

@ -1,20 +1,24 @@
import * as React from "react";
import React from "react";
import { useTranslation } from "react-i18next";
function HomePage() {
const redirect = ()=> {
window.location.href = '/organisations'
}
const HomePage: React.FC = () => {
const { t } = useTranslation();
return (
<div className="fluid-container">
<h3>Applications</h3>
<div className="e-printWidget" onClick={redirect}>
<div className="e-print">
<div className="thumbnail alert"></div><div className="label">E-print</div>
</div>
</div>
const redirect = () => {
window.location.href = "/organisations";
};
return (
<div className="fluid-container">
<h3>{t("Applications")}</h3>
<div className="e-printWidget" onClick={redirect}>
<div className="e-print">
<div className="thumbnail alert"></div>
<div className="label">{t("e-print")}</div>
</div>
);
}
</div>
</div>
);
};
export default HomePage;

View File

@ -7,351 +7,476 @@ import { InputType } from "../../../components/common/Input";
import { FormState } from "../../../components/common/Form";
import withRouter from "../../../utils/withRouter";
import { MakeGeneralIdRef } from "../../../utils/GeneralIdRef";
import customFieldsService, { numberParams, textParams } from "./services/customFieldsService";
import customFieldsService, {
numberParams,
textParams,
} from "./services/customFieldsService";
import Option from "../../../components/common/option";
import { GeneralIdRef } from "./../../../utils/GeneralIdRef";
import { Case, Else, Switch } from "../../frame/components/Switch";
import { CustomFieldValue, SystemGlossaries } from "../glossary/services/glossaryService";
import {
CustomFieldValue,
SystemGlossaries,
} from "../glossary/services/glossaryService";
import Loading from "../../../components/common/Loading";
interface CustomFieldDetailsState extends FormState {
data: {
name: string;
fieldType: string;
multiLine: boolean;
defaultValue: string;
minEntries: number;
maxEntries: string | number | undefined;
refElementId: CustomFieldValue[] | GeneralIdRef | undefined;
minValue: number | undefined;
maxValue: number | undefined;
step: number | undefined;
required: boolean;
};
redirect: string;
data: {
name: string;
fieldType: string;
multiLine: boolean;
defaultValue: string;
minEntries: number;
maxEntries: string | number | undefined;
refElementId: CustomFieldValue[] | GeneralIdRef | undefined;
minValue: number | undefined;
maxValue: number | undefined;
step: number | undefined;
required: boolean;
};
redirect: string;
}
class CustomFieldDetails extends Form<any, any, CustomFieldDetailsState> {
state: CustomFieldDetailsState = {
loaded: false,
data: {
name: "",
fieldType: "Text",
defaultValue: "",
multiLine: false,
minEntries: 0,
maxEntries: 1,
refElementId: undefined,
minValue: undefined,
maxValue: undefined,
step: undefined,
required: false,
},
errors: {},
redirect: "",
};
state: CustomFieldDetailsState = {
loaded: false,
data: {
name: "",
fieldType: "Text",
defaultValue: "",
multiLine: false,
minEntries: 0,
maxEntries: 1,
refElementId: undefined,
minValue: undefined,
maxValue: undefined,
step: undefined,
required: false,
},
errors: {},
redirect: "",
};
labelName = "Name";
labelFieldType = "Field Type";
labelMultiLine = "Multi-line";
labelDefaultValue = "Default Value";
labelMinValue = "Minimum Value";
labelMaxValue = "Maximum Value";
labelStep = "Step";
labelRequired = "Required";
labelMinEntries = "Min Entries";
labelMaxEntries = "Max Entries (empty=unlimited)";
labelRefElementId = "Sequence/Form/Glossary";
labelName = "Name";
labelFieldType = "Field Type";
labelMultiLine = "Multi-line";
labelDefaultValue = "Default Value";
labelMinValue = "Minimum Value";
labelMaxValue = "Maximum Value";
labelStep = "Step";
labelRequired = "Required";
labelMinEntries = "Min Entries";
labelMaxEntries = "Max Entries (empty=unlimited)";
labelRefElementId = "Sequence/Form/Glossary";
labelApply = "Save";
labelSave = "Save and close";
labelApply = "Save";
labelSave = "Save and close";
schema = {
name: Joi.string().required().max(450).label(this.labelName),
fieldType: Joi.string().required().label(this.labelFieldType),
multiLine: Joi.boolean().label(this.labelMultiLine),
minEntries: Joi.number().min(0).label(this.labelMinEntries),
maxEntries: Joi.number().empty("").label(this.labelMaxEntries),
refElementId: Joi.when("fieldType", {
is: Joi.string().valid("Sequence"),
then: Joi.object({
id: Joi.optional(),
guid: Joi.optional(),
schema = {
name: Joi.string().required().max(450).label(this.labelName),
fieldType: Joi.string().required().label(this.labelFieldType),
multiLine: Joi.boolean().label(this.labelMultiLine),
minEntries: Joi.number().min(0).label(this.labelMinEntries),
maxEntries: Joi.number().empty("").label(this.labelMaxEntries),
refElementId: Joi.when("fieldType", {
is: Joi.string().valid("Sequence"),
then: Joi.object({
id: Joi.optional(),
guid: Joi.optional(),
}).required(),
}).when("fieldType", {
is: Joi.string().valid("Glossary"),
then: Joi.array()
.min(1)
.items(
Joi.object({
displayValue: Joi.string().optional(),
value: Joi.object({
id: Joi.optional(),
guid: Joi.optional(),
}).required(),
}).when("fieldType", {
is: Joi.string().valid("Glossary"),
then: Joi.array()
.min(1)
.items(
Joi.object({
displayValue: Joi.string().optional(),
value: Joi.object({
id: Joi.optional(),
guid: Joi.optional(),
}).required(),
})
)
.required(),
}),
minValue: Joi.number().allow("").label(this.labelMinValue),
maxValue: Joi.number().allow("").label(this.labelMaxValue),
step: Joi.number().optional().allow("").min(0).label(this.labelStep),
required: Joi.boolean().label(this.labelRequired),
}),
)
.required(),
}),
minValue: Joi.number().allow("").label(this.labelMinValue),
maxValue: Joi.number().allow("").label(this.labelMaxValue),
step: Joi.number().optional().allow("").min(0).label(this.labelStep),
required: Joi.boolean().label(this.labelRequired),
//defaultValue: Joi.string().allow("").label(this.labelDefaultValue)
//defaultValue: Joi.string().allow("").label(this.labelDefaultValue)
defaultValue: Joi.when("fieldType", {
is: Joi.string().valid("Number"),
then: Joi.when("minValue", {
is: Joi.any().valid(null, ""),
then: Joi.number(),
otherwise: Joi.number()
.min(Joi.ref("minValue"))
.message('"Default Value" must be greater than or equal to "' + this.labelMinValue + '"'),
})
.when("maxValue", {
is: Joi.any().valid(null, ""),
then: Joi.number(),
otherwise: Joi.number()
.max(Joi.ref("maxValue"))
.message('"Default Value" must be less than or equal to "' + this.labelMaxValue + '"'),
})
.allow(""),
otherwise: Joi.string().allow(""),
}).label(this.labelDefaultValue),
};
defaultValue: Joi.when("fieldType", {
is: Joi.string().valid("Number"),
then: Joi.when("minValue", {
is: Joi.any().valid(null, ""),
then: Joi.number(),
otherwise: Joi.number()
.min(Joi.ref("minValue"))
.message(
'"Default Value" must be greater than or equal to "' +
this.labelMinValue +
'"',
),
})
.when("maxValue", {
is: Joi.any().valid(null, ""),
then: Joi.number(),
otherwise: Joi.number()
.max(Joi.ref("maxValue"))
.message(
'"Default Value" must be less than or equal to "' +
this.labelMaxValue +
'"',
),
})
.allow(""),
otherwise: Joi.string().allow(""),
}).label(this.labelDefaultValue),
};
doSubmit = async (buttonName: string) => {
try {
const { name, fieldType } = this.state.data;
let { refElementId, defaultValue, minEntries, maxEntries, required } = this.state.data;
let numberParams: numberParams | undefined = undefined;
let textParams: textParams | undefined = undefined;
let params;
let refElementIdValue: GeneralIdRef | undefined;
doSubmit = async (buttonName: string) => {
try {
const { name, fieldType } = this.state.data;
let { refElementId, defaultValue, minEntries, maxEntries, required } =
this.state.data;
let numberParams: numberParams | undefined = undefined;
let textParams: textParams | undefined = undefined;
let params;
let refElementIdValue: GeneralIdRef | undefined;
switch (fieldType) {
case "Sequence":
minEntries = 1;
maxEntries = 1;
defaultValue = "";
refElementIdValue = refElementId as GeneralIdRef;
break;
case "FormTemplate":
minEntries = 1;
maxEntries = 1;
defaultValue = "";
break;
case "Domain":
minEntries = required ? 1 : 0;
maxEntries = maxEntries === 0 ? undefined : maxEntries;
defaultValue = "";
break;
case "Glossary":
minEntries = required ? 1 : 0;
maxEntries = maxEntries === 0 ? undefined : maxEntries;
defaultValue = "";
refElementIdValue = (refElementId as CustomFieldValue[])[0].value as GeneralIdRef;
break;
case "Text":
minEntries = 1;
maxEntries = 1;
let { multiLine } = this.state.data;
textParams = { multiLine };
params = textParams;
refElementIdValue = undefined;
break;
case "Number":
refElementIdValue = undefined;
let { minValue, maxValue, step } = this.state.data;
numberParams = { minValue, maxValue, step };
params = numberParams;
minEntries = required ? 1 : 0;
maxEntries = 1;
break;
default:
refElementIdValue = undefined;
}
switch (fieldType) {
case "Sequence":
minEntries = 1;
maxEntries = 1;
defaultValue = "";
refElementIdValue = refElementId as GeneralIdRef;
break;
case "FormTemplate":
minEntries = 1;
maxEntries = 1;
defaultValue = "";
break;
case "Domain":
minEntries = required ? 1 : 0;
maxEntries = maxEntries === 0 ? undefined : maxEntries;
defaultValue = "";
break;
case "Glossary":
minEntries = required ? 1 : 0;
maxEntries = maxEntries === 0 ? undefined : maxEntries;
defaultValue = "";
refElementIdValue = (refElementId as CustomFieldValue[])[0]
.value as GeneralIdRef;
break;
case "Text":
minEntries = 1;
maxEntries = 1;
let { multiLine } = this.state.data;
textParams = { multiLine };
params = textParams;
refElementIdValue = undefined;
break;
case "Number":
refElementIdValue = undefined;
let { minValue, maxValue, step } = this.state.data;
numberParams = { minValue, maxValue, step };
params = numberParams;
minEntries = required ? 1 : 0;
maxEntries = 1;
break;
default:
refElementIdValue = undefined;
}
const cleanMaxEntries: Number | undefined = maxEntries === "" ? undefined : Number(maxEntries);
const cleanMaxEntries: Number | undefined =
maxEntries === "" ? undefined : Number(maxEntries);
if (this.isEditMode()) {
const { customFieldId } = this.props.router.params;
var generalIdRef = MakeGeneralIdRef(customFieldId);
const response = await customFieldsService.putField(
generalIdRef,
name,
fieldType,
defaultValue,
minEntries,
cleanMaxEntries,
refElementIdValue,
params
);
if (response) {
toast.info("Custom Field edited");
}
} else {
const response = await customFieldsService.postField(name, fieldType, defaultValue, minEntries, cleanMaxEntries, refElementIdValue, params);
if (response) {
toast.info("New Custom Field added");
}
}
if (buttonName === this.labelSave) this.setState({ redirect: "/customfields" });
} catch (ex: any) {
this.handleGeneralError(ex);
}
};
isEditMode = () => {
const { editMode } = this.props;
return editMode;
};
componentDidMount = async () => {
if (this.isEditMode()) {
const { customFieldId } = this.props.router.params;
if (customFieldId !== undefined) {
try {
const loadedData = await customFieldsService.getField(customFieldId);
const { data } = this.state;
if (loadedData) {
data.name = loadedData.name;
data.fieldType = loadedData.fieldType;
data.defaultValue = loadedData.defaultValue;
data.minEntries = loadedData.minEntries;
data.maxEntries = loadedData.maxEntries;
switch (data.fieldType) {
case "Glossary":
let convertedRefElementId: CustomFieldValue = {
value: loadedData.refElementId,
};
data.refElementId = [convertedRefElementId];
data.required = loadedData.minEntries > 0;
break;
case "Sequence":
data.refElementId = loadedData.refElementId;
break;
case "Domain":
data.required = loadedData.minEntries > 0;
break;
}
if (loadedData.parameters !== undefined) {
switch (data.fieldType) {
case "Number":
data.required = loadedData.minEntries > 0;
const parameters: numberParams = JSON.parse(loadedData.parameters);
data.minValue = parameters.minValue ?? undefined;
data.maxValue = parameters.maxValue ?? undefined;
data.step = parameters.step ?? undefined;
break;
case "Text":
const textParameters: textParams = JSON.parse(loadedData.parameters);
data.multiLine = textParameters.multiLine ?? false;
break;
}
}
this.setState({ loaded: true, data });
} else {
this.setState({ loaded: false });
}
} catch (ex: any) {
this.handleGeneralError(ex);
}
}
if (!this.isEditMode()) this.setState({ loaded: true });
};
render() {
const { loaded, redirect } = this.state;
if (redirect !== "") return <Navigate to={redirect} />;
const { fieldType, minValue, maxValue, step } = this.state.data;
let mode = "Add";
if (this.isEditMode()) mode = "Edit";
const fieldTypeOptions: Option[] = [
{ _id: "Text", name: "Text" },
{ _id: "Number", name: "Number" },
// { _id: "Boolean", name: "Boolean" },
// { _id: "Date", name: "Date" },
// { _id: "Time", name: "Time" },
// { _id: "DateTime", name: "DateTime" },
{ _id: "Sequence", name: "Sequence" },
{ _id: "FormTemplate", name: "Form Template" },
{ _id: "Glossary", name: "Glossary" },
{ _id: "Domain", name: "Domain" },
];
switch (fieldType) {
case "Sequence":
this.labelRefElementId = "Sequence";
break;
case "FormTemplate":
this.labelRefElementId = "Form";
break;
case "Glossary":
this.labelRefElementId = "Glossary";
break;
}
return (
<Loading loaded={loaded}>
<h1>{mode} Custom Field</h1>
<form onSubmit={this.handleSubmit}>
{this.renderError("_general")}
{this.renderInput("name", this.labelName, InputType.text)}
{this.renderSelect("fieldType", this.labelFieldType, fieldTypeOptions)}
<Switch>
<Case condition={this.state.data.fieldType === "Domain"}>
{this.renderInput("required", this.labelRequired, InputType.checkbox)}
{this.renderInput("maxEntries", this.labelMaxEntries, InputType.number)}
</Case>
<Case condition={this.state.data.fieldType === "Glossary"}>
{this.renderGlossaryPicker(true, "refElementId", this.labelRefElementId, 1, SystemGlossaries)}
{this.renderInput("required", this.labelRequired, InputType.checkbox)}
{this.renderInput("maxEntries", this.labelMaxEntries, InputType.number)}
</Case>
<Case condition={this.state.data.fieldType === "Sequence"}>
{this.renderSequencePicker(true, "refElementId", this.labelRefElementId)}
</Case>
<Case condition={this.state.data.fieldType === "FormTemplate"}>
<></>
</Case>
<Case condition={this.state.data.fieldType === "Text"}>
{this.renderInput("multiLine", this.labelMultiLine, InputType.checkbox)}
<Case condition={this.state.data.multiLine === true}>{this.renderInputTextarea(true, "defaultValue", this.labelDefaultValue)}</Case>
<Case condition={this.state.data.multiLine === false}>
{this.renderInput("defaultValue", this.labelDefaultValue, InputType.text)}
</Case>
</Case>
<Case condition={this.state.data.fieldType === "Number"}>
{this.renderInput("required", this.labelRequired, InputType.checkbox)}
{this.renderInputNumber("minValue", this.labelMinValue, false, undefined, undefined, maxValue, undefined)}
{this.renderInputNumber("maxValue", this.labelMaxValue, false, undefined, minValue, undefined, undefined)}
{this.renderInput("step", this.labelStep, InputType.number)}
{this.renderInputNumber("defaultValue", this.labelDefaultValue, false, undefined, minValue, maxValue, step)}
</Case>
<Else>
{this.renderInput("defaultValue", this.labelDefaultValue, InputType.text)}
{this.renderInput("minEntries", this.labelMinEntries, InputType.number)}
{this.renderInput("maxEntries", this.labelMaxEntries, InputType.number)}
</Else>
</Switch>
{this.isEditMode() && this.renderButton(this.labelApply)}
{this.renderButton(this.labelSave)}
</form>
</Loading>
var generalIdRef = MakeGeneralIdRef(customFieldId);
const response = await customFieldsService.putField(
generalIdRef,
name,
fieldType,
defaultValue,
minEntries,
cleanMaxEntries,
refElementIdValue,
params,
);
if (response) {
toast.info("Custom Field edited");
}
} else {
const response = await customFieldsService.postField(
name,
fieldType,
defaultValue,
minEntries,
cleanMaxEntries,
refElementIdValue,
params,
);
if (response) {
toast.info("New Custom Field added");
}
}
if (buttonName === this.labelSave)
this.setState({ redirect: "/customfields" });
} catch (ex: any) {
this.handleGeneralError(ex);
}
};
isEditMode = () => {
const { editMode } = this.props;
return editMode;
};
componentDidMount = async () => {
const { customFieldId } = this.props.router.params;
if (customFieldId !== undefined) {
try {
const loadedData = await customFieldsService.getField(customFieldId);
const { data } = this.state;
if (loadedData) {
data.name = loadedData.name;
data.fieldType = loadedData.fieldType;
data.defaultValue = loadedData.defaultValue;
data.minEntries = loadedData.minEntries;
data.maxEntries = loadedData.maxEntries;
switch (data.fieldType) {
case "Glossary":
let convertedRefElementId: CustomFieldValue = {
value: loadedData.refElementId,
};
data.refElementId = [convertedRefElementId];
data.required = loadedData.minEntries > 0;
break;
case "Sequence":
data.refElementId = loadedData.refElementId;
break;
case "Domain":
data.required = loadedData.minEntries > 0;
break;
}
if (loadedData.parameters !== undefined) {
switch (data.fieldType) {
case "Number":
data.required = loadedData.minEntries > 0;
const parameters: numberParams = JSON.parse(
loadedData.parameters,
);
data.minValue = parameters.minValue ?? undefined;
data.maxValue = parameters.maxValue ?? undefined;
data.step = parameters.step ?? undefined;
break;
case "Text":
const textParameters: textParams = JSON.parse(
loadedData.parameters,
);
data.multiLine = textParameters.multiLine ?? false;
break;
}
}
this.setState({ loaded: true, data });
} else {
this.setState({ loaded: false });
}
} catch (ex: any) {
this.handleGeneralError(ex);
}
}
if (!this.isEditMode()) this.setState({ loaded: true });
};
render() {
const { loaded, redirect } = this.state;
if (redirect !== "") return <Navigate to={redirect} />;
const { fieldType, minValue, maxValue, step } = this.state.data;
let mode = "Add";
if (this.isEditMode()) mode = "Edit";
const fieldTypeOptions: Option[] = [
{ _id: "Text", name: "Text" },
{ _id: "Number", name: "Number" },
// { _id: "Boolean", name: "Boolean" },
// { _id: "Date", name: "Date" },
// { _id: "Time", name: "Time" },
// { _id: "DateTime", name: "DateTime" },
{ _id: "Sequence", name: "Sequence" },
{ _id: "FormTemplate", name: "Form Template" },
{ _id: "Glossary", name: "Glossary" },
{ _id: "Domain", name: "Domain" },
];
switch (fieldType) {
case "Sequence":
this.labelRefElementId = "Sequence";
break;
case "FormTemplate":
this.labelRefElementId = "Form";
break;
case "Glossary":
this.labelRefElementId = "Glossary";
break;
}
return (
<Loading loaded={loaded}>
<h1>{mode} Custom Field</h1>
<form onSubmit={this.handleSubmit}>
{this.renderError("_general")}
{this.renderInput("name", this.labelName, InputType.text)}
{this.renderSelect(
"fieldType",
this.labelFieldType,
fieldTypeOptions,
)}
{this.state.data.fieldType === "Domain" && (
<>
{this.renderInput(
"required",
this.labelRequired,
InputType.checkbox,
)}
{this.renderInput(
"maxEntries",
this.labelMaxEntries,
InputType.number,
)}
</>
)}
{this.state.data.fieldType === "Glossary" && (
<>
{this.renderGlossaryPicker(
true,
"refElementId",
this.labelRefElementId,
1,
SystemGlossaries,
)}
{this.renderInput(
"required",
this.labelRequired,
InputType.checkbox,
)}
{this.renderInput(
"maxEntries",
this.labelMaxEntries,
InputType.number,
)}
</>
)}
{this.state.data.fieldType === "Sequence" && (
<>
{this.renderSequencePicker(
true,
"refElementId",
this.labelRefElementId,
)}
</>
)}
{this.state.data.fieldType === "Text" && (
<>
{this.renderInput(
"multiLine",
this.labelMultiLine,
InputType.checkbox,
)}
{this.state.data.multiLine === true &&
this.renderInputTextarea(
true,
"defaultValue",
this.labelDefaultValue,
)}
{this.state.data.multiLine === false &&
this.renderInput(
"defaultValue",
this.labelDefaultValue,
InputType.text,
)}
</>
)}
{this.state.data.fieldType === "Number" && (
<>
{this.renderInput(
"required",
this.labelRequired,
InputType.checkbox,
)}
{this.renderInputNumber(
"minValue",
this.labelMinValue,
false,
undefined,
undefined,
maxValue,
undefined,
)}
{this.renderInputNumber(
"maxValue",
this.labelMaxValue,
false,
undefined,
minValue,
undefined,
undefined,
)}
{this.renderInput("step", this.labelStep, InputType.number)}
{this.renderInputNumber(
"defaultValue",
this.labelDefaultValue,
false,
undefined,
minValue,
maxValue,
step,
)}
</>
)}
{![
"Domain",
"Glossary",
"Sequence",
"FormTemplate",
"Text",
"Number",
].includes(this.state.data.fieldType) && (
<>
{this.renderInput(
"defaultValue",
this.labelDefaultValue,
InputType.text,
)}
{this.renderInput(
"minEntries",
this.labelMinEntries,
InputType.number,
)}
{this.renderInput(
"maxEntries",
this.labelMaxEntries,
InputType.number,
)}
</>
)}
{this.isEditMode() && this.renderButton(this.labelApply)}
{this.renderButton(this.labelSave)}
</form>
</Loading>
);
}
}
const HOCCustomFieldDetails = withRouter(CustomFieldDetails);