Skip to content

Commit

Permalink
Add dropdown field for Default Address Type in IP Address Pool form t…
Browse files Browse the repository at this point in the history
…o use nodes that inherit from BuildinIPAddress (#5603)

* add custom form for ip address pool

* add fragment

* remove log

* remove wrong duplicate

* update changelog

* lint

* switch to custom field for preselected value if only 1 option

* add namespace and update type
  • Loading branch information
pa-lem authored Jan 30, 2025
1 parent 7569469 commit 7461545
Show file tree
Hide file tree
Showing 7 changed files with 297 additions and 4 deletions.
1 change: 1 addition & 0 deletions changelog/3489.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Allow Default Address Type quick selection in the Resource Manager form
6 changes: 4 additions & 2 deletions frontend/app/src/entities/ipam/constants.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { RELATIONSHIP_VIEW_BLACKLIST } from "@/config/constants";
import { IP_ADDRESS_POOL, IP_PREFIX_POOL } from "../resource-manager/constants";

export const NAMESPACE_GENERIC = "BuiltinIPNamespace";
export const IP_ADDRESS_GENERIC = "BuiltinIPAddress";
export const IP_PREFIX_GENERIC = "BuiltinIPPrefix";

export const POOLS_PEER = [IP_ADDRESS_GENERIC, IP_PREFIX_GENERIC];
export const POOLS_DICTIONNARY = {
IpamIPAddress: "CoreIPAddressPool",
IpamIPPrefix: "CoreIPPrefixPool",
IpamIPAddress: IP_ADDRESS_POOL,
IpamIPPrefix: IP_PREFIX_POOL,
};

export const TREE_ROOT_ID = "root" as const;
Expand Down
3 changes: 2 additions & 1 deletion frontend/app/src/entities/resource-manager/constants.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
export const RESOURCE_GENERIC_KIND = "CoreResourcePool";
export const RESOURCE_POOL_UTILIZATION_KIND = "InfrahubResourcePoolUtilization";
export const RESOURCE_POOL_ALLOCATED_KIND = "InfrahubResourcePoolAllocated";
export const IP_ADDRESS_POOL = "CoreIPAddressPool";
export const IP_PREFIX_POOL = "CoreIPPrefixPool";
export const NUMBER_POOL_KIND = "CoreNumberPool";

export const NUMBER_POOL_NODE_FIELD = "node";
export const NUMBER_POOL_NODE_ATTRIBUTE_FIELD = "node_attribute";
280 changes: 280 additions & 0 deletions frontend/app/src/entities/resource-manager/ui/ip-address-pool-form.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,280 @@
import { NUMBER_POOL_OBJECT } from "@/config/constants";
import { useAuth } from "@/entities/authentication/ui/useAuth";
import { currentBranchAtom } from "@/entities/branches/stores";
import { IP_ADDRESS_GENERIC } from "@/entities/ipam/constants";
import { createObject } from "@/entities/nodes/api/createObject";
import { updateObjectWithId } from "@/entities/nodes/api/updateObjectWithId";
import { AttributeType, RelationshipType } from "@/entities/nodes/getObjectItemDisplayValue";
import { useSchema } from "@/entities/schema/hooks/useSchema";
import { schemaState } from "@/entities/schema/stores/schema.atom";
import { schemaKindLabelState } from "@/entities/schema/stores/schemaKindLabel.atom";
import graphqlClient from "@/shared/api/graphql/graphqlClientApollo";
import { Button } from "@/shared/components/buttons/button-primitive";
import { DEFAULT_FORM_FIELD_VALUE } from "@/shared/components/form/constants";
import { LabelFormField } from "@/shared/components/form/fields/common";
import InputField from "@/shared/components/form/fields/input.field";
import NumberField from "@/shared/components/form/fields/number.field";
import RelationshipManyField from "@/shared/components/form/fields/relationship-many.field";
import RelationshipField from "@/shared/components/form/fields/relationship.field";
import { NodeFormProps } from "@/shared/components/form/node-form";
import { FormAttributeValue, FormFieldValue } from "@/shared/components/form/type";
import { getCurrentFieldValue } from "@/shared/components/form/utils/getFieldDefaultValue";
import { getFormFieldsFromSchema } from "@/shared/components/form/utils/getFormFieldsFromSchema";
import { getRelationshipDefaultValue } from "@/shared/components/form/utils/getRelationshipDefaultValue";
import { getCreateMutationFromFormData } from "@/shared/components/form/utils/mutations/getCreateMutationFromFormData";
import { updateFormFieldValue } from "@/shared/components/form/utils/updateFormFieldValue";
import { isRequired } from "@/shared/components/form/utils/validation";
import { ALERT_TYPES, Alert } from "@/shared/components/ui/alert";
import { Badge } from "@/shared/components/ui/badge";
import {
Combobox,
ComboboxContent,
ComboboxItem,
ComboboxList,
ComboboxTrigger,
} from "@/shared/components/ui/combobox";
import { Form, FormField, FormInput, FormSubmit } from "@/shared/components/ui/form";
import { datetimeAtom } from "@/shared/stores/time.atom";
import { stringifyWithoutQuotes } from "@/shared/utils/string";
import { gql } from "@apollo/client";
import { useAtomValue } from "jotai";
import { useState } from "react";
import { FieldValues, useForm } from "react-hook-form";
import { toast } from "react-toastify";
import { IP_ADDRESS_POOL } from "../constants";

const ADDRESS_DEFAULT_TYPE_FIELD_NAME = "default_address_type";

interface IpAddressPoolFormProps extends Pick<NodeFormProps, "onSuccess"> {
currentObject?: Record<string, AttributeType | RelationshipType>;
onCancel?: () => void;
onUpdateComplete?: () => void;
}

export const IpAddressPoolForm = ({
currentObject,
onSuccess,
onCancel,
onUpdateComplete,
}: IpAddressPoolFormProps) => {
const branch = useAtomValue(currentBranchAtom);
const date = useAtomValue(datetimeAtom);
const { schema } = useSchema(IP_ADDRESS_POOL);
const auth = useAuth();

const defaultValues = {
name: getCurrentFieldValue("name", currentObject),
description: getCurrentFieldValue("description", currentObject),
default_prefix_length: getCurrentFieldValue("default_prefix_length", currentObject),
resources: getRelationshipDefaultValue({
relationshipData: currentObject?.resources,
}),
ip_namespace: getRelationshipDefaultValue({
relationshipData: currentObject?.ip_namespace,
}),
};

const fields = getFormFieldsFromSchema({
schema,
initialObject: currentObject,
auth,
});

const form = useForm<FieldValues>({
defaultValues,
});

const prefixLenghtAttribute = schema?.attributes?.find((attribute) => {
return attribute.name === "default_prefix_length";
});

const resourcesRelatiosnhip = schema?.relationships?.find((relationship) => {
return relationship.name === "resources";
});

const namespaceRelationship = schema?.relationships?.find((relationship) => {
return relationship.name === "ip_namespace";
});

async function handleSubmit(data: Record<string, FormFieldValue>) {
try {
const newObject = getCreateMutationFromFormData(fields, data);

if (!Object.keys(newObject).length) {
return;
}

const mutationString = currentObject
? updateObjectWithId({
kind: IP_ADDRESS_POOL,
data: stringifyWithoutQuotes({
id: currentObject.id,
...newObject,
}),
})
: createObject({
kind: IP_ADDRESS_POOL,
data: stringifyWithoutQuotes({
...newObject,
}),
});

const mutation = gql`
${mutationString}
`;

const result = await graphqlClient.mutate({
mutation,
context: {
branch: branch?.name,
date,
},
});

toast(<Alert type={ALERT_TYPES.SUCCESS} message={"Number pool created"} />, {
toastId: "alert-success-number-pool-created",
});

if (onSuccess) await onSuccess(result?.data?.[`${NUMBER_POOL_OBJECT}Create`]);
if (onUpdateComplete) await onUpdateComplete();
} catch (error: unknown) {
console.error("An error occurred while creating the object: ", error);
}
}

return (
<div className={"bg-custom-white flex flex-col flex-1 overflow-auto p-4"}>
<Form form={form} onSubmit={handleSubmit}>
<InputField name="name" label="Name" rules={{ required: true }} />
<InputField name="description" label="Description" />
<AddressTypesCombobox currentObject={currentObject} />
<NumberField
name="default_prefix_length"
label={prefixLenghtAttribute?.label}
description={prefixLenghtAttribute?.description}
/>
<RelationshipManyField
name="resources"
type="relationship"
label={resourcesRelatiosnhip?.label}
description={resourcesRelatiosnhip?.description}
relationship={{
name: "resources",
peer: "BuiltinIPPrefix",
kind: "Attribute",
label: "Resources",
}}
rules={{ required: true, validate: { required: isRequired } }}
/>
<RelationshipField
name="ip_namespace"
type="relationship"
label={namespaceRelationship?.label}
description={namespaceRelationship?.description}
relationship={{ peer: "BuiltinIPNamespace", name: "ip_namespace" }}
rules={{ required: true, validate: { required: isRequired } }}
/>

<div className="text-right">
{onCancel && (
<Button variant="outline" className="mr-2" onClick={onCancel}>
Cancel
</Button>
)}

<FormSubmit>Save</FormSubmit>
</div>
</Form>
</div>
);
};

const AddressTypesCombobox = ({
currentObject,
}: { currentObject?: Record<string, AttributeType | RelationshipType> }) => {
const { schema } = useSchema(IP_ADDRESS_POOL);
const schemaList = useAtomValue(schemaState);
const { schema: genericSchema, isGeneric } = useSchema(IP_ADDRESS_GENERIC);
const schemaKindName = useAtomValue(schemaKindLabelState);
const [open, setOpen] = useState(false);

const prefixTypeAttribute = schema?.attributes?.find((attribute) => {
return attribute.name === ADDRESS_DEFAULT_TYPE_FIELD_NAME;
});

const items =
(isGeneric &&
genericSchema?.used_by?.map((kind) => {
const currentSchema = schemaList.find((schema) => schema.kind === kind);

return {
value: kind,
label: schemaKindName[kind],
namespace: currentSchema?.namespace,
};
})) ??
[];

const currentValue = getCurrentFieldValue(ADDRESS_DEFAULT_TYPE_FIELD_NAME, currentObject);

const defaultValue =
(items[0] ?? currentValue)
? { source: { type: "user" }, value: items[0].value }
: DEFAULT_FORM_FIELD_VALUE;

return (
<FormField
name={ADDRESS_DEFAULT_TYPE_FIELD_NAME}
rules={{ required: true, validate: { required: isRequired } }}
defaultValue={defaultValue}
render={({ field }) => {
const fieldData: FormAttributeValue = field.value;

return (
<div className="flex flex-col gap-2">
<LabelFormField
label={prefixTypeAttribute?.label}
required
description={prefixTypeAttribute?.description}
fieldData={fieldData}
/>

<FormInput>
<Combobox open={open} onOpenChange={setOpen}>
<ComboboxTrigger data-testid="namespace-select">
{items.find((item) => item.value === fieldData?.value)?.label}
</ComboboxTrigger>

<ComboboxContent align="start" fitTriggerWidth={false}>
<ComboboxList className="max-w-md">
{items.map((item) => {
return (
<ComboboxItem
key={item.value}
value={item.value}
selectedValue={fieldData?.value}
onSelect={() => {
const newValue = fieldData?.value === item.value ? null : item.value;
field.onChange(
updateFormFieldValue(newValue ?? null, DEFAULT_FORM_FIELD_VALUE)
);
setOpen(false);
}}
>
<div className="overflow-hidden w-full flex items-center justify-between">
<div className="truncate font-semibold">{item.label}</div>
<Badge className="font-medium">{item.namespace}</Badge>
</div>
</ComboboxItem>
);
})}
</ComboboxList>
</ComboboxContent>
</Combobox>
</FormInput>
</div>
);
}}
/>
);
};
1 change: 1 addition & 0 deletions frontend/app/src/shared/components/form/dynamic-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ export const DynamicInput = (props: DynamicFieldProps) => {
}
case "relationship": {
const { schema: peerSchema } = getSchema(props.relationship.peer);

if (peerSchema && isHierarchicalSchema(peerSchema)) {
return <RelationshipHierarchicalField {...props} />;
}
Expand Down
7 changes: 7 additions & 0 deletions frontend/app/src/shared/components/form/object-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ import {
READONLY_REPOSITORY_KIND,
REPOSITORY_KIND,
} from "@/config/constants";

import { AttributeType, RelationshipType } from "@/entities/nodes/getObjectItemDisplayValue";
import { IP_ADDRESS_POOL } from "@/entities/resource-manager/constants";
import { IpAddressPoolForm } from "@/entities/resource-manager/ui/ip-address-pool-form";
import { NumberPoolForm } from "@/entities/resource-manager/ui/number-pool-form";
import { AccountForm } from "@/entities/role-manager/ui/account-form";
import { AccountGroupForm } from "@/entities/role-manager/ui/account-group-form";
Expand Down Expand Up @@ -86,6 +89,10 @@ const ObjectForm = ({ kind, currentProfiles, ...props }: ObjectFormProps) => {
return <ObjectPermissionForm {...props} />;
}

if (kind === IP_ADDRESS_POOL) {
return <IpAddressPoolForm {...props} />;
}

if (isGeneric) {
return <GenericObjectForm genericSchema={schema} {...props} />;
}
Expand Down
3 changes: 2 additions & 1 deletion frontend/app/src/shared/components/ui/command.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ export const CommandItem = React.forwardRef<
<CommandPrimitive.Item
ref={ref}
className={classNames(
"flex items-center gap-2 cursor-default select-none rounded-md px-2 py-1.5 text-sm outline-none data-[selected='true']:bg-gray-100 data-[selected=true]:bg-gray-100 data-[disabled=true]:opacity-50 data-[disabled=true]:pointer-events-none",
"flex items-center gap-2 cursor-default select-none rounded-md px-2 py-1.5 text-sm outline-none ",
"data-[selected='true']:bg-gray-100 data-[selected=true]:bg-gray-100 data-[disabled=true]:opacity-50 data-[disabled=true]:pointer-events-none",
className
)}
{...props}
Expand Down

0 comments on commit 7461545

Please sign in to comment.