Skip to content

Commit

Permalink
Added company values filling form inputs and editCompany service
Browse files Browse the repository at this point in the history
  • Loading branch information
tomaspalma committed Sep 16, 2023
1 parent 1d05cf2 commit a8817e4
Show file tree
Hide file tree
Showing 9 changed files with 238 additions and 122 deletions.
2 changes: 1 addition & 1 deletion src/AppRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import {
import { CookieConsent } from "./cookieConsent";
import {
EditOfferController,
EditOfferControllerContext
EditOfferControllerContext,
} from "./components/Offers/Edit/EditOfferForm";
import EditOfferPage from "./pages/EditOfferPage";
import PrivacyPolicyPage from "./pages/PrivacyPolicyPage";
Expand Down
253 changes: 149 additions & 104 deletions src/components/Company/Edit/EditCompanyProfileForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ import {
} from "@material-ui/core";
import { useMobile } from "../../../utils/media-queries";
import useOfferFormStyles from "../../../components/Offers/Form/form-components/offerStyles";
import { editCompany } from "../../../services/companyEditService";
import TextEditorComponent from "../../Offers/Form/form-components/TextEditorComponent";

Check failure on line 19 in src/components/Company/Edit/EditCompanyProfileForm.js

View workflow job for this annotation

GitHub Actions / build

'TextEditorComponent' is defined but never used
import useOffer from "../../../hooks/useOffer";
import { Controller, useForm } from "react-hook-form";
import { Controller, useForm, useWatch } from "react-hook-form";
import useCompany from "../../../hooks/useCompany";
import useSession from "../../../hooks/useSession";
import { Redirect, useLocation, useParams } from "react-router-dom/cjs/react-router-dom.min";
Expand All @@ -31,19 +31,39 @@ export const EditCompanyControllerContext = React.createContext();

const useStyles = makeStyles((theme) => ({
submitBtn: {
marginTop: theme.spacing(2)
}
marginTop: theme.spacing(2),
},
}));

const parseCompany = ({
contacts,
...company
}) => ({
contacts: contacts.map((value) => ({ value })),
...company,
});

export const EditCompanyController = () => {
const { id } = useParams();
const { company, error: companyError, loading: loadingCompany } = useCompany(id);
const { data: user, isValidating } = useSession();
let canEditRaceControl = false;

const shouldRevalidateEditingPermissions = useCallback(() => {
return user?.isAdmin || user?.company?._id === id;
}, [company, user]);
const { handleSubmit, control, reset, getValues } = useForm({
mode: "all",
resolver: yupResolver(EditCompanySchema),
defaultValues: {
logo: "",
name: "",
contacts: [],
bio: "",
},
reValidateMode: "onChange",
});

const fields = useWatch({ control });

const shouldRevalidateEditingPermissions = useCallback(() => user?.isAdmin || user?.company?._id === id, [id, user]);

const [canEdit, setCanEdit] = useState(shouldRevalidateEditingPermissions());

Expand All @@ -54,6 +74,12 @@ export const EditCompanyController = () => {
}
}, [shouldRevalidateEditingPermissions, loadingCompany, company, user]);

useEffect(() => {
if (company && !isValidating && canEdit) {
reset(parseCompany(company));
}
}, [canEdit, isValidating, company, reset]);

const location = useLocation();
const redirectProps = {
to: {
Expand All @@ -65,6 +91,15 @@ export const EditCompanyController = () => {
},
};

const submit = (data) => {

Check failure on line 94 in src/components/Company/Edit/EditCompanyProfileForm.js

View workflow job for this annotation

GitHub Actions / build

'data' is defined but never used. Allowed unused args must match /^_/u
editCompany({ _id: id, name: fields.name }).then(() => {


}).catch((err) => {

Check failure on line 98 in src/components/Company/Edit/EditCompanyProfileForm.js

View workflow job for this annotation

GitHub Actions / build

'err' is defined but never used. Allowed unused args must match /^_/u

});
};

return {
controllerOptions: {
initialValue: {
Expand All @@ -75,7 +110,11 @@ export const EditCompanyController = () => {
companyError,
isValidating,
canEditRaceControl,
}
control,
fields,
getValues,
submit: handleSubmit(submit),
},
},
};
};
Expand All @@ -92,33 +131,14 @@ const EditCompanyProfileForm = ({ title }) => {
redirectProps,
isValidating,
canEditRaceControl,
control,
getValues,
submit,
} = useContext(EditCompanyControllerContext);

const classes = useStyles();

const { control } = useForm({
mode: "all",
resolver: yupResolver(EditCompanySchema),
reValidateMode: "onChange",
});

const { fields, append, remove } = useContacts({ control });

const getContacts = useCallback(() => {
if (!company) return [{}];

const contacts = company.contacts;

const result = [];
for (let i = 0; i < contacts.length; i++) {
result.push({
id: i,
value: contacts[i],
});
}

return result;
}, [company]);
const { fields: contacts, append, remove } = useContacts({ control });

const Content = isMobile ? DialogContent : CardContent;

Expand All @@ -130,89 +150,114 @@ const EditCompanyProfileForm = ({ title }) => {
<div className={formCardClasses.formCard}>
<CardHeader title={title} />
<Content className={formCardClasses.formContent}>
<Grid container spacing={4} className={formCardClasses.formArea}>
<Grid container className={formCardClasses.formArea}>
<Grid item xs={12}>
<Box
display="flex"
justifyContent="center"
<form
onSubmit={submit}
>
<Avatar
alt={`${company?.name}'s logo`}
src={company?.logo}
style={{ height: '5em', width: '5em' }}
/>
</Box>
</Grid>
<Grid item xs={12}>
<TextField
label="Name"
value={company?.name}
fullWidth
required
autoFocus
/>
</Grid>
<Grid item xs={12}>
<MultiOptionTextField
control={control}
controllerName="contacts"
values={getContacts()}
onAdd={append}
onRemove={remove}
/>
</Grid>
<Grid item xs={12}>
<Controller
name="bio"
render={(
{ field: { onChange, onBlur, ref, name, value } },
) => (
<TextField
name={name}
value={value}
label="Company Bio"
id="bio"
// error={!!errors.bio}
inputRef={ref}
onBlur={onBlur}
onChange={onChange}
multiline
// helperText={
// `${value?.length}/${FinishCompanyRegistrationConstants.bio.maxLength} ${errors.bio?.message || ""}`
// }
rows={5}
variant="outlined"
FormHelperTextProps={{
style: {
marginLeft: 0,
},
}}
fullWidth
/>)}
control={control}
/>
<Grid container spacing={4}>
<Grid item xs={12}>
<Box
display="flex"
justifyContent="center"
>
<Avatar
alt={`${company?.name}'s logo`}
src={company?.logo}
style={{ height: "5em", width: "5em" }}
/>
</Box>
</Grid>
<Grid item xs={12}>
<Controller
name="name"
render={(
{ field: {
onChange, onBlur, ref, name, value,
} }
) => (
<TextField
label="Name"
name={name}
id={name}
inputRef={ref}
onBlur={onBlur}
value={value}
fullWidth
required
autoFocus
onChange={onChange}
/>
)}
control={control}
/>
</Grid>
<Grid item xs={12}>
<MultiOptionTextField
values={contacts}
control={control}
controllerName="contacts"
getValues={getValues}
onAdd={append}
onRemove={remove}
itemLabelPrefix="Contact #"
/>
</Grid>
<Grid item xs={12}>
<Controller
name="bio"
render={(
{ field: { onChange, onBlur, ref, name, value } },
) => (
<TextField
name={name}
value={value}
label="Company Bio"
id="bio"
// error={!!errors.bio}
inputRef={ref}
onBlur={onBlur}
onChange={onChange}
multiline
// helperText={
// `${value?.length}/${FinishCompanyRegistrationConstants.bio.maxLength} ${errors.bio?.message || ""}`

Check failure on line 223 in src/components/Company/Edit/EditCompanyProfileForm.js

View workflow job for this annotation

GitHub Actions / build

This line has a length of 154. Maximum allowed is 140
// }
rows={5}
variant="outlined"
FormHelperTextProps={{
style: {
marginLeft: 0,
},
}}
fullWidth
/>)}
control={control}
/>
</Grid>
</Grid>
<Button
// disabled={loading || formDisabled}
variant="contained"
color="primary"
type="submit"
className={classes.submitBtn}
>
Submit
</Button>
<div className={formCardClasses.requiredFields}>
<Typography>* Required fields</Typography>
</div>
</form>
</Grid>
</Grid>
<Button
// disabled={loading || formDisabled}
variant="contained"
color="primary"
type="submit"
className={classes.submitBtn}
>
Submit
</Button>
<div className={formCardClasses.requiredFields}>
<Typography>* Required fields</Typography>
</div>
</Content>
</div>

</>;

Check failure on line 256 in src/components/Company/Edit/EditCompanyProfileForm.js

View workflow job for this annotation

GitHub Actions / build

Expected closing tag to match indentation of opening
};

EditCompanyProfileForm.propTypes = {
title: PropTypes.string
}
title: PropTypes.string,
};

export default EditCompanyProfileForm;
18 changes: 18 additions & 0 deletions src/components/Company/Edit/EditCompanySchema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import * as yup from "yup";
import { HumanValidationReasons } from "../../../utils";
import FinishCompanyRegistrationSchema from "../Registration/Finish/FinishCompanyRegistrationSchema";

Check failure on line 3 in src/components/Company/Edit/EditCompanySchema.js

View workflow job for this annotation

GitHub Actions / build

'FinishCompanyRegistrationSchema' is defined but never used
import { generateValidationRule } from "./EditCompanyUtils";

// export default FinishCompanyRegistrationSchema.concat(yup.object().shape({
// name: yup.string()
// .required(HumanValidationReasons.REQUIRED)
// .min(...generateValidationRule("name", "minLength", HumanValidationReasons.TOO_SHORT))
// .max(...generateValidationRule("name", "maxLength", HumanValidationReasons.TOO_LONG)),
// }));

export default yup.object().shape({
name: yup.string()
.required(HumanValidationReasons.REQUIRED)
.min(...generateValidationRule("name", "minLength", HumanValidationReasons.TOO_SHORT))
.max(...generateValidationRule("name", "maxLength", HumanValidationReasons.TOO_LONG)),
});
8 changes: 8 additions & 0 deletions src/components/Company/Edit/EditCompanyUtils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { validationRulesGenerator, generalHumanError } from "../../../utils";

Check failure on line 1 in src/components/Company/Edit/EditCompanyUtils.js

View workflow job for this annotation

GitHub Actions / build

'generalHumanError' is defined but never used
import { CompanyApplicationConstants } from "../../Apply/Company/CompanyApplicationUtils";

export const EditCompanyConstants = {
name: { ...CompanyApplicationConstants.companyName },
};

export const generateValidationRule = validationRulesGenerator(EditCompanyConstants);
10 changes: 5 additions & 5 deletions src/components/Company/Registration/Finish/LogoUploadForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export const useLogoUpload = ({ watch }) => {
useEffect(() => {
if (!logoInput) {
setLogoPreview(undefined);
return () => {};
return () => { };
} else {

const objectUrl = URL.createObjectURL(logoInput);
Expand Down Expand Up @@ -180,10 +180,10 @@ const LogoUploadForm = () => {
>
<Grid item xs={12} sm={4}>
{logoPreview &&
<LogoPreview
img={logoPreview}
setCroppedAreaPixels={setCroppedAreaPixels}
/> }
<LogoPreview
img={logoPreview}
setCroppedAreaPixels={setCroppedAreaPixels}
/>}
</Grid>
</Grid>
<Typography
Expand Down
Loading

0 comments on commit a8817e4

Please sign in to comment.