UpdateUserRole.tsx 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import {
  2. makeStyles,
  3. Theme,
  4. Checkbox,
  5. FormGroup,
  6. FormControlLabel,
  7. } from '@material-ui/core';
  8. import { FC, useState, useEffect } from 'react';
  9. import { useTranslation } from 'react-i18next';
  10. import DialogTemplate from '@/components/customDialog/DialogTemplate';
  11. import { UpdateUserRoleProps, UpdateUserRoleParams } from './Types';
  12. import { UserHttp } from '@/http/User';
  13. const useStyles = makeStyles((theme: Theme) => ({
  14. input: {
  15. margin: theme.spacing(1, 0, 0.5),
  16. },
  17. dialogWrapper: {
  18. maxWidth: theme.spacing(70),
  19. '& .MuiFormControlLabel-root': {
  20. width: theme.spacing(20),
  21. },
  22. },
  23. }));
  24. const UpdateUserRole: FC<UpdateUserRoleProps> = ({
  25. onUpdate,
  26. handleClose,
  27. roles,
  28. username,
  29. }) => {
  30. const { t: userTrans } = useTranslation('user');
  31. const { t: btnTrans } = useTranslation('btn');
  32. const [roleOptions, setRoleOptions] = useState([]);
  33. const [form, setForm] = useState<UpdateUserRoleParams>({
  34. username: username,
  35. roles: roles,
  36. });
  37. const classes = useStyles();
  38. const handleUpdate = async () => {
  39. await UserHttp.updateUserRole(form);
  40. onUpdate(form);
  41. };
  42. const fetchAllRoles = async () => {
  43. const roles = await UserHttp.getRoles();
  44. setRoleOptions(roles.results.map((r: any) => r.role.name));
  45. };
  46. useEffect(() => {
  47. fetchAllRoles();
  48. }, []);
  49. return (
  50. <DialogTemplate
  51. title={userTrans('updateRoleTitle')}
  52. handleClose={handleClose}
  53. confirmLabel={btnTrans('update')}
  54. handleConfirm={handleUpdate}
  55. confirmDisabled={false}
  56. dialogClass={classes.dialogWrapper}
  57. >
  58. <>
  59. <FormGroup row>
  60. {roleOptions.map((roleOption: string, index: number) => (
  61. <FormControlLabel
  62. control={
  63. <Checkbox
  64. onChange={(
  65. e: React.ChangeEvent<HTMLInputElement>,
  66. checked: boolean
  67. ) => {
  68. let newRoles = [...form.roles];
  69. if (!checked) {
  70. newRoles = newRoles.filter(
  71. (n: string | number) => n !== roleOption
  72. );
  73. } else {
  74. newRoles.push(roleOption);
  75. }
  76. setForm(v => ({ ...v, roles: [...newRoles] }));
  77. }}
  78. />
  79. }
  80. key={index}
  81. label={roleOption}
  82. value={roleOption}
  83. checked={form.roles.indexOf(roleOption) !== -1}
  84. />
  85. ))}
  86. </FormGroup>
  87. </>
  88. </DialogTemplate>
  89. );
  90. };
  91. export default UpdateUserRole;