Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat: allow selecting the initial organization for new users#16829

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
aslilac merged 5 commits intomainfromlilac/new-user-pick-orgs
Mar 7, 2025
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletionssite/e2e/helpers.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -1062,6 +1062,7 @@ type UserValues = {
export async function createUser(
page: Page,
userValues: Partial<UserValues> = {},
orgName = defaultOrganizationName,
): Promise<UserValues> {
const returnTo = page.url();

Expand All@@ -1082,6 +1083,16 @@ export async function createUser(
await page.getByLabel("Full name").fill(name);
}
await page.getByLabel("Email").fill(email);

// If the organization picker is present on the page, select the default
// organization.
const orgPicker = page.getByLabel("Organization *");
const organizationsEnabled = await orgPicker.isVisible();
if (organizationsEnabled) {
await orgPicker.click();
await page.getByText(orgName, { exact: true }).click();
}

await page.getByLabel("Login Type").click();
await page.getByRole("option", { name: "Password", exact: false }).click();
// Using input[name=password] due to the select element utilizing 'password'
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,17 +7,10 @@ import { organizations } from "api/queries/organizations";
import type { AuthorizationCheck, Organization } from "api/typesGenerated";
import { Avatar } from "components/Avatar/Avatar";
import { AvatarData } from "components/Avatar/AvatarData";
import { useDebouncedFunction } from "hooks/debounce";
import {
type ChangeEvent,
type ComponentProps,
type FC,
useState,
} from "react";
import { type ComponentProps, type FC, useState } from "react";
import { useQuery } from "react-query";

export type OrganizationAutocompleteProps = {
value: Organization | null;
onChange: (organization: Organization | null) => void;
label?: string;
className?: string;
Expand All@@ -27,21 +20,16 @@ export type OrganizationAutocompleteProps = {
};

export const OrganizationAutocomplete: FC<OrganizationAutocompleteProps> = ({
value,
onChange,
label,
className,
size = "small",
required,
check,
}) => {
const [autoComplete, setAutoComplete] = useState<{
value: string;
open: boolean;
}>({
value: value?.name ?? "",
open: false,
});
const [open, setOpen] = useState(false);
const [selected, setSelected] = useState<Organization | null>(null);

Comment on lines -38 to +32
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Nice this is so much clearer.

const organizationsQuery = useQuery(organizations());

const permissionsQuery = useQuery(
Expand All@@ -60,16 +48,6 @@ export const OrganizationAutocomplete: FC<OrganizationAutocompleteProps> = ({
: { enabled: false },
);

const { debounced: debouncedInputOnChange } = useDebouncedFunction(
(event: ChangeEvent<HTMLInputElement>) => {
setAutoComplete((state) => ({
...state,
value: event.target.value,
}));
},
750,
);

// If an authorization check was provided, filter the organizations based on
// the results of that check.
let options = organizationsQuery.data ?? [];
Expand All@@ -85,24 +63,18 @@ export const OrganizationAutocomplete: FC<OrganizationAutocompleteProps> = ({
className={className}
options={options}
loading={organizationsQuery.isLoading}
value={value}
data-testid="organization-autocomplete"
open={autoComplete.open}
isOptionEqualToValue={(a, b) => a.name === b.name}
open={open}
isOptionEqualToValue={(a, b) => a.id === b.id}
getOptionLabel={(option) => option.display_name}
onOpen={() => {
setAutoComplete((state) => ({
...state,
open: true,
}));
setOpen(true);
}}
onClose={() => {
setAutoComplete({
value: value?.name ?? "",
open: false,
});
setOpen(false);
}}
onChange={(_, newValue) => {
setSelected(newValue);
onChange(newValue);
}}
renderOption={({ key, ...props }, option) => (
Expand DownExpand Up@@ -130,13 +102,12 @@ export const OrganizationAutocomplete: FC<OrganizationAutocompleteProps> = ({
}}
InputProps={{
...params.InputProps,
onChange: debouncedInputOnChange,
startAdornment: value && (
<Avatar size="sm" src={value.icon} fallback={value.name} />
startAdornment: selected && (
<Avatar size="sm" src={selected.icon} fallback={selected.name} />
),
endAdornment: (
<>
{organizationsQuery.isFetching &&autoComplete.open && (
{organizationsQuery.isFetching && open && (
<CircularProgress size={16} />
)}
{params.InputProps.endAdornment}
Expand All@@ -154,6 +125,6 @@ export const OrganizationAutocomplete: FC<OrganizationAutocompleteProps> = ({
};

const root = css`
padding-left: 14px !important; // Same padding left as input
gap: 4px;
padding-left: 14px !important; // Same padding left as input
gap: 4px;
`;
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -266,7 +266,6 @@ export const CreateTemplateForm: FC<CreateTemplateFormProps> = (props) => {
{...getFieldHelpers("organization")}
required
label="Belongs to"
value={selectedOrg}
onChange={(newValue) => {
setSelectedOrg(newValue);
void form.setFieldValue("organization", newValue?.name || "");
Expand Down
51 changes: 50 additions & 1 deletionsite/src/pages/CreateUserPage/CreateUserForm.stories.tsx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
import { action } from "@storybook/addon-actions";
import type { Meta, StoryObj } from "@storybook/react";
import { mockApiError } from "testHelpers/entities";
import { userEvent, within } from "@storybook/test";
import { organizationsKey } from "api/queries/organizations";
import type { Organization } from "api/typesGenerated";
import {
MockOrganization,
MockOrganization2,
mockApiError,
} from "testHelpers/entities";
import { CreateUserForm } from "./CreateUserForm";

const meta: Meta<typeof CreateUserForm> = {
Expand All@@ -18,6 +25,48 @@ type Story = StoryObj<typeof CreateUserForm>;

export const Ready: Story = {};

const permissionCheckQuery = (organizations: Organization[]) => {
return {
key: [
"authorization",
{
checks: Object.fromEntries(
organizations.map((org) => [
org.id,
{
action: "create",
object: {
resource_type: "organization_member",
organization_id: org.id,
},
},
]),
),
},
],
data: Object.fromEntries(organizations.map((org) => [org.id, true])),
};
};

export const WithOrganizations: Story = {
parameters: {
queries: [
{
key: organizationsKey,
data: [MockOrganization, MockOrganization2],
},
permissionCheckQuery([MockOrganization, MockOrganization2]),
],
},
args: {
showOrganizations: true,
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.click(canvas.getByLabelText("Organization *"));
},
};

export const FormError: Story = {
args: {
error: mockApiError({
Expand Down
87 changes: 59 additions & 28 deletionssite/src/pages/CreateUserPage/CreateUserForm.tsx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,10 +7,11 @@ import { ErrorAlert } from "components/Alert/ErrorAlert";
import { Button } from "components/Button/Button";
import { FormFooter } from "components/Form/Form";
import { FullPageForm } from "components/FullPageForm/FullPageForm";
import { OrganizationAutocomplete } from "components/OrganizationAutocomplete/OrganizationAutocomplete";
import { PasswordField } from "components/PasswordField/PasswordField";
import { Spinner } from "components/Spinner/Spinner";
import { Stack } from "components/Stack/Stack";
import {type FormikContextType,useFormik } from "formik";
import { useFormik } from "formik";
import type { FC } from "react";
import {
displayNameValidator,
Expand DownExpand Up@@ -52,14 +53,6 @@ export const authMethodLanguage = {
},
};

export interface CreateUserFormProps {
onSubmit: (user: TypesGen.CreateUserRequestWithOrgs) => void;
onCancel: () => void;
error?: unknown;
isLoading: boolean;
authMethods?: TypesGen.AuthMethods;
}

const validationSchema = Yup.object({
email: Yup.string()
.trim()
Expand All@@ -75,27 +68,51 @@ const validationSchema = Yup.object({
login_type: Yup.string().oneOf(Object.keys(authMethodLanguage)),
});

type CreateUserFormData = {
readonly username: string;
readonly name: string;
readonly email: string;
readonly organization: string;
readonly login_type: TypesGen.LoginType;
readonly password: string;
};

export interface CreateUserFormProps {
error?: unknown;
isLoading: boolean;
onSubmit: (user: CreateUserFormData) => void;
onCancel: () => void;
authMethods?: TypesGen.AuthMethods;
showOrganizations: boolean;
}

export const CreateUserForm: FC<
React.PropsWithChildren<CreateUserFormProps>
> = ({ onSubmit, onCancel, error, isLoading, authMethods }) => {
const form: FormikContextType<TypesGen.CreateUserRequestWithOrgs> =
useFormik<TypesGen.CreateUserRequestWithOrgs>({
initialValues: {
email: "",
password: "",
username: "",
name: "",
organization_ids: ["00000000-0000-0000-0000-000000000000"],
login_type: "",
user_status: null,
},
validationSchema,
onSubmit,
});
const getFieldHelpers = getFormHelpers<TypesGen.CreateUserRequestWithOrgs>(
form,
error,
);
> = ({
error,
isLoading,
onSubmit,
onCancel,
showOrganizations,
authMethods,
}) => {
const form = useFormik<CreateUserFormData>({
initialValues: {
email: "",
password: "",
username: "",
name: "",
// If organizations aren't enabled, use the fallback ID to add the user to
// the default organization.
organization: showOrganizations
? ""
: "00000000-0000-0000-0000-000000000000",
login_type: "",
},
validationSchema,
onSubmit,
});
const getFieldHelpers = getFormHelpers(form, error);

const methods = [
authMethods?.password.enabled && "password",
Expand DownExpand Up@@ -132,6 +149,20 @@ export const CreateUserForm: FC<
fullWidth
label={Language.emailLabel}
/>
{showOrganizations && (
<OrganizationAutocomplete
{...getFieldHelpers("organization")}
required
label="Organization"
onChange={(newValue) => {
void form.setFieldValue("organization", newValue?.id ?? "");
}}
check={{
object: { resource_type: "organization_member" },
action: "create",
}}
/>
)}
<TextField
{...getFieldHelpers("login_type", {
helperText: "Authentication method for this user",
Expand Down
4 changes: 3 additions & 1 deletionsite/src/pages/CreateUserPage/CreateUserPage.test.tsx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,9 @@ import { Language as FormLanguage } from "./Language";

const renderCreateUserPage = async () => {
renderWithAuth(<CreateUserPage />, {
extraRoutes: [{ path: "/users", element: <div>Users Page</div> }],
extraRoutes: [
{ path: "/deployment/users", element: <div>Users Page</div> },
],
});
await waitForLoaderToBeRemoved();
};
Expand Down
17 changes: 14 additions & 3 deletionssite/src/pages/CreateUserPage/CreateUserPage.tsx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
import { authMethods, createUser } from "api/queries/users";
import { displaySuccess } from "components/GlobalSnackbar/utils";
import { Margins } from "components/Margins/Margins";
import { useDashboard } from "modules/dashboard/useDashboard";
import type { FC } from "react";
import { Helmet } from "react-helmet-async";
import { useMutation, useQuery, useQueryClient } from "react-query";
Expand All@@ -17,6 +18,7 @@ export const CreateUserPage: FC = () => {
const queryClient = useQueryClient();
const createUserMutation = useMutation(createUser(queryClient));
const authMethodsQuery = useQuery(authMethods());
const { showOrganizations } = useDashboard();

return (
<Margins>
Expand All@@ -26,16 +28,25 @@ export const CreateUserPage: FC = () => {

<CreateUserForm
error={createUserMutation.error}
authMethods={authMethodsQuery.data}
isLoading={createUserMutation.isLoading}
onSubmit={async (user) => {
await createUserMutation.mutateAsync(user);
await createUserMutation.mutateAsync({
username: user.username,
name: user.name,
email: user.email,
organization_ids: [user.organization],
login_type: user.login_type,
password: user.password,
user_status: null,
});
displaySuccess("Successfully created user.");
navigate("..", { relative: "path" });
}}
onCancel={() => {
navigate("..", { relative: "path" });
}}
isLoading={createUserMutation.isLoading}
authMethods={authMethodsQuery.data}
showOrganizations={showOrganizations}
/>
</Margins>
);
Expand Down
Loading

[8]ページ先頭

©2009-2025 Movatter.jp