Working on create organization and delete.

This commit is contained in:
charles-gauthereau
2024-12-29 19:34:48 +01:00
parent 05edbf4a42
commit a6f48ea762
17 changed files with 390 additions and 35 deletions
@@ -0,0 +1,38 @@
"use client"
import {ButtonWithConfirm} from "@/components/wrappers/common/button/button-with-confirm";
import {
deleteOrganizationAction,
} from "@/components/wrappers/dashboard/organization/organization.action";
import {useMutation} from "@tanstack/react-query";
import {setCurrentOrganizationId} from "@/features/dashboard/organization-cookie";
import {useRouter} from "next/navigation";
export type DeleteOrganizationButtonProps = {
organizationId: string;
}
export const DeleteOrganizationButton = (props: DeleteOrganizationButtonProps) => {
const router = useRouter();
const mutation = useMutation({
mutationFn: () => deleteOrganizationAction(props.organizationId),
onSuccess: async (result) => {
console.log(result);
if(result.data.success) {
await setCurrentOrganizationId("default")
router.push("/dashboard")
}
},
})
return(
<ButtonWithConfirm
onClick={() => {
mutation.mutate()
}}
isPending={mutation.isPending}
text="Delete Organization"
variant="destructive"/>
)
}
@@ -9,6 +9,7 @@ import {Input} from "@/components/ui/input";
import {OrganizationSchema} from "@/components/wrappers/dashboard/organization/organization.schema";
import {createOrganizationAction} from "@/components/wrappers/dashboard/organization/organization.action";
import {useRouter} from "next/navigation";
import {useState} from "react";
export type createOrganizationModalProps = {
children: any
@@ -16,6 +17,7 @@ export type createOrganizationModalProps = {
export function CreateOrganizationModal(props: createOrganizationModalProps) {
const [open, setOpen] = useState(false);
const {children} = props;
@@ -27,14 +29,16 @@ export function CreateOrganizationModal(props: createOrganizationModalProps) {
const mutation = useMutation({
mutationFn: async (values: OrganizationSchema) => {
console.log(values)
const result = await createOrganizationAction(values)
setOpen(false);
router.refresh()
}
})
return (
<Dialog>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
{children}
@@ -50,6 +54,7 @@ export function CreateOrganizationModal(props: createOrganizationModalProps) {
<Form form={form}
className="flex flex-col gap-4"
onSubmit={async (values) => {
console.log(values)
await mutation.mutateAsync(values);
}}
>
@@ -81,14 +86,14 @@ export function CreateOrganizationModal(props: createOrganizationModalProps) {
</FormItem>
)}
/>
<DialogFooter>
<div className="flex items-center justify-between w-full">
<Button type="submit">Create</Button>
</div>
</DialogFooter>
</Form>
</div>
<DialogFooter>
<div className="flex items-center justify-between w-full">
<Button type="submit">Create</Button>
</div>
</DialogFooter>
</DialogContent>
@@ -5,6 +5,9 @@ import {prisma} from "@/prisma";
import {OrganizationSchema} from "@/components/wrappers/dashboard/organization/organization.schema";
import {ServerActionResult} from "@/types/action-type";
import {Organization} from "@prisma/client";
import {z} from "zod";
import {v4 as uuidv4} from "uuid";
import {db} from "@/db";
const verifySlugUniqueness = async (slug: string) => {
@@ -63,4 +66,57 @@ export const createOrganizationAction = userAction
};
}
});
export const deleteOrganizationAction = userAction
.schema(z.string())
.action(async ({parsedInput, ctx}): Promise<ServerActionResult<Organization>> => {
console.log(parsedInput);
try {
const uuid = uuidv4()
const organization = await db.organization.findFirst({
where: {
id: parsedInput,
}
})
console.log(organization);
const organizationUpdated = await db.organization.update({
where: {
id: parsedInput,
},
data: {
name: `${organization.name}-${uuid}`,
slug: `${organization.slug}-${uuid}`,
deleted : true
}
})
return {
success: true,
value: organizationUpdated,
actionSuccess: {
message: "Organization has been successfully deleted.",
messageParams: {organizationId: organizationUpdated.id},
},
};
} catch (error) {
console.error("Error deleting organization:", error);
return {
success: false,
actionError: {
message: "Failed to delete organization.",
status: 500,
cause: error.message ?? "Unknown error",
messageParams: {message: "Error deleting the organization"},
},
};
}
});
@@ -2,8 +2,9 @@ import {z} from "zod";
export const OrganizationSchema = z.object({
name: z.string(),
slug: z.string(),
name: z.string().min(5).max(40),
slug: z.string().regex(/^[a-zA-Z0-9_-]*$/).min(5).max(20),
});
export type OrganizationSchema = z.infer<typeof OrganizationSchema>;
@@ -21,11 +21,6 @@ export const SidebarMenuCustom = (props: SidebarMenuCustomProps) => {
url: "projects",
icon: Layers,
},
{
title: "Agents",
url: "agents",
icon: ShieldHalf,
},
{
title: "Statistics",
url: "statistics",
@@ -44,9 +39,12 @@ export const SidebarMenuCustom = (props: SidebarMenuCustomProps) => {
if (currentItem) {
setActiveItem(currentItem.title);
}
else{
setActiveItem("");
}
}, [pathname]);
const [activeItem, setActiveItem] = useState(items[0].title);
const [activeItem, setActiveItem] = useState("");
const handleItemClick = (title: string) => {
setActiveItem(title);
console.log(title)
@@ -0,0 +1,69 @@
"use client"
import {useEffect, useState} from "react";
import Link from "next/link";
import {SidebarMenu, SidebarMenuAction, SidebarMenuButton, SidebarMenuItem} from "@/components/ui/sidebar";
import {cn} from "@/lib/utils";
import {buttonVariants} from "@/components/ui/button";
import {ChartArea, Layers, Settings, ShieldHalf} from "lucide-react";
import {usePathname} from "next/navigation";
export type SidebarMenuAdminProps = {}
export const SidebarMenuAdmin = (props: SidebarMenuAdminProps) => {
const BASE_URL = "/dashboard";
const pathname = usePathname();
// Menu items.
const items = [
{
title: "Agents",
url: "agents",
icon: ShieldHalf,
},
{
title: "Administration panel",
url: "admin",
icon: Settings,
},
]
useEffect(() => {
const currentUrl = pathname;
const currentItem = items.find((item) => `${BASE_URL}/${item.url}` === currentUrl);
if (currentItem) {
setActiveItem(currentItem.title);
}else{
setActiveItem("");
}
}, [pathname]);
const [activeItem, setActiveItem] = useState("");
const handleItemClick = (title: string) => {
setActiveItem(title);
console.log(title)
}
return (
<SidebarMenu>
{items.map((item) => (
<SidebarMenuItem key={item.title}>
<SidebarMenuButton asChild>
<Link
className={cn(buttonVariants({
size: "lg",
variant: activeItem === item.title ? "secondary" : 'ghost'
}), "justify-start p-0")}
href={`${BASE_URL}/${item.url}`}
onClick={() => handleItemClick(item.title)}
>
<item.icon/>
<span>{item.title}</span>
</Link>
</SidebarMenuButton>
<SidebarMenuAction
className={`peer-data-[active=true]/menu-button:opacity-100 ${activeItem === item.title ? 'active' : ''}`}/>
</SidebarMenuItem>
))}
</SidebarMenu>
)
}
@@ -13,11 +13,13 @@ import {requiredCurrentUser} from "@/auth/current-user";
import {SideBarLogo} from "@/components/wrappers/dashboard/sideBar/SideBarLogo/SideBarLogo";
import {SideBarFooterCredit} from "@/components/wrappers/dashboard/sideBar/SideBarFooterCredit/SideBarFooterCredit";
import {LoggedInButton} from "@/components/wrappers/dashboard/loggedInButton/LoggedInButton";
import {db} from "@/db";
import {checkAllPermissions} from "@/features/permissions/permissions";
import {SidebarMenuAdmin} from "@/components/wrappers/dashboard/sideBar/SideBarMenu/SideBarMenuAdmin";
export async function AppSidebar() {
const user = await requiredCurrentUser()
const organizations = await prisma.organization.findMany({
where: {
users: {
@@ -25,6 +27,7 @@ export async function AppSidebar() {
userId: user.id
},
},
deleted: {not: true},
},
})
const defaultOrganization = await prisma.organization.findUnique({
@@ -33,6 +36,8 @@ export async function AppSidebar() {
}
})
return (
<Sidebar collapsible="icon">
<SidebarHeader>
@@ -55,6 +60,14 @@ export async function AppSidebar() {
<SidebarMenuCustom/>
</SidebarGroupContent>
</SidebarGroup>
{user.role == "admin" ?
<SidebarGroup>
<SidebarGroupLabel>Administration</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenuAdmin/>
</SidebarGroupContent>
</SidebarGroup>
:null}
</SidebarContent>
<SidebarFooter>
<SidebarMenu>
-2
View File
@@ -3,7 +3,5 @@ import {enhance} from "@zenstackhq/runtime";
import {prisma} from "@/prisma";
const user = await currentUser();
console.log("bbbbbbb", user)
export const db = enhance(prisma, {user: user});
console.log("cccccccccc", db)
+35
View File
@@ -2,8 +2,43 @@
import {redirect} from "next/navigation";
import {signIn, signOut} from "@/auth/auth";
import {getServerUrl} from "@/utils/get-server-url";
//
// const baseUrl = getServerUrl();
// async function fetchCsrfToken() {
// const response = await fetch(`${baseUrl}/api/auth/csrf`);
// const data = await response.json();
// return data.csrfToken;
// }
//
// async function manualSignOut() {
// const csrfToken = await fetchCsrfToken();
//
// const formData = new URLSearchParams();
// formData.append('csrfToken', csrfToken);
// formData.append('json', 'true');
//
// const response = await fetch(`${baseUrl}/api/auth/signout`, {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded',
// },
// body: formData.toString(),
// });
//
// if (response.ok) {
// console.log('Signed out successfully');
// window.location.reload();
//
// } else {
// console.error('Failed to sign out');
// }
// }
//
export const signOutAction = async () => {
// await manualSignOut()
await signOut({redirectTo: '/', redirect: true})
window.location.reload();
}
+18
View File
@@ -0,0 +1,18 @@
export async function checkAllPermissions(db: any, model: string) {
const operations = ['read', 'create', 'update', 'delete'];
const results: Record<string, boolean> = {};
for (const operation of operations) {
// Dynamically access the model and check permissions
results[operation] = await db[model].check({ operation });
}
const hasAllPermissions = Object.values(results).every(permission => permission === true);
console.log('Permissions:', results);
console.log('Has all permissions:', hasAllPermissions);
return hasAllPermissions;
}
+5
View File
@@ -287,6 +287,11 @@ const metadata = {
isDataModel: true,
isArray: true,
backLink: 'organization',
}, deleted: {
name: "deleted",
type: "Boolean",
isOptional: true,
attributes: [{ "name": "@default", "args": [{ "value": false }] }],
},
}
, uniqueConstraints: {
+1 -1
View File
@@ -328,7 +328,7 @@ export function useSuspenseCountOrganization<TArgs extends Prisma.OrganizationCo
return useSuspenseModelQuery<TQueryFnData, TData, TError>('Organization', `${endpoint}/organization/count`, args, options, fetch);
}
export function useCheckOrganization<TError = DefaultError>(args: { operation: PolicyCrudKind; where?: { id?: string; slug?: string; name?: string }; }, options?: (Omit<UseQueryOptions<boolean, TError, boolean>, 'queryKey'> & ExtraQueryOptions)) {
export function useCheckOrganization<TError = DefaultError>(args: { operation: PolicyCrudKind; where?: { id?: string; slug?: string; name?: string; deleted?: boolean }; }, options?: (Omit<UseQueryOptions<boolean, TError, boolean>, 'queryKey'> & ExtraQueryOptions)) {
const { endpoint, fetch } = getHooksContext();
return useModelQuery<boolean, boolean, TError>('Organization', `${endpoint}/organization/check`, args, options, fetch);
}
+112 -13
View File
@@ -110,6 +110,7 @@ components:
- updatedAt
- slug
- name
- deleted
UserOrganizationScalarFieldEnum:
type: string
enum:
@@ -403,6 +404,10 @@ components:
type: array
items:
$ref: "#/components/schemas/UserOrganization"
deleted:
oneOf:
- type: "null"
- type: boolean
required:
- id
- createdAt
@@ -1650,6 +1655,11 @@ components:
oneOf:
- $ref: "#/components/schemas/StringFilter"
- type: string
deleted:
oneOf:
- $ref: "#/components/schemas/BoolNullableFilter"
- type: boolean
- type: "null"
projects:
$ref: "#/components/schemas/ProjectListRelationFilter"
users:
@@ -1669,6 +1679,10 @@ components:
$ref: "#/components/schemas/SortOrder"
name:
$ref: "#/components/schemas/SortOrder"
deleted:
oneOf:
- $ref: "#/components/schemas/SortOrder"
- $ref: "#/components/schemas/SortOrderInput"
projects:
$ref: "#/components/schemas/ProjectOrderByRelationAggregateInput"
users:
@@ -1711,6 +1725,11 @@ components:
oneOf:
- $ref: "#/components/schemas/StringFilter"
- type: string
deleted:
oneOf:
- $ref: "#/components/schemas/BoolNullableFilter"
- type: boolean
- type: "null"
projects:
$ref: "#/components/schemas/ProjectListRelationFilter"
users:
@@ -1757,6 +1776,11 @@ components:
oneOf:
- $ref: "#/components/schemas/StringWithAggregatesFilter"
- type: string
deleted:
oneOf:
- $ref: "#/components/schemas/BoolNullableWithAggregatesFilter"
- type: boolean
- type: "null"
UserOrganizationWhereInput:
type: object
properties:
@@ -3953,6 +3977,10 @@ components:
type: string
name:
type: string
deleted:
oneOf:
- type: "null"
- type: boolean
projects:
$ref: "#/components/schemas/ProjectCreateNestedManyWithoutOrganizationInput"
users:
@@ -3987,6 +4015,11 @@ components:
oneOf:
- type: string
- $ref: "#/components/schemas/StringFieldUpdateOperationsInput"
deleted:
oneOf:
- type: boolean
- $ref: "#/components/schemas/NullableBoolFieldUpdateOperationsInput"
- type: "null"
projects:
$ref: "#/components/schemas/ProjectUpdateManyWithoutOrganizationNestedInput"
users:
@@ -4009,6 +4042,10 @@ components:
type: string
name:
type: string
deleted:
oneOf:
- type: "null"
- type: boolean
required:
- slug
- name
@@ -4038,6 +4075,11 @@ components:
oneOf:
- type: string
- $ref: "#/components/schemas/StringFieldUpdateOperationsInput"
deleted:
oneOf:
- type: boolean
- $ref: "#/components/schemas/NullableBoolFieldUpdateOperationsInput"
- type: "null"
UserOrganizationCreateInput:
type: object
properties:
@@ -10235,6 +10277,10 @@ components:
type: string
name:
type: string
deleted:
oneOf:
- type: "null"
- type: boolean
projects:
$ref: "#/components/schemas/ProjectCreateNestedManyWithoutOrganizationInput"
required:
@@ -10257,6 +10303,10 @@ components:
type: string
name:
type: string
deleted:
oneOf:
- type: "null"
- type: boolean
projects:
$ref: "#/components/schemas/ProjectUncheckedCreateNestedManyWithoutOrganization\
Input"
@@ -10479,6 +10529,11 @@ components:
oneOf:
- type: string
- $ref: "#/components/schemas/StringFieldUpdateOperationsInput"
deleted:
oneOf:
- type: boolean
- $ref: "#/components/schemas/NullableBoolFieldUpdateOperationsInput"
- type: "null"
projects:
$ref: "#/components/schemas/ProjectUpdateManyWithoutOrganizationNestedInput"
OrganizationUncheckedUpdateWithoutUsersInput:
@@ -10507,6 +10562,11 @@ components:
oneOf:
- type: string
- $ref: "#/components/schemas/StringFieldUpdateOperationsInput"
deleted:
oneOf:
- type: boolean
- $ref: "#/components/schemas/NullableBoolFieldUpdateOperationsInput"
- type: "null"
projects:
$ref: "#/components/schemas/ProjectUncheckedUpdateManyWithoutOrganizationNested\
Input"
@@ -10527,6 +10587,10 @@ components:
type: string
name:
type: string
deleted:
oneOf:
- type: "null"
- type: boolean
users:
$ref: "#/components/schemas/UserOrganizationCreateNestedManyWithoutOrganization\
Input"
@@ -10550,6 +10614,10 @@ components:
type: string
name:
type: string
deleted:
oneOf:
- type: "null"
- type: boolean
users:
$ref: "#/components/schemas/UserOrganizationUncheckedCreateNestedManyWithoutOrg\
anizationInput"
@@ -10749,6 +10817,11 @@ components:
oneOf:
- type: string
- $ref: "#/components/schemas/StringFieldUpdateOperationsInput"
deleted:
oneOf:
- type: boolean
- $ref: "#/components/schemas/NullableBoolFieldUpdateOperationsInput"
- type: "null"
users:
$ref: "#/components/schemas/UserOrganizationUpdateManyWithoutOrganizationNested\
Input"
@@ -10778,6 +10851,11 @@ components:
oneOf:
- type: string
- $ref: "#/components/schemas/StringFieldUpdateOperationsInput"
deleted:
oneOf:
- type: boolean
- $ref: "#/components/schemas/NullableBoolFieldUpdateOperationsInput"
- type: "null"
users:
$ref: "#/components/schemas/UserOrganizationUncheckedUpdateManyWithoutOrganizat\
ionNestedInput"
@@ -14272,6 +14350,8 @@ components:
oneOf:
- type: boolean
- $ref: "#/components/schemas/UserOrganizationFindManyArgs"
deleted:
type: boolean
_count:
oneOf:
- type: boolean
@@ -14770,6 +14850,8 @@ components:
type: boolean
name:
type: boolean
deleted:
type: boolean
_all:
type: boolean
OrganizationMinAggregateInput:
@@ -14785,6 +14867,8 @@ components:
type: boolean
name:
type: boolean
deleted:
type: boolean
OrganizationMaxAggregateInput:
type: object
properties:
@@ -14798,6 +14882,8 @@ components:
type: boolean
name:
type: boolean
deleted:
type: boolean
UserOrganizationCountAggregateInput:
type: object
properties:
@@ -15535,6 +15621,10 @@ components:
type: string
name:
type: string
deleted:
oneOf:
- type: "null"
- type: boolean
_count:
oneOf:
- type: "null"
@@ -16493,6 +16583,8 @@ components:
type: integer
name:
type: integer
deleted:
type: integer
_all:
type: integer
required:
@@ -16501,6 +16593,7 @@ components:
- updatedAt
- slug
- name
- deleted
- _all
OrganizationMinAggregateOutputType:
type: object
@@ -16527,6 +16620,10 @@ components:
oneOf:
- type: "null"
- type: string
deleted:
oneOf:
- type: "null"
- type: boolean
OrganizationMaxAggregateOutputType:
type: object
properties:
@@ -16552,6 +16649,10 @@ components:
oneOf:
- type: "null"
- type: string
deleted:
oneOf:
- type: "null"
- type: boolean
UserOrganizationCountAggregateOutputType:
type: object
properties:
@@ -22283,6 +22384,7 @@ paths:
description: Create a new Organization
tags:
- organization
security: []
responses:
"201":
description: Successful operation
@@ -22328,6 +22430,7 @@ paths:
description: Create several Organization
tags:
- organization
security: []
responses:
"201":
description: Successful operation
@@ -22373,6 +22476,7 @@ paths:
description: Find one unique Organization
tags:
- organization
security: []
responses:
"200":
description: Successful operation
@@ -22428,6 +22532,7 @@ paths:
description: Find the first Organization matching the given condition
tags:
- organization
security: []
responses:
"200":
description: Successful operation
@@ -22483,6 +22588,7 @@ paths:
description: Find a list of Organization
tags:
- organization
security: []
responses:
"200":
description: Successful operation
@@ -22540,6 +22646,7 @@ paths:
description: Update a Organization
tags:
- organization
security: []
responses:
"200":
description: Successful operation
@@ -22585,6 +22692,7 @@ paths:
description: Update Organizations matching the given condition
tags:
- organization
security: []
responses:
"200":
description: Successful operation
@@ -22630,6 +22738,7 @@ paths:
description: Upsert a Organization
tags:
- organization
security: []
responses:
"200":
description: Successful operation
@@ -22785,6 +22894,7 @@ paths:
description: Find a list of Organization
tags:
- organization
security: []
responses:
"200":
description: Successful operation
@@ -22842,6 +22952,7 @@ paths:
description: Aggregate Organizations
tags:
- organization
security: []
responses:
"200":
description: Successful operation
@@ -22897,6 +23008,7 @@ paths:
description: Group Organizations by fields
tags:
- organization
security: []
responses:
"200":
description: Successful operation
@@ -24296,7 +24408,6 @@ paths:
description: Create a new Agent
tags:
- agent
security: []
responses:
"201":
description: Successful operation
@@ -24342,7 +24453,6 @@ paths:
description: Create several Agent
tags:
- agent
security: []
responses:
"201":
description: Successful operation
@@ -24388,7 +24498,6 @@ paths:
description: Find one unique Agent
tags:
- agent
security: []
responses:
"200":
description: Successful operation
@@ -24444,7 +24553,6 @@ paths:
description: Find the first Agent matching the given condition
tags:
- agent
security: []
responses:
"200":
description: Successful operation
@@ -24500,7 +24608,6 @@ paths:
description: Find a list of Agent
tags:
- agent
security: []
responses:
"200":
description: Successful operation
@@ -24558,7 +24665,6 @@ paths:
description: Update a Agent
tags:
- agent
security: []
responses:
"200":
description: Successful operation
@@ -24604,7 +24710,6 @@ paths:
description: Update Agents matching the given condition
tags:
- agent
security: []
responses:
"200":
description: Successful operation
@@ -24650,7 +24755,6 @@ paths:
description: Upsert a Agent
tags:
- agent
security: []
responses:
"200":
description: Successful operation
@@ -24696,7 +24800,6 @@ paths:
description: Delete one unique Agent
tags:
- agent
security: []
responses:
"200":
description: Successful operation
@@ -24752,7 +24855,6 @@ paths:
description: Delete Agents matching the given condition
tags:
- agent
security: []
responses:
"200":
description: Successful operation
@@ -24808,7 +24910,6 @@ paths:
description: Find a list of Agent
tags:
- agent
security: []
responses:
"200":
description: Successful operation
@@ -24866,7 +24967,6 @@ paths:
description: Aggregate Agents
tags:
- agent
security: []
responses:
"200":
description: Successful operation
@@ -24922,7 +25022,6 @@ paths:
description: Group Agents by fields
tags:
- agent
security: []
responses:
"200":
description: Successful operation