This commit is contained in:
fro1991
2025-02-01 23:51:53 +07:00
parent d216a5bb8c
commit 76d65df562
19 changed files with 56 additions and 70 deletions

View File

@ -0,0 +1,20 @@
import { Container, DataGridInner } from '@/components';
import { EditDialog } from './blocks';
import { ManageUserContextProvider } from './hooks';
import { AddDialog } from './blocks/AddDialog';
import { DeleteDialog } from './blocks/DeleteDialog';
export default function ConfigUserPage() {
return (
<ManageUserContextProvider>
<Container>
<div className="grid gap-5 lg:gap-7.5">
<DataGridInner />
</div>
<EditDialog />
<AddDialog />
<DeleteDialog />
</Container>
</ManageUserContextProvider>
);
}

View File

@ -0,0 +1,354 @@
import { MouseEvent, useCallback, useEffect, useRef, useState } from 'react';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from '@/components/ui/select';
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog';
import { useUserContext } from '../hooks';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { apiConfig } from '@/config/api.config';
import { Alert, KeenIcon, useDataGrid } from '@/components';
import { toast } from 'sonner';
import { useCallApi } from '@/hooks';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import clsx from 'clsx';
interface CreateUserParams {
email: string;
username: string;
password: string;
retype_password: string;
name: string;
id_role: string;
status: string;
}
const API_URL = apiConfig.service_dashboard;
type PasswordType = 'password' | 'retype_password';
const AddDialog = () => {
const parentRef = useRef<any | null>(null);
const { showAddDialog, handleAddDialog, roles } = useUserContext();
const { reload } = useDataGrid();
const { PostData, PutData } = useCallApi();
const [alert, setAlert] = useState({
show: false,
message: ''
});
const initialState = {
email: '',
username: '',
password: '',
retype_password: '',
name: '',
id_role: '',
status: ''
};
const [formField, setFormField] = useState(initialState);
const resetForm = () => {
setFormField(initialState);
};
const [showPassword, setShowPassword] = useState({
password: false,
retype_password: false
});
const [messagePassword, setMessagePassword] = useState(true);
const [isSubmitting, setIsSubmitting] = useState(false);
const [passwordErrors, setPasswordErrors] = useState<string[]>([]);
const validatePassword = (password: string, confirmPassword: string) => {
const errors: string[] = [];
if (password) {
if (password.length < 8) {
errors.push('Password must be at least 8 characters long');
}
if (!/[A-Z]/.test(password)) {
errors.push('Password must contain at least one capital letter');
}
if (!/[0-9]/.test(password)) {
errors.push('Password must contain at least one number');
}
if (!/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
errors.push('Password must contain at least one special character');
}
if (password !== confirmPassword) {
errors.push('Passwords do not match');
}
}
return {
isValid: errors.length === 0,
errors
};
};
useEffect(() => {
const validation = validatePassword(formField.password, formField.retype_password);
setMessagePassword(validation.isValid);
setPasswordErrors(validation.errors);
}, [formField.password, formField.retype_password]);
const isButtonDisabled = !messagePassword || isSubmitting || passwordErrors.length > 0;
/* actions */
const doCreateUser = useCallback(
async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const response = await PostData(`${API_URL}/user/create`, {
...formField,
id_role: undefined
});
if (response?.status) {
const responseUserAddRole = await PutData(
`${API_URL}/user/add_role/${response?.message?.id}/${formField.id_role}`,
{}
);
setAlert((prev) => ({ ...prev, show: false, message: '' }));
handleAddDialog(false);
toast.success('Success Create User');
reload();
const createActivity = {
module: 'Manage User',
description: `Create New User => ${formField.username}`,
action: 'C'
};
doSaveLogActivity(createActivity);
} else {
setAlert((prev) => ({ ...prev, show: true, message: response?.message }));
}
},
[formField]
);
const togglePassword = useCallback((event: MouseEvent<HTMLButtonElement>, key: string) => {
event.preventDefault();
setShowPassword((prev) => ({ ...prev, [key]: !prev[key as PasswordType] }));
}, []);
return (
<Dialog open={showAddDialog} onOpenChange={(open) => handleAddDialog(open)}>
<DialogContent className="container-fixed max-w-[768px] flex flex-col p-5 overflow-hidden [&>button]:hidden">
<DialogHeader className="p-0 border-0">
<DialogTitle></DialogTitle>
<DialogDescription></DialogDescription>
<div className="flex items-center justify-between flex-wrap grow">
<div className="flex flex-col justify-center">
<h1 className="text-xl font-semibold leading-none text-gray-900">User - Create</h1>
<div className="flex items-center gap-2 text-sm font-normal text-gray-700"></div>
</div>
<div
className="cursor-pointer hover:opacity-100 opacity-50"
onClick={() => {
handleAddDialog(false);
resetForm();
}}
>
<KeenIcon icon="cross" className="text-1.5xl" />
</div>
</div>
</DialogHeader>
<DialogBody className="scrollable-y px-0 pb-0" ref={parentRef}>
<div className="flex flex-col px-0">
{alert.show && (
<Alert variant="danger" className="mb-3">
<h3>{alert.message}</h3>
</Alert>
)}
<form action="" onSubmit={doCreateUser}>
<div className="card-body grid gap-5 p-0">
<div className="w-full">
<div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label className="form-label flex items-center gap-1 max-w-56">Name</label>
<Input
className="input"
type="text"
autoComplete="off"
value={formField.name}
onChange={({ target }) =>
setFormField((prev) => ({ ...prev, name: target.value }))
}
/>
</div>
</div>
<div className="w-full">
<div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label className="form-label flex items-center gap-1 max-w-56">Username</label>
<Input
className="input"
type="text"
autoComplete="off"
value={formField.username}
onChange={({ target }) =>
setFormField((prev) => ({ ...prev, username: target.value }))
}
/>
</div>
</div>
<div className="w-full">
<div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label className="form-label flex items-center gap-1 max-w-56">Email</label>
<Input
className="input"
type="email"
autoComplete="off"
value={formField.email}
onChange={({ target }) =>
setFormField((prev) => ({ ...prev, email: target.value }))
}
/>
</div>
</div>
<div className="w-full">
<div className="flex items-center flex-wrap gap-2.5">
<label className="form-label max-w-56">Role</label>
<div className="grow">
<Select
value={formField.id_role}
onValueChange={(id_role) => setFormField((prev) => ({ ...prev, id_role }))}
>
<SelectTrigger>
<SelectValue placeholder="Select" />
</SelectTrigger>
<SelectContent>
{roles.map((role, idx) => (
<SelectItem value={role.id} key={role.id}>
{role.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</div>
<div className="flex items-center flex-wrap gap-2.5">
<label className="form-label max-w-56">Status</label>
<div className="grow">
<Select
value={formField.status}
onValueChange={(status) => setFormField((prev) => ({ ...prev, status }))}
>
<SelectTrigger>
<SelectValue placeholder="Select" />
</SelectTrigger>
<SelectContent>
<SelectItem value="Y">Active</SelectItem>
<SelectItem value="N">Non Active</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="w-full">
<div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label className="form-label flex items-center gap-1 max-w-56">Password</label>
<div className="input">
<input
className="form-control"
type={showPassword.password ? 'text' : 'password'}
value={formField.password}
onChange={({ target }) =>
setFormField((prev) => ({ ...prev, password: target.value }))
}
/>
<button
className="btn btn-icon"
onClick={(e) => togglePassword(e, 'password')}
>
<KeenIcon
icon="eye"
className={clsx('text-gray-500', { hidden: showPassword.password })}
/>
<KeenIcon
icon="eye-slash"
className={clsx('text-gray-500', {
hidden: !showPassword.password
})}
/>
</button>
</div>
</div>
</div>
<div className="w-full">
<div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label className="form-label flex items-center gap-1 max-w-56">
Confirm Password
</label>
<div className="w-full">
<div className="input block">
<input
className="form-control"
autoComplete="off"
type={showPassword.retype_password ? 'text' : 'password'}
value={formField.retype_password}
onChange={({ target }) =>
setFormField((prev) => ({ ...prev, retype_password: target.value }))
}
/>
<button
className="btn btn-icon"
onClick={(e) => togglePassword(e, 'retype_password')}
>
<KeenIcon
icon="eye"
className={clsx('text-gray-500', {
hidden: showPassword.retype_password
})}
/>
<KeenIcon
icon="eye-slash"
className={clsx('text-gray-500', {
hidden: !showPassword.retype_password
})}
/>
</button>
</div>
<div className="w-full">
{passwordErrors.length > 0 && (
<div className="text-xs text-red-500 mt-2">
{passwordErrors.map((error, index) => (
<p key={index}>{error}</p>
))}
</div>
)}
</div>
</div>
</div>
</div>
<div className="flex justify-end pt-2.5">
<Button className="btn btn-primary" type="submit" disabled={isButtonDisabled}>
Save Changes
</Button>
</div>
</div>
</form>
</div>
</DialogBody>
</DialogContent>
</Dialog>
);
};
export { AddDialog };

View File

@ -0,0 +1,83 @@
import { Dialog, DialogContent, DialogFooter, DialogHeader } from '@/components/ui/dialog';
import { useUserContext } from '../hooks';
import { Button } from '@/components/ui/button';
import { Alert, useDataGrid } from '@/components';
import { ChangeEvent, useCallback, useState } from 'react';
import { apiConfig } from '@/config/api.config';
import { toast } from 'sonner';
import { useCallApi } from '@/hooks';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import { EnforceSwitch } from '@/components/switch';
const API_URL = apiConfig.service_dashboard;
const DeleteDialog = () => {
const { showDeleteDialog, handleDeleteDialog, selectedUser } = useUserContext();
const { reload } = useDataGrid();
const [enforce, setEnforce] = useState(false);
const { DeleteData } = useCallApi();
const [alert, setAlert] = useState({
show: false,
message: ''
});
/* actions */
const doDeleteData = useCallback(async () => {
const response = await DeleteData(`${API_URL}/user/delete/${selectedUser}/${enforce}`, {
id: selectedUser
});
if (response?.status) {
setAlert((prev) => ({ ...prev, show: false, message: '' }));
handleDeleteDialog(false, null);
toast.success('Success Delete User');
reload();
const createActivity = {
module: 'Manage User',
description: `Delete User => ${selectedUser}`,
action: 'D'
};
doSaveLogActivity(createActivity);
} else {
setAlert((prev) => ({ ...prev, show: true, message: response?.message }));
}
}, [selectedUser, enforce]);
return (
<Dialog open={showDeleteDialog} onOpenChange={(open) => handleDeleteDialog(open, null)}>
<DialogContent className="container-fixed max-w-md flex flex-col p-5 overflow-hidden [&>button]:hidden">
<DialogHeader className="p-0 border-0 block">
<Alert variant="warning">
<h3 className="text-lg">Are you sure?</h3>
<span className="text-sm">you will delete this data!</span>
<div className="mt-2 flex items-center gap-x-2">
<label className="form-label max-w-56">Hard Delete</label>
<EnforceSwitch
enforce={enforce}
onChange={(e: ChangeEvent<HTMLInputElement>) => {
setEnforce(e.target.checked);
}}
/>
</div>
</Alert>
{alert.show && (
<Alert variant="danger">
<h3>{alert.message}</h3>
</Alert>
)}
</DialogHeader>
<DialogFooter className="flex justify-end items-center gap-4 mt-3">
<Button variant={'outline'} onClick={() => handleDeleteDialog(false, null)}>
Cancel
</Button>
<Button variant={'destructive'} onClick={() => doDeleteData()}>
Delete
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
};
export { DeleteDialog };

View File

@ -0,0 +1,231 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from '@/components/ui/select';
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog';
import { useUserContext } from '../hooks';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { apiConfig } from '@/config/api.config';
import { Alert, KeenIcon, useDataGrid } from '@/components';
import { toast } from 'sonner';
import { useCallApi } from '@/hooks';
import { doSaveLogActivity } from '@/actions/GlobalActions';
const API_URL = apiConfig.service_dashboard;
const EditDialog = () => {
const parentRef = useRef<any | null>(null);
const { showEditDialog, selectedUser, handleEditDialog, roles } = useUserContext();
const { reload } = useDataGrid();
const { GetData, PutData } = useCallApi();
const [alert, setAlert] = useState({
show: false,
message: ''
});
const [formField, setFormField] = useState({
name: '',
username: '',
email: '',
id_role: '',
id_role_old: '',
status: ''
});
/* actions */
const doUpdateUser = useCallback(
async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const response = await PutData(`${API_URL}/user/update/${selectedUser}`, {
...formField,
id_role_old: undefined
});
if (response?.status) {
handleEditDialog(false, null);
toast.success('Success Update User');
reload();
const createActivity = {
module: 'Manage User',
description: `Edit User => ${formField.username}`,
action: 'U'
};
doSaveLogActivity(createActivity);
} else {
setAlert((prev) => ({ ...prev, show: true, message: response?.message }));
}
},
[selectedUser, formField]
);
const doFetchUserData = useCallback(async (id: string) => {
const response = await GetData(`${API_URL}/user/detail/${id}`, { id });
if (response?.status) {
let id_role = response.data.role.id || '';
setFormField((prev) => ({
...prev,
name: response.data.name,
username: response.data.username,
email: response.data.email,
id_role: id_role,
id_role_old: id_role,
status: response.data.status
}));
} else {
setFormField((prev) => ({
...prev,
name: '',
username: '',
email: '',
id_role: '0',
id_role_old: '',
status: ''
}));
}
}, []);
useEffect(() => {
if (selectedUser) {
doFetchUserData(selectedUser);
}
}, [selectedUser]);
return (
<Dialog open={showEditDialog} onOpenChange={(open) => handleEditDialog(open, null)}>
<DialogContent className="container-fixed max-w-[768px] flex flex-col p-5 overflow-hidden [&>button]:hidden">
<DialogHeader className="p-0 border-0">
<DialogTitle></DialogTitle>
<DialogDescription></DialogDescription>
<div className="flex items-center justify-between flex-wrap grow">
<div className="flex flex-col justify-center">
<h1 className="text-xl font-semibold leading-none text-gray-900">User - Update</h1>
<div className="flex items-center gap-2 text-sm font-normal text-gray-700"></div>
</div>
<div
className="cursor-pointer hover:opacity-100 opacity-50"
onClick={() => handleEditDialog(false, null)}
>
<KeenIcon icon="cross" className="text-1.5xl" />
</div>
</div>
</DialogHeader>
<DialogBody className="scrollable-y px-0 pb-0" ref={parentRef}>
<div className="flex flex-col px-0">
{alert.show && (
<Alert variant="danger">
<h3>{alert.message}</h3>
</Alert>
)}
<form onSubmit={doUpdateUser}>
<div className="card-body grid gap-5 p-0">
<div className="w-full">
<div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label className="form-label flex items-center gap-1 max-w-56">Name</label>
<Input
className="input"
type="text"
value={formField.name}
onChange={({ target }) =>
setFormField((prev) => ({ ...prev, name: target.value }))
}
/>
</div>
</div>
<div className="w-full">
<div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label className="form-label flex items-center gap-1 max-w-56">Username</label>
<Input
className="input"
type="text"
value={formField.username}
onChange={({ target }) =>
setFormField((prev) => ({ ...prev, username: target.value }))
}
/>
</div>
</div>
<div className="w-full">
<div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label className="form-label flex items-center gap-1 max-w-56">Email</label>
<Input
className="input"
type="email"
value={formField.email}
onChange={({ target }) =>
setFormField((prev) => ({ ...prev, email: target.value }))
}
/>
</div>
</div>
<div className="w-full">
<div className="flex items-center flex-wrap gap-2.5">
<label className="form-label max-w-56">Role</label>
<div className="grow">
<Select
value={formField.id_role}
onValueChange={(id_role) => setFormField((prev) => ({ ...prev, id_role }))}
>
<SelectTrigger>
<SelectValue placeholder="Select" />
</SelectTrigger>
<SelectContent>
{roles.map((role, idx) => (
<SelectItem value={role.id} key={role.id}>
{role.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</div>
<div className="flex items-center flex-wrap gap-2.5">
<label className="form-label max-w-56">Status</label>
<div className="grow">
<Select
value={formField.status}
onValueChange={(status) => setFormField((prev) => ({ ...prev, status }))}
>
<SelectTrigger>
<SelectValue placeholder="Select" />
</SelectTrigger>
<SelectContent>
<SelectItem value="Y">Active</SelectItem>
<SelectItem value="N">Non Active</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="flex justify-end">
<Button className="btn btn-primary">Save Changes</Button>
</div>
</div>
</form>
</div>
</DialogBody>
</DialogContent>
</Dialog>
);
};
export { EditDialog };

View File

@ -0,0 +1,57 @@
import { DefaultTooltip, KeenIcon, useDataGrid } from '@/components';
import { useUserContext } from '../hooks';
import { Button } from '@/components/ui/button';
const ListToolBar = () => {
const { table, reload } = useDataGrid();
const { handleAddDialog } = useUserContext();
return (
<div className="card-header flex-wrap gap-2 border-b-0 px-5">
<div className="flex flex-wrap gap-2 lg:gap-5 w-full">
<div className="flex justify-between w-full items-center">
<div className="flex w-[50%] gap-3 items-center">
<label className="input input-sm w-1/3">
<KeenIcon icon="magnifier" />
<input
type="text"
placeholder="Search users"
value={(table.getColumn('username')?.getFilterValue() as string) ?? ''}
onChange={(event) =>
table.getColumn('username')?.setFilterValue(event.target.value)
}
/>
</label>
<DefaultTooltip title={'Filter'} placement={'top'}>
<Button
variant="outline"
className="h-7.5 disabled:bg-gray-400"
// disabled={isLoading}
// onClick={handleFilterData}
>
{/* {loadingButton === 'filter' ? <ContentLoader /> : <KeenIcon icon="filter" />} */}
<KeenIcon icon="filter" />
</Button>
</DefaultTooltip>
</div>
<div className="flex gap-3 items-center">
<Button
variant="outline"
className="h-7.5 text-[0.8rem]"
onClick={() => handleAddDialog(true)}
>
Add Data
</Button>
<DefaultTooltip title={'Refresh'} placement={'top'}>
<Button variant="outline" className="h-7.5" onClick={() => reload()}>
<KeenIcon icon="arrows-circle" />
</Button>
</DefaultTooltip>
</div>
</div>
</div>
</div>
);
};
export { ListToolBar };

View File

@ -0,0 +1,2 @@
export * from './ListToolBar';
export * from './EditDialog';

View File

@ -0,0 +1,247 @@
import React, { createContext, useCallback, useEffect, useMemo, useState } from 'react';
import { apiConfig } from '@/config/api.config';
import { Toaster } from '@/components/ui/sonner';
import { ColumnDef } from '@tanstack/react-table';
import { DataGridColumnHeader, DataGridProvider, KeenIcon } from '@/components';
import { EnforceSwitch } from '@/components/switch';
import { ListToolBar } from '../blocks';
import { useCallApi } from '@/hooks';
interface ContextProps {
showEditDialog: boolean;
handleEditDialog: (show: boolean, selected_user: string | null) => void;
showAddDialog: boolean;
handleAddDialog: (show: boolean) => void;
showDeleteDialog: boolean;
handleDeleteDialog: (show: boolean, selected_user: string | null) => void;
selectedUser: string | null;
roles: RoleListProps[];
}
interface SelectedUser {
id: string;
name: string;
email: string;
username: string;
role: string;
new_password: string;
check_new_password: string;
}
interface RoleListProps {
id: string;
name: string;
status: string;
}
const initialProps: ContextProps = {
showEditDialog: false,
handleEditDialog: () => {},
showAddDialog: false,
handleAddDialog: () => {},
showDeleteDialog: false,
handleDeleteDialog: () => {},
selectedUser: null,
roles: []
};
const ManageUserContext = createContext<ContextProps>(initialProps);
const API_URL = apiConfig.service_dashboard;
const ManageUserContextProvider = ({ children }: { children: React.ReactNode }) => {
/* state */
const [showEditDialog, setShowEditDialog] = useState(false);
const [showAddDialog, setShowAddDialog] = useState(false);
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const [selectedUser, setSelectedUser] = useState<string | null>(null);
const [roles, setRoles] = useState<RoleListProps[]>([]);
const { GetData } = useCallApi();
/* action */
const handleEditDialog = useCallback((show: boolean, selected_user: string | null) => {
setSelectedUser(show ? selected_user : null);
setShowEditDialog(show);
}, []);
const handleAddDialog = useCallback((show: boolean) => {
setShowAddDialog(show);
}, []);
const handleDeleteDialog = useCallback((show: boolean, selected_user: string | null) => {
setSelectedUser(show ? selected_user : null);
setShowDeleteDialog(show);
}, []);
/* Data Grid Options */
const columns = useMemo<ColumnDef<any>[]>(
() => [
{
accessorFn: (row) => row.username,
id: 'username',
header: ({ column }) => <DataGridColumnHeader title="Username" column={column} />,
enableSorting: true,
enableHiding: false
},
{
accessorFn: (row) => row.email,
id: 'email',
header: ({ column }) => <DataGridColumnHeader title="Email" column={column} />,
enableSorting: false,
enableHiding: false,
meta: {
headerClassName: 'w-[350px]'
}
},
{
accessorFn: (row) => row.name,
id: 'name',
header: ({ column }) => <DataGridColumnHeader title="Name" column={column} />,
enableSorting: false,
enableHiding: false,
meta: {
headerClassName: 'w-[350px]'
}
},
{
accessorFn: (row) => row.role.name,
id: 'role_name',
header: ({ column }) => <DataGridColumnHeader title="Role Name" column={column} />,
enableSorting: false,
enableHiding: false,
cell: (data: any) => {
const { role } = data.row.original;
console.log('role :', role);
let html = <p className="text-danger italic">Unassigned</p>;
if (role && role.name) html = role.name;
return html;
},
meta: {
headerClassName: 'w-[350px]'
}
},
{
accessorFn: (row) => row.status,
id: 'status',
header: ({ column }) => <DataGridColumnHeader title="Status" column={column} />,
enableSorting: false,
enableHiding: false,
cell: ({ row }) => {
return (
<EnforceSwitch
enforce={row.original.status == 'Y' ? true : false}
onChange={() => {}}
/>
);
},
meta: {
headerClassName: 'w-[100px]',
cellClassName: 'text-center'
}
},
{
id: 'actions',
enableSorting: false,
enableHiding: false,
header: ({ column }) => <DataGridColumnHeader title="Action" column={column} />,
cell: (data: any) => {
const row = data.row.original;
return (
<>
<button
className="btn btn-sm btn-icon btn-clear btn-light"
onClick={() => handleEditDialog(true, row.id)}
>
<KeenIcon icon="notepad-edit" />
</button>
<button
className="btn btn-sm btn-icon btn-clear btn-light"
onClick={() => handleDeleteDialog(true, row.id)}
>
<KeenIcon icon="trash" />
</button>
</>
);
},
meta: {
headerClassName: 'w-[100px]',
cellClassName: 'text-center'
}
}
],
[handleEditDialog, handleDeleteDialog]
);
const doGetListData = async (page: number, limit: number, sorting: any, filter: any) => {
sorting = sorting.length == 0 ? [{ id: 'username', desc: false }] : sorting;
filter = filter.length == 0 ? {} : { any: filter[0].value.toLowerCase() };
const response = await GetData(`${API_URL}/user/list`, {
limit: limit,
page: page + 1,
with_deleted: true,
order_field: sorting[0].id,
order_direction: sorting[0].desc == false ? 'ASC' : 'DESC',
filter: JSON.stringify(filter)
});
return { data: response?.data.list, totalCount: response?.data.total_count };
};
const fetchRoles = useCallback(async () => {
const params = {
limit: 100,
page: 1,
with_deleted: false,
order_field: 'name',
order_direction: 'ASC',
filter: JSON.stringify({
status: 'Y'
})
};
const response = await GetData(`${API_URL}/user_role/list`, params);
if (response?.status) {
setRoles(() => [...response.data.list]);
} else {
setRoles(() => []);
}
}, []);
useEffect(() => {
fetchRoles();
}, [fetchRoles]);
return (
<ManageUserContext.Provider
value={{
showEditDialog,
handleEditDialog,
selectedUser,
showAddDialog,
handleAddDialog,
roles,
showDeleteDialog,
handleDeleteDialog
}}
>
<Toaster expand visibleToasts={9} duration={3000} />
<DataGridProvider
columns={columns}
pagination={{ size: 10 }}
toolbar={<ListToolBar />}
layout={{ card: true }}
sorting={[{ id: 'username', desc: false }]}
serverSide={true}
onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
doGetListData(pageIndex, pageSize, sorting, columnFilters)
}
>
{children}
</DataGridProvider>
</ManageUserContext.Provider>
);
};
export { ManageUserContextProvider, ManageUserContext };
export type { SelectedUser };

View File

@ -0,0 +1,2 @@
export * from './ManageUserContext';
export * from './useManageUserContext';

View File

@ -0,0 +1,12 @@
import { useContext } from 'react';
import { ManageUserContext } from './ManageUserContext';
const useUserContext = () => {
const context = useContext(ManageUserContext);
if (!context) throw new Error('useUserContext must be used within AuthProvider');
return context;
};
export { useUserContext };

View File

@ -0,0 +1 @@
export * from './ConfigUserPage';