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 18, 2023
1 parent 1d05cf2 commit 2e4ebe9
Show file tree
Hide file tree
Showing 9 changed files with 280 additions and 148 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
271 changes: 167 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 @@ -29,21 +29,59 @@ import { useContacts } from "../Registration/Finish/ContactsForm";

export const EditCompanyControllerContext = React.createContext();

const EditImage = ({ style, image, imageAlt }) => {

Check warning on line 32 in src/components/Company/Edit/EditCompanyProfileForm.js

View workflow job for this annotation

GitHub Actions / build

'style' is missing in props validation

Check warning on line 32 in src/components/Company/Edit/EditCompanyProfileForm.js

View workflow job for this annotation

GitHub Actions / build

'image' is missing in props validation

Check warning on line 32 in src/components/Company/Edit/EditCompanyProfileForm.js

View workflow job for this annotation

GitHub Actions / build

'imageAlt' is missing in props validation

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

View workflow job for this annotation

GitHub Actions / build

Unexpected block statement surrounding arrow body; move the returned value immediately after the `=>`
return (<Avatar
alt={imageAlt}
src={image}
style={style}
/>);

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

View workflow job for this annotation

GitHub Actions / build

The closing bracket must be aligned with the opening tag (expected column 13)
};

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

const getParsedCompanyContacts = (contacts) => {
const newContacts = [];
for (const contact of contacts) {
newContacts.push(contact.value);
}

return newContacts;
};

const parseCompany = ({
contacts,
...company
}) => ({
contacts: contacts.map((value) => ({ value })),
...company,
logo: "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.1SzV5xZOzNbaUOENWpw9vwHaHa%26pid%3DApi&f=1&ipt=36ec7cc75953554a84897bc0aaa6402e9267a031b8618c412927094349aca538&ipo=images"

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

View workflow job for this annotation

GitHub Actions / build

This line has a length of 227. Maximum allowed is 140

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

View workflow job for this annotation

GitHub Actions / build

Missing trailing comma
});

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 +92,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 +109,15 @@ export const EditCompanyController = () => {
},
};

const submit = (data) => {
const contacts = getParsedCompanyContacts(data.contacts);
editCompany({ ...data, contacts: contacts }).then(() => {

}).catch((err) => {

Check failure on line 116 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 +128,11 @@ export const EditCompanyController = () => {
companyError,
isValidating,
canEditRaceControl,
}
control,
fields,
getValues,
submit: handleSubmit(submit),
},
},
};
};
Expand All @@ -92,33 +149,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 +168,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"
>
<EditImage
image={company?.logo}
style={{ height: "5em", width: "5em" }}
imageAlt={`${company?.name}'s logo`}
/>
</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 241 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 274 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";
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";
import { CompanyApplicationConstants } from "../../Apply/Company/CompanyApplicationUtils";

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

export const generateValidationRule = validationRulesGenerator(EditCompanyConstants);
Loading

0 comments on commit 2e4ebe9

Please sign in to comment.