diff --git a/.eslintrc.yml b/.eslintrc.yml index 5d350c5..b66a32e 100644 --- a/.eslintrc.yml +++ b/.eslintrc.yml @@ -16,6 +16,7 @@ plugins: - "react-hooks" - "@typescript-eslint" - "prettier" + - "unused-imports" rules: "react/react-in-jsx-scope": "off" "camelcase": "error" diff --git a/.prettierrc b/.prettierrc index 61e4fa6..ee155f9 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1,7 +1,7 @@ { "semi": false, "tabWidth": 2, - "printWidth": 100, + "printWidth": 120, "singleQuote": true, "trailingComma": "all", "jsxSingleQuote": true, diff --git a/package.json b/package.json index e2287ee..6345967 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "clean": "rm -rf dist", "build": "yarn run clean && yarn run webpack-build", "start": "yarn run clean && webpack-dev-server --mode development --devtool inline-source-map", - "lint": "eslint src/**/*.{js,jsx,ts,tsx,json}", + "lint": "eslint 'src/**/*.{js,jsx,ts,tsx,json}'", "lint:fix": "eslint --fix 'src/**/*.{js,jsx,ts,tsx,json}'", "format": "prettier --write 'src/**/*.{js,jsx,ts,tsx,css,md,json}' --config ./.prettierrc", "eject": "react-scripts eject" @@ -67,6 +67,7 @@ "eslint-plugin-prettier": "^4.2.1", "eslint-plugin-react": "^7.31.11", "eslint-plugin-react-hooks": "^4.6.0", + "eslint-plugin-unused-imports": "^2.0.0", "extract-text-webpack-plugin": "^4.0.0-beta.0", "html-webpack-plugin": "^3.2.0", "prettier": "^2.8.0", diff --git a/src/App.tsx b/src/App.tsx index 65a0a91..e304933 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,106 +1,66 @@ -import * as React from "react"; -import Form from "./components/manifest/Form"; -import ShowDeploymentManifest from "./components/manifest/ShowDeploymentManifest"; -import {Redirect, Route} from "react-router"; -import {BrowserRouter as Router} from "react-router-dom"; -import Dashboard from "./components/Dashboard"; -import ProtectedRoute from "./components/ProtectedRoute"; -import {CookiesProvider, withCookies} from "react-cookie"; -import {getUser} from "./action/action"; -import {store} from "./store/store"; -import {ToastContainer} from "react-toastify"; -import "react-toastify/dist/ReactToastify.css"; -import ShowJson from "./components/manifest/ShowJson"; -import ImportManifestJson from "./components/manifest/ImportManifestJson"; -import Faults from "./components/manifest/Faults"; -import Notification from "./components/manifest/Notification"; -import EcrRepo from "./components/EcrRepo"; -import GocdYamlGenerator from "./components/gocd-yaml/PipelineBaseForm"; +import * as React from 'react' +import Form from './components/manifest/Form' +import ShowDeploymentManifest from './components/manifest/ShowDeploymentManifest' +import { Redirect, Route } from 'react-router' +import { BrowserRouter as Router } from 'react-router-dom' +import Dashboard from './components/Dashboard' +import ProtectedRoute from './components/ProtectedRoute' +import { CookiesProvider, withCookies } from 'react-cookie' +import { getUser } from './action/action' +import { store } from './store/store' +import { ToastContainer } from 'react-toastify' +import 'react-toastify/dist/ReactToastify.css' +import ShowJson from './components/manifest/ShowJson' +import ImportManifestJson from './components/manifest/ImportManifestJson' +import Faults from './components/manifest/Faults' +import Notification from './components/manifest/Notification' +import EcrRepo from './components/EcrRepo' +import GocdYamlGenerator from './components/gocd-yaml/PipelineBaseForm' function App() { - const { state, dispatch } = React.useContext(store); - const isAuthenticated = state.isAuthenticated; - const userInfo = state.userInfo; - let loginRedirect = state.loginRedirect; + const { state, dispatch } = React.useContext(store) + const isAuthenticated = state.isAuthenticated + const userInfo = state.userInfo + const loginRedirect = state.loginRedirect React.useEffect(() => { if (Object.keys(userInfo).length == 0) { - getUser(state, dispatch); + getUser(state, dispatch) } - }, []); + }, []) return (
- +

Healthy

- - {isAuthenticated ? : } + + {isAuthenticated ? : } - - {isAuthenticated ? : } + + {isAuthenticated ? : } + + + + + - - - - - - - - + + +
- +
- ); + ) } -export default withCookies(App); +export default withCookies(App) diff --git a/src/AppConfig.d.ts b/src/AppConfig.d.ts index 6fd50c5..892fb08 100644 --- a/src/AppConfig.d.ts +++ b/src/AppConfig.d.ts @@ -1,3 +1,3 @@ export interface AppConfig { - INFRA_VERTICAL: InfraVertical -} \ No newline at end of file + INFRA_VERTICAL: InfraVertical +} diff --git a/src/action/action.ts b/src/action/action.ts index 272c709..15fbfc2 100644 --- a/src/action/action.ts +++ b/src/action/action.ts @@ -1,24 +1,23 @@ export const getUser = (state, dispatch) => { - fetch("/api/user", { - credentials: "include", + fetch('/api/user', { + credentials: 'include', }) .then((response) => { if (response.redirected) { - window.location.href = response.url; - } - else if (response.ok) { - return response.text(); + window.location.href = response.url + } else if (response.ok) { + return response.text() } }) .then((body) => { - if (body === "" || typeof body === undefined) { - dispatch({ type: "setAuthentication", value: false }); - dispatch({ type: "setLoginRedirect", value: "/dashboard" }); + if (body === '' || typeof body === undefined) { + dispatch({ type: 'setAuthentication', value: false }) + dispatch({ type: 'setLoginRedirect', value: '/dashboard' }) } else { - dispatch({ type: "setAuthentication", value: true }); - dispatch({ type: "setLoginRedirect", value: "" }); - dispatch({ type: "setUserInfo", value: JSON.parse(body!) }); + dispatch({ type: 'setAuthentication', value: true }) + dispatch({ type: 'setLoginRedirect', value: '' }) + dispatch({ type: 'setUserInfo', value: JSON.parse(body!) }) } }) - .catch((err) => console.error("Caught error: ", err)); -}; \ No newline at end of file + .catch((err) => console.error('Caught error: ', err)) +} diff --git a/src/components/Dashboard.tsx b/src/components/Dashboard.tsx index 2ec720d..541f4d9 100644 --- a/src/components/Dashboard.tsx +++ b/src/components/Dashboard.tsx @@ -1,26 +1,45 @@ -import React, { useContext } from "react"; -import { withCookies } from "react-cookie"; -import { store } from "../store/store"; -import { Paper, Button, Avatar } from "@material-ui/core"; +import React, { useContext } from 'react' +import { withCookies } from 'react-cookie' +import { store } from '../store/store' +import { Paper, Button, Avatar } from '@material-ui/core' const Dashboard = () => { - const { state, dispatch } = useContext(store); + const { state, dispatch } = useContext(store) const handleLogin = () => { - window.location.href = "/login/okta"; - dispatch({ type: "setAuthentication", value: true }); - }; + window.location.href = '/login/okta' + dispatch({ type: 'setAuthentication', value: true }) + } return ( -
- -
- - +
+ +
+ +
- ); -}; + ) +} -export default withCookies(Dashboard); +export default withCookies(Dashboard) diff --git a/src/components/EcrRepo.tsx b/src/components/EcrRepo.tsx index 99dee09..5ab2dcf 100644 --- a/src/components/EcrRepo.tsx +++ b/src/components/EcrRepo.tsx @@ -1,75 +1,77 @@ -import * as React from 'react'; -import Button from '@material-ui/core/Button'; -import {httpClient} from "../helper/api-client" -import {withCookies} from "react-cookie"; -import {makeStyles, TextField} from "@material-ui/core"; -import {toast} from "react-toastify"; -import {useEffect, useState} from "react"; -import Header from "./layout/Header"; +import * as React from 'react' +import Button from '@material-ui/core/Button' +import { httpClient } from '../helper/api-client' +import { withCookies } from 'react-cookie' +import { makeStyles, TextField } from '@material-ui/core' +import { toast } from 'react-toastify' +import { useEffect, useState } from 'react' +import Header from './layout/Header' const createRepository = (props: string) => { - const toastId = toast.info("In Progress ...", {autoClose: 50000}); - httpClient(`/api/aws/ecr?name=${props}`, { - method: "POST" - }).then(r => r.text().then(response => { - if (r.ok) { - toast.update(toastId, { - type: "success", - autoClose: 3000, - render: "Respository Created" - }) - } else { - toast.update(toastId, { - type: "error", - autoClose: 3000, - render: `Respository could not be created due to ${response}` - }) - } - })); + const toastId = toast.info('In Progress ...', { autoClose: 50000 }) + httpClient(`/api/aws/ecr?name=${props}`, { + method: 'POST', + }).then((r) => + r.text().then((response) => { + if (r.ok) { + toast.update(toastId, { + type: 'success', + autoClose: 3000, + render: 'Respository Created', + }) + } else { + toast.update(toastId, { + type: 'error', + autoClose: 3000, + render: `Respository could not be created due to ${response}`, + }) + } + }), + ) } const useStyles = makeStyles((theme) => ({ - root: { - "& > *": { - margin: theme.spacing(0), - }, + root: { + '& > *': { + margin: theme.spacing(0), }, -})); + }, +})) const CreateECR = () => { - const [repositoryName, setRepositoryName] = useState(""); - const classes = useStyles(); - return ( -
-
-
-
- setRepositoryName(event.target.value)} - /> -
-
- -
+ const [repositoryName, setRepositoryName] = useState('') + const classes = useStyles() + return ( +
+
+
+
+ setRepositoryName(event.target.value)} + /> +
+
+
-
- ); -}; -export default withCookies(CreateECR); \ No newline at end of file +
+
+ ) +} +export default withCookies(CreateECR) diff --git a/src/components/ProtectedRoute.tsx b/src/components/ProtectedRoute.tsx index 06819d1..abdeccd 100644 --- a/src/components/ProtectedRoute.tsx +++ b/src/components/ProtectedRoute.tsx @@ -1,12 +1,8 @@ -import { Route, Redirect } from "react-router"; -import React from "react"; +import { Route, Redirect } from 'react-router' +import React from 'react' const ProtectedRoute = ({ loginRedirect, ...props }) => { - return loginRedirect === "" ? ( - - ) : ( - - ); -}; + return loginRedirect === '' ? : +} -export default ProtectedRoute; +export default ProtectedRoute diff --git a/src/components/admin/editform/DropDownOptions.tsx b/src/components/admin/editform/DropDownOptions.tsx index 61629fa..d58d818 100644 --- a/src/components/admin/editform/DropDownOptions.tsx +++ b/src/components/admin/editform/DropDownOptions.tsx @@ -1,103 +1,97 @@ -import * as React from 'react'; +import * as React from 'react' -import AddIcon from '@material-ui/icons/Add'; -import Button from '@material-ui/core/Button'; -import Dialog from '@material-ui/core/Dialog'; -import DialogActions from '@material-ui/core/DialogActions'; -import DialogContent from '@material-ui/core/DialogContent'; -import DialogContentText from '@material-ui/core/DialogContentText'; -import DialogTitle from '@material-ui/core/DialogTitle'; -import IconButton from '@material-ui/core/IconButton'; -import Switch from '@material-ui/core/Switch'; -import TextField from '@material-ui/core/TextField'; -import Tooltip from '@material-ui/core/Tooltip'; -import {FormControl, InputLabel, MenuItem, Select} from '@material-ui/core'; - -interface Interface { +import AddIcon from '@material-ui/icons/Add' +import Button from '@material-ui/core/Button' +import Dialog from '@material-ui/core/Dialog' +import DialogActions from '@material-ui/core/DialogActions' +import DialogContent from '@material-ui/core/DialogContent' +import DialogContentText from '@material-ui/core/DialogContentText' +import DialogTitle from '@material-ui/core/DialogTitle' +import IconButton from '@material-ui/core/IconButton' +import Switch from '@material-ui/core/Switch' +import TextField from '@material-ui/core/TextField' +import Tooltip from '@material-ui/core/Tooltip' +import { FormControl, InputLabel, MenuItem, Select } from '@material-ui/core' +interface Interface {} +const initialUser: any = { + options: '', } -const initialUser:any = { - options:'' -}; -const initialOpen:any = false; -const initialSwitchState : any = { - addMultiple: false, -}; -const DropDownOptions = (props:any) => { - const [options, setOptions] = React.useState(''); - const { addItem } = props; - const [switchState, setSwitchState] = React.useState(initialSwitchState); +const initialOpen: any = false +const initialSwitchState: any = { + addMultiple: false, +} +const DropDownOptions = (props: any) => { + const [options, setOptions] = React.useState('') + const { addItem } = props + const [switchState, setSwitchState] = React.useState(initialSwitchState) - const [open, setOpen] = React.useState(initialOpen); + const [open, setOpen] = React.useState(initialOpen) - const handleSwitchChange = (name:any) => (event:any) => { - setSwitchState({ ...switchState, [name]: event.target.checked }); - }; + const handleSwitchChange = (name: any) => (event: any) => { + setSwitchState({ ...switchState, [name]: event.target.checked }) + } - const resetSwitch = () => { - setSwitchState({ addMultiple: false }); - }; + const resetSwitch = () => { + setSwitchState({ addMultiple: false }) + } - const handleClickOpen = () => { - setOpen(true); - }; + const handleClickOpen = () => { + setOpen(true) + } - const handleClose = () => { - setOpen(false); - setOptions(initialUser); - resetSwitch(); - }; + const handleClose = () => { + setOpen(false) + setOptions(initialUser) + resetSwitch() + } - const handleAdd = (event:any) => { - console.log(options); - addItem(options); - setOptions(''); - switchState.addMultiple ? setOpen(true) : setOpen(false); - }; + const handleAdd = (event: any) => { + console.log(options) + addItem(options) + setOptions('') + switchState.addMultiple ? setOpen(true) : setOpen(false) + } - return ( -
- - - - - - - New Exposed Port - - Port exposed by your service + return ( +
+ + + + + + + New Exposed Port + + Port exposed by your service - setOptions(event.target.value)} - /> - - - - - - - - - -
- ); -}; + setOptions(event.target.value)} + /> +
+ + + + + + + +
+
+ ) +} -export default DropDownOptions; +export default DropDownOptions diff --git a/src/components/admin/editform/ShowDemo.tsx b/src/components/admin/editform/ShowDemo.tsx index f1f0dd0..21c9578 100644 --- a/src/components/admin/editform/ShowDemo.tsx +++ b/src/components/admin/editform/ShowDemo.tsx @@ -1,69 +1,64 @@ -import React, {useEffect, useState} from 'react'; -import {materialCells, materialRenderers} from "@jsonforms/material-renderers"; +import React, { useEffect, useState } from 'react' +import { materialCells, materialRenderers } from '@jsonforms/material-renderers' -import {JsonForms} from "@jsonforms/react"; -import createStyles from "@material-ui/core/styles/createStyles"; -import withStyles, {WithStyles} from "@material-ui/core/styles/withStyles"; -import {Card} from "@material-ui/core"; +import { JsonForms } from '@jsonforms/react' +import createStyles from '@material-ui/core/styles/createStyles' +import withStyles, { WithStyles } from '@material-ui/core/styles/withStyles' +import { Card } from '@material-ui/core' -const data:any ={ - -} +const data: any = {} const styles = createStyles({ - container: { - padding: '2em' - }, - title: { - textAlign: 'center', - padding: '0.5em' - }, - dataContent: { - display: 'flex', - justifyContent: 'center', - borderRadius: '0.25em', - backgroundColor: '#cecece' - }, - demoform: { - margin: 'auto', - padding: '1rem', - color:'green' - } -}); + container: { + padding: '2em', + }, + title: { + textAlign: 'center', + padding: '0.5em', + }, + dataContent: { + display: 'flex', + justifyContent: 'center', + borderRadius: '0.25em', + backgroundColor: '#cecece', + }, + demoform: { + margin: 'auto', + padding: '1rem', + color: 'green', + }, +}) export interface AppProps extends WithStyles { - schema:any; - uischema:any; + schema: any + uischema: any } -const ShowDemo = ({ schema,uischema ,classes }: AppProps) => { - const [standaloneData, setStandaloneData] = useState(data); - const [displayDataAsString, setDisplayDataAsString] = useState(''); +const ShowDemo = ({ schema, uischema, classes }: AppProps) => { + const [standaloneData, setStandaloneData] = useState(data) + const [displayDataAsString, setDisplayDataAsString] = useState('') - useEffect(() => { - setDisplayDataAsString(JSON.stringify(standaloneData, null, 2)); - }, [standaloneData]); + useEffect(() => { + setDisplayDataAsString(JSON.stringify(standaloneData, null, 2)) + }, [standaloneData]) - return ( -
- + + setStandaloneData(data)} + /> + +
+
+
{displayDataAsString}
+
+
+ ) +} - - ]} - cells={materialCells} - onChange={({ errors, data }) => setStandaloneData(data)} - /> - -
-
-
{displayDataAsString}
-
-
- ); -}; - -export default withStyles(styles)(ShowDemo); \ No newline at end of file +export default withStyles(styles)(ShowDemo) diff --git a/src/components/common/AddButton.tsx b/src/components/common/AddButton.tsx index 17f7c59..33d73e7 100644 --- a/src/components/common/AddButton.tsx +++ b/src/components/common/AddButton.tsx @@ -1,21 +1,23 @@ -import * as React from 'react'; -import Button, { ButtonProps } from '@material-ui/core/Button'; -import AddIcon from '@material-ui/icons/Add'; +import * as React from 'react' +import Button, { ButtonProps } from '@material-ui/core/Button' +import AddIcon from '@material-ui/icons/Add' export interface AddButtonProps extends ButtonProps { - addAction: React.MouseEventHandler + addAction: React.MouseEventHandler } const AddButton = (props: AddButtonProps) => { - const { addAction, ...buttonProps } = props; - return ; + toggleConfirmation(true) + setTimeout(() => toggleConfirmation(false), 3000) } - return + ) + } + return - - Pipeline - - - - - - - - + return ( + <> + + + Pipeline + + + + + + + + + ) } -export default GeneratePipelineButton; \ No newline at end of file +export default GeneratePipelineButton diff --git a/src/components/common/Popup.tsx b/src/components/common/Popup.tsx index 2b51aaf..5787bc6 100644 --- a/src/components/common/Popup.tsx +++ b/src/components/common/Popup.tsx @@ -1,16 +1,15 @@ +import { Dialog, DialogContent, DialogTitle } from '@material-ui/core' -import { Dialog, DialogContent, DialogTitle } from "@material-ui/core"; - -import * as React from "react"; +import * as React from 'react' const Popup = (props: any) => { - const {title, open, onClose, ...restOfProps} = props; + const { title, open, onClose, ...restOfProps } = props return ( - + {props.title} - + - ); -}; + ) +} -export default Popup; \ No newline at end of file +export default Popup diff --git a/src/components/common/RemoveButton.tsx b/src/components/common/RemoveButton.tsx index 01cb752..3c13f4f 100644 --- a/src/components/common/RemoveButton.tsx +++ b/src/components/common/RemoveButton.tsx @@ -1,21 +1,23 @@ -import * as React from 'react'; -import Button, { ButtonProps } from '@material-ui/core/Button'; -import RemoveIcon from '@material-ui/icons/Remove'; +import * as React from 'react' +import Button, { ButtonProps } from '@material-ui/core/Button' +import RemoveIcon from '@material-ui/icons/Remove' export interface RemoveButtonProps extends ButtonProps { - removeAction: React.MouseEventHandler + removeAction: React.MouseEventHandler } const RemoveButton = (props: RemoveButtonProps) => { - const { removeAction, ...buttonProps } = props; - return - - ) - } - -
- ); + return ( +
+
+ { + if (value !== null) { + getManifestByName(String(value)) + } + }} + clearOnEscape={true} + renderInput={(props) => ( + + )} + /> + { + submitManifest(values) + }} + > + {(props) => ( +
+ +
+
+ +
+
+ {yamlText !== '' ? ( + + ) : ( + '' + )} +
+
+ {/* */} + + + )} +
+
+ ) } -export default withCookies(PipelineBaseForm); \ No newline at end of file +export default withCookies(PipelineBaseForm) diff --git a/src/components/gocd-yaml/PipelineList.tsx b/src/components/gocd-yaml/PipelineList.tsx index 4feb132..94b7a71 100644 --- a/src/components/gocd-yaml/PipelineList.tsx +++ b/src/components/gocd-yaml/PipelineList.tsx @@ -1,148 +1,167 @@ -import React from "react"; -import {Field, FieldArray, getIn, setIn, useField, useFormikContext} from "formik"; +import React from 'react' +import { Field, FieldArray, getIn, setIn, useField, useFormikContext } from 'formik' import { - Card, - CardContent, - Checkbox, - FormControlLabel, - Grid, - IconButton, - makeStyles, - TableCell, Typography -} from "@material-ui/core"; -import DeleteIcon from "@material-ui/icons/Delete"; -import {FormikTable} from "../common/FormikTable"; -import * as _p from "./pipeline"; -import {FormikTextField} from "../common/FormikTextField"; -import {toMenuItems} from "../../coreform/FormUtil"; -import {FormikCheckbox} from "../common/FormikCheckbox"; + Card, + CardContent, + Checkbox, + FormControlLabel, + Grid, + IconButton, + makeStyles, + TableCell, + Typography, +} from '@material-ui/core' +import DeleteIcon from '@material-ui/icons/Delete' +import { FormikTable } from '../common/FormikTable' +import * as _p from './pipeline' +import { FormikTextField } from '../common/FormikTextField' +import { toMenuItems } from '../../coreform/FormUtil' +import { FormikCheckbox } from '../common/FormikCheckbox' const useStyles = makeStyles({ - card: { - width: 430, - padding: '5px' - }, - root:{ - marginLeft: 5, - padding: 15 - }, - twoFieldBigCard: { - width: 150 - }, - oneFieldBigCard: { - width: 405, - margin: '5px' - }, - gridRow: { - width: 1200 - } + card: { + width: 430, + padding: '5px', + }, + root: { + marginLeft: 5, + padding: 15, + }, + twoFieldBigCard: { + width: 150, + }, + oneFieldBigCard: { + width: 405, + margin: '5px', + }, + gridRow: { + width: 1200, + }, }) interface FormikCheckboxCardListProps { - name: string, - children: Function, - direction?: 'row' | 'column' + name: string + children: Function + direction?: 'row' | 'column' } const getCardName = { - 'test': 'Test', - 'build': 'Build', - 'dev': 'Dev', - 'qa': 'Qa', - 'prod': 'Prod' + test: 'Test', + build: 'Build', + dev: 'Dev', + qa: 'Qa', + prod: 'Prod', } -const approvalTypes = ['success', 'manual']; +const approvalTypes = ['success', 'manual'] const stageMap = { - test: ['test'], - build: ['build'], - 'migrate-deploy': ['migrate', 'deploy'], - 'rds-deploy': ['rds-deploy'], - 'redis-deploy': ['redis-deploy'], - 'iam-deploy': ['iam-deploy'], - 'docdb-deploy': ['docdb-deploy'], - 's3-deploy': ['s3-deploy'] + test: ['test'], + build: ['build'], + 'migrate-deploy': ['migrate', 'deploy'], + 'rds-deploy': ['rds-deploy'], + 'redis-deploy': ['redis-deploy'], + 'iam-deploy': ['iam-deploy'], + 'docdb-deploy': ['docdb-deploy'], + 's3-deploy': ['s3-deploy'], } interface StageCardProps { - type: string, - index: number + type: string + index: number } const StageCard = (props: StageCardProps) => { - const classes = useStyles(); - return ( - <> - - {(i) => ( - <> - - - {toMenuItems(stageMap[props.type])} - - - - - {toMenuItems(approvalTypes)} - - - - )} - - - ); + const classes = useStyles() + return ( + <> + + {(i) => ( + <> + + + {toMenuItems(stageMap[props.type])} + + + + + {toMenuItems(approvalTypes)} + + + + )} + + + ) } - const PipelineCard = (props: any) => { - const classes = useStyles(); + const classes = useStyles() - return ( - - {props.title} - - - ) + return ( + + {props.title} + + + ) } const PipelineCardList = (props: FormikCheckboxCardListProps) => { - const classes = useStyles(); - const {name, direction = 'column'} = props; + const classes = useStyles() + const { name, direction = 'column' } = props - return ( - - {({remove, form}) => (<> - - {getIn(form.values, name, []).map((_, i) => ( - - - - - remove(i)}> - {props.children(i, getCardName[_.env], _.type)} - - - - - ))} - - ) - } - - ); + return ( + + {({ remove, form }) => ( + <> + + {getIn(form.values, name, []).map((_, i) => ( + + + + + remove(i)}> + {' '} + {' '} + + {props.children(i, getCardName[_.env], _.type)} + + + + + ))} + + + )} + + ) } export const PipelineList = () => { - const classes = useStyles(); - return - {(i, title, type) => <> - - } - ; + const classes = useStyles() + return ( + + {(i, title, type) => ( + <> + + + )} + + ) } - - diff --git a/src/components/gocd-yaml/PipelineManifestValidationSchema.ts b/src/components/gocd-yaml/PipelineManifestValidationSchema.ts index 3f78a50..90b2201 100644 --- a/src/components/gocd-yaml/PipelineManifestValidationSchema.ts +++ b/src/components/gocd-yaml/PipelineManifestValidationSchema.ts @@ -1,6 +1,6 @@ -import * as yup from "yup"; +import * as yup from 'yup' export const pipelineManifestValidationSchema = yup.object({ - name: yup.string().required('is Required'), - pipelines: yup.array().required('is Required') + name: yup.string().required('is Required'), + pipelines: yup.array().required('is Required'), }) diff --git a/src/components/gocd-yaml/pipeline.ts b/src/components/gocd-yaml/pipeline.ts index 6bbaaa0..9a36f21 100644 --- a/src/components/gocd-yaml/pipeline.ts +++ b/src/components/gocd-yaml/pipeline.ts @@ -1,47 +1,46 @@ -import {toast} from "react-toastify"; -import {getFormattedRuntimeException, httpClient} from "../../helper/api-client"; +import { toast } from 'react-toastify' +import { getFormattedRuntimeException, httpClient } from '../../helper/api-client' -export const initData = +export const initData = { + name: '', + pipelines: [ { - "name": "", - "pipelines": [ - { - "type": "test", - "env": "test", - "stages": [{"type": "test", "approvalType": "success"}] - }, - { - "type": "build", - "env": "build", - "stages": [{"type": "build", "approvalType": "success"}] - }, - { - "type": "migrate-deploy", - "env": "dev", - "stages": [ - {"type": "migrate", "approvalType": "success"}, - {"type": "deploy", "approvalType": "success"} - ] - }, - { - "type": "migrate-deploy", - "env": "qa", - "stages": [ - {"type": "migrate", "approvalType": "manual"}, - {"type": "deploy", "approvalType": "manual"} - ] - }, - { - "type": "migrate-deploy", - "env": "prod", - "approvalType": "manual", - "stages": [ - {"type": "migrate", "approvalType": "manual"}, - {"type": "deploy", "approvalType": "manual"} - ] - } - ] - }; + type: 'test', + env: 'test', + stages: [{ type: 'test', approvalType: 'success' }], + }, + { + type: 'build', + env: 'build', + stages: [{ type: 'build', approvalType: 'success' }], + }, + { + type: 'migrate-deploy', + env: 'dev', + stages: [ + { type: 'migrate', approvalType: 'success' }, + { type: 'deploy', approvalType: 'success' }, + ], + }, + { + type: 'migrate-deploy', + env: 'qa', + stages: [ + { type: 'migrate', approvalType: 'manual' }, + { type: 'deploy', approvalType: 'manual' }, + ], + }, + { + type: 'migrate-deploy', + env: 'prod', + approvalType: 'manual', + stages: [ + { type: 'migrate', approvalType: 'manual' }, + { type: 'deploy', approvalType: 'manual' }, + ], + }, + ], +} export const addStage = () => { - return {"type": "", "approvalType": ""} -} \ No newline at end of file + return { type: '', approvalType: '' } +} diff --git a/src/components/layout/Header.tsx b/src/components/layout/Header.tsx index 9949c4e..7ef50de 100644 --- a/src/components/layout/Header.tsx +++ b/src/components/layout/Header.tsx @@ -1,20 +1,20 @@ -import React, { useState, useContext } from "react"; -import { createStyles, makeStyles, Theme } from "@material-ui/core/styles"; -import AppBar from "@material-ui/core/AppBar"; -import Toolbar from "@material-ui/core/Toolbar"; -import Typography from "@material-ui/core/Typography"; -import IconButton from "@material-ui/core/IconButton"; -import MenuIcon from "@material-ui/icons/Menu"; -import AccountCircle from "@material-ui/icons/AccountCircle"; +import React, { useState, useContext } from 'react' +import { createStyles, makeStyles, Theme } from '@material-ui/core/styles' +import AppBar from '@material-ui/core/AppBar' +import Toolbar from '@material-ui/core/Toolbar' +import Typography from '@material-ui/core/Typography' +import IconButton from '@material-ui/core/IconButton' +import MenuIcon from '@material-ui/icons/Menu' +import AccountCircle from '@material-ui/icons/AccountCircle' -import MenuItem from "@material-ui/core/MenuItem"; -import Menu from "@material-ui/core/Menu"; -import { Link } from "react-router-dom"; -import { store } from "../../store/store"; -import { withCookies } from "react-cookie"; -import { LinearProgress } from "@material-ui/core"; -import { httpClient } from "../../helper/api-client"; -import PortalMenu from "./PortalMenu"; +import MenuItem from '@material-ui/core/MenuItem' +import Menu from '@material-ui/core/Menu' +import { Link } from 'react-router-dom' +import { store } from '../../store/store' +import { withCookies } from 'react-cookie' +import { LinearProgress } from '@material-ui/core' +import { httpClient } from '../../helper/api-client' +import PortalMenu from './PortalMenu' const useStyles = makeStyles((theme: Theme) => createStyles({ @@ -25,130 +25,121 @@ const useStyles = makeStyles((theme: Theme) => flexGrow: 1, }, progressBar: { - width: "100%", - "& > * + *": { + width: '100%', + '& > * + *': { marginTop: theme.spacing(1), }, }, - }) -); + }), +) function MenuAppBar(props: any) { - const { state, dispatch } = useContext(store); - const classes = useStyles(); - const [anchorEl, setAnchorEl] = React.useState(null); - const open = Boolean(anchorEl); - const [anchorEl1, setAnchorEl1] = React.useState(null); - const isAuthenticated = state.isAuthenticated; - const showBurger = props.showBurger != null ? props.showBurger : true; + const { state, dispatch } = useContext(store) + const classes = useStyles() + const [anchorEl, setAnchorEl] = React.useState(null) + const open = Boolean(anchorEl) + const [anchorEl1, setAnchorEl1] = React.useState(null) + const isAuthenticated = state.isAuthenticated + const showBurger = props.showBurger != null ? props.showBurger : true const handleMenu = (event: React.MouseEvent) => { - setAnchorEl(event.currentTarget); - }; + setAnchorEl(event.currentTarget) + } const handleClose = () => { - setAnchorEl(null); - setAnchorEl1(null); - }; + setAnchorEl(null) + setAnchorEl1(null) + } const handleLogin = () => { - window.location.href = "/login/okta"; - dispatch({ type: "setAuthentication", value: true }); - }; + window.location.href = '/login/okta' + dispatch({ type: 'setAuthentication', value: true }) + } const handleLogout = async () => { - httpClient("/api/logout", { - method: "POST", + httpClient('/api/logout', { + method: 'POST', }).then((response) => { if (response.ok) { - dispatch({ type: "setAuthentication", value: false }); - window.location.href = "/"; + dispatch({ type: 'setAuthentication', value: false }) + window.location.href = '/' } - }); - }; + }) + } return (
- + {isAuthenticated && showBurger ? (
- setAnchorEl1(e.currentTarget)} - aria-label="menu" - > - + setAnchorEl1(e.currentTarget)} aria-label='menu'> + - - {" "} + + {' '}
) : null} - + {props.name} - {( + {
- {isAuthenticated ? ( - Logout - ) : null} - {isAuthenticated ? null : ( - Login - )} + {isAuthenticated ? Logout : null} + {isAuthenticated ? null : Login}
- )} + }
{props.loading ? (
- +
) : ( <> )}
- ); + ) } -export default withCookies(MenuAppBar); +export default withCookies(MenuAppBar) diff --git a/src/components/layout/PortalMenu.tsx b/src/components/layout/PortalMenu.tsx index bca796b..2024687 100644 --- a/src/components/layout/PortalMenu.tsx +++ b/src/components/layout/PortalMenu.tsx @@ -1,46 +1,28 @@ -import React from "react"; -import MenuItem from "@material-ui/core/MenuItem"; -import {Link} from "react-router-dom"; -import {MenuList} from "@material-ui/core"; - +import React from 'react' +import MenuItem from '@material-ui/core/MenuItem' +import { Link } from 'react-router-dom' +import { MenuList } from '@material-ui/core' const PortalMenu = (props) => { - - return ( - - - Home - - - List - - - Create - - - Image Registries - - - Create Pipeline - - - ); + return ( + + + Home + + + List + + + Create + + + Image Registries + + + Create Pipeline + + + ) } -export default PortalMenu; \ No newline at end of file +export default PortalMenu diff --git a/src/components/manifest/Faults.tsx b/src/components/manifest/Faults.tsx index 83b4ec3..0f1ba7f 100644 --- a/src/components/manifest/Faults.tsx +++ b/src/components/manifest/Faults.tsx @@ -1,136 +1,125 @@ -import { withCookies } from "react-cookie"; -import { useState, useRef, useEffect } from "react"; -import * as React from "react"; -import SchemaForm from "./SchemaForm"; -import MenuAppBar from "../layout/Header"; -import { httpClient } from "../../helper/api-client"; -import { - Button, - Paper, - Typography, - IconButton, - Snackbar, -} from "@material-ui/core"; -import RefreshIcon from "@material-ui/icons/Refresh"; -import DeleteOutlineIcon from "@material-ui/icons/DeleteOutline"; -import { toast } from "react-toastify"; -import { Alert } from "@material-ui/lab"; +import { withCookies } from 'react-cookie' +import { useState, useRef, useEffect } from 'react' +import * as React from 'react' +import SchemaForm from './SchemaForm' +import MenuAppBar from '../layout/Header' +import { httpClient } from '../../helper/api-client' +import { Button, Paper, Typography, IconButton, Snackbar } from '@material-ui/core' +import RefreshIcon from '@material-ui/icons/Refresh' +import DeleteOutlineIcon from '@material-ui/icons/DeleteOutline' +import { toast } from 'react-toastify' +import { Alert } from '@material-ui/lab' const Faults = (props: any) => { - const { cookies } = props; - const manifestIdParam = props?.match?.params?.manifestId; - const [submitResponse, setSubmitResponse] = useState(""); - const [submitResponseStatus, setSubmitResponseStatus] = useState(""); - const [inProgress, setInProgress] = useState(false); + const { cookies } = props + const manifestIdParam = props?.match?.params?.manifestId + const [submitResponse, setSubmitResponse] = useState('') + const [submitResponseStatus, setSubmitResponseStatus] = useState('') + const [inProgress, setInProgress] = useState(false) const handleSubmit = async (): Promise => { - const toastId = toast.info("In Progress ...", { autoClose: 50000 }); - setInProgress(true); + const toastId = toast.info('In Progress ...', { autoClose: 50000 }) + setInProgress(true) httpClient(`/api/faults?manifestId=${manifestIdParam}`, { - method: "POST", + method: 'POST', body: JSON.stringify(standaloneData.current), }).then((r) => { r.text().then((resJson) => { - setInProgress(false); + setInProgress(false) if (r.ok) { toast.update(toastId, { - render: "Done", - type: "success", + render: 'Done', + type: 'success', autoClose: 3000, - }); - setSubmitResponseStatus("success"); + }) + setSubmitResponseStatus('success') } else { - toast.dismiss(toastId); - setSubmitResponseStatus("error"); - setSubmitResponse(resJson); + toast.dismiss(toastId) + setSubmitResponseStatus('error') + setSubmitResponse(resJson) } - }); - }); - }; + }) + }) + } const fetchK8Resources = async (): Promise => { - setk8Resources(["Loading..."]); + setk8Resources(['Loading...']) httpClient(`/api/faults?manifestId=${manifestIdParam}`, { - method: "GET", + method: 'GET', }).then((res) => { res.json().then((resJson) => { if (res.ok) { - setk8Resources(resJson); + setk8Resources(resJson) } else { - setk8Resources([resJson]); + setk8Resources([resJson]) } - }); - }); - }; + }) + }) + } const deleteK8Resources = async (): Promise => { - const toastId = toast.info("In Progress ...", { autoClose: 50000 }); + const toastId = toast.info('In Progress ...', { autoClose: 50000 }) httpClient(`/api/faults?manifestId=${manifestIdParam}`, { - method: "DELETE", + method: 'DELETE', }).then((r) => { r.text().then((resJson) => { if (r.ok) { toast.update(toastId, { - render: "Deleted", - type: "success", + render: 'Deleted', + type: 'success', autoClose: 3000, - }); - setSubmitResponseStatus("success"); + }) + setSubmitResponseStatus('success') } else { - toast.dismiss(toastId); - setSubmitResponseStatus("error"); - setSubmitResponse(resJson); + toast.dismiss(toastId) + setSubmitResponseStatus('error') + setSubmitResponse(resJson) } - }); - }); - }; + }) + }) + } - const [csrfToken] = useState(cookies.get("XSRF-TOKEN")); - const [k8Resources, setk8Resources] = useState([]); - const standaloneData = useRef({}); + const [csrfToken] = useState(cookies.get('XSRF-TOKEN')) + const [k8Resources, setk8Resources] = useState([]) + const standaloneData = useRef({}) useEffect(() => { - fetchK8Resources(); - }, []); + fetchK8Resources() + }, []) return ( <> - +
-
+
{ - standaloneData.current = data; + standaloneData.current = data }} csrfToken={csrfToken} >
- setSubmitResponseStatus("")} + open={submitResponseStatus === 'error'} + onClose={() => setSubmitResponseStatus('')} > - {JSON.stringify(submitResponse)} + {JSON.stringify(submitResponse)}
- ); -}; + ) +} -export default withCookies(Faults); +export default withCookies(Faults) diff --git a/src/components/manifest/Form.tsx b/src/components/manifest/Form.tsx index e88f703..d9b6508 100644 --- a/src/components/manifest/Form.tsx +++ b/src/components/manifest/Form.tsx @@ -1,152 +1,144 @@ -import * as React from "react"; -import {useEffect, useState, useRef, Dispatch, SetStateAction} from "react"; -import MenuAppBar from "../layout/Header"; -import { Button, Grid, Snackbar, TextField } from "@material-ui/core"; -import { Alert } from "@material-ui/lab"; -import { withCookies } from "react-cookie"; -import { toast } from "react-toastify"; -import ConfirmationButton from "../common/ConfirmationButton"; -import _ from "lodash"; -import {getFormattedRuntimeException, httpClient, post} from "../../helper/api-client"; -import { Link } from "react-router-dom"; -import BaseForm from "../../coreform/BaseForm"; +import * as React from 'react' +import { useEffect, useState, useRef, Dispatch, SetStateAction } from 'react' +import MenuAppBar from '../layout/Header' +import { Button, Grid, Snackbar, TextField } from '@material-ui/core' +import { Alert } from '@material-ui/lab' +import { withCookies } from 'react-cookie' +import { toast } from 'react-toastify' +import ConfirmationButton from '../common/ConfirmationButton' +import _ from 'lodash' +import { getFormattedRuntimeException, httpClient, post } from '../../helper/api-client' +import { Link } from 'react-router-dom' +import BaseForm from '../../coreform/BaseForm' import { NewManifest } from '../../models/Manifest' -import Popup from "../common/Popup"; +import Popup from '../common/Popup' -const API_TO_POST_MANIFEST = '/api/manifest'; +const API_TO_POST_MANIFEST = '/api/manifest' const formatDisplayData = (standaloneData) => { - return JSON.stringify(standaloneData, null, 2); -}; + return JSON.stringify(standaloneData, null, 2) +} -const parseLines = (value) => value.replace(/(\\n)/g, "\n"); +const parseLines = (value) => value.replace(/(\\n)/g, '\n') -const withError = ( - error: Object, - component: React.ReactElement -): React.ReactElement => { +const withError = (error: Object, component: React.ReactElement): React.ReactElement => { if (_.isEmpty(error)) { - return component; + return component } else { - return {formatDisplayData(error)}; + return {formatDisplayData(error)} } -}; +} const Form = (props: any) => { - const { cookies, location } = props; - const standaloneData = useRef({}); - const apiResponse = useRef(""); - const responseSeverity = useRef(""); - const [formInitData, setFormInitData] = useState({}); - const [loading, setLoading] = useState(true); - const [fetchError, setFetchError] = useState({}); - const manifestIdParam = props?.match?.params?.manifestId; - const [csrfToken] = useState(cookies.get("XSRF-TOKEN")); - const [errorData, setErrorData] = useState([]); - const [popupOpen, setPopupOpen] = React.useState(false); - const [canSubmit, setCanSubmit] = useState(true); + const { cookies, location } = props + const standaloneData = useRef({}) + const apiResponse = useRef('') + const responseSeverity = useRef('') + const [formInitData, setFormInitData] = useState({}) + const [loading, setLoading] = useState(true) + const [fetchError, setFetchError] = useState({}) + const manifestIdParam = props?.match?.params?.manifestId + const [csrfToken] = useState(cookies.get('XSRF-TOKEN')) + const [errorData, setErrorData] = useState([]) + const [popupOpen, setPopupOpen] = React.useState(false) + const [canSubmit, setCanSubmit] = useState(true) - const [rolloutPopupOpen, setRolloutPopupOpen] = React.useState(false); + const [rolloutPopupOpen, setRolloutPopupOpen] = React.useState(false) const handleRolloutClick = () => { - setRolloutPopupOpen(true); - }; + setRolloutPopupOpen(true) + } const handleRolloutPopupClose = () => { - setRolloutPopupOpen(false); - }; + setRolloutPopupOpen(false) + } const getManifestData = async (manifestId: number): Promise => { - console.log(`Fetching manifest id ${manifestId}`); - return httpClient(`/api/manifest/${manifestId}`); - }; + console.log(`Fetching manifest id ${manifestId}`) + return httpClient(`/api/manifest/${manifestId}`) + } const getManifestDefaults = async (): Promise => { - return httpClient(`/api/manifest/defaults`); - }; + return httpClient('/api/manifest/defaults') + } useEffect(() => { - const queryParams = new URLSearchParams(props.location.search); - const isCopy = String(props.location.search).includes("copyId"); + const queryParams = new URLSearchParams(props.location.search) + const isCopy = String(props.location.search).includes('copyId') const handleFetchResponse = (res: Response) => { res.json().then((resJson) => { if (res.ok) { - setFormInitData(resJson); + setFormInitData(resJson) } else { - setFetchError(resJson); + setFetchError(resJson) } - setLoading(false); - }); - }; + setLoading(false) + }) + } if (isCopy) { - setFormInitData(location.state.cloneValues); - setLoading(false); + setFormInitData(location.state.cloneValues) + setLoading(false) } else if (manifestIdParam) { - getManifestData(manifestIdParam).then(handleFetchResponse); + getManifestData(manifestIdParam).then(handleFetchResponse) } else { - //TODO: fetch defaults from backend for new ui - //getManifestDefaults().then(handleFetchResponse); + // TODO: fetch defaults from backend for new ui + // getManifestDefaults().then(handleFetchResponse); setFormInitData(NewManifest()) - setLoading(false); + setLoading(false) } // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); + }, []) const submitManifest = (manifest: any, disableSubmitButton: Dispatch>) => { - const toastId = toast.info("In Progress ...", { + const toastId = toast.info('In Progress ...', { autoClose: 50000, - }); + }) - post(manifest,API_TO_POST_MANIFEST).then((r) => { - disableSubmitButton(false); + post(manifest, API_TO_POST_MANIFEST).then((r) => { + disableSubmitButton(false) r.json().then((resJson) => { if (r.ok) { toast.update(toastId, { - render: "Updated", - type: "success", + render: 'Updated', + type: 'success', autoClose: 3000, - }); + }) if (manifestIdParam) { - setFormInitData(resJson.manifest); + setFormInitData(resJson.manifest) } else { - props.history.push( - `/manifests/${resJson.manifest.id}/edit` - ); + props.history.push(`/manifests/${resJson.manifest.id}/edit`) } - apiResponse.current = ""; + apiResponse.current = '' } else { - apiResponse.current = getFormattedRuntimeException(resJson); - responseSeverity.current = "error"; - setPopupOpen(true); - toast.dismiss(toastId); + apiResponse.current = getFormattedRuntimeException(resJson) + responseSeverity.current = 'error' + setPopupOpen(true) + toast.dismiss(toastId) } - }); - }); + }) + }) } return ( -
- +
+ {loading ? ( <> ) : ( withError( fetchError, - + { - setPopupOpen(false); + setPopupOpen(false) }} > { - setPopupOpen(false); + setPopupOpen(false) }} severity={responseSeverity.current} > @@ -154,80 +146,77 @@ const Form = (props: any) => { { - const toastId = toast.info("In Progress ...", { + const toastId = toast.info('In Progress ...', { autoClose: 50000, - }); - httpClient( - `/api/manifest/${manifestIdParam}?deleteManifest=false`, - { method: "DELETE" } - ).then((res) => { + }) + httpClient(`/api/manifest/${manifestIdParam}?deleteManifest=false`, { + method: 'DELETE', + }).then((res) => { res.json().then((resJson) => { if (res.ok) { - responseSeverity.current = "success"; - apiResponse.current = `Deleted resources: ${JSON.stringify( - resJson - )}`; + responseSeverity.current = 'success' + apiResponse.current = `Deleted resources: ${JSON.stringify(resJson)}` } else { - responseSeverity.current = "error"; - apiResponse.current = JSON.stringify(resJson); + responseSeverity.current = 'error' + apiResponse.current = JSON.stringify(resJson) } - toast.dismiss(toastId); - setPopupOpen(true); - }); - }); + toast.dismiss(toastId) + setPopupOpen(true) + }) + }) }} - variant="outlined" + variant='outlined' disabled={!manifestIdParam} > Delete Resources   - + { - const toastId = toast.info("In Progress ...", { + const toastId = toast.info('In Progress ...', { autoClose: 50000, - }); + }) httpClient(`/api/kube/manifest/${manifestIdParam}/restart`, { - method: "POST", + method: 'POST', }).then((res) => { if (res.ok) { - responseSeverity.current = "success"; - apiResponse.current = `Successfully started rollout restart `; + responseSeverity.current = 'success' + apiResponse.current = 'Successfully started rollout restart ' } else { res.json().then((resJson) => { - responseSeverity.current = "error"; - apiResponse.current = JSON.stringify(resJson); - }); + responseSeverity.current = 'error' + apiResponse.current = JSON.stringify(resJson) + }) } - toast.dismiss(toastId); - setPopupOpen(true); - }); + toast.dismiss(toastId) + setPopupOpen(true) + }) }} - variant="outlined" + variant='outlined' disabled={!manifestIdParam} > Rollout Restart @@ -235,7 +224,7 @@ const Form = (props: any) => {     - + , ) )}
- ); -}; + ) +} -export default withCookies(Form); +export default withCookies(Form) diff --git a/src/components/manifest/ImportManifestJson.tsx b/src/components/manifest/ImportManifestJson.tsx index 0e68793..3a7ab91 100644 --- a/src/components/manifest/ImportManifestJson.tsx +++ b/src/components/manifest/ImportManifestJson.tsx @@ -1,15 +1,19 @@ -import { withCookies } from "react-cookie"; -import * as React from "react"; -import MenuAppBar from "../layout/Header"; -import { TextField, Button, Select, MenuItem } from "@material-ui/core"; -import { Alert } from "@material-ui/lab"; -import { httpClient } from "../../helper/api-client"; -import { useState } from "react"; +import { withCookies } from 'react-cookie' +import * as React from 'react' +import MenuAppBar from '../layout/Header' +import { TextField, Button, Select, MenuItem } from '@material-ui/core' +import { Alert } from '@material-ui/lab' +import { httpClient } from '../../helper/api-client' +import { useState } from 'react' -const environments = ["dev", "qa", "prod"] +const environments = ['dev', 'qa', 'prod'] const ImportManifestJson = (props: any) => { - const [importRequest, setImportRequest] = useState({ environment: "dev", vaultPath: 'config/medici/nonprod/dev/loan-account-service', manifest: '' }); + const [importRequest, setImportRequest] = useState({ + environment: 'dev', + vaultPath: 'config/medici/nonprod/dev/loan-account-service', + manifest: '', + }) const [importResponse, setImportResponse] = useState('') const [importResSeverity, setImportResSeverity] = useState('') @@ -26,47 +30,61 @@ const ImportManifestJson = (props: any) => { } const handleSubmit = () => { - httpClient(`/api/manifest/import`, { - method: "POST", + httpClient('/api/manifest/import', { + method: 'POST', body: JSON.stringify(importRequest), - }).then(res => { - if(res.ok) { + }).then((res) => { + if (res.ok) { setImportResSeverity('success') setImportResponse('Imported') } else { setImportResSeverity('error') - res.json().then(resJson => setImportResponse(resJson)) + res.json().then((resJson) => setImportResponse(resJson)) } }) - }; + } return ( <> - -
+ +
- + {environments.map((environment) => ( + + {environment} + + ))} - +
- - - {JSON.stringify(importResponse)} - + + {JSON.stringify(importResponse)}
) -}; +} -export default withCookies(ImportManifestJson); +export default withCookies(ImportManifestJson) diff --git a/src/components/manifest/Notification.tsx b/src/components/manifest/Notification.tsx index e8dd3da..d517076 100644 --- a/src/components/manifest/Notification.tsx +++ b/src/components/manifest/Notification.tsx @@ -1,125 +1,113 @@ -import { withCookies } from "react-cookie"; -import { useState, useRef, useEffect } from "react"; -import * as React from "react"; -import SchemaForm from "./SchemaForm"; -import MenuAppBar from "../layout/Header"; -import { httpClient } from "../../helper/api-client"; -import { - Button, - Paper, - Typography, - IconButton, - Snackbar, -} from "@material-ui/core"; -import RefreshIcon from "@material-ui/icons/Refresh"; -import DeleteOutlineIcon from "@material-ui/icons/DeleteOutline"; -import { toast } from "react-toastify"; -import { Alert } from "@material-ui/lab"; +import { withCookies } from 'react-cookie' +import { useState, useRef, useEffect } from 'react' +import * as React from 'react' +import SchemaForm from './SchemaForm' +import MenuAppBar from '../layout/Header' +import { httpClient } from '../../helper/api-client' +import { Button, Paper, Typography, IconButton, Snackbar } from '@material-ui/core' +import RefreshIcon from '@material-ui/icons/Refresh' +import DeleteOutlineIcon from '@material-ui/icons/DeleteOutline' +import { toast } from 'react-toastify' +import { Alert } from '@material-ui/lab' const Notification = (props: any) => { - const { cookies } = props; - const manifestIdParam = props?.match?.params?.manifestId; - const [submitResponse, setSubmitResponse] = useState(""); - const [submitResponseStatus, setSubmitResponseStatus] = useState(""); - const [inProgress, setInProgress] = useState(false); - const [formInitData, setFormInitData] = useState({}); - const [loading, setLoading] = useState(true); - const [fetchError, setFetchError] = useState({}); + const { cookies } = props + const manifestIdParam = props?.match?.params?.manifestId + const [submitResponse, setSubmitResponse] = useState('') + const [submitResponseStatus, setSubmitResponseStatus] = useState('') + const [inProgress, setInProgress] = useState(false) + const [formInitData, setFormInitData] = useState({}) + const [loading, setLoading] = useState(true) + const [fetchError, setFetchError] = useState({}) const handleSubmit = async (): Promise => { - const toastId = toast.info("In Progress ...", { autoClose: 50000 }); - setInProgress(true); + const toastId = toast.info('In Progress ...', { autoClose: 50000 }) + setInProgress(true) httpClient(`/api/notification?manifestId=${manifestIdParam}`, { - method: "POST", + method: 'POST', body: JSON.stringify(standaloneData.current), }).then((r) => { r.text().then((resJson) => { - setInProgress(false); + setInProgress(false) if (r.ok) { toast.update(toastId, { - render: "Done", - type: "success", + render: 'Done', + type: 'success', autoClose: 3000, - }); - setSubmitResponseStatus("success"); + }) + setSubmitResponseStatus('success') } else { - toast.dismiss(toastId); - setSubmitResponseStatus("error"); - setSubmitResponse(resJson); + toast.dismiss(toastId) + setSubmitResponseStatus('error') + setSubmitResponse(resJson) } - }); - }); - }; + }) + }) + } const getManifestData = async (manifestId: number): Promise => { - console.log(`Fetching notification info for manifest id ${manifestId}`); - return httpClient(`/api/notification?manifestId=${manifestId}`); - }; + console.log(`Fetching notification info for manifest id ${manifestId}`) + return httpClient(`/api/notification?manifestId=${manifestId}`) + } - - const [csrfToken] = useState(cookies.get("XSRF-TOKEN")); - const standaloneData = useRef({}); + const [csrfToken] = useState(cookies.get('XSRF-TOKEN')) + const standaloneData = useRef({}) useEffect(() => { - const queryParams = new URLSearchParams(props.location.search); + const queryParams = new URLSearchParams(props.location.search) const handleFetchResponse = (res: Response) => { res.json().then((resJson) => { - setLoading(false); + setLoading(false) if (res.ok) { - console.log("got json notification reponse"); - setFormInitData(resJson); + console.log('got json notification reponse') + setFormInitData(resJson) } else { - setFetchError(resJson); + setFetchError(resJson) } - }); - }; + }) + } if (manifestIdParam) { - getManifestData(manifestIdParam).then(handleFetchResponse); + getManifestData(manifestIdParam).then(handleFetchResponse) } else { // getManifestDefaults().then(handleFetchResponse); } // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); + }, []) return ( <> - +
-
+
{ - standaloneData.current = data; + standaloneData.current = data }} csrfToken={csrfToken} manifestData={formInitData} >
- setSubmitResponseStatus("")} + open={submitResponseStatus === 'error'} + onClose={() => setSubmitResponseStatus('')} > - {JSON.stringify(submitResponse)} + {JSON.stringify(submitResponse)}
- ); -}; + ) +} -export default withCookies(Notification); +export default withCookies(Notification) diff --git a/src/components/manifest/SchemaForm.css b/src/components/manifest/SchemaForm.css index 15b5fbd..24fddbc 100644 --- a/src/components/manifest/SchemaForm.css +++ b/src/components/manifest/SchemaForm.css @@ -8,4 +8,4 @@ } .MuiInputBase-root { font-size: 1.1rem !important; -} \ No newline at end of file +} diff --git a/src/components/manifest/SchemaForm.tsx b/src/components/manifest/SchemaForm.tsx index 9c25db6..e38366e 100644 --- a/src/components/manifest/SchemaForm.tsx +++ b/src/components/manifest/SchemaForm.tsx @@ -6,47 +6,43 @@ */ -import * as React from "react"; -import { JsonForms } from "@jsonforms/react"; -import { - materialCells, - materialRenderers, -} from "@jsonforms/material-renderers"; -import customAjv from "../../configuration/jsonforms/CustomAjv"; -import _ from "lodash"; -import { - FoldableGroupTester, - FoldableGroupRenderer, -} from "../../renderer/FoldableGroup"; -import { FoldableGroupContextProvider } from "../../renderer/FoldableGroupContext"; -import { ThemeProvider, CircularProgress } from "@material-ui/core"; -import { jsonformThemeOverride } from "../../configuration/jsonforms/Theme"; -import { httpClient } from "../../helper/api-client"; -import "./SchemaForm.css"; +import * as React from 'react' +import { JsonForms } from '@jsonforms/react' +import { materialCells, materialRenderers } from '@jsonforms/material-renderers' +import customAjv from '../../configuration/jsonforms/CustomAjv' +import _ from 'lodash' +import { FoldableGroupTester, FoldableGroupRenderer } from '../../renderer/FoldableGroup' +import { FoldableGroupContextProvider } from '../../renderer/FoldableGroupContext' +import { ThemeProvider, CircularProgress } from '@material-ui/core' +import { jsonformThemeOverride } from '../../configuration/jsonforms/Theme' +import { httpClient } from '../../helper/api-client' +import './SchemaForm.css' interface IProps { - csrfToken?: any; - name: string; - onDataChange?: any; - children?: any; - updateCompleteSchemaHandler?: any; - schemaPath?: string; - uiSchema?: any; - manifestData?: any; - additionalOptions?: any; + csrfToken?: any + name: string + onDataChange?: any + children?: any + updateCompleteSchemaHandler?: any + schemaPath?: string + uiSchema?: any + manifestData?: any + additionalOptions?: any } function isProperJsonSchema(completeSchema: any) { - let jsonSchema = completeSchema.jsonSchema; - const schemaStr = JSON.stringify(jsonSchema); - let isProperSchema = schemaStr.search("resource:/") === -1; - return isProperSchema; + const jsonSchema = completeSchema.jsonSchema + const schemaStr = JSON.stringify(jsonSchema) + const isProperSchema = schemaStr.search('resource:/') === -1 + return isProperSchema } function optionsToUrlParams(options: any) { - if(!options) { return ''} + if (!options) { + return '' + } return Object.keys(options) - .map(k => `${encodeURIComponent(k)}=${encodeURIComponent(options[k])}`) + .map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(options[k])}`) .join('&') } @@ -54,59 +50,54 @@ export default function SchemaForm(props: IProps) { const [completeSchema, setCompleteSchema] = React.useState({ uiSchema: undefined, jsonSchema: undefined, - }); - const [isLoading, setIsLoading] = React.useState(true); + }) + const [isLoading, setIsLoading] = React.useState(true) React.useEffect(() => { - console.log(`Getting schema for ${props.name}`); + console.log(`Getting schema for ${props.name}`) httpClient(`/api/schema/${props.name}?${optionsToUrlParams(props.additionalOptions)}`).then((res) => { res.json().then((resBody) => { if (props.uiSchema) { - props.uiSchema.push(JSON.parse(resBody.data.uiSchema)); + props.uiSchema.push(JSON.parse(resBody.data.uiSchema)) } else { setCompleteSchema({ uiSchema: JSON.parse(resBody.data.uiSchema), jsonSchema: undefined, - }); + }) } - const schemaHandler = - props.updateCompleteSchemaHandler || setCompleteSchema; + const schemaHandler = props.updateCompleteSchemaHandler || setCompleteSchema schemaHandler((prevSchema) => { _.set( prevSchema, - `jsonSchema${props.schemaPath ? props.schemaPath : ""}`, - JSON.parse(resBody.data.jsonSchema) - ); - //Creating new object here because if objectId is not changed react doesnt rerenders it + `jsonSchema${props.schemaPath ? props.schemaPath : ''}`, + JSON.parse(resBody.data.jsonSchema), + ) + // Creating new object here because if objectId is not changed react doesnt rerenders it const newSchema = { uiSchema: prevSchema.uiSchema, jsonSchema: prevSchema.jsonSchema, - }; - return newSchema; - }); - setIsLoading(false); - }); - }); + } + return newSchema + }) + setIsLoading(false) + }) + }) // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); + }, []) return !isLoading ? (
{React.Children.map(props.children, (child) => { return React.cloneElement(child, { - updateCompleteSchemaHandler: - props.updateCompleteSchemaHandler || setCompleteSchema, - schemaPath: `${props.schemaPath || ""}.properties.${ - child.props.name - }`, + updateCompleteSchemaHandler: props.updateCompleteSchemaHandler || setCompleteSchema, + schemaPath: `${props.schemaPath || ''}.properties.${child.props.name}`, uiSchema: (props.uiSchema || completeSchema.uiSchema).elements, - }); + }) })} - {!props.updateCompleteSchemaHandler && - isProperJsonSchema(completeSchema) ? ( + {!props.updateCompleteSchemaHandler && isProperJsonSchema(completeSchema) ? ( { if (props.onDataChange) { - props.onDataChange(data, errors); + props.onDataChange(data, errors) } }} /> @@ -134,5 +125,5 @@ export default function SchemaForm(props: IProps) {
) : ( - ); + ) } diff --git a/src/components/manifest/ShowDeploymentManifest.tsx b/src/components/manifest/ShowDeploymentManifest.tsx index 4026085..ed21468 100644 --- a/src/components/manifest/ShowDeploymentManifest.tsx +++ b/src/components/manifest/ShowDeploymentManifest.tsx @@ -1,226 +1,220 @@ -import React from "react"; -import { Button, makeStyles, TextField, Snackbar, Paper} from "@material-ui/core"; -import { Autocomplete, Alert } from "@material-ui/lab"; -import { toast } from "react-toastify"; -import MenuAppBar from "../layout/Header"; -import { withCookies } from "react-cookie"; -import _ from "lodash"; -import { Link } from "react-router-dom"; -import { httpClient } from "../../helper/api-client"; -import ConfirmationButton from "../common/ConfirmationButton"; -import PortalMenu from "../layout/PortalMenu"; +import React from 'react' +import { Button, makeStyles, TextField, Snackbar, Paper } from '@material-ui/core' +import { Autocomplete, Alert } from '@material-ui/lab' +import { toast } from 'react-toastify' +import MenuAppBar from '../layout/Header' +import { withCookies } from 'react-cookie' +import _ from 'lodash' +import { Link } from 'react-router-dom' +import { httpClient } from '../../helper/api-client' +import ConfirmationButton from '../common/ConfirmationButton' +import PortalMenu from '../layout/PortalMenu' -import * as _m from '../../models/Manifest'; +import * as _m from '../../models/Manifest' -import CloneManifestForm from "../../coreform/CloneManifestForm"; -import Popup from "../common/Popup"; +import CloneManifestForm from '../../coreform/CloneManifestForm' +import Popup from '../common/Popup' const useStyles = makeStyles((theme) => ({ container: { - padding: '2em' + padding: '2em', }, root: { - "& > *": { + '& > *': { margin: theme.spacing(1), }, }, paper: { - marginRight: theme.spacing(2), + marginRight: theme.spacing(2), }, field: { - marginTop: 20, - width: 300 - } -})); + marginTop: 20, + width: 300, + }, +})) export const ManifestListActions = (props: any) => { - const deletePopupMsg = `WARNING! \n\n1. You are about to delete deployment manifest & kubernetes resources.\n2. This does not delete aws resources like rds, docdb, etc. \n3. run resource pipeline with destroy option before proceeding`; - const { useRef } = React; - const [popupOpen, setPopupOpen] = React.useState(false); - const apiResponse = useRef('') + const deletePopupMsg = + 'WARNING! \n\n1. You are about to delete deployment manifest & kubernetes resources.\n2. This does not delete aws resources like rds, docdb, etc. \n3. run resource pipeline with destroy option before proceeding' + const { useRef } = React + const [popupOpen, setPopupOpen] = React.useState(false) + const apiResponse = useRef('') const responseSeverity = useRef('') - const classes = useStyles(); - const [open, setOpen] = React.useState(false); + const classes = useStyles() + const [open, setOpen] = React.useState(false) - const [deletePopupOpen, setDeletePopupOpen] = React.useState(false); + const [deletePopupOpen, setDeletePopupOpen] = React.useState(false) const handleDeleteClick = () => { - setDeletePopupOpen(true); - }; + setDeletePopupOpen(true) + } const handleDeletePopupClose = () => { - setDeletePopupOpen(false); - }; + setDeletePopupOpen(false) + } const handleCloneClick = () => { - setOpen(true); - }; + setOpen(true) + } const handleCloneClose = () => { - setOpen(false); - }; - const parseLines = (value) => value.replace(/(\\n)/g, "\n"); + setOpen(false) + } + const parseLines = (value) => value.replace(/(\\n)/g, '\n') return ( <>
+ - - - + + + - - + + { - const toastId = toast.info("In Progress ...", { - autoClose: 50000, - }); - httpClient(`/api/manifest/${props.manifestId}?deleteManifest=true`, { method: 'DELETE' }) - .then((res) => { - res.json().then(resJson => { - if (res.ok) { - responseSeverity.current = "success" - apiResponse.current = `Deleted manifest with resources: ${JSON.stringify(resJson)}` - } else { - responseSeverity.current = "error" - apiResponse.current = JSON.stringify(resJson) - } - toast.dismiss(toastId) - setPopupOpen(true) - }) - }) + const toastId = toast.info('In Progress ...', { + autoClose: 50000, + }) + httpClient(`/api/manifest/${props.manifestId}?deleteManifest=true`, { + method: 'DELETE', + }).then((res) => { + res.json().then((resJson) => { + if (res.ok) { + responseSeverity.current = 'success' + apiResponse.current = `Deleted manifest with resources: ${JSON.stringify(resJson)}` + } else { + responseSeverity.current = 'error' + apiResponse.current = JSON.stringify(resJson) + } + toast.dismiss(toastId) + setPopupOpen(true) + }) + }) }} - variant="outlined" + variant='outlined' disabled={!_.isNumber(props.manifestId)} > Delete
- { setPopupOpen(false) }}> - { setPopupOpen(false) }} severity={responseSeverity.current}> + { + setPopupOpen(false) + }} + > + { + setPopupOpen(false) + }} + severity={responseSeverity.current} + > {apiResponse.current} - ); -}; + ) +} const ShowDeploymentManifest = () => { - const { useState } = React; - const [manifestNameList, setManifestNameList] = useState([]); - const [selectedManifestId, setSelectedManifestId] = useState(); - const [isLoading, setIsLoading] = React.useState(false); + const { useState } = React + const [manifestNameList, setManifestNameList] = useState([]) + const [selectedManifestId, setSelectedManifestId] = useState() + const [isLoading, setIsLoading] = React.useState(false) function fetchListOfManifests(): Promise { setIsLoading(true) - return httpClient(`/api/manifest/list`) + return httpClient('/api/manifest/list') .then((res) => { console.log(`REDIRECTED: ${res.redirected}`) console.log(`OK: ${res.ok}`) - return res.json(); + return res.json() }) .then((response) => { setIsLoading(false) - return response; + return response }) .catch((error) => { - console.log(error); - return []; - }); + console.log(error) + return [] + }) } React.useEffect(() => { fetchListOfManifests().then((manifestList) => { - setManifestNameList(manifestList); - }); - }, []); + setManifestNameList(manifestList) + }) + }, []) - const classes = useStyles(); + const classes = useStyles() return ( <> - -
+
- - {}}/> - + + {}} /> +
-
+
- `${option.environment}/${option.name}` - } - renderInput={(params) => ( - - )} - onChange={(_, value) => - value - ? setSelectedManifestId(value.id) - : setSelectedManifestId(undefined) - } + getOptionLabel={(option: any) => `${option.environment}/${option.name}`} + renderInput={(params) => } + onChange={(_, value) => (value ? setSelectedManifestId(value.id) : setSelectedManifestId(undefined))} />
-
+
- ); -}; + ) +} -export default withCookies(ShowDeploymentManifest); +export default withCookies(ShowDeploymentManifest) diff --git a/src/components/manifest/ShowJson.tsx b/src/components/manifest/ShowJson.tsx index 399d3e3..b584a41 100644 --- a/src/components/manifest/ShowJson.tsx +++ b/src/components/manifest/ShowJson.tsx @@ -1,23 +1,23 @@ -import { withCookies } from "react-cookie"; -import * as React from "react"; -import { httpClient } from "../../helper/api-client"; +import { withCookies } from 'react-cookie' +import * as React from 'react' +import { httpClient } from '../../helper/api-client' const ShowJson = (props: any) => { - const [jsonData, setJsonData] = React.useState({}); + const [jsonData, setJsonData] = React.useState({}) const getManifestData = async (manifestId: number): Promise => { - console.log(`Fetching manifest id ${manifestId}`); - return httpClient(`/api/manifest/${manifestId}`).then((res) => res.json()); - }; + console.log(`Fetching manifest id ${manifestId}`) + return httpClient(`/api/manifest/${manifestId}`).then((res) => res.json()) + } React.useEffect(() => { - const manifestIdParam = props?.match?.params?.manifestId; + const manifestIdParam = props?.match?.params?.manifestId getManifestData(manifestIdParam).then((res) => { - setJsonData(res); - }); - }, []); + setJsonData(res) + }) + }, []) - return
{JSON.stringify(jsonData, null, 2)}
; -}; + return
{JSON.stringify(jsonData, null, 2)}
+} -export default withCookies(ShowJson); +export default withCookies(ShowJson) diff --git a/src/configuration/jsonforms/CustomAjv.ts b/src/configuration/jsonforms/CustomAjv.ts index 15f363a..430a9a1 100644 --- a/src/configuration/jsonforms/CustomAjv.ts +++ b/src/configuration/jsonforms/CustomAjv.ts @@ -1,7 +1,7 @@ -import { createAjv } from "@jsonforms/core"; +import { createAjv } from '@jsonforms/core' const customAjv = (() => { - console.log("Creating custom ajv for jsonforms") - return createAjv({useDefaults: true}) + console.log('Creating custom ajv for jsonforms') + return createAjv({ useDefaults: true }) })() -export default customAjv \ No newline at end of file +export default customAjv diff --git a/src/configuration/jsonforms/Theme.tsx b/src/configuration/jsonforms/Theme.tsx index f05a346..3cb083e 100644 --- a/src/configuration/jsonforms/Theme.tsx +++ b/src/configuration/jsonforms/Theme.tsx @@ -1,7 +1,7 @@ -import { createMuiTheme } from "@material-ui/core"; +import { createMuiTheme } from '@material-ui/core' export const jsonformThemeOverride = createMuiTheme({ - // typography: { - // fontSize: 18, - // }, - }); \ No newline at end of file + // typography: { + // fontSize: 18, + // }, +}) diff --git a/src/coreform/AWSAccessForm.tsx b/src/coreform/AWSAccessForm.tsx index 707c9df..a7dd82f 100644 --- a/src/coreform/AWSAccessForm.tsx +++ b/src/coreform/AWSAccessForm.tsx @@ -1,67 +1,81 @@ -import { Grid, makeStyles, TableCell } from '@material-ui/core'; -import { useFormikContext } from 'formik'; -import * as React from 'react'; -import { FormikTable } from '../components/common/FormikTable'; -import { FormikTextField } from '../components/common/FormikTextField'; -import { FormikCardList } from '../components/common/FormikCardList'; +import { Grid, makeStyles, TableCell } from '@material-ui/core' +import { useFormikContext } from 'formik' +import * as React from 'react' +import { FormikTable } from '../components/common/FormikTable' +import { FormikTextField } from '../components/common/FormikTextField' +import { FormikCardList } from '../components/common/FormikCardList' import * as _m from '../models/Manifest' -import NotConfigured from './NotConfiguredPanel'; -import GeneratePipelineButton from "../components/common/GeneratePipelineButton"; +import NotConfigured from './NotConfiguredPanel' +import GeneratePipelineButton from '../components/common/GeneratePipelineButton' const useStyles = makeStyles({ - root: { - width: 1200 - }, - field: { - width: 510, - marginTop: 10 - }, - smallField: { - width: 400 - } -}); + root: { + width: 1200, + }, + field: { + width: 510, + marginTop: 10, + }, + smallField: { + width: 400, + }, +}) const PolicyAction = (props: { policy: string }) => { - const { policy } = props - const classes = useStyles(); - return ( - - {(i) => ( - <> - - - - - )} - ) + const { policy } = props + const classes = useStyles() + return ( + + {(i) => ( + <> + + + + + )} + + ) } const AWSAccessForm = () => { - const { values, setValues }: { values: any, setValues: any } = useFormikContext() - const classes = useStyles(); - return (<> - setValues(_m.addAwsAccess(values))} - removeAction={() => setValues(_m.removeAwsAccess(values))} > - - - - {(i) => <> - - - - } - - - - - <>{ values.extraResources !== undefined && values.extraResources.aws_access !== undefined? - - :''} - - ) + const { values, setValues }: { values: any; setValues: any } = useFormikContext() + const classes = useStyles() + return ( + <> + setValues(_m.addAwsAccess(values))} + removeAction={() => setValues(_m.removeAwsAccess(values))} + > + + + {(i) => ( + <> + + + + )} + + + + <> + {values.extraResources !== undefined && values.extraResources.aws_access !== undefined ? ( + + ) : ( + '' + )} + + + ) } export default AWSAccessForm diff --git a/src/coreform/AdditionalIpWhitelistingForm.tsx b/src/coreform/AdditionalIpWhitelistingForm.tsx index 5c9e136..d7d3bee 100644 --- a/src/coreform/AdditionalIpWhitelistingForm.tsx +++ b/src/coreform/AdditionalIpWhitelistingForm.tsx @@ -1,79 +1,107 @@ -import { makeStyles, TableCell } from '@material-ui/core'; -import * as React from 'react'; -import { FormikTextField } from '../components/common/FormikTextField'; -import { FormikCardList } from '../components/common/FormikCardList'; +import { makeStyles, TableCell } from '@material-ui/core' +import * as React from 'react' +import { FormikTextField } from '../components/common/FormikTextField' +import { FormikCardList } from '../components/common/FormikCardList' import * as _m from '../models/Manifest' -import { FormikTable } from '../components/common/FormikTable'; -import { toMenuItems } from './FormUtil'; -import { useFormikContext } from 'formik'; -import NotConfigured from './NotConfiguredPanel'; +import { FormikTable } from '../components/common/FormikTable' +import { toMenuItems } from './FormUtil' +import { useFormikContext } from 'formik' +import NotConfigured from './NotConfiguredPanel' const useStyles = makeStyles({ - root: { - width: 1200 - }, - groupField: { - width: 500 - }, - ruleField: { - width: 280 - }, - cidrField: { - width: 180 - } -}); + root: { + width: 1200, + }, + groupField: { + width: 500, + }, + ruleField: { + width: 280, + }, + cidrField: { + width: 180, + }, +}) const IngresCidr = (props: { securityGroupRule: string }) => { - const classes = useStyles(); - const { securityGroupRule } = props - return ( - - {(i) => } - - ) + const classes = useStyles() + const { securityGroupRule } = props + return ( + + {(i) => ( + + + + )} + + ) } const SecurityGroupRule = (props: { securityGroup: string }) => { - const classes = useStyles(); - const { securityGroup } = props - return ( - - {(i) => ( - <> - - - - - {toMenuItems(['http', 'tcp'])} - - - - )} - - ) + const classes = useStyles() + const { securityGroup } = props + return ( + + {(i) => ( + <> + + + + + {toMenuItems(['http', 'tcp'])} + + + + )} + + ) } const AdditionalIpWhitelistingForm = () => { - const classes = useStyles(); - const { values, setValues }: { values: any, setValues: any } = useFormikContext() - return ( - setValues(_m.addAdditionalIpWhitelisting(values))} - removeAction={() => setValues(_m.removeAdditionalIpWhitelisting(values))} > -
- - {(i) => ( - <> - - - - )} - -
-
- ) + const classes = useStyles() + const { values, setValues }: { values: any; setValues: any } = useFormikContext() + return ( + setValues(_m.addAdditionalIpWhitelisting(values))} + removeAction={() => setValues(_m.removeAdditionalIpWhitelisting(values))} + > +
+ + {(i) => ( + <> + + + + )} + +
+
+ ) } -export default AdditionalIpWhitelistingForm \ No newline at end of file +export default AdditionalIpWhitelistingForm diff --git a/src/coreform/AlertForm.tsx b/src/coreform/AlertForm.tsx index d1673a5..7a044e1 100644 --- a/src/coreform/AlertForm.tsx +++ b/src/coreform/AlertForm.tsx @@ -1,169 +1,197 @@ -import { AppBar, createStyles, makeStyles, styled, Tab, Tabs, Theme, withStyles } from '@material-ui/core'; +import { AppBar, createStyles, makeStyles, styled, Tab, Tabs, Theme, withStyles } from '@material-ui/core' import * as React from 'react' -import { tabA11yProps, TabPanel, toMenuItems } from './FormUtil'; +import { tabA11yProps, TabPanel, toMenuItems } from './FormUtil' import * as _m from '../models/Manifest' -import { FormikTextField } from '../components/common/FormikTextField'; -import { FormikCardList } from '../components/common/FormikCardList'; -import NotConfigured from './NotConfiguredPanel'; -import { useField, useFormikContext } from 'formik'; +import { FormikTextField } from '../components/common/FormikTextField' +import { FormikCardList } from '../components/common/FormikCardList' +import NotConfigured from './NotConfiguredPanel' +import { useField, useFormikContext } from 'formik' const useStyles = makeStyles((theme: Theme) => ({ - root: { - flexGrow: 1, - backgroundColor: theme.palette.background.paper, - }, - alertPanel: { - width: 1200 - }, -})); + root: { + flexGrow: 1, + backgroundColor: theme.palette.background.paper, + }, + alertPanel: { + width: 1200, + }, +})) const alertTypes = { - 'loadBalancer': ['http4xx', 'http5xx', 'elb4xx', 'elb5xx', 'latency'], - 'database': ['highActiveConnection', 'connectionAcquireTimeIsHigh', 'maxConnectionPoolReached'], - 'kafka': ['consumerGroupLag', 'kafkaMessageRate'], + loadBalancer: ['http4xx', 'http5xx', 'elb4xx', 'elb5xx', 'latency'], + database: ['highActiveConnection', 'connectionAcquireTimeIsHigh', 'maxConnectionPoolReached'], + kafka: ['consumerGroupLag', 'kafkaMessageRate'], } const severity = ['critical', 'warning'] const FixWidthTextField = styled(FormikTextField)({ - margin: 5, - width: 300 + margin: 5, + width: 300, }) interface StyledTabProps { - label: string; + label: string } -const commonAlerts = (i, alertType) => (<> - - {toMenuItems(alertTypes[alertType])} +const commonAlerts = (i, alertType) => ( + <> + + {toMenuItems(alertTypes[alertType])} - - {toMenuItems(severity)} + + {toMenuItems(severity)} - - - + + + ) const LoadBalancerAlert = () => { - const alertType = 'loadBalancer' - return ( - - {(i) => commonAlerts(i, alertType)} - - ) + const alertType = 'loadBalancer' + return ( + + {(i) => commonAlerts(i, alertType)} + + ) } const DatabaseAlert = () => { - const alertType = 'database' - return ( - - {(i) => commonAlerts(i, alertType)} - - ) + const alertType = 'database' + return ( + + {(i) => commonAlerts(i, alertType)} + + ) } const KafkaAlertGroupField = (props) => { - const { i } = props - const [kafkaAlertType] = useField(`deployment.alerts.kafka.${i}.type`) - if (kafkaAlertType.value === "consumerGroupLag") { - return - } else { - return <> - } + const { i } = props + const [kafkaAlertType] = useField(`deployment.alerts.kafka.${i}.type`) + if (kafkaAlertType.value === 'consumerGroupLag') { + return + } else { + return <> + } } const KafkaAlert = () => { - const alertType = 'kafka' - return ( - - {(i) => (<> - {commonAlerts(i, alertType)} - - - )} - - ) + const alertType = 'kafka' + return ( + + {(i) => ( + <> + {commonAlerts(i, alertType)} + + + + )} + + ) } const RecordingRules = () => { - const alertType = 'prometheusRecordingRule' - const classes = useStyles(); - const { values, setValues }: { values: any, setValues: any } = useFormikContext() - return ( - - {(i) => (<> - - - - - )} - - ) + const alertType = 'prometheusRecordingRule' + const classes = useStyles() + const { values, setValues }: { values: any; setValues: any } = useFormikContext() + return ( + + {(i) => ( + <> + + + + + + )} + + ) } const CustomAlert = () => { - const alertType = 'custom' - return ( - - {(i) => (<> - - - - - - - {toMenuItems(severity)} - - )} - - ) + const alertType = 'custom' + return ( + + {(i) => ( + <> + + + + + + + {toMenuItems(severity)} + + + )} + + ) } const AlertForm = () => { - const classes = useStyles(); - const { values, setValues }: { values: any, setValues: any } = useFormikContext() - const [currentTab, setCurrentTab] = React.useState(0); + const classes = useStyles() + const { values, setValues }: { values: any; setValues: any } = useFormikContext() + const [currentTab, setCurrentTab] = React.useState(0) - const handleTabChange = (event: React.ChangeEvent<{}>, newTab: number) => { - setCurrentTab(newTab); - }; - return ( - setValues(_m.addAlerts(values))} - removeAction={() => setValues(_m.removeAlerts(values))} > - -
- - - - - - - - - - -
-
- -
-
- -
-
- -
-
- -
-
- -
-
- ) + const handleTabChange = (event: React.ChangeEvent<{}>, newTab: number) => { + setCurrentTab(newTab) + } + return ( + setValues(_m.addAlerts(values))} + removeAction={() => setValues(_m.removeAlerts(values))} + > +
+ + + + + + + + + + +
+ +
+
+ +
+ +
+
+ +
+ +
+
+ +
+ +
+
+ +
+ +
+
+
+
+ ) } -export default AlertForm \ No newline at end of file +export default AlertForm diff --git a/src/coreform/AutoscalingCard.tsx b/src/coreform/AutoscalingCard.tsx index 0a5dbf8..7350d3e 100644 --- a/src/coreform/AutoscalingCard.tsx +++ b/src/coreform/AutoscalingCard.tsx @@ -1,89 +1,159 @@ -import * as React from 'react'; -import {makeStyles, Typography, Box, TableCell, Tooltip} from '@material-ui/core'; -import { FormikTextField } from '../components/common/FormikTextField'; -import { toMenuItems } from './FormUtil'; +import * as React from 'react' +import { makeStyles, Typography, Box, TableCell, Tooltip } from '@material-ui/core' +import { FormikTextField } from '../components/common/FormikTextField' +import { toMenuItems } from './FormUtil' import * as _m from '../models/Manifest' -import { FormikTable } from '../components/common/FormikTable'; -import { FormikCardList } from '../components/common/FormikCardList'; +import { FormikTable } from '../components/common/FormikTable' +import { FormikCardList } from '../components/common/FormikCardList' import { cardStyles, boxStyleProps } from './Styles' -import CardLayout from '../components/common/CardLayout'; -import {FormikSelect} from "../components/common/FormikSelect"; +import CardLayout from '../components/common/CardLayout' +import { FormikSelect } from '../components/common/FormikSelect' const useStyles = makeStyles(() => { - return { - ...cardStyles, - boxTableField: { - width: 170 - }, - } -}); + return { + ...cardStyles, + boxTableField: { + width: 170, + }, + } +}) const ScalingParameters = () => { - const classes = useStyles(); - return ( - - Scaling Parameters (CPU or Memory) - - {(i) => <> - {toMenuItems(['cpu', 'memory'])} - - } - - - ) + const classes = useStyles() + return ( + + + Scaling Parameters (CPU or Memory) + + + {(i) => ( + <> + + {' '} + + {' '} + {toMenuItems(['cpu', 'memory'])}{' '} + {' '} + + + {' '} + {' '} + + + )} + + + ) } const ScalingParametersAdvanced = () => { - const classes = useStyles(); - return ( - - Scaling Parameters (Advanced) - - {(i) => <> - - - - } - - - ) + const classes = useStyles() + return ( + + + Scaling Parameters (Advanced){' '} + + + {(i) => ( + <> + + + + + )} + + + ) } const Replicas = () => { - const classes = useStyles(); - return ( - - Replicas Count - - - - ) + const classes = useStyles() + return ( + + + Replicas Count + + + + + ) } const CronHPAAutoscaling = () => { - const classes = useStyles(); - return ( - - Schedule Autoscaling - - {(i) => <> - {toMenuItems(['ScaleDown', 'ScaleUp'])} - - } - - - ) + const classes = useStyles() + return ( + + + Schedule Autoscaling + + + {(i) => ( + <> + + {' '} + + {toMenuItems(['ScaleDown', 'ScaleUp'])}{' '} + {' '} + + + {' '} + {' '} + + + )} + + + ) } const AutoscalingCard = () => { - return ( - - - - - - - ) + return ( + + + + + + + ) } -export default AutoscalingCard \ No newline at end of file +export default AutoscalingCard diff --git a/src/coreform/BaseForm.tsx b/src/coreform/BaseForm.tsx index 6d11e00..47796ef 100644 --- a/src/coreform/BaseForm.tsx +++ b/src/coreform/BaseForm.tsx @@ -1,25 +1,25 @@ -import * as React from 'react'; -import {makeStyles, Theme} from '@material-ui/core/styles'; -import Tabs from '@material-ui/core/Tabs'; -import Tab from '@material-ui/core/Tab'; +import * as React from 'react' +import { makeStyles, Theme } from '@material-ui/core/styles' +import Tabs from '@material-ui/core/Tabs' +import Tab from '@material-ui/core/Tab' import ManifestForm from './ManifestForm' import DatabaseForm from './DatabaseForm' import ElasticCacheForm from './ElasticCacheForm' import * as _m from '../models/Manifest' -import {Form, Formik, validateYupSchema, yupToFormErrors} from 'formik'; -import {manifestValidationSchema} from "../models/ManifestValidationSchema"; -import {tabA11yProps, TabPanel} from './FormUtil'; -import Configuration from './ConfigurationForm'; -import S3BucketForm from './S3BucketForm'; -import {Button, Divider, Snackbar, Typography} from '@material-ui/core'; -import {Alert} from "@material-ui/lab"; -import DeploymentForm from './DeploymentForm'; -import AWSAccessForm from './AWSAccessForm'; -import ServiceMonitorForm from "./ServiceMonitorForm"; -import DocumentDbForm from "./DocumentDbForm"; -import ElasticSearchForm from "./ElasticSearchForm"; -import { Dispatch, SetStateAction } from 'react'; -import DynamoDbForm from "./DynamoDbForm"; +import { Form, Formik, validateYupSchema, yupToFormErrors } from 'formik' +import { manifestValidationSchema } from '../models/ManifestValidationSchema' +import { tabA11yProps, TabPanel } from './FormUtil' +import Configuration from './ConfigurationForm' +import S3BucketForm from './S3BucketForm' +import { Button, Divider, Snackbar, Typography } from '@material-ui/core' +import { Alert } from '@material-ui/lab' +import DeploymentForm from './DeploymentForm' +import AWSAccessForm from './AWSAccessForm' +import ServiceMonitorForm from './ServiceMonitorForm' +import DocumentDbForm from './DocumentDbForm' +import ElasticSearchForm from './ElasticSearchForm' +import { Dispatch, SetStateAction } from 'react' +import DynamoDbForm from './DynamoDbForm' const useStyles = makeStyles((theme: Theme) => ({ root: { flexGrow: 1, @@ -29,12 +29,12 @@ const useStyles = makeStyles((theme: Theme) => ({ tabs: { borderRight: `1px solid ${theme.palette.divider}`, }, -})); +})) interface BaseFormProps { - initData: any, - setFormInitData: Dispatch>, - onSubmit: (values: any, setCanSubmit: Dispatch>) => void, + initData: any + setFormInitData: Dispatch> + onSubmit: (values: any, setCanSubmit: Dispatch>) => void } interface FormTab { @@ -55,55 +55,55 @@ const tabList: Array = [ name: 'database', displayName: 'database', component: , - errorCheckFn: _m.hasDatabase + errorCheckFn: _m.hasDatabase, }, { name: 'docdb', displayName: 'document db', component: , - errorCheckFn: _m.hasDatabase + errorCheckFn: _m.hasDatabase, }, { name: 'elastic Cache', displayName: 'elastic Cache', component: , - errorCheckFn: _m.hasElasticCache + errorCheckFn: _m.hasElasticCache, }, { name: 's3 bucket', displayName: 's3 bucket', component: , - errorCheckFn: _m.hasS3Bucket + errorCheckFn: _m.hasS3Bucket, }, { name: 'configuration', displayName: 'configuration', component: , - errorCheckFn: _m.hasConfiguration + errorCheckFn: _m.hasConfiguration, }, { name: 'aws access', displayName: 'aws access', component: , - errorCheckFn: _m.hasAwsAccess + errorCheckFn: _m.hasAwsAccess, }, { name: 'Service Monitor', displayName: 'service monitor', component: , - errorCheckFn: _m.hasServiceMonitor + errorCheckFn: _m.hasServiceMonitor, }, { name: 'Elastic Search', displayName: 'elastic search', component: , - errorCheckFn: _m.hasElasticSearch + errorCheckFn: _m.hasElasticSearch, }, { name: 'DynamoDB', displayName: 'DynamoDB', component: , - errorCheckFn: _m.hasDynamoDb + errorCheckFn: _m.hasDynamoDb, }, ] @@ -116,35 +116,33 @@ const ErrorSnackBar = (props: { errors: any }) => { const errorData = Object.entries(errors).slice(0, 4) return ( 0} autoHideDuration={5000}> - + {errorData.map((data, idx) => { return ( - - { JSON.stringify(data)} + + {JSON.stringify(data)} - ); + ) })} - ) + + ) } const BaseForm = (props: BaseFormProps) => { - const classes = useStyles(); - const [currentTab, setCurrentTab] = React.useState(0); + const classes = useStyles() + const [currentTab, setCurrentTab] = React.useState(0) const { initData, onSubmit } = props - const setFormInitData = props.setFormInitData; + const setFormInitData = props.setFormInitData const [manifestVersion, setManifestVersion] = React.useState() - const [versionListData, setVersionListData] = React.useState([]); + const [versionListData, setVersionListData] = React.useState([]) const [isSubmitButtonDisabled, disableSubmitButton] = React.useState(false) const isDisabled = () => { - if (!isSubmitButtonDisabled && - (manifestVersion === Math.max(...versionListData) - || manifestVersion === undefined - || manifestVersion === 'None')) { + if ( + !isSubmitButtonDisabled && + (manifestVersion === Math.max(...versionListData) || manifestVersion === undefined || manifestVersion === 'None') + ) { disableSubmitButton(false) } else { disableSubmitButton(true) @@ -153,8 +151,8 @@ const BaseForm = (props: BaseFormProps) => { } const handleTabChange = (e: React.ChangeEvent<{}>, newValue: number) => { - setCurrentTab(newValue); - }; + setCurrentTab(newValue) + } return (
@@ -162,61 +160,72 @@ const BaseForm = (props: BaseFormProps) => { enableReinitialize initialValues={initData} validate={async (value) => { - try { - await validateYupSchema(value, manifestValidationSchema, false, value); - } catch (err) { - return yupToFormErrors(err); //for rendering validation errors - } - return {}; + try { + await validateYupSchema(value, manifestValidationSchema, false, value) + } catch (err) { + return yupToFormErrors(err) // for rendering validation errors + } + return {} }} validateOnChange={false} - onSubmit={values => { - disableSubmitButton(true); - onSubmit(values, disableSubmitButton); - }} > - { - props => ( -
- - -
- - { - tabList.map((tab, index) => ( - - )) - } - - { - tabList.map((tab, index) => ( - - {tab.component} - - )) - } -
- - {/**/} - - - ) - } + onSubmit={(values) => { + disableSubmitButton(true) + onSubmit(values, disableSubmitButton) + }} + > + {(props) => ( +
+ + +
+ + {tabList.map((tab, index) => ( + + ))} + + {tabList.map((tab, index) => ( + + {tab.component} + + ))} +
+ + {/* */} + + + )}
- ); + ) } export default BaseForm diff --git a/src/coreform/CloneManifestForm.tsx b/src/coreform/CloneManifestForm.tsx index 22d8a57..b5ab0b1 100644 --- a/src/coreform/CloneManifestForm.tsx +++ b/src/coreform/CloneManifestForm.tsx @@ -1,147 +1,132 @@ -import React, {useState} from "react"; -import {withCookies} from "react-cookie"; -import {toMenuItems} from './FormUtil'; -import {makeStyles} from "@material-ui/core/styles"; -import * as _m from '../models/Manifest'; -import {Button,Grid,Snackbar} from "@material-ui/core"; -import {Form, Formik} from "formik"; -import {FormikTextField} from "../components/common/FormikTextField" -import {cardStyles, text} from "../coreform/Styles"; -import {toast} from "react-toastify"; -import {getFormattedRuntimeException, post} from "../helper/api-client"; -import { FormikCheckbox } from "../components/common/FormikCheckbox"; -import * as yup from "yup"; -import {useHistory} from "react-router-dom"; -const { useRef } = React; -import FormControlLabel from "@material-ui/core/FormControlLabel"; -import {Alert} from "@material-ui/lab"; +import React, { useState } from 'react' +import { withCookies } from 'react-cookie' +import { toMenuItems } from './FormUtil' +import { makeStyles } from '@material-ui/core/styles' +import * as _m from '../models/Manifest' +import { Button, Grid, Snackbar } from '@material-ui/core' +import { Form, Formik } from 'formik' +import { FormikTextField } from '../components/common/FormikTextField' +import { cardStyles, text } from '../coreform/Styles' +import { toast } from 'react-toastify' +import { getFormattedRuntimeException, post } from '../helper/api-client' +import { FormikCheckbox } from '../components/common/FormikCheckbox' +import * as yup from 'yup' +import { useHistory } from 'react-router-dom' +const { useRef } = React +import FormControlLabel from '@material-ui/core/FormControlLabel' +import { Alert } from '@material-ui/lab' - -const API_PATH = '/api/manifest/clone'; +const API_PATH = '/api/manifest/clone' const useStyles = makeStyles({ - ...cardStyles, - text, - root: { - minWidth: 500, - padding: '2px', - display: 'inline-block', - margin: '4px' - }, - field: { - marginTop: 20, - width: '100%' - }, -}); + ...cardStyles, + text, + root: { + minWidth: 500, + padding: '2px', + display: 'inline-block', + margin: '4px', + }, + field: { + marginTop: 20, + width: '100%', + }, +}) const initialFormValues = { - name: "", - environment: "", - teamName: "", - copyEnvVariables: false, - copyOutbound: false, - manifestId: 0 - }; + name: '', + environment: '', + teamName: '', + copyEnvVariables: false, + copyOutbound: false, + manifestId: 0, +} const CloneForm = (props: any) => { - const classes = useStyles(); - const [formValues, setFormValues] = useState(initialFormValues); - const [submitResponse, setSubmitResponse] = useState(""); - const [submitResponseStatus, setSubmitResponseStatus] = useState(""); - const apiResponse = useRef(""); - const history = useHistory(); + const classes = useStyles() + const [formValues, setFormValues] = useState(initialFormValues) + const [submitResponse, setSubmitResponse] = useState('') + const [submitResponseStatus, setSubmitResponseStatus] = useState('') + const apiResponse = useRef('') + const history = useHistory() - const submitManifest = (cloneManifest: any) => { - console.log(props.clone); - - const toastId = toast.info("In Progress ...", { - autoClose: 50000, - }); - cloneManifest.manifestId = props.clone; - let path =`/manifests/create?copyId=`+props.clone - post(cloneManifest, API_PATH).then((r) => { - r.json().then((resJson) => { - if (r.ok) { - toast.update(toastId, { - render: "Updated", - type: "success", - autoClose: 3000, - }); - history.push(path , { cloneValues: resJson }); - apiResponse.current = ""; - } else { - toast.dismiss(toastId); - setSubmitResponseStatus("error"); - setSubmitResponse(getFormattedRuntimeException(resJson)); - } - }); - }); - } + const submitManifest = (cloneManifest: any) => { + console.log(props.clone) - return ( -
- { - submitManifest(values) - }}> - {props => ( -
- - - - {toMenuItems(_m.environments)} - - - {toMenuItems(_m.teams)} - - - - - } - label="Copy Environment variables" - /> - - } - label="Copy Outbound" - /> - - - - -
- ) - } -
- setSubmitResponseStatus("")} - > - {JSON.stringify(submitResponse)} - -
- ); + const toastId = toast.info('In Progress ...', { + autoClose: 50000, + }) + cloneManifest.manifestId = props.clone + const path = '/manifests/create?copyId=' + props.clone + post(cloneManifest, API_PATH).then((r) => { + r.json().then((resJson) => { + if (r.ok) { + toast.update(toastId, { + render: 'Updated', + type: 'success', + autoClose: 3000, + }) + history.push(path, { cloneValues: resJson }) + apiResponse.current = '' + } else { + toast.dismiss(toastId) + setSubmitResponseStatus('error') + setSubmitResponse(getFormattedRuntimeException(resJson)) + } + }) + }) + } + + return ( +
+ { + submitManifest(values) + }} + > + {(props) => ( +
+ + + + {toMenuItems(_m.environments)} + + + {toMenuItems(_m.teams)} + + + + } + label='Copy Environment variables' + /> + } label='Copy Outbound' /> + + + + +
+ )} +
+ setSubmitResponseStatus('')} + > + {JSON.stringify(submitResponse)} + +
+ ) } -export default withCookies(CloneForm); - - +export default withCookies(CloneForm) export const cloneFormValidationSchema = yup.object({ - name: yup.string().required('is Required'), - environment: yup.string().required('is Required'), - teamName: yup.string().required('is Required') + name: yup.string().required('is Required'), + environment: yup.string().required('is Required'), + teamName: yup.string().required('is Required'), }) diff --git a/src/coreform/ConfigurationForm.tsx b/src/coreform/ConfigurationForm.tsx index 44c9d83..289b2c8 100644 --- a/src/coreform/ConfigurationForm.tsx +++ b/src/coreform/ConfigurationForm.tsx @@ -1,36 +1,35 @@ -import * as React from 'react'; -import { useFormikContext } from 'formik'; +import * as React from 'react' +import { useFormikContext } from 'formik' import * as _m from '../models/Manifest' -import { AppBar, Tab, Tabs } from '@material-ui/core'; -import { tabA11yProps, TabPanel } from './FormUtil'; -import EnvironmentVariablesForm from './EnvironmentVariablesForm'; -import DynamicConfigurationForm from './DynamicConfig'; +import { AppBar, Tab, Tabs } from '@material-ui/core' +import { tabA11yProps, TabPanel } from './FormUtil' +import EnvironmentVariablesForm from './EnvironmentVariablesForm' +import DynamicConfigurationForm from './DynamicConfig' const ConfigurationForm = () => { - const { values, setValues }: { values: any, setValues: any } = useFormikContext() - const [currentTab, setCurrentTab] = React.useState(0); + const { values, setValues }: { values: any; setValues: any } = useFormikContext() + const [currentTab, setCurrentTab] = React.useState(0) - const handleTabChange = (event: React.ChangeEvent<{}>, newTab: number) => { - setCurrentTab(newTab); - }; - - return ( - <> - - - - - - - - - - - - - - ) + const handleTabChange = (event: React.ChangeEvent<{}>, newTab: number) => { + setCurrentTab(newTab) + } + return ( + <> + + + + + + + + + + + + + + ) } export default ConfigurationForm diff --git a/src/coreform/DatabaseForm.tsx b/src/coreform/DatabaseForm.tsx index caf4814..531fb1c 100644 --- a/src/coreform/DatabaseForm.tsx +++ b/src/coreform/DatabaseForm.tsx @@ -1,8 +1,8 @@ -import * as React from "react"; -import { FormikTable } from "../components/common/FormikTable"; -import { FormikTextField } from "../components/common/FormikTextField"; -import { toMenuItems } from "./FormUtil"; -import * as _m from "../models/Manifest"; +import * as React from 'react' +import { FormikTable } from '../components/common/FormikTable' +import { FormikTextField } from '../components/common/FormikTextField' +import { toMenuItems } from './FormUtil' +import * as _m from '../models/Manifest' import { FormControlLabel, Grid, @@ -17,16 +17,16 @@ import { TableHead, TableRow, Tooltip, -} from "@material-ui/core"; -import FormikMultiSelect from "../components/common/FormikMultiSelect"; -import { cardStyles } from "./Styles"; -import {useField, useFormikContext} from "formik"; -import NotConfigured from "./NotConfiguredPanel"; -import { FormikCheckbox } from "../components/common/FormikCheckbox"; -import AddRemoveButton from "../components/common/AddRemoveButton"; -import CardLayout from "../components/common/CardLayout"; -import { EnvironmentVariable } from "./Types"; -import GeneratePipelineButton from "../components/common/GeneratePipelineButton"; +} from '@material-ui/core' +import FormikMultiSelect from '../components/common/FormikMultiSelect' +import { cardStyles } from './Styles' +import { useField, useFormikContext } from 'formik' +import NotConfigured from './NotConfiguredPanel' +import { FormikCheckbox } from '../components/common/FormikCheckbox' +import AddRemoveButton from '../components/common/AddRemoveButton' +import CardLayout from '../components/common/CardLayout' +import { EnvironmentVariable } from './Types' +import GeneratePipelineButton from '../components/common/GeneratePipelineButton' const useStyles = makeStyles({ ...cardStyles, @@ -37,82 +37,82 @@ const useStyles = makeStyles({ width: 185, }, button: { - float: "right", + float: 'right', marginRight: 10, }, gridRow: { width: 1200, }, -}); +}) const rdsAlertFields = [ - { field: "cpuUtilization", label: "cpuUtilization(percent)" }, - { field: "cpuCreditBalance", label: "cpuCreditBalance(credit)" }, - { field: "burstBalance", label: "burstBalance(percent)" }, - { field: "dbConnections", label: "dbConnections(integer)" }, - { field: "queueDepth", label: "queueDepth(iops)" }, + { field: 'cpuUtilization', label: 'cpuUtilization(percent)' }, + { field: 'cpuCreditBalance', label: 'cpuCreditBalance(credit)' }, + { field: 'burstBalance', label: 'burstBalance(percent)' }, + { field: 'dbConnections', label: 'dbConnections(integer)' }, + { field: 'queueDepth', label: 'queueDepth(iops)' }, { - field: "freeStorageSpacePercent", - label: "freeStorageSpacePercent(percent)", + field: 'freeStorageSpacePercent', + label: 'freeStorageSpacePercent(percent)', }, - { field: "freeMemoryTooLowInMB", label: "freeMemoryTooLowInMB(MB)" }, - { field: "readLatency", label: "readLatency(ms)" }, - { field: "writeLatency", label: "writeLatency(ms)" }, -]; -const rdsAlertHeaders = ["Metric", "Threshold", "Duration\n(minutes)"]; + { field: 'freeMemoryTooLowInMB', label: 'freeMemoryTooLowInMB(MB)' }, + { field: 'readLatency', label: 'readLatency(ms)' }, + { field: 'writeLatency', label: 'writeLatency(ms)' }, +] +const rdsAlertHeaders = ['Metric', 'Threshold', 'Duration\n(minutes)'] const gravitonInstanceClass = [ - "db.t4g.nano", - "db.t4g.micro", - "db.t4g.small", - "db.t4g.medium", - "db.t4g.large", - "db.t4g.xlarge", - "db.t4g.2xlarge", - "db.m6g.large", - "db.m6g.xlarge", - "db.m6g.2xlarge", - "db.m6g.4xlarge", - "db.m6g.12xlarge", - "db.m6g.16xlarge", -]; + 'db.t4g.nano', + 'db.t4g.micro', + 'db.t4g.small', + 'db.t4g.medium', + 'db.t4g.large', + 'db.t4g.xlarge', + 'db.t4g.2xlarge', + 'db.m6g.large', + 'db.m6g.xlarge', + 'db.m6g.2xlarge', + 'db.m6g.4xlarge', + 'db.m6g.12xlarge', + 'db.m6g.16xlarge', +] const intelInstanceClasses = [ - "db.t3.micro", - "db.t3.small", - "db.t3.medium", - "db.t3.large", - "db.t3.xlarge", - "db.t3.2xlarge", - "db.m5.large", - "db.m5.xlarge", - "db.m5.2xlarge", - "db.m5.4xlarge", - "db.m5.12xlarge", - "db.m5.24xlarge", -]; + 'db.t3.micro', + 'db.t3.small', + 'db.t3.medium', + 'db.t3.large', + 'db.t3.xlarge', + 'db.t3.2xlarge', + 'db.m5.large', + 'db.m5.xlarge', + 'db.m5.2xlarge', + 'db.m5.4xlarge', + 'db.m5.12xlarge', + 'db.m5.24xlarge', +] const awsInstanceClasses = { - "11": [...gravitonInstanceClass, ...intelInstanceClasses], - "13": gravitonInstanceClass -}; -const databaseExtensions = ["pgcrypto", "uuid-ossp", "postgis"]; -const psqlEngineVersion = ["11", "13"]; + '11': [...gravitonInstanceClass, ...intelInstanceClasses], + '13': gravitonInstanceClass, +} +const databaseExtensions = ['pgcrypto', 'uuid-ossp', 'postgis'] +const psqlEngineVersion = ['11', '13'] const MarginedTextField = styled(FormikTextField)({ marginBottom: 10, -}); +}) const MarginedFormControlLabel = styled(FormControlLabel)({ marginBottom: 10, width: 400, -}); +}) const DbParameters = () => { - const classes = useStyles(); + const classes = useStyles() return ( {(i) => ( @@ -124,201 +124,149 @@ const DbParameters = () => { className={classes.tableField} > {toMenuItems([ - "rds.logical_replication", - "log_lock_waits", - "shared_preload_libraries", - "auto_explain.log_analyze", - "auto_explain.log_min_duration", + 'rds.logical_replication', + 'log_lock_waits', + 'shared_preload_libraries', + 'auto_explain.log_analyze', + 'auto_explain.log_min_duration', ])} - + )} - ); -}; + ) +} const DbSchemaNames = () => { - const classes = useStyles(); + const classes = useStyles() return ( {(i) => ( - + )} - ); -}; + ) +} -const toEnvironmentKeys = ( - environmentVariables: Array, - environmentVariableType: string -) => { +const toEnvironmentKeys = (environmentVariables: Array, environmentVariableType: string) => { return environmentVariables .filter( - (environmentVariable) => - environmentVariableType === "" || - environmentVariable.type === environmentVariableType + (environmentVariable) => environmentVariableType === '' || environmentVariable.type === environmentVariableType, ) .map((environmentVariable) => ( - + {environmentVariable.name} - )); -}; + )) +} -const SelectEnvironmentVariableField = (props: { - label: string; - name: string; - type: string; -}) => { - const [environmentVariables] = useField("environmentVariables"); +const SelectEnvironmentVariableField = (props: { label: string; name: string; type: string }) => { + const [environmentVariables] = useField('environmentVariables') return ( {toEnvironmentKeys(environmentVariables.value, props.type)} - ); -}; + ) +} const DatabaseConfiguration = () => { - const { values, setFieldValue }: { values: any, setFieldValue: any } = useFormikContext(); - return ( - - + const { values, setFieldValue }: { values: any; setFieldValue: any } = useFormikContext() + return ( + + + + + - - - - + { - setFieldValue("extraResources.database.PsqlEngineVersion", e.target.value) - setFieldValue("extraResources.database.awsInstanceClass", "db.t4g.micro") + onChange={(e) => { + setFieldValue('extraResources.database.PsqlEngineVersion', e.target.value) + setFieldValue('extraResources.database.awsInstanceClass', 'db.t4g.micro') if (_m.hasDatabaseReadReplica(values)) { - setFieldValue("extraResources.database.readReplica.awsInstanceClass", "db.t4g.nano") + setFieldValue('extraResources.database.readReplica.awsInstanceClass', 'db.t4g.nano') } }} > {toMenuItems(psqlEngineVersion)} - + {toMenuItems(awsInstanceClasses[values.extraResources.database.PsqlEngineVersion])} - ); -}; + ) +} const DatabaseAdvancedConfiguration = () => { - const classes = useStyles(); - const [extraResourcesId] = useField("extraResources.id"); + const classes = useStyles() + const [extraResourcesId] = useField('extraResources.id') return ( - + - } - label="Apply Immediately" + control={} + label='Apply Immediately' /> - } - label="Performance Insights" + control={} + label='Performance Insights' /> {extraResourcesId.value !== undefined ? ( - } - label="Storage Encryption" + control={} + label='Storage Encryption' /> ) : null} - } - label="Disable Multi-AZ" + control={} + label='Disable Multi-AZ' /> {toMenuItems(databaseExtensions)} - ); -}; + ) +} const DatabaseAlerts = () => { return ( - + - +
{rdsAlertHeaders.map((header, i) => ( @@ -331,16 +279,10 @@ const DatabaseAlerts = () => { {label} - + - + ))} @@ -348,78 +290,60 @@ const DatabaseAlerts = () => {
- ); -}; + ) +} const DatabaseReplicas = () => { - const classes = useStyles(); - const { values }: { values: any } = useFormikContext(); - const [field, , fieldHelper] = useField( - "extraResources.database.readReplica" - ); - const isReadReplicaDefined = field.value !== undefined; + const classes = useStyles() + const { values }: { values: any } = useFormikContext() + const [field, , fieldHelper] = useField('extraResources.database.readReplica') + const isReadReplicaDefined = field.value !== undefined return ( - + { - fieldHelper.setValue(_m.newReadReplica()); + fieldHelper.setValue(_m.newReadReplica()) }} removeAction={() => { - fieldHelper.setValue(undefined); + fieldHelper.setValue(undefined) }} > {isReadReplicaDefined ? ( <> {toMenuItems(awsInstanceClasses[values.extraResources.database.PsqlEngineVersion])} - } - label="Performance Insights" + control={} + label='Performance Insights' /> ) : null} - ); -}; + ) +} const DatabaseForm = () => { - const { - values, - setValues, - }: { values: any; setValues: any } = useFormikContext(); - const classes = useStyles(); + const { values, setValues }: { values: any; setValues: any } = useFormikContext() + const classes = useStyles() return ( <> setValues(_m.addDatabase(values))} removeAction={() => setValues(_m.removeDatabase(values))} > - - + + @@ -432,15 +356,14 @@ const DatabaseForm = () => { <> - {values.extraResources !== undefined && - values.extraResources.database !== undefined ? ( - + {values.extraResources !== undefined && values.extraResources.database !== undefined ? ( + ) : ( - "" + '' )} - ); -}; + ) +} -export default DatabaseForm; +export default DatabaseForm diff --git a/src/coreform/DeploymentBasicTab.tsx b/src/coreform/DeploymentBasicTab.tsx index 725ad1c..bfcf391 100644 --- a/src/coreform/DeploymentBasicTab.tsx +++ b/src/coreform/DeploymentBasicTab.tsx @@ -1,10 +1,10 @@ -import * as React from "react"; -import Grid from "@material-ui/core/Grid"; -import { toMenuItems } from "./FormUtil"; -import * as _m from "../models/Manifest"; -import { FormikTextField } from "../components/common/FormikTextField"; -import { FormikAutocomplete } from "../components/common/FormikAutocomplete"; -import { useFormikContext, Field } from "formik"; +import * as React from 'react' +import Grid from '@material-ui/core/Grid' +import { toMenuItems } from './FormUtil' +import * as _m from '../models/Manifest' +import { FormikTextField } from '../components/common/FormikTextField' +import { FormikAutocomplete } from '../components/common/FormikAutocomplete' +import { useFormikContext, Field } from 'formik' import { Box, makeStyles, @@ -14,16 +14,16 @@ import { TextField, styled, FormControlLabel, -} from "@material-ui/core"; -import { FormikTable } from "../components/common/FormikTable"; -import HealthCheckCard from "./HealthCheckCard"; -import { boxStyleProps, cardStyles } from "./Styles"; -import AutoscalingCard from "./AutoscalingCard"; -import CardLayout from "../components/common/CardLayout"; -import { useEffect, useState } from "react"; -import { httpClient } from "../helper/api-client"; -import { Autocomplete } from "@material-ui/lab"; -import { FormikCheckbox } from "../components/common/FormikCheckbox"; +} from '@material-ui/core' +import { FormikTable } from '../components/common/FormikTable' +import HealthCheckCard from './HealthCheckCard' +import { boxStyleProps, cardStyles } from './Styles' +import AutoscalingCard from './AutoscalingCard' +import CardLayout from '../components/common/CardLayout' +import { useEffect, useState } from 'react' +import { httpClient } from '../helper/api-client' +import { Autocomplete } from '@material-ui/lab' +import { FormikCheckbox } from '../components/common/FormikCheckbox' const useStyles = makeStyles({ ...cardStyles, @@ -36,7 +36,7 @@ const useStyles = makeStyles({ card: { marginBottom: 10, width: 300, - border: "5px solid #E8E8E8", + border: '5px solid #E8E8E8', }, twoFieldBigCard: { width: 180, @@ -51,25 +51,25 @@ const useStyles = makeStyles({ gridRow: { width: 1200, }, -}); +}) const MarginedFormControlLabel = styled(FormControlLabel)({ marginBottom: 10, width: 400, -}); +}) const ClusterCard = () => { - const classes = useStyles(); - const { values }: { values: any } = useFormikContext(); + const classes = useStyles() + const { values }: { values: any } = useFormikContext() const isDeployed: boolean = values?.deployment?.isDeployed return ( - + {toMenuItems(_m.clusters)} @@ -77,62 +77,47 @@ const ClusterCard = () => { - {toMenuItems(_m.getProp( _m.teamNamespace, [values?.team.name, values?.environment]) || _m.namespaces[values?.environment] || [])} + {toMenuItems( + _m.getProp(_m.teamNamespace, [values?.team.name, values?.environment]) || + _m.namespaces[values?.environment] || + [], + )} - ); -}; + ) +} const InstanceCard = () => { - const classes = useStyles(); + const classes = useStyles() return ( - - - + + + - ); -}; + ) +} const ExposedPortsCard = () => { - const classes = useStyles(); + const classes = useStyles() return ( - - + + {(i) => ( <> - + {toMenuItems(_m.portTypes)} @@ -140,19 +125,19 @@ const ExposedPortsCard = () => { )} - ); -}; + ) +} const OutboundConnectivityCard = (props) => { - const classes = useStyles(); + const classes = useStyles() return ( - + {(i) => ( @@ -170,75 +155,58 @@ const OutboundConnectivityCard = (props) => { )} - ); -}; + ) +} const PerfUtilityCard = () => { - const classes = useStyles(); - const { values }: { values: any } = useFormikContext(); + const classes = useStyles() + const { values }: { values: any } = useFormikContext() return ( - + - } - label="Perf Mock Server" + control={} + label='Perf Mock Server' /> - } - label="Perf Postgres Server" + control={} + label='Perf Postgres Server' /> - ); -}; + ) +} const DeploymentBasicTab = () => { - const [serviceEntries, setServiceEntries] = useState>([]); - const [FetchError, setFetchError] = useState({}); + const [serviceEntries, setServiceEntries] = useState>([]) + const [FetchError, setFetchError] = useState({}) - const classes = useStyles(); - const { values }: { values: any } = useFormikContext(); - const cluster = values?.deployment?.cluster; - const environmentFlag = values?.environment; + const classes = useStyles() + const { values }: { values: any } = useFormikContext() + const cluster = values?.deployment?.cluster + const environmentFlag = values?.environment const getServiceEntries = async (cluster: string): Promise => { - return httpClient(`/api/kube/allowedEndpoint?cluster=${cluster}`); - }; + return httpClient(`/api/kube/allowedEndpoint?cluster=${cluster}`) + } useEffect(() => { getServiceEntries(cluster).then((res) => res.json().then((resJson) => { if (res.ok) { - setServiceEntries(resJson); + setServiceEntries(resJson) } else { - setFetchError(resJson); + setFetchError(resJson) } - }) - ); - }, [cluster]); + }), + ) + }, [cluster]) return ( - - + + - {environmentFlag === 'perf' && ( - - )} + {environmentFlag === 'perf' && } @@ -248,7 +216,7 @@ const DeploymentBasicTab = () => { - ); -}; + ) +} -export default DeploymentBasicTab; +export default DeploymentBasicTab diff --git a/src/coreform/DeploymentForm.tsx b/src/coreform/DeploymentForm.tsx index 7248c1a..5bb3eb5 100644 --- a/src/coreform/DeploymentForm.tsx +++ b/src/coreform/DeploymentForm.tsx @@ -1,55 +1,55 @@ -import * as React from 'react'; -import NotConfigured from './NotConfiguredPanel'; -import { useFormikContext } from 'formik'; +import * as React from 'react' +import NotConfigured from './NotConfiguredPanel' +import { useFormikContext } from 'formik' import * as _m from '../models/Manifest' -import DeploymentBasicTab from './DeploymentBasicTab'; -import { AppBar, Tab, Tabs } from '@material-ui/core'; -import { tabA11yProps, TabPanel } from './FormUtil'; -import AlertForm from './AlertForm'; -import LoadBalancerForm from './LoadBalancerForm'; -import DeploymentStrategyForm from './DeploymentStrategyForm'; +import DeploymentBasicTab from './DeploymentBasicTab' +import { AppBar, Tab, Tabs } from '@material-ui/core' +import { tabA11yProps, TabPanel } from './FormUtil' +import AlertForm from './AlertForm' +import LoadBalancerForm from './LoadBalancerForm' +import DeploymentStrategyForm from './DeploymentStrategyForm' const DeploymentForm = () => { - const { values, setValues }: { values: any, setValues: any } = useFormikContext() - const [currentTab, setCurrentTab] = React.useState(0); + const { values, setValues }: { values: any; setValues: any } = useFormikContext() + const [currentTab, setCurrentTab] = React.useState(0) - const handleTabChange = (event: React.ChangeEvent<{}>, newTab: number) => { - setCurrentTab(newTab); - }; - - return ( - { - setValues(_m.addDeployment(values)) - }} - removeAction={() => { - setValues(_m.removeDeployment(values)) - }} > - - - - - - - - - - - - - - - - - - - - - - ) + const handleTabChange = (event: React.ChangeEvent<{}>, newTab: number) => { + setCurrentTab(newTab) + } + return ( + { + setValues(_m.addDeployment(values)) + }} + removeAction={() => { + setValues(_m.removeDeployment(values)) + }} + > + + + + + + + + + + + + + + + + + + + + + + ) } export default DeploymentForm diff --git a/src/coreform/DeploymentStrategyForm.tsx b/src/coreform/DeploymentStrategyForm.tsx index dedec21..9f14568 100644 --- a/src/coreform/DeploymentStrategyForm.tsx +++ b/src/coreform/DeploymentStrategyForm.tsx @@ -3,169 +3,201 @@ // {name: "5xx-error", clusterScope: true}, // {name: "all-error", clusterScope: true} // ] -import * as React from "react"; -import { Radio, Table, TableRow, FormLabel } from '@material-ui/core'; -import { FormikTextField } from '../components/common/FormikTextField'; -import { FormikRadioGroup } from '../components/common/FormikRadioGroup'; -import { toMenuItems } from './FormUtil'; +import * as React from 'react' +import { Radio, Table, TableRow, FormLabel } from '@material-ui/core' +import { FormikTextField } from '../components/common/FormikTextField' +import { FormikRadioGroup } from '../components/common/FormikRadioGroup' +import { toMenuItems } from './FormUtil' import * as _m from '../models/Manifest' -import { Grid, FormControlLabel, styled, makeStyles, TableCell, TextField } from '@material-ui/core'; -import { cardStyles } from './Styles'; -import { getIn, useFormikContext } from 'formik'; -import NotConfigured from './NotConfiguredPanel'; -import CardLayout from '../components/common/CardLayout'; -import GeneratePipelineButton from "../components/common/GeneratePipelineButton"; -import {FormikTable} from "../components/common/FormikTable"; +import { Grid, FormControlLabel, styled, makeStyles, TableCell, TextField } from '@material-ui/core' +import { cardStyles } from './Styles' +import { getIn, useFormikContext } from 'formik' +import NotConfigured from './NotConfiguredPanel' +import CardLayout from '../components/common/CardLayout' +import GeneratePipelineButton from '../components/common/GeneratePipelineButton' +import { FormikTable } from '../components/common/FormikTable' const useStyles = makeStyles({ - ...cardStyles, - field: { - marginBottom: 20, - }, - tableField: { - width: 185 - }, - button: { - float: 'right', - marginRight: 10 - }, - label: { - fontSize: '15px' - }, - gridRow: { - width: 1200 - } -}); + ...cardStyles, + field: { + marginBottom: 20, + }, + tableField: { + width: 185, + }, + button: { + float: 'right', + marginRight: 10, + }, + label: { + fontSize: '15px', + }, + gridRow: { + width: 1200, + }, +}) -const strategyType = ["rollingUpdate","canary", "rollingUpdateWithCanaryMixIn"] -const deploymentController = ["default","argo"] +const strategyType = ['rollingUpdate', 'canary', 'rollingUpdateWithCanaryMixIn'] +const deploymentController = ['default', 'argo'] const MarginedTextField = styled(FormikTextField)({ - marginBottom: 10, + marginBottom: 10, }) const MarginedFormControlLabel = styled(FormControlLabel)({ - marginBottom: 10, - width: 400 + marginBottom: 10, + width: 400, }) const parameters = { - "manualPromotion": null, - "pause": "string", - "setWeight": "number" - } - + manualPromotion: null, + pause: 'string', + setWeight: 'number', +} const displayValue = (values, name) => { - let key = getIn(values, name); - if (key == '' || parameters[key]== null) { + const key = getIn(values, name) + if (key == '' || parameters[key] == null) { return false - } - return true + } + return true } const Steps = () => { -const classes = useStyles(); - return ( - - {(i, values, insert, setFieldValue, push) => ( - <> - - - {toMenuItems(Object.keys(parameters))} - - - { displayValue(values, `deployment.strategyConfig.canaryConfig.steps.${i}.name`) ? ( - - - - ) : null} - - )} - ) + const classes = useStyles() + return ( + + {(i, values, insert, setFieldValue, push) => ( + <> + + + {toMenuItems(Object.keys(parameters))} + + + {displayValue(values, `deployment.strategyConfig.canaryConfig.steps.${i}.name`) ? ( + + + + ) : null} + + )} + + ) } -const RollingUpdateWithCanaryMixIn = (props: {values?: any, disable?: boolean}) => { - const {values, disable} = props - const classes = useStyles(); - return disable ? null : ( - - <> +const RollingUpdateWithCanaryMixIn = (props: { values?: any; disable?: boolean }) => { + const { values, disable } = props + const classes = useStyles() + return disable ? null : ( + + <> - - CurrentStrategy - - } label="RollingUpdate" /> - } label="Canary" /> - - - {values.deployment.strategyConfig?.rollingUpdateWithCanaryMixInConfig?.currentStrategy == 'canary' ?( - <> - - - - - - - - ) : null } + + + CurrentStrategy + + + } label='RollingUpdate' /> + } label='Canary' /> + + + {values.deployment.strategyConfig?.rollingUpdateWithCanaryMixInConfig?.currentStrategy == 'canary' ? ( + <> + + + + + + + + ) : null}
- -
- ) - } + +
+ ) +} -const CanaryConfiguration = (props: {disable: boolean}) => { - const { disable } = props - return disable ? null : - ( -
- -
- -
- ) - } +const CanaryConfiguration = (props: { disable: boolean }) => { + const { disable } = props + return disable ? null : ( + +
+ +
+ +
+ ) +} const DeploymentStrategyConfiguration = () => { - return ( - - - {toMenuItems(strategyType)} - - - {toMenuItems(deploymentController)} - - - ) + return ( + + + {toMenuItems(strategyType)} + + + {toMenuItems(deploymentController)} + + + ) } const DeplomentStrategyForm = () => { - const { values, setValues }: { values: any, setValues: any } = useFormikContext() - const classes = useStyles(); + const { values, setValues }: { values: any; setValues: any } = useFormikContext() + const classes = useStyles() - return ( - <> - setValues(_m.addDeploymentStrategy(values))} - removeAction={() => setValues(_m.removeDeploymentStrategy(values))} > - - - - - - - - + return ( + <> + setValues(_m.addDeploymentStrategy(values))} + removeAction={() => setValues(_m.removeDeploymentStrategy(values))} + > + + + + + + - - - ) + +
+ + + ) } -export default DeplomentStrategyForm \ No newline at end of file +export default DeplomentStrategyForm diff --git a/src/coreform/DocumentDbForm.tsx b/src/coreform/DocumentDbForm.tsx index 1859e59..635966e 100644 --- a/src/coreform/DocumentDbForm.tsx +++ b/src/coreform/DocumentDbForm.tsx @@ -1,6 +1,6 @@ -import {useField, useFormikContext} from "formik"; -import NotConfigured from "./NotConfiguredPanel"; -import * as _m from "../models/Manifest"; +import { useField, useFormikContext } from 'formik' +import NotConfigured from './NotConfiguredPanel' +import * as _m from '../models/Manifest' import { FormControlLabel, Grid, @@ -15,16 +15,16 @@ import { TableHead, TableRow, Tooltip, -} from "@material-ui/core"; -import GeneratePipelineButton from "../components/common/GeneratePipelineButton"; -import * as React from "react"; -import {cardStyles} from "./Styles"; -import CardLayout from "../components/common/CardLayout"; -import {toMenuItems} from "./FormUtil"; -import {FormikCheckbox} from "../components/common/FormikCheckbox"; -import {FormikTextField} from "../components/common/FormikTextField"; -import {EnvironmentVariable} from "./Types"; -import {FormikTable} from "../components/common/FormikTable"; +} from '@material-ui/core' +import GeneratePipelineButton from '../components/common/GeneratePipelineButton' +import * as React from 'react' +import { cardStyles } from './Styles' +import CardLayout from '../components/common/CardLayout' +import { toMenuItems } from './FormUtil' +import { FormikCheckbox } from '../components/common/FormikCheckbox' +import { FormikTextField } from '../components/common/FormikTextField' +import { EnvironmentVariable } from './Types' +import { FormikTable } from '../components/common/FormikTable' const useStyles = makeStyles({ ...cardStyles, @@ -32,16 +32,16 @@ const useStyles = makeStyles({ marginBottom: 20, }, tableField: { - width: 185 + width: 185, }, button: { float: 'right', - marginRight: 10 + marginRight: 10, }, gridRow: { - width: 1200 - } -}); + width: 1200, + }, +}) const MarginedTextField = styled(FormikTextField)({ marginBottom: 10, @@ -49,27 +49,39 @@ const MarginedTextField = styled(FormikTextField)({ const MarginedFormControlLabel = styled(FormControlLabel)({ marginBottom: 10, - width: 400 + width: 400, }) -const docDBAlertHeaders = ["Metric", "Threshold", "Duration\n(minutes)"]; +const docDBAlertHeaders = ['Metric', 'Threshold', 'Duration\n(minutes)'] const docDBAlertFields = [ - { field: "cpuUtilization", label: "cpuUtilization(percent)" }, - { field: "cpuCreditBalance", label: "cpuCreditBalance(credit)" }, - { field: "volumeUsageTooHigh", label: "volumeUsageTooHigh(MB)" }, - { field: "freeMemoryTooLowInMB", label: "freeMemoryTooLow(MB)" }, - { field: "dbConnections", label: "highDBConnections(integer)" }, - { field: "readLatency", label: "readLatency(ms)" }, - { field: "writeLatency", label: "writeLatency(ms)" }, -]; + { field: 'cpuUtilization', label: 'cpuUtilization(percent)' }, + { field: 'cpuCreditBalance', label: 'cpuCreditBalance(credit)' }, + { field: 'volumeUsageTooHigh', label: 'volumeUsageTooHigh(MB)' }, + { field: 'freeMemoryTooLowInMB', label: 'freeMemoryTooLow(MB)' }, + { field: 'dbConnections', label: 'highDBConnections(integer)' }, + { field: 'readLatency', label: 'readLatency(ms)' }, + { field: 'writeLatency', label: 'writeLatency(ms)' }, +] -const awsInstanceClasses = ["db.t3.medium", "db.t4g.medium", "db.r6g.large", "db.r6g.xlarge", "db.r6g.2xlarge", "db.r6g.4xlarge", - "db.r6g.8xlarge", "db.r6g.12xlarge", "db.r6g.16xlarge", "db.r6g.24xlarge"] +const awsInstanceClasses = [ + 'db.t3.medium', + 'db.t4g.medium', + 'db.r6g.large', + 'db.r6g.xlarge', + 'db.r6g.2xlarge', + 'db.r6g.4xlarge', + 'db.r6g.8xlarge', + 'db.r6g.12xlarge', + 'db.r6g.16xlarge', + 'db.r6g.24xlarge', +] const toEnvironmentKeys = (environmentVariables: Array, environmentVariableType: string) => { return environmentVariables - .filter(environmentVariable => environmentVariableType === '' || environmentVariable.type === environmentVariableType) - .map(environmentVariable => ( + .filter( + (environmentVariable) => environmentVariableType === '' || environmentVariable.type === environmentVariableType, + ) + .map((environmentVariable) => ( {environmentVariable.name} @@ -77,45 +89,55 @@ const toEnvironmentKeys = (environmentVariables: Array, env } const parameters = { - "audit_logs": "immediate", - "change_stream_log_retention_duration": "immediate", - "profiler": "immediate", - "profiler_sampling_rate": "immediate", - "profiler_threshold_ms": "immediate", - "tls": "pending-reboot", - "ttl_monitor": "immediate" + audit_logs: 'immediate', + change_stream_log_retention_duration: 'immediate', + profiler: 'immediate', + profiler_sampling_rate: 'immediate', + profiler_threshold_ms: 'immediate', + tls: 'pending-reboot', + ttl_monitor: 'immediate', } const DbParameters = () => { - const classes = useStyles(); + const classes = useStyles() - const updateApplyMethod = ({target}, i, values, setFieldValue) => { - setFieldValue(`extraResources.docdb.parameters.${i}.name`, target.value, true); - setFieldValue(`extraResources.docdb.parameters.${i}.applyMethod`, parameters[target.value], true); + const updateApplyMethod = ({ target }, i, values, setFieldValue) => { + setFieldValue(`extraResources.docdb.parameters.${i}.name`, target.value, true) + setFieldValue(`extraResources.docdb.parameters.${i}.applyMethod`, parameters[target.value], true) } return ( - + {(i, values, insert, setFieldValue) => ( <> { - updateApplyMethod(e, i, values, setFieldValue); + updateApplyMethod(e, i, values, setFieldValue) }} - select name={`extraResources.docdb.parameters.${i}.name`} - className={classes.tableField}> + select + name={`extraResources.docdb.parameters.${i}.name`} + className={classes.tableField} + > {toMenuItems(Object.keys(parameters))} - - )} - ) + + + + + )} + + ) } -const SelectEnvironmentVariableField = (props: { label: string, name: string, type: string }) => { +const SelectEnvironmentVariableField = (props: { label: string; name: string; type: string }) => { const [environmentVariables] = useField('environmentVariables') return ( @@ -128,34 +150,39 @@ const SelectEnvironmentVariableField = (props: { label: string, name: string, ty const DatabaseConfiguration = () => { return ( - - - - - + + + + + {toMenuItems(awsInstanceClasses)} - + ) - } const DatabaseAdvancedConfiguration = () => { return ( - - } - label="Apply Immediately"/> - + + } + label='Apply Immediately' + /> + ) } const DocDBAlerts = () => { return ( - + - +
{docDBAlertHeaders.map((header, i) => ( @@ -168,16 +195,10 @@ const DocDBAlerts = () => { {label} - + - + ))} @@ -185,34 +206,26 @@ const DocDBAlerts = () => {
- ); -}; + ) +} const DocumentDbForm = () => { - const {values, setValues}: { values: any, setValues: any } = useFormikContext() - const classes = useStyles(); + const { values, setValues }: { values: any; setValues: any } = useFormikContext() + const classes = useStyles() return ( <> setValues(_m.addDocumentDb(values))} - removeAction={() => setValues(_m.removeDocumentDb(values))}> - - + removeAction={() => setValues(_m.removeDocumentDb(values))} + > + + - - + + @@ -220,12 +233,9 @@ const DocumentDbForm = () => { - <>{_m.hasDocumentDb(values) ? - - : ''} - + <>{_m.hasDocumentDb(values) ? : ''} ) } -export default DocumentDbForm \ No newline at end of file +export default DocumentDbForm diff --git a/src/coreform/DynamicConfig.tsx b/src/coreform/DynamicConfig.tsx index 3eab932..134d212 100644 --- a/src/coreform/DynamicConfig.tsx +++ b/src/coreform/DynamicConfig.tsx @@ -1,55 +1,74 @@ -import * as React from 'react'; +import * as React from 'react' import * as _m from '../models/Manifest' -import { Grid, makeStyles,TextField } from '@material-ui/core'; -import {cardStyles, warning} from './Styles'; -import { Field, useFormikContext } from 'formik'; -import NotConfigured from './NotConfiguredPanel'; -import { FormikCardList } from '../components/common/FormikCardList'; -import { FormikTextField } from "../components/common/FormikTextField"; -import {useEffect, useState} from "react"; - +import { Grid, makeStyles, TextField } from '@material-ui/core' +import { cardStyles, warning } from './Styles' +import { Field, useFormikContext } from 'formik' +import NotConfigured from './NotConfiguredPanel' +import { FormikCardList } from '../components/common/FormikCardList' +import { FormikTextField } from '../components/common/FormikTextField' +import { useEffect, useState } from 'react' const useStyles = makeStyles({ - ...cardStyles, - warning, - root: { - width: 1300 - }, - field: { - margin: 5, - width: 1000 - } -}); - + ...cardStyles, + warning, + root: { + width: 1300, + }, + field: { + margin: 5, + width: 1000, + }, +}) - const CustomInputComponent = (props) => ( -