Skip to content
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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added feature to move private network to a organization #240

Merged
merged 4 commits into from
Dec 13, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
8 changes: 4 additions & 4 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -77,20 +77,20 @@ model network_members {
@@unique([id, nwid])
}
model network {
nwid String @id
nwid String @id
name String?
description String?
creationTime DateTime?
lastModifiedTime DateTime?
flowRule String?
autoAssignIp Boolean? @default(true)
nw_userid User? @relation(fields: [authorId], references: [id], onDelete: Cascade)
autoAssignIp Boolean? @default(true)
nw_userid User? @relation(fields: [authorId], references: [id], onDelete: Cascade)
authorId String?
tagsByName Json?
capabilitiesByName Json?

organizationId String?
organization Organization? @relation(fields: [organizationId], references: [id], onDelete: Cascade)
organization Organization? @relation(fields: [organizationId], references: [id], onDelete: Cascade)

networkMembers network_members[]
notations Notation[]
Expand Down
209 changes: 209 additions & 0 deletions src/components/networkPage/networkOptionsModal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
import React, { useState } from "react";
import cn from "classnames";
import { useModalStore } from "~/utils/store";
import { useTranslations } from "next-intl";
import { api } from "~/utils/api";
import { ErrorData } from "~/types/errorHandling";
import toast from "react-hot-toast";

interface Iprops {
networkId: string;
}

const NetworkOptionsModal = ({ networkId }: Iprops) => {
const b = useTranslations("commonButtons");
const t = useTranslations("networks");
const [action, setAction] = useState({ deleteNetwork: false, moveNetwork: false });
const [input, setInput] = useState({ name: "", organizationId: "" });
const { closeModal } = useModalStore((state) => state);

const { refetch: refetchNetwork } = api.network.getUserNetworks.useQuery({
central: false,
});
const { mutate: transferNetwork } = api.org.transferNetworkOwnership.useMutation({
onError: (error) => {
if ((error.data as ErrorData)?.zodError) {
const fieldErrors = (error.data as ErrorData)?.zodError.fieldErrors;
for (const field in fieldErrors) {
toast.error(`${fieldErrors[field].join(", ")}`);
}
} else if (error.message) {
toast.error(error.message);
} else {
toast.error("An unknown error occurred");
}
},
onSuccess: () => {
refetchNetwork();
closeModal();
},
});
const { mutate: deleteNetwork, isLoading: loadingDeleteNetwork } =
api.network.deleteNetwork.useMutation({
onError: (error) => {
if ((error.data as ErrorData)?.zodError) {
const fieldErrors = (error.data as ErrorData)?.zodError.fieldErrors;
for (const field in fieldErrors) {
toast.error(`${fieldErrors[field].join(", ")}`);
}
} else if (error.message) {
toast.error(error.message);
} else {
toast.error("An unknown error occurred");
}
},
onSuccess: () => {
refetchNetwork();
closeModal();
},
});

const inputHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
setInput({
...input,
[e.target.name]: e.target.value,
});
};

if (loadingDeleteNetwork) {
return (
<div className="fixed inset-0 z-50 flex items-center justify-center">
<span className="loading loading-bars loading-lg"></span>
</div>
);
}
return (
<div>
<div className={cn({ "opacity-30": false })}>
<div className="grid grid-cols-4 items-start gap-4 space-y-10">
<div className="col-span-4 ">
<header className="text-md">{b("moveNetworkToOrganization")}</header>
<p className="text-sm text-gray-500">
{t("networkActionModal.moveNetwork.description")}
</p>

{action.moveNetwork ? (
<form>
<p className="text-sm text-red-600">
{t.rich("networkActionModal.moveNetwork.warningText", {
strong: (children) => <strong>{children}</strong>,
br: () => <br />,
})}
</p>

<input
type="text"
name="organizationId"
onChange={inputHandler}
placeholder="Type the organization ID"
className="input input-bordered border-warning input-sm w-full max-w-xs my-2"
/>

<div className="flex gap-5">
<button
onClick={(e) => {
e.preventDefault();
transferNetwork({
nwid: networkId,
organizationId: input.organizationId,
});
}}
type="submit"
className="btn-sm btn-error btn w-2/6"
>
{b("moveNetwork")}
</button>
<button
onClick={() =>
setAction((prev) => ({
...prev,
moveNetwork: !prev.moveNetwork,
}))
}
type="submit"
className="btn-sm btn w-2/6"
>
{b("cancel")}
</button>
</div>
</form>
) : (
<button
onClick={() =>
setAction((prev) => ({ ...prev, moveNetwork: !prev.moveNetwork }))
}
type="submit"
className="btn-sm btn btn-error btn-outline"
>
{b("moveNetwork")}
</button>
)}
</div>

<div className="col-span-4 ">
<header className="text-md">
{t("networkActionModal.deleteNetwork.title")}
</header>
<p className="text-sm text-gray-500">
{t("networkActionModal.deleteNetwork.description")}
</p>
{action.deleteNetwork ? (
<form>
<p className="text-sm text-red-600">
{t.rich("networkActionModal.deleteNetwork.warningText", {
strong: (children) => <strong>{children}</strong>,
br: () => <br />,
})}
</p>
<input
type="text"
name="name"
onChange={inputHandler}
placeholder="Type the network ID"
className="input input-bordered border-warning input-sm w-full max-w-xs my-2"
/>

<div className="flex gap-5">
<button
onClick={(e) => {
e.preventDefault();
deleteNetwork({ nwid: networkId });
}}
type="submit"
className="btn-sm btn-error btn w-2/6"
>
{t("networkActionModal.deleteNetwork.title")}
</button>
<button
onClick={() =>
setAction((prev) => ({
...prev,
deleteNetwork: !prev.deleteNetwork,
}))
}
type="submit"
className="btn-sm btn w-2/6"
>
{b("cancel")}
</button>
</div>
</form>
) : (
<button
onClick={() =>
setAction((prev) => ({ ...prev, deleteNetwork: !prev.deleteNetwork }))
}
type="submit"
className="btn-sm btn btn-error btn-outline"
>
{b("deleteNetwork")}
</button>
)}
</div>
</div>
</div>
</div>
);
};

export default NetworkOptionsModal;
52 changes: 45 additions & 7 deletions src/components/networkPage/networkTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import { useTranslations } from "next-intl";
import { type network_members } from "@prisma/client";
import { getLocalStorageItem, setLocalStorageItem } from "~/utils/localstorage";
import TableFooter from "../shared/tableFooter";
import { useModalStore } from "~/utils/store";
import NetworkOptionsModal from "./networkOptionsModal";

const LOCAL_STORAGE_KEY = "networkTableSorting";

Expand All @@ -38,7 +40,9 @@ const TruncateText = ({ text }: { text: string }) => {
};
export const NetworkTable = ({ tableData = [] }) => {
const router = useRouter();
const t = useTranslations("commonTable");
const t = useTranslations("networks");
const ct = useTranslations("commonTable");
const { callModal } = useModalStore((state) => state);

// Load initial state from localStorage or set to default
const initialSortingState = getLocalStorageItem(LOCAL_STORAGE_KEY, [
Expand All @@ -53,34 +57,68 @@ export const NetworkTable = ({ tableData = [] }) => {
nwid: string;
members: network_members[];
networkMembers: network_members[];
action: string;
};
const columnHelper = createColumnHelper<ColumnsType>();
// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
const columns = useMemo(
() => [
columnHelper.accessor("name", {
cell: (info) => info.getValue(),
header: () => <span>{t("header.name")}</span>,
header: () => <span>{ct("header.name")}</span>,
}),
columnHelper.accessor("description", {
size: 300,
cell: (info) => <TruncateText text={info.getValue()} />,
header: () => <span>{t("header.description")}</span>,
header: () => <span>{ct("header.description")}</span>,
}),
columnHelper.accessor("nwid", {
cell: (info) => info.getValue(),
header: () => <span>{t("header.networkId")}</span>,
header: () => <span>{ct("header.networkId")}</span>,
// footer: (info) => info.column.id,
}),
columnHelper.accessor("members", {
header: () => <span>{t("header.members")}</span>,
header: () => <span>{ct("header.members")}</span>,
cell: ({ row: { original } }) => {
if (!Array.isArray(original.networkMembers)) return <span>0</span>;
return <span>{original.networkMembers.length}</span>;
},
}),
columnHelper.accessor("action", {
header: () => <span>{ct("header.actions")}</span>,
id: "action",
cell: ({ row: { original } }) => {
return (
<div className="space-x-2">
<button
onClick={(event) => {
event.stopPropagation(); // This will prevent the event from propagating to the row
callModal({
title: (
<p>
<span>
{t.rich("networkActionModal.modalTitle", {
span: (children) => (
<span className="text-primary">{children}</span>
),
networkName: original.nwid,
})}
</span>
</p>
),
rootStyle: "text-left",
content: <NetworkOptionsModal networkId={original.nwid} />,
});
}}
className="btn btn-outline btn-xs rounded-sm"
>
{ct("cell.Options")}
</button>
</div>
);
},
}),
],
// eslint-disable-next-line react-hooks/exhaustive-deps
[],
);

Expand Down Expand Up @@ -140,7 +178,7 @@ export const NetworkTable = ({ tableData = [] }) => {
value={globalFilter ?? ""}
onChange={(value) => setGlobalFilter(String(value))}
className="font-lg border-block border p-2 shadow"
placeholder={t("search.networkSearchPlaceholder")}
placeholder={ct("search.networkSearchPlaceholder")}
/>
</div>
<div className="overflow-auto rounded-lg border border-base-200/50">
Expand Down
21 changes: 20 additions & 1 deletion src/locales/en/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
"yes": "Yes",
"generate": "Generate",
"addNetwork": "Create a network",
"deleteNetwork": "Delete network",
"moveNetwork": "Move network",
"moveNetworkToOrganization": "Move network to organization",
"leaveOrganization": "Leave Organization",
"inviteUser": "Invite User",
"meta": "Meta",
Expand Down Expand Up @@ -65,6 +68,9 @@
"show": "Show",
"page": "Page",
"of": "of"
},
"cell": {
"Options": "Options"
}
},
"commonToast": {
Expand All @@ -90,7 +96,20 @@
"loading": "Loading",
"title": "Networks",
"description": "VPN Networks",
"noNetworksMessage": "No networks have been created yet. Start by creating one and it will appear here."
"noNetworksMessage": "No networks have been created yet. Start by creating one and it will appear here.",
"networkActionModal": {
"modalTitle": "Options for Network <span>{networkName}</span>",
"moveNetwork": {
"title": "Move network",
"description": "You can locate the ID in the organization URL.",
"warningText": "<strong>Warning:</strong> Transferring the network will move both the network and its members to the selected organization. This action is irreversible and cannot be undone. Please confirm the organization ID carefully before proceeding.<br></br>Additionally, ensure you have write permissions to the organization to which you are transferring the network."
},
"deleteNetwork": {
"title": "Delete network",
"description": "Deleting a network will permanently remove it along with all its associated data.",
"warningText": "<strong>Warning:</strong> This action will irreversibly delete the network and all related members, settings, and data. This process cannot be undone. Please ensure you have backed up any necessary information before proceeding with deletion."
}
}
},
"networkById": {
"loading": "Loading...",
Expand Down
Loading
Loading