Skip to content

Instantly share code, notes, and snippets.

@gcmatheusj
Created May 5, 2020 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gcmatheusj/67b0da4704d69a7fe375f9b48fbbfd19 to your computer and use it in GitHub Desktop.
Save gcmatheusj/67b0da4704d69a7fe375f9b48fbbfd19 to your computer and use it in GitHub Desktop.
import * as React from 'react';
import styled from 'styled-components';
import media from 'styled-media-query';
import { Form, FormikProps } from 'formik';
import LinearProgress from '@material-ui/core/LinearProgress';
import CardContent from '@material-ui/core/CardContent';
import CardActions from '@material-ui/core/CardActions';
import Button from '@material-ui/core/Button';
import addYears from 'date-fns/addYears';
import SwitchOptionals from './components/form/SwitchOptionals';
import Card from '../common/Card';
import {
SelectInput,
TextInput,
DateInput,
SliderInput,
} from '../common/inputs';
import { useSnackbarWithStatus } from '../common/snackbar/SnackbarContext';
import { MASK_TYPES } from '../utils/masks';
import {
TypeProduct,
TERM_RANGE,
LOAN_VALUE_RANGE,
calculateMaxTermByBirthDate,
} from './components/form/helpers';
import { Simulation } from '../lead/preProposal/simulator/helpers';
export { simulatorValidationSchema } from './components/form/validationSchema';
const Wrapper = styled.div`
.MuiCardActions-root {
padding: 16px;
}
height: 100%;
> form {
height: 100%;
}
${media.lessThan('medium')`
.MuiCard-root {
border-radius: 0;
}
width: 100% !important;
`}
`;
const StyledCardActions = styled(CardActions)`
&& {
justify-content: center;
}
> button {
${media.lessThan('medium')`
width: 100%;
`}
}
`;
const OptionsWrapper = styled.div`
width: 100%;
> div {
flex-wrap: wrap;
flex-direction: row;
margin-bottom: 0;
}
`;
const InputWrapper = styled.div`
display: flex;
flex-direction: column;
> div {
margin-top: 0 !important;
margin-bottom: 0.8rem !important;
}
`;
const StyledCard = styled(Card)`
border-radius: 4px !important;
`;
export const simulatorInitialValues = {
propertyValue: 0,
loanValue: 0,
term: TERM_RANGE[TypeProduct.PURCHASE].max,
product: TypeProduct.PURCHASE,
birthDate: null,
timePeriod: 0,
financialAnalysisValue: 0, //financiar analise juridica
fundEvaluatingPropertyValue: 0, //financiar Avaliacao Imovel
financialAnalysis: false, //financiar analise juridica
fundEvaluatingProperty: false, //financiar Avaliacao Imovel
fundRateFee: false, //financiarTaxaCartorio
fundIOF: false, //financiarIOF
financeRateRegister: false, //financiarTaxaCadastro
fundITBI: false, //financiarITBI
};
export const onChangeProduct = ({ name, setFieldValue, values }) => (e) => {
const { value } = e.target;
const termRange = TERM_RANGE[value];
const loanValueRange = LOAN_VALUE_RANGE[value];
setFieldValue(name, value);
Object.entries(simulatorInitialValues).map(([field, value]) => {
if (
!['propertyValue', 'birthDate', 'loanValue', 'term', 'product'].includes(
field,
)
) {
setFieldValue(field, value);
}
});
if (termRange) setFieldValue('term', termRange.max);
if (loanValueRange) {
const { propertyValue } = values;
if (loanValueRange.max(propertyValue) < loanValueRange.min)
return setFieldValue('loanValue', loanValueRange.min);
if (propertyValue < 200000)
return setFieldValue('loanValue', loanValueRange.max(200000));
setFieldValue('loanValue', loanValueRange.max(200000));
}
};
export const onChangeBirthDate = ({ name, setFieldValue, values }) => (
value,
) => {
const range = TERM_RANGE[values.product];
const months = calculateMaxTermByBirthDate({
birthDate: value,
value: range.max,
});
const termExcess = months - 966;
setFieldValue(name, value);
if (termExcess > 0) {
const maxTerm = range.max - termExcess;
if (maxTerm < 0) setFieldValue('term', 0);
else setFieldValue('term', maxTerm);
}
};
export const FormContent = ({ values, setFieldValue }) => {
const handleBlurPropertyValue = () => {
if (!values.loanValue) setFieldValue('loanValue', values.propertyValue * 0.8)
};
return (
<>
<SelectInput
name="product"
label={'Produto'}
options={Object.values(TypeProduct).map((type) => ({
label: type,
value: type,
}))}
handleChange={onChangeProduct({
name: 'product',
setFieldValue,
values,
})}
/>
<TextInput
required
name="propertyValue"
onBlur={handleBlurPropertyValue}
label="Valor do Imóvel"
mask={MASK_TYPES.MONEY}
max={100000000}
/>
<TextInput
required
name="loanValue"
label="Valor do financiamento"
mask={MASK_TYPES.MONEY}
/>
<DateInput
required
name="birthDate"
label="Data de nascimento"
maxDate={addYears(new Date(), -18)}
minDate={addYears(new Date(), -80)}
minErrorMessage="A idade deve ser até 80 anos"
maxErrorMessage="A idade deve ser maior que 18 anos"
onChange={onChangeBirthDate({
name: 'birthDate',
values,
setFieldValue,
})}
/>
<SliderInput
required
name="term"
label="Prazo"
defaultValue={TERM_RANGE[values.product].max}
color="primary"
value={values.term}
setFieldValue={setFieldValue}
min={TERM_RANGE[values.product].min}
max={TERM_RANGE[values.product].max}
/>
{values.product === TypeProduct.PRICE_LIGHT && (
<TextInput name="timePeriod" label="Carência" type="number" />
)}
{values.product !== TypeProduct.PRICE_LIGHT && <div />}
</>
);
};
interface Props {
onSimulator: boolean;
onNextStep?: () => void;
}
const SimulatorInnerForm = ({
isSubmitting,
setFieldValue,
isValid,
status,
handleChange,
values,
onSimulator,
errors
}: Props & FormikProps<Simulation>) => {
useSnackbarWithStatus(status);
<<<<<<< Updated upstream
=======
//console.log(values)
>>>>>>> Stashed changes
return (
<Wrapper onSimulator={onSimulator}>
<Form data-testid="simulator-form">
<StyledCard hideContentWrapper>
<CardContent>
<InputWrapper>
<FormContent
values={values}
setFieldValue={setFieldValue}
handleChange={handleChange}
/>
</InputWrapper>
{onSimulator && (
<OptionsWrapper>
<SwitchOptionals
values={values}
handleChange={handleChange}
setFieldValue={setFieldValue}
/>
</OptionsWrapper>
)}
{isSubmitting && <LinearProgress />}
</CardContent>
<StyledCardActions>
<Button
variant={'contained'}
color={'primary'}
type={'submit'}
data-testid={'submit-button'}
disabled={!isValid || isSubmitting}
>
Simular
</Button>
</StyledCardActions>
</StyledCard>
</Form>
</Wrapper>
);
};
export default SimulatorInnerForm;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment