The communications platform that puts data protection first.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Rocket.Chat/apps/meteor/client/views/admin/users/AddUser.js

152 lines
4.2 KiB

import { Field, Box, Button } from '@rocket.chat/fuselage';
import { useMutableCallback } from '@rocket.chat/fuselage-hooks';
import { useEndpoint, useRoute, useSetting, useTranslation } from '@rocket.chat/ui-contexts';
import { useQuery } from '@tanstack/react-query';
import React, { useMemo, useCallback, useState } from 'react';
import { parseCSV } from '../../../../lib/utils/parseCSV';
import { useEndpointAction } from '../../../hooks/useEndpointAction';
import { useForm } from '../../../hooks/useForm';
import UserForm from './UserForm';
import { useSmtpConfig } from './hooks/useSmtpConfig';
Chore: Rewrite Admin UsersTable to Typescript (#25698) <!-- This is a pull request template, you do not need to uncomment or remove the comments, they won't show up in the PR text. --> <!-- Your Pull Request name should start with one of the following tags [NEW] For new features [IMPROVE] For an improvement (performance or little improvements) in existing features [FIX] For bug fixes that affect the end-user [BREAK] For pull requests including breaking changes Chore: For small tasks Doc: For documentation --> <!-- Checklist!!! If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your code. - I have read the Contributing Guide - https://github.com/RocketChat/Rocket.Chat/blob/develop/.github/CONTRIBUTING.md#contributing-to-rocketchat doc - I have signed the CLA - https://cla-assistant.io/RocketChat/Rocket.Chat - Lint and unit tests pass locally with my changes - I have added tests that prove my fix is effective or that my feature works (if applicable) - I have added necessary documentation (if applicable) - Any dependent changes have been merged and published in downstream modules --> ## Proposed changes (including videos or screenshots) <!-- CHANGELOG --> <!-- Describe the big picture of your changes here to communicate to the maintainers why we should accept this pull request. If it fixes a bug or resolves a feature request, be sure to link to that issue below. This description will appear in the release notes if we accept the contribution. --> <!-- END CHANGELOG --> ## Issue(s) <!-- Link the issues being closed by or related to this PR. For example, you can use #594 if this PR closes issue number 594 --> ## Steps to test or reproduce <!-- Mention how you would reproduce the bug if not mentioned on the issue page already. Also mention which screens are going to have the changes if applicable --> ## Further comments <!-- If this is a relatively large or complex change, kick off the discussion by explaining why you chose the solution you did and what alternatives you considered, etc... --> Co-authored-by: Tasso Evangelista <2263066+tassoevan@users.noreply.github.com>
4 years ago
const AddUser = ({ onReload, ...props }) => {
const t = useTranslation();
const router = useRoute('admin-users');
const getRoleData = useEndpoint('GET', '/v1/roles.list');
const { data } = useQuery(['roles'], async () => {
const roles = await getRoleData();
return roles;
});
const isSmtpEnabled = useSmtpConfig();
const [errors, setErrors] = useState({});
const validationKeys = {
name: (name) =>
setErrors((errors) => ({
...errors,
name: !name.trim().length ? t('The_field_is_required', t('name')) : undefined,
})),
username: (username) =>
setErrors((errors) => ({
...errors,
username: !username.trim().length ? t('The_field_is_required', t('username')) : undefined,
})),
email: (email) =>
setErrors((errors) => ({
...errors,
email: !email.trim().length ? t('The_field_is_required', t('email')) : undefined,
})),
password: (password, values) =>
setErrors((errors) => ({
...errors,
password: !password.trim().length && !values.setRandomPassword ? t('The_field_is_required', t('password')) : undefined,
})),
setRandomPassword: (setRandomPassword, values) =>
setErrors((errors) => ({
...errors,
password: !values.password.trim().length && !setRandomPassword ? t('The_field_is_required', t('password')) : undefined,
})),
};
const validateForm = ({ key, value, values }) => {
validationKeys[key] && validationKeys[key](value, values);
};
const defaultUserRoles = parseCSV(String(useSetting('Accounts_Registration_Users_Default_Roles')));
const { values, handlers, reset, hasUnsavedChanges } = useForm(
{
roles: defaultUserRoles,
name: '',
username: '',
statusText: '',
bio: '',
nickname: '',
email: '',
password: '',
verified: false,
requirePasswordChange: false,
setRandomPassword: false,
sendWelcomeEmail: isSmtpEnabled,
joinDefaultChannels: true,
customFields: {},
},
validateForm,
);
const goToUser = useCallback(
(id) =>
router.push({
context: 'info',
id,
}),
[router],
);
const saveAction = useEndpointAction('POST', '/v1/users.create', { successMessage: t('User_created_successfully!') });
const eventStats = useEndpointAction('POST', '/v1/statistics.telemetry');
const handleSave = useMutableCallback(async () => {
Object.entries(values).forEach(([key, value]) => {
validateForm({ key, value, values });
});
const { name, username, password, email, setRandomPassword } = values;
if (name === '' || username === '' || email === '') {
return false;
}
if (password === '' && setRandomPassword === false) {
return false;
}
const result = await saveAction(values);
if (result.success) {
eventStats({
params: [{ eventName: 'updateCounter', settingsId: 'Manual_Entry_User_Count' }],
});
goToUser(result.user._id);
[NEW] Seats Cap (#23017) * Base commit * [NEW] licenses.maxActiveUsers endpoint (#23011) * [IMPROVE] Banner Service (#22989) * WIP * Fix type import Co-authored-by: Tasso Evangelista <tasso.evangelista@rocket.chat> * [NEW] canAddNewUser function * [NEW] Seats usage bar (#23018) * usage bar component * Seats limit in admin users page * Remove dangling console.log * Add some details on StatisticsEndpoint type * Move to EE and use new endpoint * Rename some components and hooks * Refactor UsersPage Co-authored-by: Gabriel Henriques <gabriel.henriques@rocket.chat> * Fix edit and info page * [NEW] Seats Card (#23077) * Seats Card * Fix review, make ts * Fix review * Add type guard for CardIcon props Co-authored-by: Tasso Evangelista <tasso.evangelista@rocket.chat> * [NEW] Seats Cap: Request seats link (#23151) * create endpoint and consume it in the ui * Fix review * Remove unused param type Co-authored-by: Tasso Evangelista <tasso.evangelista@rocket.chat> * [NEW] Remove license downgrade if exceeding seats cap (#23220) * [IMPROVE] Ensure Seats-cap design and UI are the same (#23222) * Fix labels and buttons * Reload seats cap data on user changes * Use Fuselage on development version Co-authored-by: Tasso Evangelista <tasso.evangelista@rocket.chat> * [NEW] Prevent users from accidentally deactivating an enterprise license by adding more users than the license allows. (#23050) Co-authored-by: Gabriel Henriques <gabriel.henriques@rocket.chat> Co-authored-by: Tasso Evangelista <tasso.evangelista@rocket.chat> * [NEW] stats on seats request (#23225) Co-authored-by: Gabriel Henriques <gabriel.henriques@rocket.chat> * [NEW] Seats cap banners (#23211) * [NEW] Prevent users from accidentally deactivating an enterprise license by adding more users than the license allows. * Seats cap banners * Deprecate preserveDismiss * use request seats link * Fix banner not closing and request seats link Co-authored-by: Pierre Lehnen <pierre.lehnen@rocket.chat> * [FIX] Banner not parsing markdown (#23036) * Parse markdown * Use markdownText * Fix translations * Move startup * Always create seats limit banners * Remove uneffective conditional * [FIX] Seats Cap QA reports (#23272) * Fix create banner and link * Remove call from startup * QA * Improve readability * Avoid using an outdated absolute URL * Embedded counters into translation strings Co-authored-by: Tasso Evangelista <tasso.evangelista@rocket.chat> * Patch object-path so Snyk stop complaining Co-authored-by: pierre-lehnen-rc <55164754+pierre-lehnen-rc@users.noreply.github.com> Co-authored-by: Guilherme Gazzo <guilhermegazzo@gmail.com> Co-authored-by: Pierre Lehnen <pierre.lehnen@rocket.chat> Co-authored-by: Gabriel Henriques <gabriel.henriques@rocket.chat> Co-authored-by: gabriellsh <40830821+gabriellsh@users.noreply.github.com> Co-authored-by: Gabriel Thomé <38537062+g-thome@users.noreply.github.com>
4 years ago
onReload();
}
});
const availableRoles = useMemo(() => data?.roles?.map(({ _id, description, name }) => [_id, description || name]) ?? [], [data]);
const append = useMemo(
() => (
<Field>
<Field.Row>
<Box display='flex' flexDirection='row' justifyContent='space-between' w='full'>
<Button flexGrow={1} disabled={!hasUnsavedChanges} onClick={reset} mie='x4'>
{t('Cancel')}
</Button>
<Button primary flexGrow={1} disabled={!hasUnsavedChanges} onClick={handleSave}>
{t('Save')}
</Button>
</Box>
</Field.Row>
</Field>
),
[hasUnsavedChanges, reset, t, handleSave],
);
return (
<UserForm
errors={errors}
formValues={values}
formHandlers={handlers}
availableRoles={availableRoles}
append={append}
isSmtpEnabled={isSmtpEnabled}
{...props}
/>
);
Chore: Rewrite Admin UsersTable to Typescript (#25698) <!-- This is a pull request template, you do not need to uncomment or remove the comments, they won't show up in the PR text. --> <!-- Your Pull Request name should start with one of the following tags [NEW] For new features [IMPROVE] For an improvement (performance or little improvements) in existing features [FIX] For bug fixes that affect the end-user [BREAK] For pull requests including breaking changes Chore: For small tasks Doc: For documentation --> <!-- Checklist!!! If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your code. - I have read the Contributing Guide - https://github.com/RocketChat/Rocket.Chat/blob/develop/.github/CONTRIBUTING.md#contributing-to-rocketchat doc - I have signed the CLA - https://cla-assistant.io/RocketChat/Rocket.Chat - Lint and unit tests pass locally with my changes - I have added tests that prove my fix is effective or that my feature works (if applicable) - I have added necessary documentation (if applicable) - Any dependent changes have been merged and published in downstream modules --> ## Proposed changes (including videos or screenshots) <!-- CHANGELOG --> <!-- Describe the big picture of your changes here to communicate to the maintainers why we should accept this pull request. If it fixes a bug or resolves a feature request, be sure to link to that issue below. This description will appear in the release notes if we accept the contribution. --> <!-- END CHANGELOG --> ## Issue(s) <!-- Link the issues being closed by or related to this PR. For example, you can use #594 if this PR closes issue number 594 --> ## Steps to test or reproduce <!-- Mention how you would reproduce the bug if not mentioned on the issue page already. Also mention which screens are going to have the changes if applicable --> ## Further comments <!-- If this is a relatively large or complex change, kick off the discussion by explaining why you chose the solution you did and what alternatives you considered, etc... --> Co-authored-by: Tasso Evangelista <2263066+tassoevan@users.noreply.github.com>
4 years ago
};
export default AddUser;