From 78e693edf52e8c03e46df44eef9c0e013d6b59c7 Mon Sep 17 00:00:00 2001 From: Sergio Betanzos Date: Wed, 11 Nov 2020 19:00:15 +0100 Subject: [PATCH] F #3951: Add deploy flow form (#409) --- .../client/components/Cards/ProviderCard.js | 4 +- .../client/components/Dialogs/DialogForm.js | 10 +- .../FormControl/SelectController.js | 19 +-- .../FormControl/SliderController.js | 88 ++++++++++ .../components/FormStepper/MobileStepper.js | 15 +- .../client/components/FormStepper/Stepper.js | 35 ++-- .../client/components/FormStepper/index.js | 19 ++- .../client/components/Forms/FormWithSchema.js | 16 +- .../src/client/components/HOC/MainLayout.js | 2 +- .../src/client/components/List/ListCards.js | 86 +++++----- .../src/client/constants/translates.js | 15 +- .../containers/ApplicationsInstances/index.js | 26 +-- .../Create/Steps/BasicConfiguration/index.js | 1 + .../Create/Steps/BasicConfiguration/schema.js | 1 - .../Form/Create/Steps/Clusters/index.js | 7 +- .../Form/Create/Steps/Networking/index.js | 2 +- .../Form/Create/Steps/Networking/schema.js | 2 +- .../Tiers/Steps/BasicConfiguration/index.js | 1 + .../Tiers/Steps/BasicConfiguration/schema.js | 2 +- .../Steps/Tiers/Steps/Policies/index.js | 47 +++--- .../Tiers/Steps/Policies/schemas/index.js | 2 + .../Form/Create/Steps/Tiers/Steps/index.js | 8 +- .../Form/Create/Steps/Tiers/index.js | 6 +- .../Form/Create/Steps/index.js | 4 +- .../Form/Create/index.js | 4 +- .../Deploy/Steps/BasicConfiguration/index.js | 20 +++ .../Deploy/Steps/BasicConfiguration/schema.js | 33 ++++ .../Form/Deploy/Steps/Networking/index.js | 44 +++++ .../Form/Deploy/Steps/Networking/schema.js | 84 ++++++++++ .../Form/Deploy/Steps/Tiers/index.js | 65 ++++++++ .../Form/Deploy/Steps/Tiers/schema.js | 153 ++++++++++++++++++ .../Form/Deploy/Steps/index.js | 30 ++++ .../Form/Deploy/index.js | 105 ++++++++++++ .../containers/ApplicationsTemplates/index.js | 50 +++--- .../src/client/containers/Login/schema.js | 4 +- .../Form/Create/Steps/Provider/index.js | 6 +- .../src/client/containers/Providers/index.js | 7 +- .../src/client/containers/Provisions/index.js | 7 +- .../src/client/hooks/useApplication.js | 27 ++-- src/fireedge/src/client/hooks/useFetchAll.js | 26 +++ .../src/client/hooks/useOpennebula.js | 5 +- .../src/client/services/application.js | 5 - src/fireedge/src/client/utils/helpers.js | 6 + src/fireedge/src/client/utils/merge.js | 73 +++++++++ .../utils/parser/toApplicationTemplate.js | 2 +- .../utils/parser/toDeployApplication.js | 69 ++++++++ 46 files changed, 1044 insertions(+), 199 deletions(-) create mode 100644 src/fireedge/src/client/components/FormControl/SliderController.js create mode 100644 src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/BasicConfiguration/index.js create mode 100644 src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/BasicConfiguration/schema.js create mode 100644 src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/Networking/index.js create mode 100644 src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/Networking/schema.js create mode 100644 src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/Tiers/index.js create mode 100644 src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/Tiers/schema.js create mode 100644 src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/index.js create mode 100644 src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/index.js create mode 100644 src/fireedge/src/client/hooks/useFetchAll.js create mode 100644 src/fireedge/src/client/utils/merge.js create mode 100644 src/fireedge/src/client/utils/parser/toDeployApplication.js diff --git a/src/fireedge/src/client/components/Cards/ProviderCard.js b/src/fireedge/src/client/components/Cards/ProviderCard.js index 041afbfa73..a483e4948d 100644 --- a/src/fireedge/src/client/components/Cards/ProviderCard.js +++ b/src/fireedge/src/client/components/Cards/ProviderCard.js @@ -9,13 +9,11 @@ import { Card, CardHeader, CardContent, - CardActions, - Chip + CardActions } from '@material-ui/core' import FileIcon from '@material-ui/icons/Description' import { Tr } from 'client/components/HOC' -import { APPLICATION_STATES } from 'client/constants/states' const useStyles = makeStyles(theme => ({ root: { diff --git a/src/fireedge/src/client/components/Dialogs/DialogForm.js b/src/fireedge/src/client/components/Dialogs/DialogForm.js index 1ea06e2999..020c3e1f82 100644 --- a/src/fireedge/src/client/components/Dialogs/DialogForm.js +++ b/src/fireedge/src/client/components/Dialogs/DialogForm.js @@ -29,11 +29,11 @@ const DialogForm = memo( }) => { const isMobile = useMediaQuery(theme => theme.breakpoints.only('xs')) - const { handleSubmit, formState, ...methods } = useForm({ + const methods = useForm({ mode: 'onBlur', reValidateMode: 'onSubmit', defaultValues: values, - resolver: yupResolver(resolver) + resolver: yupResolver(resolver()) }) return ( @@ -63,8 +63,8 @@ const DialogForm = memo( {onSubmit && ( @@ -83,7 +83,7 @@ DialogForm.propTypes = { PropTypes.arrayOf(PropTypes.any), PropTypes.objectOf(PropTypes.any) ]), - resolver: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired, + resolver: PropTypes.func.isRequired, onSubmit: PropTypes.func, onCancel: PropTypes.func, submitButtonProps: PropTypes.objectOf(PropTypes.any), diff --git a/src/fireedge/src/client/components/FormControl/SelectController.js b/src/fireedge/src/client/components/FormControl/SelectController.js index 29a5a0ab0c..7365a26424 100644 --- a/src/fireedge/src/client/components/FormControl/SelectController.js +++ b/src/fireedge/src/client/components/FormControl/SelectController.js @@ -8,13 +8,13 @@ import ErrorHelper from 'client/components/FormControl/ErrorHelper' import { Tr } from 'client/components/HOC/Translate' const SelectController = memo( - ({ control, cy, name, label, values, error, fieldProps }) => ( + ({ control, cy, name, label, multiple, values, error, fieldProps }) => ( - {Array.isArray(values) && - values?.map(({ text, value }) => ( - - {text} - - ))} + {values?.map(({ text, value }) => ( + + {text} + + ))} } name={name} control={control} - defaultValue={values[0]?.value} + defaultValue={multiple ? [values[0]?.value] : values[0]?.value} /> ), (prevProps, nextProps) => prevProps.error === nextProps.error @@ -43,6 +42,7 @@ SelectController.propTypes = { cy: PropTypes.string, name: PropTypes.string.isRequired, label: PropTypes.oneOfType([PropTypes.string, PropTypes.node]), + multiple: PropTypes.bool, values: PropTypes.arrayOf(PropTypes.object).isRequired, error: PropTypes.oneOfType([ PropTypes.bool, @@ -56,6 +56,7 @@ SelectController.defaultProps = { cy: 'cy', name: '', label: '', + multiple: false, values: [], error: false, fieldProps: undefined diff --git a/src/fireedge/src/client/components/FormControl/SliderController.js b/src/fireedge/src/client/components/FormControl/SliderController.js new file mode 100644 index 0000000000..aaa02242ad --- /dev/null +++ b/src/fireedge/src/client/components/FormControl/SliderController.js @@ -0,0 +1,88 @@ +import React, { memo } from 'react' +import PropTypes from 'prop-types' + +import { Typography, TextField, Slider, FormHelperText, Grid } from '@material-ui/core' +import { Controller } from 'react-hook-form' + +import ErrorHelper from 'client/components/FormControl/ErrorHelper' +import { Tr } from 'client/components/HOC/Translate' + +const SliderController = memo( + ({ control, cy, name, label, error, fieldProps }) => ( + <> + + {Tr(label)} + + + + + onChange(val)} + /> + + + onChange( + evt.target.value === '' ? '0' : Number(evt.target.value) + )} + onBlur={onBlur} + /> + + + } + name={name} + control={control} + /> + {Boolean(error) && ( + + + + )} + + ), + (prevProps, nextProps) => prevProps.error === nextProps.error +) + +SliderController.propTypes = { + control: PropTypes.object, + cy: PropTypes.string, + name: PropTypes.string.isRequired, + label: PropTypes.oneOfType([PropTypes.string, PropTypes.node]), + multiple: PropTypes.bool, + values: PropTypes.arrayOf(PropTypes.object).isRequired, + error: PropTypes.oneOfType([ + PropTypes.bool, + PropTypes.objectOf(PropTypes.any) + ]), + fieldProps: PropTypes.object +} + +SliderController.defaultProps = { + control: {}, + cy: 'cy', + name: '', + label: '', + multiple: false, + values: [], + error: false, + fieldProps: undefined +} + +SliderController.displayName = 'SliderController' + +export default SliderController diff --git a/src/fireedge/src/client/components/FormStepper/MobileStepper.js b/src/fireedge/src/client/components/FormStepper/MobileStepper.js index ec5b86bcaa..014413bf0e 100644 --- a/src/fireedge/src/client/components/FormStepper/MobileStepper.js +++ b/src/fireedge/src/client/components/FormStepper/MobileStepper.js @@ -42,12 +42,14 @@ const CustomMobileStepper = ({ return ( - {label} - {Boolean(errors[id]) && ( - - {errors[id]?.message} - - )} + + {label} + {Boolean(errors[id]) && ( + + {errors[id]?.message} + + )} + } /> - ) } diff --git a/src/fireedge/src/client/components/FormStepper/Stepper.js b/src/fireedge/src/client/components/FormStepper/Stepper.js index ba30a3f647..c65cbc2182 100644 --- a/src/fireedge/src/client/components/FormStepper/Stepper.js +++ b/src/fireedge/src/client/components/FormStepper/Stepper.js @@ -11,11 +11,14 @@ import { Typography } from '@material-ui/core' +import ButtonSubmit from 'client/components/FormControl/SubmitButton' +import { Finish, Back, Next } from 'client/constants/translates' import { Tr } from 'client/components/HOC' const StickyStepper = styled(Stepper)({ position: 'sticky', top: -15, + minHeight: 100, backdropFilter: 'blur(5px)', background: '#fafafa9c', zIndex: 1 @@ -28,32 +31,34 @@ const CustomStepper = ({ disabledBack, handleNext, handleBack, - errors + errors, + isSubmitting }) => ( <> {steps?.map(({ id, label }) => ( - {errors[id]?.message} - - ) - })} + {...(Boolean(errors[id]) && { error: true })} + optional={ + + {errors[id]?.message} + + } >{label} ))} - + ) @@ -71,6 +76,7 @@ CustomStepper.propTypes = { activeStep: PropTypes.number.isRequired, lastStep: PropTypes.number.isRequired, disabledBack: PropTypes.bool.isRequired, + isSubmitting: PropTypes.bool, handleNext: PropTypes.func, handleBack: PropTypes.func, errors: PropTypes.shape({ @@ -85,7 +91,8 @@ CustomStepper.defaultProps = { disabledBack: false, handleNext: () => undefined, handleBack: () => undefined, - errors: undefined + errors: undefined, + isSubmitting: false } CustomStepper.displayName = 'Stepper' diff --git a/src/fireedge/src/client/components/FormStepper/index.js b/src/fireedge/src/client/components/FormStepper/index.js index 6c11fc7aed..63bbb57fe4 100644 --- a/src/fireedge/src/client/components/FormStepper/index.js +++ b/src/fireedge/src/client/components/FormStepper/index.js @@ -6,6 +6,7 @@ import { useMediaQuery } from '@material-ui/core' import CustomMobileStepper from 'client/components/FormStepper/MobileStepper' import CustomStepper from 'client/components/FormStepper/Stepper' +import { groupBy } from 'client/utils/helpers' const FIRST_STEP = 0 @@ -26,8 +27,7 @@ const FormStepper = ({ steps, schema, onSubmit }) => { const handleNext = () => { const { id, resolver, optionsValidate } = steps[activeStep] - const currentData = watch()[id] - + const currentData = watch(id) const stepSchema = typeof resolver === 'function' ? resolver() : resolver stepSchema @@ -41,7 +41,16 @@ const FormStepper = ({ steps, schema, onSubmit }) => { } }) .catch(({ inner, ...err }) => { - setError(id, err) + const errorsByPath = groupBy(inner, 'path') ?? {} + const totalErrors = Object.keys(errorsByPath).length + + totalErrors > 0 + ? setError(id, { + type: 'manual', + message: `${totalErrors} error(s) occurred` + }) + : setError(id, err) + inner?.forEach(({ path, type, message }) => setError(`${id}.${path}`, { type, message }) ) @@ -51,6 +60,10 @@ const FormStepper = ({ steps, schema, onSubmit }) => { const handleBack = useCallback(() => { if (activeStep <= FIRST_STEP) return + const { id } = steps[activeStep] + const currentData = watch(id) + + setFormData(prev => ({ ...prev, [id]: currentData })) setActiveStep(prevActiveStep => prevActiveStep - 1) }, [activeStep]) diff --git a/src/fireedge/src/client/components/Forms/FormWithSchema.js b/src/fireedge/src/client/components/Forms/FormWithSchema.js index 32b0a3633b..efe16b3199 100644 --- a/src/fireedge/src/client/components/Forms/FormWithSchema.js +++ b/src/fireedge/src/client/components/Forms/FormWithSchema.js @@ -7,6 +7,7 @@ import { useFormContext, useWatch } from 'react-hook-form' import { INPUT_TYPES } from 'client/constants' import TextController from 'client/components/FormControl/TextController' import SelectController from 'client/components/FormControl/SelectController' +import SliderController from 'client/components/FormControl/SliderController' import CheckboxController from 'client/components/FormControl/CheckboxController' import AutocompleteController from 'client/components/FormControl/AutocompleteController' import { get } from 'client/utils/helpers' @@ -14,6 +15,7 @@ import { get } from 'client/utils/helpers' const InputController = { [INPUT_TYPES.TEXT]: TextController, [INPUT_TYPES.SELECT]: SelectController, + [INPUT_TYPES.SLIDER]: SliderController, [INPUT_TYPES.CHECKBOX]: CheckboxController, [INPUT_TYPES.AUTOCOMPLETE]: AutocompleteController } @@ -26,7 +28,18 @@ const FormWithSchema = ({ id, cy, fields }) => { return ( {fields?.map( - ({ name, type, htmlType, label, values, dependOf, tooltip, grid, fieldProps }) => { + ({ + name, + type, + htmlType, + label, + values, + multiple, + dependOf, + tooltip, + grid, + fieldProps + }) => { const dataCy = `${cy}-${name}` const inputName = id ? `${id}.${name}` : name @@ -53,6 +66,7 @@ const FormWithSchema = ({ id, cy, fields }) => { name: inputName, label, tooltip, + multiple, values: typeof values === 'function' ? values(dependValue) : values, diff --git a/src/fireedge/src/client/components/HOC/MainLayout.js b/src/fireedge/src/client/components/HOC/MainLayout.js index 24bfe3ea0c..99e1820571 100644 --- a/src/fireedge/src/client/components/HOC/MainLayout.js +++ b/src/fireedge/src/client/components/HOC/MainLayout.js @@ -22,7 +22,7 @@ import useOpennebula from 'client/hooks/useOpennebula' import LoadingScreen from 'client/components/LoadingScreen' -const findRouteByPathname = (endpoints=[], pathname='') => { +const findRouteByPathname = (endpoints = [], pathname = '') => { const routes = endpoints.flatMap( ({ endpoint, ...item }) => endpoint ?? item ) diff --git a/src/fireedge/src/client/components/List/ListCards.js b/src/fireedge/src/client/components/List/ListCards.js index c505f3b112..7aeab553e7 100644 --- a/src/fireedge/src/client/components/List/ListCards.js +++ b/src/fireedge/src/client/components/List/ListCards.js @@ -1,4 +1,4 @@ -import React, { memo, useMemo } from 'react' +import React, { memo } from 'react' import PropTypes from 'prop-types' import { @@ -6,20 +6,20 @@ import { CardActionArea, CardContent, Card, - Grid + Grid, + LinearProgress } from '@material-ui/core' import AddIcon from '@material-ui/icons/Add' import { EmptyCard } from 'client/components/Cards' -const gridValues = [false, 'auto', true, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] - const useStyles = makeStyles(() => ({ cardPlus: { height: '100%', minHeight: 140, display: 'flex', textAlign: 'center' - } + }, + loading: { width: '100%' } })) const ListCards = memo(({ @@ -30,49 +30,51 @@ const ListCards = memo(({ CardComponent, cardsProps, EmptyComponent, - displayEmpty + displayEmpty, + isLoading }) => { const classes = useStyles() + if (isLoading) { + return + } + return ( - {handleCreate && - useMemo( - () => ( - - {ButtonCreateComponent ? ( - - ) : ( - - - - - - - - )} - - ), - [handleCreate, classes] - )} - {Array.isArray(list) && - list.length > 0 ? ( - list?.map((value, index) => ( - - - - )) - ) : ( - (displayEmpty || EmptyComponent) && ( - - {EmptyComponent ?? } - - ) - )} + {handleCreate && ( + + {ButtonCreateComponent ? ( + + ) : ( + + + + + + + + )} + + )} + {list.length > 0 ? ( + list?.map((value, index) => ( + + + + )) + ) : ( + (displayEmpty || EmptyComponent) && ( + + {EmptyComponent ?? } + + ) + )} ) }) +const gridValues = [false, 'auto', true, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + ListCards.propTypes = { list: PropTypes.arrayOf(PropTypes.any).isRequired, breakpoints: PropTypes.shape({ @@ -99,7 +101,8 @@ ListCards.propTypes = { EmptyComponent: PropTypes.oneOfType([ PropTypes.element ]), - displayEmpty: PropTypes.bool + displayEmpty: PropTypes.bool, + isLoading: PropTypes.bool } ListCards.defaultProps = { @@ -110,7 +113,8 @@ ListCards.defaultProps = { CardComponent: null, cardsProps: () => undefined, EmptyComponent: undefined, - displayEmpty: false + displayEmpty: false, + isLoading: false } ListCards.displayName = 'ListCards' diff --git a/src/fireedge/src/client/constants/translates.js b/src/fireedge/src/client/constants/translates.js index f5775d6bc6..b475e3d199 100644 --- a/src/fireedge/src/client/constants/translates.js +++ b/src/fireedge/src/client/constants/translates.js @@ -1,25 +1,30 @@ module.exports = { - /* FORM */ + /* pagination / stepper */ Back: 'Back', Next: 'Next', - /* VERBS */ + /* actions */ + Finish: 'Finish', SignIn: 'Sign In', SignOut: 'Sign Out', Cancel: 'Cancel', Save: 'Save', Deploy: 'Deploy', Submit: 'Submit', + Show: 'Show', + ShowAll: 'Show all', + SelectGroup: 'Select a group', - /* LOGIN */ + /* login */ Username: 'Username', Password: 'Password', Token2FA: '2FA Token', KeepLoggedIn: 'Keep me logged in', - SelectGroup: 'Select a group', - ShowAll: 'Show all', + /* errors */ + CannotConnectOneFlow: 'Cannot connect to OneFlow server', NotFound: 'Not found', + Language: 'Language', Response: 'Response', Settings: 'Settings' diff --git a/src/fireedge/src/client/containers/ApplicationsInstances/index.js b/src/fireedge/src/client/containers/ApplicationsInstances/index.js index dada93c924..269856807a 100644 --- a/src/fireedge/src/client/containers/ApplicationsInstances/index.js +++ b/src/fireedge/src/client/containers/ApplicationsInstances/index.js @@ -1,6 +1,6 @@ import React, { useEffect, useMemo, useState } from 'react' -import { LinearProgress, Container, Box } from '@material-ui/core' +import { Container, Box } from '@material-ui/core' import { Alert } from '@material-ui/lab' import useApplication from 'client/hooks/useApplication' @@ -9,9 +9,18 @@ import useFetch from 'client/hooks/useFetch' import ListCards from 'client/components/List/ListCards' import DialogInfo from 'client/containers/ApplicationsInstances/DialogInfo' import { ApplicationCard, EmptyCard } from 'client/components/Cards' -import { Tr } from 'client/components/HOC' import { DONE, APPLICATION_STATES } from 'client/constants/states' +import { CannotConnectOneFlow } from 'client/constants/translates' +import { Tr } from 'client/components/HOC' + +const Error = () => ( + + + {Tr(CannotConnectOneFlow)} + + +) function ApplicationsInstances () { const { applications, getApplications } = useApplication() @@ -31,17 +40,7 @@ function ApplicationsInstances () { ), [applications]) if (error) { - return ( - - - {Tr('Cannot connect to OneFlow server')} - - - ) - } - - if (loading) { - return + return } return ( @@ -49,6 +48,7 @@ function ApplicationsInstances () { } CardComponent={ApplicationCard} cardsProps={({ value }) => ({ diff --git a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/BasicConfiguration/index.js b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/BasicConfiguration/index.js index 9504559499..389f2c2940 100644 --- a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/BasicConfiguration/index.js +++ b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/BasicConfiguration/index.js @@ -10,6 +10,7 @@ const BasicConfiguration = () => ({ id: STEP_ID, label: 'Application Overview', resolver: STEP_FORM_SCHEMA, + optionsValidate: { abortEarly: false }, content: useCallback( () => , [] diff --git a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/BasicConfiguration/schema.js b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/BasicConfiguration/schema.js index 5438d9d79e..ed6928f24e 100644 --- a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/BasicConfiguration/schema.js +++ b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/BasicConfiguration/schema.js @@ -29,7 +29,6 @@ export const FORM_FIELDS = [ validation: yup .string() .min(1, 'Name field is required') - .matches(/^[\w+\s*]+$/g, { message: 'Invalid characters' }) .trim() .required('Name field is required') .default('') diff --git a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Clusters/index.js b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Clusters/index.js index 07636900c8..1a7968b87e 100644 --- a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Clusters/index.js +++ b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Clusters/index.js @@ -1,8 +1,9 @@ import React, { useEffect, useCallback } from 'react' import useOpennebula from 'client/hooks/useOpennebula' - import useListForm from 'client/hooks/useListForm' +import useFetch from 'client/hooks/useFetch' + import ListCards from 'client/components/List/ListCards' import { ClusterCard, EmptyCard } from 'client/components/Cards' @@ -16,18 +17,20 @@ const Clusters = () => ({ resolver: STEP_FORM_SCHEMA, content: useCallback(({ data, setFormData }) => { const { clusters, getClusters } = useOpennebula() + const { fetchRequest, loading } = useFetch(getClusters) const { handleSelect, handleUnselect } = useListForm({ key: STEP_ID, setList: setFormData }) useEffect(() => { - getClusters() + fetchRequest() }, []) return ( } CardComponent={ClusterCard} cardsProps={({ value: { ID } }) => { diff --git a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Networking/index.js b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Networking/index.js index 693a02ae72..fa2228ac87 100644 --- a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Networking/index.js +++ b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Networking/index.js @@ -67,7 +67,7 @@ const Networks = () => ({ {showDialog && ( NETWORK_FORM_SCHEMA} open={showDialog} values={editingData} onSubmit={values => { diff --git a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Networking/schema.js b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Networking/schema.js index 046ffd9550..5cdc9bea48 100644 --- a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Networking/schema.js +++ b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Networking/schema.js @@ -53,7 +53,7 @@ const NAME = { validation: yup .string() .trim() - .matches(/^[\w+\s*]+$/g, { message: 'Invalid characters' }) + .matches(/^[\w+\s*]*$/g, { message: 'Invalid characters' }) .required('Name field is required') .default('') } diff --git a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/Steps/BasicConfiguration/index.js b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/Steps/BasicConfiguration/index.js index 14f06cc3e6..b58b29b851 100644 --- a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/Steps/BasicConfiguration/index.js +++ b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/Steps/BasicConfiguration/index.js @@ -10,6 +10,7 @@ const BasicConfiguration = () => ({ id: STEP_ID, label: 'Configuration', resolver: STEP_FORM_SCHEMA, + optionsValidate: { abortEarly: false }, content: useCallback( () => , [] diff --git a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/Steps/BasicConfiguration/schema.js b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/Steps/BasicConfiguration/schema.js index 0fc29944d3..7c8daf0619 100644 --- a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/Steps/BasicConfiguration/schema.js +++ b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/Steps/BasicConfiguration/schema.js @@ -15,7 +15,7 @@ const NAME = { validation: yup .string() .trim() - .matches(/^[\w+\s*]+$/g, { message: 'Invalid characters' }) + .matches(/^[\w+\s*]*$/g, { message: 'Invalid characters' }) .required('Name field is required') .default('') } diff --git a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/Steps/Policies/index.js b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/Steps/Policies/index.js index 21af4e968b..d64bb91433 100644 --- a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/Steps/Policies/index.js +++ b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/Steps/Policies/index.js @@ -1,8 +1,9 @@ -import React, { useCallback, useEffect, useState, useMemo } from 'react' +import React, { useCallback, useState, useMemo } from 'react' import { useFormContext } from 'react-hook-form' import { Box, Tab, Tabs, Fab, AppBar } from '@material-ui/core' import AddIcon from '@material-ui/icons/Add' +import WarningIcon from '@material-ui/icons/Warning' import FormWithSchema from 'client/components/Forms/FormWithSchema' import { PolicyCard } from 'client/components/Cards' @@ -43,32 +44,31 @@ const Policies = () => ({ id: STEP_ID, label: 'Policies', resolver: POLICIES_SCHEMA, + optionsValidate: { abortEarly: false }, content: useCallback( - ({ setFormData }) => { - const [tab, setTab] = useState(TABS.elasticity.name) + ({ data, setFormData }) => { + const [tabSelected, setTab] = useState(TABS.elasticity.name) + const { watch, errors } = useFormContext() const { handleSetList } = useListForm({ key: STEP_ID, setList: setFormData }) - const { watch } = useFormContext() - const policies = watch(STEP_ID) - - useEffect(() => () => { - handleSetList(policies) - }, []) - const handleRemove = id => { - const newDataTab = policies?.[tab]?.filter(item => item.id !== id) - const newPolicies = set(policies, tab, newDataTab) + const policies = watch(STEP_ID) + + const newDataTab = policies?.[tabSelected]?.filter(item => item.id !== id) + const newPolicies = set(policies, tabSelected, newDataTab) handleSetList(newPolicies) } const handleCreate = () => { - const defaultValues = TABS[tab]?.schema.default() - const newDataTab = [...policies?.[tab] ?? []].concat(defaultValues) - const newPolicies = set(policies, tab, newDataTab) + const policies = watch(STEP_ID) + + const defaultValues = TABS[tabSelected]?.schema.default() + const newDataTab = [...policies?.[tabSelected] ?? []].concat(defaultValues) + const newPolicies = set(policies, tabSelected, newDataTab) handleSetList(newPolicies) } @@ -84,18 +84,25 @@ const Policies = () => ({ {useMemo(() => ( - setTab(tab)}> + setTab(tab)}> {Object.keys(TABS).map(key => + )} /> )} - ), [tab])} + ), [ + tabSelected, + errors[STEP_ID]?.[TABS.elasticity.name], + errors[STEP_ID]?.[TABS.scheduled.name] + ])} ({ {useMemo(() => ( Object.keys(TABS).map(key => ( - ) diff --git a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/Steps/Policies/schemas/index.js b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/Steps/Policies/schemas/index.js index a13c2da438..20e6cf8e6e 100644 --- a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/Steps/Policies/schemas/index.js +++ b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/Steps/Policies/schemas/index.js @@ -15,6 +15,7 @@ const MIN_VMS = { tooltip: 'Minimum number of VMs for elasticity adjustments', validation: yup .number() + .typeError('Min. value must be a number') .when(ELASTICITY_ID, (value, schema) => value?.length > 0 ? schema.required('Minimum field is required') : schema.notRequired().nullable() @@ -32,6 +33,7 @@ const MAX_VMS = { tooltip: 'Maximum number of VMs for elasticity adjustments', validation: yup .number() + .typeError('Min. value must be a number') .moreThan(yup.ref(MIN_VMS.name), 'Max. vms field must be greater than min vms') .when(ELASTICITY_ID, (value, schema) => value?.length > 0 ? schema.required('Maximum field is required') diff --git a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/Steps/index.js b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/Steps/index.js index c0625eaf06..f2483e9365 100644 --- a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/Steps/index.js +++ b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/Steps/index.js @@ -14,7 +14,7 @@ const Steps = () => { const steps = [basic, networks, template, policies] - const resolvers = yup.object({ + const resolvers = () => yup.object({ id: yup .string() .uuid() @@ -25,12 +25,12 @@ const Steps = () => { [policies.id]: policies.resolver, parents: yup.array().default([]), position: yup.object({ - x: yup.number().default(0), - y: yup.number().default(0) + x: yup.number().round().default(0), + y: yup.number().round().default(0) }) }) - const defaultValues = () => resolvers.default() + const defaultValues = resolvers().default() return { steps, defaultValues, resolvers } } diff --git a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/index.js b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/index.js index b074358115..e3ca061aa4 100644 --- a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/index.js +++ b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/Tiers/index.js @@ -31,7 +31,7 @@ const Tiers = () => { id: STEP_ID, label: 'Tier Definition', resolver: yup - .array(resolvers) + .array(resolvers()) .min(1, 'Should be at least one tier') .required('Tiers field is required') .default([]), @@ -49,7 +49,7 @@ const Tiers = () => { key: STEP_ID, list: data, setList: setFormData, - defaultValue: defaultValues() + defaultValue: defaultValues }) const handleEditTier = id => { @@ -74,7 +74,7 @@ const Tiers = () => { handleEditTier()} handleEdit={handleEditTier} handleSetData={handleSetList} diff --git a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/index.js b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/index.js index 6b88622274..e4344a4d40 100644 --- a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/index.js +++ b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/Steps/index.js @@ -13,14 +13,14 @@ const Steps = () => { const steps = [basic, clusters, networking, tiers] - const resolvers = yup.object({ + const resolvers = () => yup.object({ [basic.id]: basic.resolver, [clusters.id]: clusters.resolver, [networking.id]: networking.resolver, [tiers.id]: tiers.resolver }) - const defaultValues = resolvers.default() + const defaultValues = resolvers().default() return { steps, defaultValues, resolvers } } diff --git a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/index.js b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/index.js index 266f4e2ba2..0ea409d483 100644 --- a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/index.js +++ b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Create/index.js @@ -30,7 +30,7 @@ function ApplicationsTemplatesCreateForm () { const methods = useForm({ mode: 'onSubmit', defaultValues, - resolver: yupResolver(resolvers) + resolver: yupResolver(resolvers()) }) const onSubmit = formData => { @@ -53,7 +53,7 @@ function ApplicationsTemplatesCreateForm () { useEffect(() => { const formData = data ? mapApplicationToForm(data) : {} - methods.reset(resolvers.cast(formData), { errors: false }) + methods.reset(resolvers().cast(formData), { errors: false }) }, [data]) if (error) { diff --git a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/BasicConfiguration/index.js b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/BasicConfiguration/index.js new file mode 100644 index 0000000000..389f2c2940 --- /dev/null +++ b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/BasicConfiguration/index.js @@ -0,0 +1,20 @@ +import React, { useCallback } from 'react' + +import FormWithSchema from 'client/components/Forms/FormWithSchema' + +import { FORM_FIELDS, STEP_FORM_SCHEMA } from './schema' + +export const STEP_ID = 'application' + +const BasicConfiguration = () => ({ + id: STEP_ID, + label: 'Application Overview', + resolver: STEP_FORM_SCHEMA, + optionsValidate: { abortEarly: false }, + content: useCallback( + () => , + [] + ) +}) + +export default BasicConfiguration diff --git a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/BasicConfiguration/schema.js b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/BasicConfiguration/schema.js new file mode 100644 index 0000000000..f1c78cba89 --- /dev/null +++ b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/BasicConfiguration/schema.js @@ -0,0 +1,33 @@ +import * as yup from 'yup' + +import { INPUT_TYPES } from 'client/constants' +import { getValidationFromFields } from 'client/utils/helpers' + +const NAME = { + name: 'name', + label: 'Application name', + type: INPUT_TYPES.TEXT, + validation: yup + .string() + .trim() + .default(() => undefined) +} + +const INSTANCES = { + name: 'instances', + label: 'Number of instances', + type: INPUT_TYPES.TEXT, + htmlType: 'number', + validation: yup + .number() + .min(1, 'Instances minimum is 1') + .integer('Instances should be an integer number') + .required('Instances field is required') + .default(1) +} + +export const FORM_FIELDS = [NAME, INSTANCES] + +export const STEP_FORM_SCHEMA = yup.object( + getValidationFromFields(FORM_FIELDS) +) diff --git a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/Networking/index.js b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/Networking/index.js new file mode 100644 index 0000000000..4c1dc0010b --- /dev/null +++ b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/Networking/index.js @@ -0,0 +1,44 @@ +import React, { useEffect, useCallback } from 'react' + +import { Divider, Paper, Typography } from '@material-ui/core' + +import useOpennebula from 'client/hooks/useOpennebula' +import FormWithSchema from 'client/components/Forms/FormWithSchema' + +import { FORM_FIELDS, STEP_FORM_SCHEMA } from './schema' + +export const STEP_ID = 'networking' + +const Networks = () => ({ + id: STEP_ID, + label: 'Configure Networking', + resolver: STEP_FORM_SCHEMA, + optionsValidate: { abortEarly: false }, + content: useCallback(({ data }) => { + const { getVNetworks, getVNetworksTemplates } = useOpennebula() + + useEffect(() => { + getVNetworks() + getVNetworksTemplates() + }, []) + + return data?.map(({ id, name, description }, index) => ( + + {name} + {description && {description}} + + + + )) + }, []) +}) + +export default Networks diff --git a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/Networking/schema.js b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/Networking/schema.js new file mode 100644 index 0000000000..590171cd5c --- /dev/null +++ b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/Networking/schema.js @@ -0,0 +1,84 @@ +import * as yup from 'yup' +import { INPUT_TYPES } from 'client/constants' +import { getValidationFromFields } from 'client/utils/helpers' +import useOpennebula from 'client/hooks/useOpennebula' + +const SELECT = { + template: 'template', + network: 'network' +} + +const TYPES_NETWORKS = [ + { text: 'Create', value: 'template_id', select: SELECT.template }, + { text: 'Reserve', value: 'reserve_from', select: SELECT.network }, + { text: 'Existing', value: 'id', select: SELECT.network, extra: false } +] + +const hasExtraValue = type => TYPES_NETWORKS.some( + ({ value, extra }) => value === type && extra === false +) + +const TYPE = { + name: 'type', + label: 'Select a type', + type: INPUT_TYPES.SELECT, + values: TYPES_NETWORKS, + validation: yup + .string() + .oneOf(TYPES_NETWORKS.map(({ value }) => value)) + .required('Type field is required') + .default(TYPES_NETWORKS[0].value) +} + +const ID_VNET = { + name: 'idVnet', + label: 'Select a network', + type: INPUT_TYPES.AUTOCOMPLETE, + dependOf: TYPE.name, + values: dependValue => { + const { vNetworks, vNetworksTemplates } = useOpennebula() + const type = TYPES_NETWORKS.find(({ value }) => value === dependValue) + + const values = + type?.select === SELECT.network ? vNetworks : vNetworksTemplates + + return values + .map(({ ID: value, NAME: text }) => ({ text, value })) + .sort((a, b) => a.value - b.value) + }, + validation: yup + .string() + .trim() + .when(TYPE.name, (type, schema) => + TYPES_NETWORKS.some( + ({ value, select }) => type === value && select === SELECT.network + ) + ? schema.required('Network field is required') + : schema.required('Network template field is required') + ) + .default(undefined) +} + +const EXTRA = { + name: 'extra', + label: 'Extra', + multiline: true, + type: INPUT_TYPES.TEXT, + dependOf: TYPE.name, + htmlType: dependValue => hasExtraValue(dependValue) ? INPUT_TYPES.HIDDEN : INPUT_TYPES.TEXT, + validation: yup + .string() + .trim() + .when(TYPE.name, (type, schema) => hasExtraValue(type) ? schema.strip() : schema) + .default('') +} + +export const FORM_FIELDS = [TYPE, ID_VNET, EXTRA] + +export const NETWORK_FORM_SCHEMA = yup.object( + getValidationFromFields(FORM_FIELDS) +) + +export const STEP_FORM_SCHEMA = yup + .array(NETWORK_FORM_SCHEMA) + .default([]) diff --git a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/Tiers/index.js b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/Tiers/index.js new file mode 100644 index 0000000000..3308b23d8e --- /dev/null +++ b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/Tiers/index.js @@ -0,0 +1,65 @@ +import React, { useMemo, useCallback, useState } from 'react' + +import { useFormContext } from 'react-hook-form' +import { AppBar, Tabs, Tab } from '@material-ui/core' +import { Warning as WarningIcon } from '@material-ui/icons' + +import FormWithSchema from 'client/components/Forms/FormWithSchema' +import { ID, FORM_FIELDS, STEP_FORM_SCHEMA } from './schema' + +export const STEP_ID = 'tiers' + +const Tiers = ({ tiers, vmTemplates }) => { + const userInputsFields = useMemo(() => vmTemplates.reduce( + (list, { ID, TEMPLATE: { USER_INPUTS = {} } }) => ({ + ...list, [ID]: FORM_FIELDS(USER_INPUTS) + }), {}) + , [vmTemplates]) + + return { + id: STEP_ID, + label: 'Configure Tiers', + resolver: STEP_FORM_SCHEMA({ tiers, vmTemplates }), + optionsValidate: { abortEarly: false }, + content: useCallback(() => { + const { errors } = useFormContext() + const [tabSelected, setTab] = useState(tiers?.[0]?.id) + + return ( + <> + + setTab(tab)}> + {tiers?.map(({ id, tier }, idx) => ( + + )} + /> + ))} + + + {useMemo(() => tiers?.map(({ id, template }, index) => ( + + )), [tiers, userInputsFields, tabSelected])} + + ) + }, [tiers, userInputsFields]) + } +} + +export default Tiers diff --git a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/Tiers/schema.js b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/Tiers/schema.js new file mode 100644 index 0000000000..a992995f54 --- /dev/null +++ b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/Tiers/schema.js @@ -0,0 +1,153 @@ +import * as yup from 'yup' +import { v4 as uuidv4 } from 'uuid' + +import { INPUT_TYPES } from 'client/constants' +import { getValidationFromFields } from 'client/utils/helpers' +import { parseFloat } from 'window-or-global' + +export const ID = { + name: 'id', + label: 'ID', + type: INPUT_TYPES.TEXT, + htmlType: INPUT_TYPES.HIDDEN, + validation: yup + .string() + .trim() + .uuid() + .required() + .default(uuidv4) +} + +const requiredSchema = (mandatory, name, schema) => + mandatory + ? schema.required(`${name} field is required`) + : schema.notRequired().nullable() + +const getRange = (options) => + options.split('..').map(option => parseFloat(option)) + +const getOptionsFromList = (options, separator = ',') => + options?.split(separator).map(value => ({ text: value, value })) + +const getUserInput = ({ mandatory, name, type, options, defaultValue }) => { + switch (type) { + case 'text': + case 'text64': + case 'password': return { + type: INPUT_TYPES.TEXT, + htmlType: type === 'password' ? 'password' : 'text', + validation: yup.string() + .trim() + .concat(requiredSchema(mandatory, name, yup.string())) + .default(defaultValue || undefined) + } + case 'number': + case 'number-float': return { + type: INPUT_TYPES.TEXT, + htmlType: 'number', + validation: yup.number() + .typeError(`${name} must be a number`) + .concat(requiredSchema(mandatory, name, yup.number())) + .transform(value => !isNaN(value) ? value : null) + .default(() => parseFloat(defaultValue) ?? undefined) + } + case 'range': + case 'range-float': { + const [min, max] = getRange(options) + + return { + type: INPUT_TYPES.SLIDER, + validation: yup.number() + .typeError(`${name} must be a number`) + .concat(requiredSchema(mandatory, name, yup.number())) + .min(min, `${name} must be greater than or equal to ${min}`) + .max(max, `${name} must be less than or equal to ${max}`) + .transform(value => !isNaN(value) ? value : undefined) + .default(parseFloat(defaultValue) ?? undefined), + fieldProps: { min, max, step: type === 'range-float' ? 0.01 : 1 } + } + } + case 'boolean': return { + type: INPUT_TYPES.CHECKBOX, + validation: yup.boolean() + .concat(requiredSchema(mandatory, name, yup.boolean())) + .default(defaultValue === 'YES' ?? false) + } + case 'list': { + const values = getOptionsFromList(options) + + return { + values, + type: INPUT_TYPES.SELECT, + validation: yup.string() + .trim() + .concat(requiredSchema(mandatory, name, yup.string())) + .oneOf(values.map(({ value }) => value)) + .default(defaultValue ?? undefined) + } + } + case 'list-multiple': { + const values = getOptionsFromList(options) + const defaultValues = defaultValue?.split(',') ?? undefined + + return { + values, + type: INPUT_TYPES.SELECT, + multiple: true, + validation: yup.array(yup.string().trim()) + .concat(requiredSchema(mandatory, name, yup.array())) + .default(defaultValues) + } + } + default: return { + type: INPUT_TYPES.TEXT, + validation: yup.string() + .trim() + .concat(requiredSchema(mandatory, name, yup.string())) + .default(defaultValue || undefined) + } + } +} + +export const FORM_FIELDS = userInputs => + Object.entries(userInputs)?.map(([name, values]) => { + const input = String(values).split('|') + // 0 mandatory; 1 type; 2 description; 3 range/options; 4 defaultValue; + const mandatory = input[0] === 'M' + const type = input[1] + const description = input[2] + const options = input[3] + const defaultValue = input[4] + + return { + name, + label: `${description}${mandatory ? '  *' : ''}`, + ...getUserInput({ mandatory, name, type, options, defaultValue }) + } + }) + +export const USER_INPUTS_FORM_SCHEMA = userInputs => yup.object( + getValidationFromFields(FORM_FIELDS(userInputs)) +) + +export const STEP_FORM_SCHEMA = ({ tiers, vmTemplates }) => { + const schemasUI = tiers?.reduce((schemas, tier) => { + const { id: tierId, template: { id } } = tier + const vmTemplate = vmTemplates?.find(({ ID }) => id === ID) ?? {} + + const { TEMPLATE: { USER_INPUTS = {} } = {} } = vmTemplate + + return { ...schemas, [tierId]: USER_INPUTS_FORM_SCHEMA(USER_INPUTS) } + }, {}) + + return yup + .array(yup.lazy(value => yup.object({ + ...getValidationFromFields([ID]), + user_inputs_values: schemasUI[value?.id] + }))) + .min(1, 'Should be at least one tier') + .required('Tiers field is required') + .default(() => tiers.map((tier) => ({ + ...tier, user_inputs_values: schemasUI[tier.id].default() + }))) +} diff --git a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/index.js b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/index.js new file mode 100644 index 0000000000..e777ca6dad --- /dev/null +++ b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/Steps/index.js @@ -0,0 +1,30 @@ +import * as yup from 'yup' + +import BasicConfiguration from './BasicConfiguration' +import Networking, { STEP_ID as NETWORKING_ID } from './Networking' +import Tiers, { STEP_ID as TIERS_ID } from './Tiers' + +const Steps = ({ applicationTemplate = {}, vmTemplates }) => { + const { + [TIERS_ID]: appTiers, + [NETWORKING_ID]: appNetworking + } = applicationTemplate + + const basic = BasicConfiguration() + const tiers = Tiers({ tiers: appTiers, vmTemplates }) + const networking = Networking() + + const steps = [basic, tiers] + appNetworking?.length > 0 && steps.push(networking) + + const resolvers = () => yup + .object(steps.reduce((res, step) => ({ + ...res, [step.id]: step.resolver + }), {})) + + const defaultValues = resolvers().default() + + return { steps, defaultValues, resolvers } +} + +export default Steps diff --git a/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/index.js b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/index.js new file mode 100644 index 0000000000..7219720731 --- /dev/null +++ b/src/fireedge/src/client/containers/ApplicationsTemplates/Form/Deploy/index.js @@ -0,0 +1,105 @@ +import React, { useEffect, useMemo, useState } from 'react' +import PropTypes from 'prop-types' + +import { makeStyles, CircularProgress, Backdrop } from '@material-ui/core' + +import useFetchAll from 'client/hooks/useFetchAll' +import useOpennebula from 'client/hooks/useOpennebula' +import useApplication from 'client/hooks/useApplication' + +import { DialogForm } from 'client/components/Dialogs' +import FormStepper from 'client/components/FormStepper' +import mapApplicationToForm from 'client/utils/parser/toApplicationForm' +import mapFormToDeployApplication from 'client/utils/parser/toDeployApplication' + +import Steps from './Steps' + +const useStyles = makeStyles(theme => ({ + backdrop: { + zIndex: theme.zIndex.appBar, + color: theme.palette.common.white + } +})) + +const DeployForm = ({ applicationTemplate, handleCancel }) => { + const classes = useStyles() + const [vmTemplates, setVmTemplates] = useState([]) + const { instantiateApplicationTemplate } = useApplication() + const { getTemplate } = useOpennebula() + const { data, fetchRequestAll, loading } = useFetchAll() + + const applicationParsed = useMemo(() => + mapApplicationToForm(applicationTemplate) + , []) + + const { steps, resolvers } = Steps({ + applicationTemplate: applicationParsed, + vmTemplates + }) + + useEffect(() => { + const { tiers } = applicationParsed + + const fetchTemplates = tiers + ?.map(({ template: { id } }) => id) + ?.reduce((list, templateId) => + list.includes(templateId) ? list : [...list, templateId] + , []) + ?.map(templateId => + getTemplate({ id: templateId }).then(vmTemplate => + setVmTemplates(prev => [...prev, vmTemplate]) + ) + ) + + fetchRequestAll(fetchTemplates) + }, [applicationParsed]) + + const handleSubmit = values => { + const { + instances, + ...application + } = mapFormToDeployApplication(values, applicationParsed) + + return instantiateApplicationTemplate({ + id: applicationTemplate.ID, + data: application, + instances + }).then(() => handleCancel()) + } + + if ((applicationTemplate && !data) || loading) { + return ( + + + + ) + } + + return ( + + + + ) +} + +DeployForm.propTypes = { + applicationTemplate: PropTypes.object.isRequired, + handleCancel: PropTypes.func +} + +DeployForm.defaultProps = { + applicationTemplate: undefined, + handleCancel: undefined +} + +export default DeployForm diff --git a/src/fireedge/src/client/containers/ApplicationsTemplates/index.js b/src/fireedge/src/client/containers/ApplicationsTemplates/index.js index 14ff8f759c..9990acd090 100644 --- a/src/fireedge/src/client/containers/ApplicationsTemplates/index.js +++ b/src/fireedge/src/client/containers/ApplicationsTemplates/index.js @@ -1,21 +1,31 @@ -import React, { useEffect } from 'react' +import React, { useEffect, useState } from 'react' import { useHistory } from 'react-router-dom' -import { LinearProgress, Container, Box } from '@material-ui/core' +import { Container, Box } from '@material-ui/core' import { Alert } from '@material-ui/lab' import { PATH } from 'client/router/fireedge' import useApplication from 'client/hooks/useApplication' import useFetch from 'client/hooks/useFetch' -// import DeployForm from 'client/containers/Applications/Form' +import DeployForm from 'client/containers/ApplicationsTemplates/Form/Deploy' import ListCards from 'client/components/List/ListCards' import { ApplicationTemplateCard } from 'client/components/Cards' -import { Tr } from 'client/components/HOC' -const ApplicationsTemplates = () => { +import { Tr } from 'client/components/HOC' +import { CannotConnectOneFlow } from 'client/constants/translates' + +const Error = () => ( + + + {Tr(CannotConnectOneFlow)} + + +) + +function ApplicationsTemplates () { const history = useHistory() - // const [showDialog, setShowDialog] = useState(false) + const [showDialog, setShowDialog] = useState(false) const { applicationsTemplates, getApplicationsTemplates } = useApplication() const { fetchRequest, loading, error } = useFetch(getApplicationsTemplates) @@ -24,17 +34,7 @@ const ApplicationsTemplates = () => { }, []) if (error) { - return ( - - - {Tr('Cannot connect to OneFlow server')} - - - ) - } - - if (loading) { - return + return } return ( @@ -42,18 +42,22 @@ const ApplicationsTemplates = () => { history.push(PATH.APPLICATIONS_TEMPLATES.CREATE)} CardComponent={ApplicationTemplateCard} - cardsProps={({ value: { ID } }) => ({ + cardsProps={({ value }) => ({ handleEdit: () => - history.push(PATH.APPLICATIONS_TEMPLATES.EDIT.replace(':id', ID)), - // handleShow: () => setShowDialog(ID), + history.push(PATH.APPLICATIONS_TEMPLATES.EDIT.replace(':id', value?.ID)), + handleDeploy: () => setShowDialog(value), handleRemove: undefined })} /> - {/* {showDialog !== false && ( - setShowDialog(false)} /> - )} */} + {showDialog !== false && ( + setShowDialog(false)} + /> + )} ) diff --git a/src/fireedge/src/client/containers/Login/schema.js b/src/fireedge/src/client/containers/Login/schema.js index 3ce543bcd5..98db842211 100644 --- a/src/fireedge/src/client/containers/Login/schema.js +++ b/src/fireedge/src/client/containers/Login/schema.js @@ -109,9 +109,7 @@ export const GROUP = { .nullable() .default(FILTER_POOL.ALL_RESOURCES), grid: { md: 12 }, - fieldProps: { - variant: 'outlined' - } + fieldProps: { variant: 'outlined' } } export const FORM_USER_FIELDS = [USERNAME, PASSWORD, REMEMBER] diff --git a/src/fireedge/src/client/containers/Providers/Form/Create/Steps/Provider/index.js b/src/fireedge/src/client/containers/Providers/Form/Create/Steps/Provider/index.js index f0fc4ce229..8ef820e12c 100644 --- a/src/fireedge/src/client/containers/Providers/Form/Create/Steps/Provider/index.js +++ b/src/fireedge/src/client/containers/Providers/Form/Create/Steps/Provider/index.js @@ -1,7 +1,6 @@ import React, { useCallback, useEffect } from 'react' import { Redirect } from 'react-router-dom' -import { LinearProgress } from '@material-ui/core' import FileIcon from '@material-ui/icons/Description' import useFetch from 'client/hooks/useFetch' @@ -42,11 +41,10 @@ const Provider = () => ({ return } - return (!templates || loading) ? ( - - ) : ( + return ( } CardComponent={SelectCard} cardsProps={({ value: { name } }) => { diff --git a/src/fireedge/src/client/containers/Providers/index.js b/src/fireedge/src/client/containers/Providers/index.js index e135e51e76..06b27281b4 100644 --- a/src/fireedge/src/client/containers/Providers/index.js +++ b/src/fireedge/src/client/containers/Providers/index.js @@ -1,7 +1,7 @@ import React, { useEffect } from 'react' import { useHistory } from 'react-router-dom' -import { LinearProgress, Container, Box } from '@material-ui/core' +import { Container, Box } from '@material-ui/core' import { Alert } from '@material-ui/lab' import { PATH } from 'client/router/provision' @@ -31,15 +31,12 @@ const Providers = () => { ) } - if (loading) { - return - } - return ( history.push(PATH.PROVIDERS.CREATE)} CardComponent={ProviderCard} cardsProps={({ value: { ID } }) => ({ diff --git a/src/fireedge/src/client/containers/Provisions/index.js b/src/fireedge/src/client/containers/Provisions/index.js index 8bda90fe02..f333726f58 100644 --- a/src/fireedge/src/client/containers/Provisions/index.js +++ b/src/fireedge/src/client/containers/Provisions/index.js @@ -1,7 +1,7 @@ import React, { useEffect } from 'react' import { useHistory } from 'react-router-dom' -import { LinearProgress, Container, Box } from '@material-ui/core' +import { Container, Box } from '@material-ui/core' import { Alert } from '@material-ui/lab' import { PATH } from 'client/router/provision' @@ -31,15 +31,12 @@ const Provisions = () => { ) } - if (loading) { - return - } - return ( history.push(PATH.PROVISIONS.CREATE)} CardComponent={ProviderCard} cardsProps={({ value: { ID } }) => ({ diff --git a/src/fireedge/src/client/hooks/useApplication.js b/src/fireedge/src/client/hooks/useApplication.js index 8bc28db427..980686c553 100644 --- a/src/fireedge/src/client/hooks/useApplication.js +++ b/src/fireedge/src/client/hooks/useApplication.js @@ -53,7 +53,10 @@ export default function useOpennebula () { ({ end, start } = { end: -1, start: -1 }) => serviceApplication .getTemplates({ filter, end, start }) - .then(doc => dispatch(setApplicationsTemplates(doc))) + .then(doc => { + dispatch(setApplicationsTemplates(doc)) + return doc + }) .catch(err => { dispatch(enqueueError(err ?? 'Error GET applications templates')) }), @@ -103,24 +106,22 @@ export default function useOpennebula () { ) const instantiateApplicationTemplate = useCallback( - ({ id, data }) => - serviceApplication - .instantiateTemplate({ id, data }) - .then(doc => { - dispatch( - setApplicationsTemplates( - filterBy([doc].concat(applicationsTemplates), 'ID') - ) - ) + ({ id, data, instances }) => { + const promises = [...new Array(instances)] + .map(() => serviceApplication.instantiateTemplate({ id, data })) - return dispatch(enqueueSuccess(`Template instantiate - ID: ${doc.ID}`)) + return Promise.all(promises) + .then(docs => { + dispatch(enqueueSuccess(`Template instantiate - x${instances}`)) + return docs }) .catch(err => { dispatch( enqueueError(err?.message ?? 'Error INSTANTIATE application template') ) - }), - [dispatch] + }) + } + , [dispatch] ) return { diff --git a/src/fireedge/src/client/hooks/useFetchAll.js b/src/fireedge/src/client/hooks/useFetchAll.js new file mode 100644 index 0000000000..5012cc0b7e --- /dev/null +++ b/src/fireedge/src/client/hooks/useFetchAll.js @@ -0,0 +1,26 @@ +import { useState, useCallback } from 'react' + +const useRequestAll = () => { + const [data, setData] = useState(undefined) + const [loading, setLoading] = useState(false) + const [error, setError] = useState(false) + + const fetchRequestAll = useCallback( + requests => { + setLoading(true) + setError(false) + + Promise + .all(requests) + .then(response => { + if (response !== undefined) setData(response) + else setError(true) + }) + .finally(() => { setLoading(false) }) + }, + [] + ) + + return { data, fetchRequestAll, loading, error } +} +export default useRequestAll diff --git a/src/fireedge/src/client/hooks/useOpennebula.js b/src/fireedge/src/client/hooks/useOpennebula.js index f42e8bf1a2..51f3118b08 100644 --- a/src/fireedge/src/client/hooks/useOpennebula.js +++ b/src/fireedge/src/client/hooks/useOpennebula.js @@ -100,7 +100,10 @@ export default function useOpennebula () { dispatch(startOneRequest()) return servicePool .getClusters({ filter }) - .then(data => dispatch(actions.setCluster(data))) + .then(data => { + dispatch(actions.setCluster(data)) + return data + }) .catch(err => dispatch(failureOneRequest({ error: err }))) }, [dispatch, filter]) diff --git a/src/fireedge/src/client/services/application.js b/src/fireedge/src/client/services/application.js index ed602dd301..16a2821781 100644 --- a/src/fireedge/src/client/services/application.js +++ b/src/fireedge/src/client/services/application.js @@ -30,10 +30,6 @@ export const getApplications = ({ filter }) => return [res?.data?.DOCUMENT_POOL?.DOCUMENT ?? []].flat() }) -export const createApplication = () => { - // request -} - export const getTemplate = ({ id }) => requestData(`/api/${SERVICE_TEMPLATE}/list/${id}`, { method: GET, @@ -96,7 +92,6 @@ export const instantiateTemplate = ({ id, data = {} }) => export default { getApplication, getApplications, - createApplication, getTemplate, getTemplates, diff --git a/src/fireedge/src/client/utils/helpers.js b/src/fireedge/src/client/utils/helpers.js index fbd2521dad..93707759b2 100644 --- a/src/fireedge/src/client/utils/helpers.js +++ b/src/fireedge/src/client/utils/helpers.js @@ -25,6 +25,12 @@ export const filterBy = (arr, predicate) => { .values() ] } +export const groupBy = (array, key) => + array.reduce((objectsByKeyValue, obj) => { + const value = obj[key] + objectsByKeyValue[value] = (objectsByKeyValue[value] || []).concat(obj) + return objectsByKeyValue + }, {}) export const get = (obj, path, defaultValue = undefined) => { const travel = regexp => diff --git a/src/fireedge/src/client/utils/merge.js b/src/fireedge/src/client/utils/merge.js new file mode 100644 index 0000000000..f57b4c4a92 --- /dev/null +++ b/src/fireedge/src/client/utils/merge.js @@ -0,0 +1,73 @@ +export const isMergeableObject = (val) => { + var nonNullObject = val && typeof val === 'object' + + return nonNullObject && + Object.prototype.toString.call(val) !== '[object RegExp]' && + Object.prototype.toString.call(val) !== '[object Date]' +} + +export const emptyTarget = (val) => { + return Array.isArray(val) ? [] : {} +} + +export const cloneIfNecessary = (value, optionsArgument) => { + var clone = optionsArgument && optionsArgument.clone === true + return (clone && isMergeableObject(value)) + ? deepmerge(emptyTarget(value), value, optionsArgument) : value +} + +export const defaultArrayMerge = (target, source, optionsArgument) => { + var destination = target.slice() + source.forEach(function (e, i) { + if (typeof destination[i] === 'undefined') { + destination[i] = cloneIfNecessary(e, optionsArgument) + } else if (isMergeableObject(e)) { + destination[i] = deepmerge(target[i], e, optionsArgument) + } else if (target.indexOf(e) === -1) { + destination.push(cloneIfNecessary(e, optionsArgument)) + } + }) + return destination +} + +export const mergeObject = (target, source, optionsArgument) => { + var destination = {} + if (isMergeableObject(target)) { + Object.keys(target).forEach(function (key) { + destination[key] = cloneIfNecessary(target[key], optionsArgument) + }) + } + Object.keys(source).forEach(function (key) { + if (!isMergeableObject(source[key]) || !target[key]) { + destination[key] = cloneIfNecessary(source[key], optionsArgument) + } else { + destination[key] = deepmerge(target[key], source[key], optionsArgument) + } + }) + return destination +} + +export const deepmerge = (target, source, optionsArgument) => { + var array = Array.isArray(source) + var options = optionsArgument || { arrayMerge: defaultArrayMerge } + var arrayMerge = options.arrayMerge || defaultArrayMerge + + if (array) { + return Array.isArray(target) + ? arrayMerge(target, source, optionsArgument) + : cloneIfNecessary(source, optionsArgument) + } else { + return mergeObject(target, source, optionsArgument) + } +} + +deepmerge.all = function deepmergeAll (array, optionsArgument) { + if (!Array.isArray(array) || array.length < 2) { + throw new Error('first argument should be an array with at least two elements') + } + + // we are sure there are at least 2 values, so it is safe to have no initial value + return array.reduce(function (prev, next) { + return deepmerge(prev, next, optionsArgument) + }) +} diff --git a/src/fireedge/src/client/utils/parser/toApplicationTemplate.js b/src/fireedge/src/client/utils/parser/toApplicationTemplate.js index 6d820c57bb..51682f344c 100644 --- a/src/fireedge/src/client/utils/parser/toApplicationTemplate.js +++ b/src/fireedge/src/client/utils/parser/toApplicationTemplate.js @@ -14,7 +14,7 @@ const mapNetworkToUserInput = network => { return `${mandatoryValue}|network|${descriptionValue}| |${type}:${idVnetValue}${extraValue}` } -const mapTiersToRoles = (tiers, networking, cluster) => +export const mapTiersToRoles = (tiers, networking, cluster) => tiers?.map(data => { const { template, networks, parents, policies, position, tier } = data const { shutdown_action: action, ...information } = tier diff --git a/src/fireedge/src/client/utils/parser/toDeployApplication.js b/src/fireedge/src/client/utils/parser/toDeployApplication.js new file mode 100644 index 0000000000..4b7b9ff0dd --- /dev/null +++ b/src/fireedge/src/client/utils/parser/toDeployApplication.js @@ -0,0 +1,69 @@ +import { STEP_ID as BASIC_ID } from 'client/containers/ApplicationsTemplates/Form/Deploy/Steps/BasicConfiguration' +import { STEP_ID as NETWORKING_ID } from 'client/containers/ApplicationsTemplates/Form/Deploy/Steps/Networking' +import { STEP_ID as TIERS_ID } from 'client/containers/ApplicationsTemplates/Form/Deploy/Steps/Tiers' +import { STEP_ID as CLUSTER_ID } from 'client/containers/ApplicationsTemplates/Form/Create/Steps/Clusters' + +import { deepmerge } from 'client/utils/merge' + +export const parseUserInputValue = value => { + if (value === true) { + return 'YES' + } if (value === false) { + return 'NO' + } else if (Array.isArray(value)) { + return value.join(',') + } else return value +} + +export const mapUserInputs = userInputs => + Object.entries(userInputs)?.reduce((res, [key, value]) => ({ + ...res, [key]: parseUserInputValue(value) + }), {}) + +export const mapTiersToRoles = (tiers, networking, cluster) => + tiers?.map(data => { + const { template, parents, networks, user_inputs_values = {}, tier } = data + + const networksValue = networks + ?.reduce((res, id, idx) => { + const network = networking.find(net => net.id === id) + const networkString = `NIC = [\n NAME = "NIC${idx}",\n NETWORK_ID = "$${network.name}" ]\n` + + return [...res, networkString] + }, []) + ?.join('') + ?.concat(`SCHED_REQUIREMENTS = "ClUSTER_ID=\\"${cluster}\\""`) + + const parentsValue = parents?.reduce((res, id) => { + const parent = tiers.find(t => t.id === id) + return [...res, parent?.tier?.name] + }, []) + + return { + ...tier, + parents: parentsValue, + vm_template: template?.id ?? template?.app, + vm_template_contents: networksValue, + user_inputs_values: mapUserInputs(user_inputs_values) + } + }) + +const mapFormToDeployApplication = (formData, template) => { + const { + [BASIC_ID]: application, + [NETWORKING_ID]: networking, + [CLUSTER_ID]: cluster, + [TIERS_ID]: tiers + } = deepmerge(template, formData) + + return { + ...application, + custom_attrs_values: {}, + networks_values: networking?.map(({ name, type, idVnet }) => ({ + [name]: { [type]: idVnet } + })), + roles: mapTiersToRoles(tiers, networking, cluster) + } +} + +export default mapFormToDeployApplication